st80

Smalltalk-80 (image Xerox de 1983) dans le navigateur, VM du livre bleu en WebAssembly
git clone https://git.schurger.org/st80.git
Log | Files | Refs | README

commit 8f531bb153c0d623d662ee6aa06c84fa7e54b625
Author: Jean Schurger <jean@schurger.org>
Date:   Wed,  4 Nov 2026 13:17:38 -0500

Smalltalk-80 (image Xerox 1983) dans le navigateur : VM de Dan Banay en WebAssembly

VM « by the Bluebook » (vm/, MIT, commit ab6ab55) avec un patch Emscripten dans main.cpp :
boucle par trame avec budget de temps, SDL_TEXTINPUT, bouton du milieu = bleu, repli logiciel.
Page statique web/ (image Xerox livrée ou image Banay 2020 avec sources), tests Chromium headless
par DevTools, vhost nginx d'apostrophe.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyJB9yqUAYm3wRQi4uytj9

Diffstat:
A.gitignore | 7+++++++
AMakefile | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
AREADME.md | 33+++++++++++++++++++++++++++++++++
Adeploy/st80.schurger.org | 39+++++++++++++++++++++++++++++++++++++++
Atest/browser.mjs | 21+++++++++++++++++++++
Atest/cdp.mjs | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atest/interact.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/LICENSE.dbanay | 19+++++++++++++++++++
Avm/bitblt.cpp | 594+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/bitblt.h | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/filesystem.h | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/hal.h | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/interpreter.cpp | 5502+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/interpreter.h | 1453+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/main.cpp | 1099+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/objmemory.cpp | 1732+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/objmemory.h | 858+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/oops.h | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/posixfilesystem.h | 269+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Avm/realwordmemory.h | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/app.js | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/images/Smalltalk-80.changes | 2++
Aweb/images/Smalltalk-80.sources | 2++
Aweb/images/banay-2020.im | 0
Aweb/images/xerox-v2.im | 0
Aweb/index.html | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/style.css | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27 files changed, 12825 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,7 @@ +.emcache/ +.serve.pid +upstream/ +xerox/ +web/st80.js +web/st80.wasm +.DS_Store diff --git a/Makefile b/Makefile @@ -0,0 +1,51 @@ +# st80 : Smalltalk-80 (image Xerox du 1er avril 1983) dans le navigateur, servi sur https://st80.schurger.org +# La VM « by the Bluebook » de Dan Banay (vm/, MIT) est compilée en WebAssembly par Emscripten ; +# l'image et les sources sont servies en fichiers statiques (web/images/). +HOST = apostrophe +WWW = /var/www/st80.schurger.org +VHOST = st80.schurger.org + +# Emscripten par l'image Docker officielle (le paquet Debian est incompatible avec le nodejs de nodesource). +# Le cache (port SDL2 compilé) vit dans .emcache/, ignoré par git. +EMSDK_IMAGE = emscripten/emsdk:6.0.13 +DOCKER = docker run --rm -u $(shell id -u):$(shell id -g) -e HOME=/tmp -e EM_CACHE=/src/.emcache \ + -v $(CURDIR):/src -w /src $(EMSDK_IMAGE) + +SRCS = vm/objmemory.cpp vm/bitblt.cpp vm/interpreter.cpp vm/main.cpp +HDRS = $(wildcard vm/*.h) +EMFLAGS = -std=c++17 -O3 -sUSE_SDL=2 -sALLOW_MEMORY_GROWTH=1 -sENVIRONMENT=web \ + -sMODULARIZE=1 -sEXPORT_NAME=createST80 \ + -sEXPORTED_RUNTIME_METHODS=FS,callMain,ccall,UTF8ToString \ + -sEXPORTED_FUNCTIONS=_main,_st80_set_budget,_st80_set_paused,_st80_cycle_count,_st80_image_name + +.PHONY: all build test serve deploy install-vhost clean + +all: build + +build: web/st80.js + +web/st80.js: $(SRCS) $(HDRS) Makefile + $(DOCKER) em++ $(EMFLAGS) $(SRCS) -o web/st80.js + +# Démarrage dans un Chromium headless : capture d'écran et compteur de bytecodes +test: build + python3 -m http.server 8082 -d web --bind 127.0.0.1 >/dev/null 2>&1 & echo $$! > .serve.pid; \ + sleep 1; node test/browser.mjs http://127.0.0.1:8082/ 12 /tmp/st80.png; r=$$?; kill `cat .serve.pid`; rm -f .serve.pid; exit $$r + +# Essai local : http://localhost:8082/ +serve: + python3 -m http.server 8082 -d web + +# Publication : fichiers statiques copiés sur apostrophe +deploy: build + ssh $(HOST) 'sudo install -d -o jeansch -g jeansch $(WWW)' + rsync -rc --delete --exclude '.*' web/ $(HOST):$(WWW)/ + @echo "https://$(VHOST)/" + +# Vhost nginx (une fois) : 8443 derrière sslh, certificat joker, comme les autres sites d'apostrophe +install-vhost: + scp deploy/$(VHOST) $(HOST):/tmp/$(VHOST) + ssh $(HOST) 'sudo install -m 644 /tmp/$(VHOST) /etc/nginx/sites-available/$(VHOST) && sudo ln -sf /etc/nginx/sites-available/$(VHOST) /etc/nginx/sites-enabled/$(VHOST) && sudo nginx -t && sudo systemctl reload nginx && rm /tmp/$(VHOST)' + +clean: + rm -f web/st80.js web/st80.wasm diff --git a/README.md b/README.md @@ -0,0 +1,33 @@ +# st80 : Smalltalk-80 (image Xerox de 1983) dans le navigateur + +https://st80.schurger.org — l'image `VirtualImage` de Smalltalk-80 version 2 (Xerox PARC, 1er avril 1983), +telle que distribuée par [Mario Wolczko](http://www.wolczko.com/st80/), exécutée par la machine virtuelle +« by the Bluebook » de [Dan Banay](https://github.com/dbanay/Smalltalk) (C++, MIT) compilée en WebAssembly. + +## Contenu + +- `vm/` : sources de la VM de Dan Banay (commit `ab6ab55`, 2023-04-20) avec un patch Emscripten dans `main.cpp` + (`#ifdef __EMSCRIPTEN__`) : boucle principale par trame avec budget de temps, caractères par `SDL_TEXTINPUT` + (disposition du clavier respectée), bouton du milieu = bouton bleu, repli sur le rendu logiciel, fonctions + `st80_*` exportées vers la page. Licence : `vm/LICENSE.dbanay`. +- `web/` : site statique. `index.html`, `style.css`, `app.js` (charge l'image dans le MEMFS d'Emscripten puis + `callMain`) ; `st80.js` + `st80.wasm` produits par `make build` (ignorés par git). +- `web/images/` : `xerox-v2.im` = `VirtualImage` de Xerox passée par `imageswapper.c` (petit-boutiste, flottants + compris), c'est `org/VirtualImageLSB` du dépôt de Banay ; `banay-2020.im` = la même image avec les classes + `PosixFile*` et `SourceFiles` branché sur `Smalltalk-80.sources` + `Smalltalk-80.changes` (sources lisibles). +- `test/` : `cdp.mjs` (Chromium headless par DevTools), `browser.mjs` (démarrage + capture + compteur de + bytecodes), `interact.mjs` (menus tenus, frappe). +- `deploy/st80.schurger.org` : vhost nginx d'apostrophe (8443 derrière sslh, joker, `application/wasm`). + +## Commandes + +- `make build` : Emscripten par Docker (`emscripten/emsdk:6.0.13`, cache dans `.emcache/`). +- `make test` : démarrage dans Chromium headless, capture `/tmp/st80.png`, échec si < 1 M bytecodes. +- `make serve` : http://localhost:8082/ ; `?image=banay` pour l'image avec sources. +- `make deploy` : rsync vers `apostrophe:/var/www/st80.schurger.org` ; `make install-vhost` une fois. + +## Utilisation + +Souris : gauche = rouge, droit ou Ctrl+gauche = jaune, milieu ou Alt+gauche = bleu. Les menus se tiennent +enfoncés et se choisissent au relâchement. `_` = ←, `^` = ↑. Un `save` écrit l'instantané dans le MEMFS ; +« Télécharger l'image » le récupère. diff --git a/deploy/st80.schurger.org b/deploy/st80.schurger.org @@ -0,0 +1,39 @@ +# https://st80.schurger.org : Smalltalk-80 (image Xerox de 1983) dans le navigateur (fichiers statiques, +# dépôt ~/src/perso/st80 de hotrats, publié par « make deploy »). +# TLS on 8443 behind sslh, like the other vhosts; wildcard certificate. +server { + server_name st80.schurger.org; + listen 8443 ssl; + http2 on; + ssl_certificate /etc/letsencrypt/live/schurger.org/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/schurger.org/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + + root /var/www/st80.schurger.org; + index index.html; + + types { + text/html html; + text/css css; + text/javascript js mjs; + application/wasm wasm; + application/octet-stream im sources changes; + image/svg+xml svg; + image/png png; + } + + gzip on; + gzip_types text/css text/javascript application/wasm application/octet-stream; + + location / { + try_files $uri $uri/ =404; + } +} + +server { + listen 80; + listen [::]:80; + server_name st80.schurger.org; + return 301 https://$host$request_uri; +} diff --git a/test/browser.mjs b/test/browser.mjs @@ -0,0 +1,21 @@ +// Démarrage : ouvre l'URL, attend `secondes`, affiche la ligne de statut, le compteur de bytecodes et +// les erreurs console, puis enregistre une capture d'écran. Échoue si la VM n'a pas démarré. +// node test/browser.mjs [url] [secondes] [capture.png] [js à évaluer après l'attente] +import { open, sleep } from './cdp.mjs'; + +const url = process.argv[2] ?? 'http://localhost:8082/'; +const secs = Number(process.argv[3] ?? 12); +const shot = process.argv[4] ?? '/tmp/st80.png'; +const extra = process.argv[5]; + +const page = await open(url); +await sleep(secs * 1000); +const status = await page.evaluate("document.getElementById('status')?.textContent"); +const cycles = await page.evaluate('window.st80?.cycles() ?? 0'); +console.log('Statut :', status); +console.log('Bytecodes exécutés :', cycles); +if (extra) console.log('Évaluation :', JSON.stringify(await page.evaluate(extra))); +for (const l of page.logs) console.log(l); +console.log('Capture :', await page.screenshot(shot)); +page.close(); +if (!(cycles > 1_000_000)) { console.error('ÉCHEC : la VM n’a pas (assez) tourné'); process.exit(1); } diff --git a/test/cdp.mjs b/test/cdp.mjs @@ -0,0 +1,72 @@ +// Pilotage d'un Chromium headless par le protocole DevTools, sans dépendance (pas de Playwright sur hotrats). +import { spawn } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +export async function open(url, { port = 9334, width = 1000, height = 1400 } = {}) { + const chrome = spawn(process.env.CHROME ?? 'chromium', [ + '--headless=new', '--no-sandbox', '--hide-scrollbars', + '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', + `--remote-debugging-port=${port}`, `--window-size=${width},${height}`, 'about:blank', + ], { stdio: 'ignore' }); + + let target; + for (let i = 0; i < 50 && !target; i++) { + await sleep(200); + try { + const r = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: 'PUT' }); + target = await r.json(); + } catch { /* pas encore prêt */ } + } + if (!target) { chrome.kill(); throw new Error('Chromium ne répond pas'); } + + const ws = new WebSocket(target.webSocketDebuggerUrl); + await new Promise((r) => ws.addEventListener('open', r)); + let id = 0; + const pending = new Map(); + const logs = []; + ws.addEventListener('message', (ev) => { + const m = JSON.parse(ev.data); + if (m.id && pending.has(m.id)) { pending.get(m.id)(m.result ?? m.error); pending.delete(m.id); } + else if (m.method === 'Runtime.consoleAPICalled') logs.push(`[${m.params.type}] ${m.params.args.map((a) => a.value ?? a.description).join(' ')}`); + else if (m.method === 'Runtime.exceptionThrown') logs.push(`[exception] ${m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text}`); + }); + const send = (method, params = {}) => new Promise((r) => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); }); + const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; + const screenshot = async (path) => { + const png = (await send('Page.captureScreenshot', { format: 'png' })).data; + writeFileSync(path, Buffer.from(png, 'base64')); + return path; + }; + // Coordonnées de la page pour un point de l'écran Smalltalk (640×480 mis à l'échelle CSS) + const canvasPoint = async (x, y) => { + const r = await evaluate("(() => { const c = document.getElementById('canvas').getBoundingClientRect(); return [c.left, c.top, c.width, c.height]; })()"); + const [left, top, w, h] = r; + return { x: left + (x * w) / 640, y: top + (y * h) / 480 }; + }; + const mouse = async (type, x, y, button = 'none', clickCount = 1) => + send('Input.dispatchMouseEvent', { type, x, y, button, clickCount, buttons: button === 'left' ? 1 : button === 'right' ? 2 : button === 'middle' ? 4 : 0 }); + const click = async (sx, sy, button = 'left') => { + const p = await canvasPoint(sx, sy); + await mouse('mouseMoved', p.x, p.y); + await sleep(100); + await mouse('mousePressed', p.x, p.y, button); + await sleep(120); + await mouse('mouseReleased', p.x, p.y, button); + }; + const type = async (text) => { + for (const ch of text) { + const key = ch === '\r' ? 'Enter' : ch; + await send('Input.dispatchKeyEvent', { type: 'keyDown', key, text: ch, unmodifiedText: ch }); + await send('Input.dispatchKeyEvent', { type: 'keyUp', key }); + await sleep(40); + } + }; + const close = () => { ws.close(); chrome.kill(); }; + + await send('Runtime.enable'); + await send('Page.enable'); + await send('Page.navigate', { url }); + return { send, evaluate, logs, screenshot, canvasPoint, mouse, click, type, close }; +} diff --git a/test/interact.mjs b/test/interact.mjs @@ -0,0 +1,58 @@ +// Interaction dans l'image Xerox livrée : le clavier va au volet sous la souris et les menus de +// Smalltalk-80 s'ouvrent bouton enfoncé et se choisissent au relâchement. +// 1. clic rouge dans le volet de code du System Browser (vide), frappe de « 3 + 4 » → capture ; +// 2. sélection de la ligne par glissement, bouton jaune tenu → capture du menu de texte, +// déplacement d'un cran vers le bas (« print it », « do it » étant sous le curseur) et relâchement ; +// 3. capture du résultat (« 7 » imprimé après l'expression). +// node test/interact.mjs [url] [préfixe des captures] +import { open, sleep } from './cdp.mjs'; + +const url = process.argv[2] ?? 'http://localhost:8082/'; +const prefix = process.argv[3] ?? '/tmp/st80-interact'; + +const page = await open(url); +await sleep(10000); + +// Le volet de code du System Browser occupe le bas de l'écran livré ; sa première ligne est en (99, 274). +const PANE = { x: 400, y: 330 }; +const LINE = { x: 97, y: 274 }; + +// 1. Clic rouge dans le volet (le browser passe devant, caret au début du texte vide), frappe +await page.click(PANE.x, PANE.y, 'left'); +await sleep(800); +await page.type('3 + 4'); +await sleep(1200); +console.log('Capture :', await page.screenshot(`${prefix}-1-texte.png`)); + +// 2. Sélection de la ligne par glissement rouge, puis menu jaune tenu +let a = await page.canvasPoint(LINE.x, LINE.y); +let b = await page.canvasPoint(LINE.x + 200, LINE.y); +await page.mouse('mouseMoved', a.x, a.y); +await page.mouse('mousePressed', a.x, a.y, 'left'); +await sleep(150); +await page.mouse('mouseMoved', (a.x + b.x) / 2, a.y, 'left'); +await sleep(150); +await page.mouse('mouseMoved', b.x, b.y, 'left'); +await sleep(150); +await page.mouse('mouseReleased', b.x, b.y, 'left'); +await sleep(600); + +const m = await page.canvasPoint(LINE.x + 100, LINE.y); +await page.mouse('mouseMoved', m.x, m.y); +await sleep(100); +await page.mouse('mousePressed', m.x, m.y, 'right'); +await sleep(1200); +console.log('Capture :', await page.screenshot(`${prefix}-2-menu.png`)); +const item = await page.canvasPoint(LINE.x + 100, LINE.y + 13); // « print it », un cran sous « do it » +await page.mouse('mouseMoved', item.x, item.y, 'right'); +await sleep(300); +await page.mouse('mouseReleased', item.x, item.y, 'right'); +await sleep(1500); + +// 3. Résultat +console.log('Capture :', await page.screenshot(`${prefix}-3-resultat.png`)); +const status = await page.evaluate("document.getElementById('status')?.textContent"); +console.log('Statut :', status); +for (const l of page.logs) console.log(l); +page.close(); +if (/quitté|Erreur/.test(status)) { console.error('ÉCHEC'); process.exit(1); } diff --git a/vm/LICENSE.dbanay b/vm/LICENSE.dbanay @@ -0,0 +1,19 @@ +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vm/bitblt.cpp b/vm/bitblt.cpp @@ -0,0 +1,594 @@ +// +// bitblt.cpp +// Smalltalk-80 +// +// Created by Dan Banay on 2/20/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +#include "bitblt.h" + +/* "source" + "initialize a table of bit masks ... p.356" + RightMasks <- + #(0 16r1 16r3 16r7 16rF + 16r1F 16r3F 16r7F 16rFF + 16r1FF 16r3FF 16r7FF 16rFFF + 16r1FFF 16r3FFF 16r7FFF 16rFFFF). + AllOnes <- 16rFFFF +*/ + +static std::uint16_t RightMasks[] = { + 0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, + 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF +}; + + +// clipRange +void BitBlt::clipRange() +{ + /* "source" + "clip and adjust source origin and extent appropriately" + "first in x" + destX >= clipX + ifTrue: [sx <- sourceX. + dx <- destX. + w <- width] + ifFalse: [sx <- sourceX + (clipX - destX). + w <- width - (clipX - destX). + dx <- clipX]. + (dx + w) > (clipX + clipWidth) + ifTrue: [w <- w - ((dx + w) - (clipX + clipWidth))]. + "then in y" + destY >= clipY + ifTrue: [sy <- sourceY. + dy <- destY. + h <- height] + ifFalse: [sy <- sourceY + clipY - destY. + h <- height - (clipY - destY). + dy <- clipY]. + (dy + h) > (clipY + clipHeight) + ifTrue: [h <- h - ((dy + h) - (clipY + clipHeight))]. + sx < 0 + ifTrue: [dx <- dx - sx. + w <- w + sx. + sx <- 0]. + "ERROR dbanay need to check if sourceForm is nil." + + sx + w > sourceForm width + ifTrue: [w <- w - (sx + w - sourceForm width)]. + sy < 0 + ifTrue: [dy <- dy - sy. + h <- h + sy. + sy <- 0]. + sy + h > sourceForm height + ifTrue: [h <- h - (sy + h - sourceForm height)] + */ + + if (clipX < 0) + { + clipWidth += clipX; + clipX = 0; + } + if (clipY < 0) + { + clipHeight += clipY; + clipY = 0; + } + + if ((clipX + clipWidth) > destFormWidth) + { + clipWidth = destFormWidth - clipX; + } + + if ((clipY + clipHeight) > destFormHeight) + { + clipHeight = destFormHeight - clipY; + } + + // clip and adjust source origin and extent appropriately + // first in x + if (destX >= clipX) + { + sx = sourceX; + dx = destX; + w = width; + } + else + { + sx = sourceX + (clipX - destX); + w = width - (clipX - destX); + dx = clipX; + } + if ((dx + w) > (clipX + clipWidth)) + { + w = w - ((dx + w) - (clipX + clipWidth)); + } + + //then in y + if (destY >= clipY) + { + sy = sourceY; + dy = destY; + h = height; + } + else + { + sy = sourceY + clipY - destY; + h = height - (clipY - destY); + dy = clipY; + } + if ((dy + h) > (clipY + clipHeight)) + { + h = h - ((dy + h) - (clipY + clipHeight)); + } + + if (sourceForm == NilPointer) + return; + + if (sx < 0) + { + dx = dx - sx; + w = w + sx; + sx = 0; + } + + if (sx + w > sourceFormWidth) + { + w = w - (sx + w - sourceFormWidth); + } + + if (sy < 0) + { + dy = dy - sy; + h = h + sy; + sy = 0; + } + + if (sy + h > sourceFormHeight) + { + h = h - (sy + h - sourceFormHeight); + } +} + + +// WordArray class>>maxSize +// maxSize +// "The maximum size of a WordArray is 64640 elements." +// ^64640 +// +// When a Form is allocated, the number of words required to hold the bits is +// (width + 15)/16 * height. If the form is large enough this will exceed maxSize +// and rather than fail, Smalltalk clamps the array size to 64640! This mucks +// things up if such a form is used as a source or target. + +// copyBits +bool BitBlt::copyBits() +{ + /* "source" + "from copyBits, p.356" + "sets w and h" + self clipRange. + (w <= 0 or: [h <= 0]) ifTrue: [^self ]. "null range" + self computeMasks. + self checkOverlap. + self calculateOffsets. + self copyLoop + */ + + // from copyBits, p.356 + clipRange(); + if (w > 0 && h > 0) + { + updatedX = dx; + updatedY = dy; + updatedWidth = w; + updatedHeight = h; + computeMasks(); + // Check if source or dest is "bad" + if (sourceForm != NilPointer && formWordCount(sourceFormWidth, sourceFormHeight) != sourceBitsWordLength ) + return false; + if (formWordCount(destFormWidth, destFormHeight) != destBitsWordLength ) + return false; + + checkOverlap(); + calculateOffsets(); + copyLoop(); + } + else + { + updatedX = 0; + updatedY = 0; + updatedWidth = 0; + updatedHeight = 0; + + } + + return true; + +} + + +// copyLoop +void BitBlt::copyLoop() +{ + std::uint16_t prevWord; + std::uint16_t thisWord = 0; //eliminate warning + std::uint16_t skewWord; + std::uint16_t mergeMask; + std::uint16_t halftoneWord; + std::uint16_t mergeWord; + int word; + + /* "source" + 1 to: h do: "here is the vertical loop" + [ :i | + (halftoneForm notNil) + ifTrue: [halftoneWord <- halftoneBits at: (1 + (dy bitAnd: 15)). + dy <- dy + vDir] + ifFalse: [halftoneWord <- AllOnes]. + skewWord <- halftoneWord. + preload + ifTrue: [prevWord <- sourceBits at: sourceIndex + 1. + "load the 32-bit shifter" + sourceIndex <- sourceIndex + hDir] + ifFalse: [prevWord <- 0]. + mergeMask <- mask1. + "ERROR: extra to on next line" + 1 to: nWords do: "here is the inner horizontal loop" + [ :word | + sourceForm notNil "if source used" + ifTrue: [prevWord <- prevWord bitAnd: skewMask. + "ERROR: dbanay need to check if out of range. use 0 if that is the case" + thisWord <- sourceBits at: sourceIndex + 1. + "pick up next word" + skewWord <- + prevWord bitOr: (thisWord bitAnd: + skewMask bitInvert). + prevWord <- thisWord. + skewWord <- (skewWord bitShift: skew) bitOr: + (skewWord bitShift: skew - 16)]. + "16-bit rotate" + mergeWord <- self merge: (skewWord bitAnd: halftoneWord) + with: (destBits at: destIndex + 1). + destBits + at: destIndex + 1 + put: ((mergeMask bitAnd: mergeWord) + bitOr: (mergeMask bitInvert + bitAnd: (destBits at: destIndex + 1))). + sourceIndex <- sourceIndex + hDir. + destIndex <- destIndex + hDir. + word = (nWords - 1) + ifTrue: [mergeMask <- mask2] + ifFalse: [mergeMask <- AllOnes]]. + sourceIndex <- sourceIndex + sourceDelta. + destIndex <- destIndex + destDelta] + */ + + + + for(int i = 1; i <=h; i++) + { + // here is the vertical loop + if (halftoneForm != NilPointer) + { + halftoneWord = memory.fetchWord_ofObject((dy & 15), halftoneBits); + dy = dy + vDir; + } + else + { + halftoneWord = AllOnes; + } + skewWord = halftoneWord; + if (preload) + { + // load the 32-bit shifter + + prevWord = memory.fetchWord_ofObject(sourceIndex, sourceBits); + sourceIndex = sourceIndex + hDir; + } + else + { + prevWord = 0; + } + mergeMask = mask1; + + // here is the inner horizontal loop + for(word = 1; word <= nWords; word++) + { + if (sourceForm != NilPointer) // if source used + { + prevWord = prevWord & skewMask; + if (word <= sourceRaster && sourceIndex >= 0 && sourceIndex < sourceBitsWordLength) + thisWord = memory.fetchWord_ofObject(sourceIndex, sourceBits); + //else + // thisWord = 0; + skewWord = prevWord | (thisWord & ~skewMask); + + prevWord = thisWord; + // Note: replaced left shift by negative value with a right shift of complement + skewWord = (skewWord << skew) | (skewWord >> (16-skew)); + } + + if (destIndex >= destBitsWordLength) return; + + std::uint16_t destWord = memory.fetchWord_ofObject(destIndex, destBits); + // 16-bit rotate + mergeWord = merge_with(skewWord & halftoneWord, destWord); + + memory.storeWord_ofObject_withValue(destIndex, destBits, + (mergeMask & mergeWord) | + (~mergeMask & destWord)); + sourceIndex = sourceIndex + hDir; + destIndex = destIndex + hDir; + + + if (word == (nWords - 1)) + mergeMask = mask2; + else + mergeMask = AllOnes; + } + + sourceIndex = sourceIndex + sourceDelta; + destIndex = destIndex + destDelta; + + } +} + + +// calculateOffsets +void BitBlt::calculateOffsets() +{ + /* "source" + "check if need to preload buffer + (i.e., two words of source needed for first word of destination)" + preload <- (sourceForm notNil) and: + [skew ~= 0 and: [skew <= (sx bitAnd: 15)]]. + hDir < 0 ifTrue: [preload <- preload == false]. + "calculate starting offsets" + sourceIndex <- sy * sourceRaster + (sx // 16). + destIndex <- dy * destRaster + (dx // 16). + "calculate increments from end of 1 line to start of next" + sourceDelta <- + (sourceRaster * vDir) - + (nWords + (preload ifTrue: [1] ifFalse: [0]) * hDir). + destDelta <- (destRaster * vDir) - (nWords * hDir) + */ + + // check if need to preload buffer + // (i.e., two words of source needed for first word of destination) + preload = (sourceForm != NilPointer) && skew != 0 && skew <= (sx & 15); + if (hDir < 0) preload = !preload; + + // calculate starting offsets + sourceIndex = sy * sourceRaster + (sx / 16); + destIndex = dy * destRaster + (dx / 16); + // calculate increments from end of 1 line to start of next + // dbanay - note operator precedence change! + sourceDelta = + (sourceRaster * vDir) - ((nWords + (preload ? 1 : 0)) * hDir); + destDelta = (destRaster * vDir) - (nWords * hDir); +} + + +// computeMasks +void BitBlt::computeMasks() +{ + int startBits; + int endBits; + + /* "source" + "calculate skew and edge masks" + destBits <- destForm bits. + destRaster <- destForm width - 1 // 16 + 1. + sourceForm notNil + ifTrue: [sourceBits <- sourceForm bits. + sourceRaster <- sourceForm width - 1 // 16 + 1]. + halftoneForm notNil + ifTrue: [halftoneBits <- halftoneForm bits]. + skew <- (sx - dx) bitAnd: 15. + "how many bits source gets skewed to right" + startBits <- 16 - (dx bitAnd: 15). + " how many bits in first word" + mask1 <- RightMasks at: startBits + 1. + endBits <- 15 - ((dx + w - 1) bitAnd: 15). + "how many bits in last word" + mask2 <- (RightMasks at: endBits + 1) bitInvert. + skewMask <- + (skew = 0 + ifTrue: [0] + ifFalse: [RightMasks at: 16 - skew + 1]). + "determine number of words stored per line; merge masks if necessary" + "ERROR dbanay : nWords <- (w - startBits + 15) // 16 + 1 for False case" + w < startBits + ifTrue: [mask1 <- mask1 bitAnd: mask2. + mask2 <- 0. + nWords <- 1] + ifFalse: [nWords <- (w - startBits - 1) // 16 + 2] + */ + + const int BitsInForm = 0; + + + // calculate skew and edge masks + destBits = memory.fetchPointer_ofObject(BitsInForm, destForm); + destBitsWordLength = memory.fetchWordLengthOf(destBits); + + destRaster = (destFormWidth - 1) / 16 + 1; + if (sourceForm != NilPointer) + { + sourceBits = memory.fetchPointer_ofObject(BitsInForm, sourceForm); + sourceBitsWordLength = memory.fetchWordLengthOf(sourceBits); + sourceRaster = (sourceFormWidth - 1) / 16 + 1; + } + else + sourceBitsWordLength = 0; + + if (halftoneForm != NilPointer) + { + halftoneBits = memory.fetchPointer_ofObject(BitsInForm, halftoneForm); + } + + // how many bits source gets skewed to right + skew = (sx - dx) & 15; + + // how many bits in first word + startBits = 16 - (dx & 15); + + mask1 = RightMasks[startBits]; // +1 removed - dbanay -- C/C++ arrays start at 0 + + // how many bits in last word + endBits = 15 - ((dx + w - 1) & 15); + + mask2 = ~RightMasks[endBits]; // +1 removed - dbanay -- C/C++ arrays start at 0 + skewMask = skew == 0 ? 0 : RightMasks[16 - skew]; + // determine number of words stored per line; merge masks if necessary + // Bluebook had the nWords calculation wrong when w == startBits + if (w < startBits) + { + mask1 = mask1 & mask2; + mask2 = 0; + nWords = 1; + } + else + { + nWords = (w - startBits + 15) / 16 + 1; + } +} + + +// checkOverlap +void BitBlt::checkOverlap() +{ + int t; + + /* "source" + "check for possible overlap of source and destination" + hDir <- vDir <- 1. "defaults for no overlap" + (sourceForm == destForm and: [dy >= sy]) + ifTrue: [dy > sy "have to start at bottom" + ifTrue: [vDir <- -1. + sy <- sy + h - 1. + dy <- dy + h - 1] + ifFalse: [dx > sx "y's are equal, but x's are backward" + ifTrue: [hDir <- -1. + sx <- sx + w - 1. + "start at right" + dx <- dx + w - 1. + "and fix up masks" + skewMask <- skewMask bitInvert. + t <- mask1. + mask1 <- mask2. + mask2 <- t]]] + */ + + // check for possible overlap of source and destination + hDir = vDir = 1; // defaults for no overlap + if (sourceForm == destForm && (dy >= sy)) + { + if (dy > sy) // have to start at bottom + { + vDir = -1; + sy = sy + h - 1; + dy = dy + h - 1; + } + else + { + if (dx > sx) + { + // y's are equal, but x's are backward + hDir = -1; + // start at right + sx = sx + w - 1; + dx = dx + w - 1; + // and fix up masks + skewMask = ~skewMask; + t = mask1; + mask1 = mask2; + mask2 = t; + } + } + } +} + + + +// CharacterScanner + +int CharacterScanner::scanCharactersFrom_to_in_rightX_stopConditions_displaying( + int startIndex, + int stopIndex, + int sourceString, + int rightX, + int stops, + bool displaying) +{ + const int EndOfRun = 257; // TextConstants at: #EndOfRun put: 257. + const int CrossedX = 258; // TextConstants at: #CrossedX put: 258. + + /* "source" + | ascii nextDestX | + lastIndex <- startIndex. + [lastIndex <= stopIndex] + whileTrue: + [ascii <- (sourceString at: lastIndex) asciiValue. + (stopConditions at: ascii + 1) ~~ nil ifTrue: [^stops at: ascii + 1]. + sourceX <- xTable at: ascii + 1. + nextDestX <- destX + (width _ (xTable at: ascii + 2) - sourceX). + nextDestX > rightX ifTrue: [^stops at: CrossedX]. + display ifTrue: [self copyBits]. + destX <- nextDestX. + lastIndex <- lastIndex + 1]. + lastIndex <- stopIndex. + ^stops at: EndOfRun + + + */ + int ascii; + int nextDestX; + + lastIndex = startIndex; + while (lastIndex <= stopIndex) + { + ascii = memory.fetchByte_ofObject(lastIndex-1, sourceString); + + if (memory.fetchPointer_ofObject(ascii, stopConditions) != NilPointer) + { + return memory.fetchPointer_ofObject(ascii, stops); + } + + sourceX = memory.integerValueOf(memory.fetchPointer_ofObject(ascii, xTable)); + width = memory.integerValueOf(memory.fetchPointer_ofObject(ascii+1, xTable)) - sourceX; + nextDestX = destX + width; + if (nextDestX > rightX) + { + return memory.fetchPointer_ofObject(CrossedX-1, stops); + } + if (displaying) copyBits(); + destX = nextDestX; + lastIndex = lastIndex + 1; + } + + lastIndex = stopIndex; + return memory.fetchPointer_ofObject(EndOfRun-1, stops); +} + diff --git a/vm/bitblt.h b/vm/bitblt.h @@ -0,0 +1,363 @@ +// +// bitblt.h +// Smalltalk-80 +// +// Created by Dan Banay on 2/20/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#pragma once +#include "objmemory.h" +#include <cstdint> + + +//BItBlt +static const int DestFormIndex = 0; +static const int SourceFormIndex = 1; +static const int HalftoneFormIndex = 2; +static const int CombinationRuleIndex = 3; +static const int DestXIndex = 4; +static const int DestYIndex = 5; +static const int WidthIndex = 6; +static const int HeightIndex = 7; +static const int SourceXIndex = 8; +static const int SourceYIndex = 9; +static const int ClipXIndex = 10; +static const int ClipYIndex = 11; +static const int ClipWidthIndex = 12; +static const int ClipHeightIndex = 13; + + +// BitBltSimulation +class BitBlt +{ +public: + + BitBlt(ObjectMemory &memory, + int destForm, + int sourceForm, + int halftoneForm, + int combinationRule, + int destX, + int destY, + int width, + int height, + int sourceX, + int sourceY, + int clipX, + int clipY, + int clipWidth, + int clipHeight): + memory(memory), + destForm(destForm), + sourceForm(sourceForm), + halftoneForm(halftoneForm), + combinationRule(combinationRule), + destX(destX), + destY(destY), + width(width), + height(height), + sourceX(sourceX), + sourceY(sourceY), + clipX(clipX), + clipY(clipY), + clipWidth(clipWidth), + clipHeight(clipHeight) + + { + const int WidthInForm = 1; + const int HeightInForm = 2; + + if (sourceForm != NilPointer) + { + sourceFormWidth = memory.integerValueOf(memory.fetchWord_ofObject(WidthInForm, sourceForm)); + sourceFormHeight = memory.integerValueOf(memory.fetchWord_ofObject(HeightInForm, sourceForm)); + } + else + { + sourceX = sourceY = 0; + sourceFormHeight = sourceFormWidth = 0; + } + destFormWidth = memory.integerValueOf(memory.fetchWord_ofObject(WidthInForm, destForm)); + destFormHeight = memory.integerValueOf(memory.fetchWord_ofObject(HeightInForm, destForm)); + updatedX = 0; + updatedY = 0; + updatedWidth = 0; + updatedHeight = 0; + } + + + bool copyBits(); + + void getUpdatedBounds(int *boundsX, int *boundsY, int *boundsWidth, int *boundsHeight) + { + *boundsX = updatedX; + *boundsY = updatedY; + *boundsWidth = updatedWidth; + *boundsHeight = updatedHeight; + } + +protected: + + + static const std::uint16_t AllOnes = 0xFFFF; + + // clipRange + void clipRange(); + + // merge:with: + inline std::uint16_t merge_with(std::uint16_t sourceWord, std::uint16_t destinationWord) + { + /* "source" + "These are the 16 combination rules:" + combinationRule = 0 + ifTrue: [^0]. + combinationRule = 1 + ifTrue: [^sourceWord bitAnd: destinationWord]. + combinationRule = 2 + ifTrue: [^sourceWord bitAnd: destinationWord bitInvert]. + combinationRule = 3 + ifTrue: [^sourceWord]. + combinationRule = 4 + ifTrue: [^sourceWord bitInvert bitAnd: destinationWord]. + combinationRule = 5 + ifTrue: [^destinationWord]. + combinationRule = 6 + ifTrue: [^sourceWord bitXor: destinationWord]. + combinationRule = 7 + ifTrue: [^sourceWord bitOr: destinationWord]. + combinationRule = 8 + ifTrue: [^sourceWord bitInvert bitAnd: destinationWord bitInvert]. + combinationRule = 9 + ifTrue: [^sourceWord bitInvert bitXor: destinationWord]. + combinationRule = 10 + ifTrue: [^destinationWord bitInvert]. + combinationRule = 11 + ifTrue: [^sourceWord bitOr: destinationWord bitInvert]. + combinationRule = 12 + ifTrue: [^sourceWord bitInvert]. + combinationRule = 13 + ifTrue: [^sourceWord bitInvert bitOr: destinationWord]. + combinationRule = 14 + ifTrue: [^sourceWord bitInvert bitOr: destinationWord bitInvert]. + combinationRule = 15 + ifTrue: [^AllOnes] + */ + + // These are the 16 combination rules: + switch (combinationRule) + { + case 0 + : return 0; + case 1 // [^sourceWord bitAnd: destinationWord] + : return sourceWord & destinationWord; + + case 2 // [^sourceWord bitAnd: destinationWord bitInvert] + : return sourceWord & (~destinationWord); + + case 3 // [^sourceWord] + : return sourceWord; + + case 4 // [^sourceWord bitInvert bitAnd: destinationWord] + : return (~sourceWord) & destinationWord; + + case 5 // [^destinationWord] + : return destinationWord; + + case 6 // [^sourceWord bitXor: destinationWord] + : return sourceWord ^ destinationWord; + + case 7 // [^sourceWord bitOr: destinationWord] + : return sourceWord | destinationWord; + + case 8 // [^sourceWord bitInvert bitAnd: destinationWord bitInvert]. + : return (~sourceWord) & (~destinationWord); + + case 9 // [^sourceWord bitInvert bitXor: destinationWord]. + : return (~sourceWord) ^ destinationWord; + + case 10 // [^destinationWord bitInvert] + : return ~destinationWord; + + case 11 // [^sourceWord bitOr: destinationWord bitInvert]. + : return sourceWord | (~destinationWord); + + case 12 // [^sourceWord bitInvert] + : return ~sourceWord; + + case 13 // [^sourceWord bitInvert bitOr: destinationWord] + : return (~sourceWord) | destinationWord; + + case 14 // [^sourceWord bitInvert bitOr: destinationWord bitInvert]. + : return (~sourceWord) | (~destinationWord); + + case 15 + : return AllOnes; + default: + assert(0); + } + + return 0; + } + + // copyLoop + void copyLoop(); + + // calculateOffsets + void calculateOffsets(); + + // computeMasks + void computeMasks(); + + // checkOverlap + void checkOverlap(); + + ObjectMemory& memory; + int destForm; + int sourceForm; + int halftoneForm; + int combinationRule; + int destX; + int destY; + int width; + int height; + int sourceX; + int sourceY; + int clipX; + int clipY; + int clipWidth; + int clipHeight; + + // instance variables (pg. 356 G&R) + int sourceBits, sourceRaster, destBits, destRaster, halftoneBits, + skew, + preload, nWords, + hDir, vDir, + sourceIndex, sourceDelta, destIndex, destDelta, + sx, sy, dx, dy, w, h; + + int sourceBitsWordLength, destBitsWordLength; + + //sourceRaster is the source pitch, and destRaster the destination pitch. + //I guess these terms were unknown to the implementors. + + std::uint16_t mask1, mask2, skewMask; + + // Additional info + int sourceFormWidth; + int sourceFormHeight; + int destFormWidth; + int destFormHeight; + + // Actual area affected by last copyBots + int updatedX, updatedY, updatedWidth, updatedHeight; +protected: + inline int formWordCount(int width, int height) + { + return (width + 15) / 16 * height; + } + +}; + +//Character Scanner +static const int LastIndexIndex = 14; +static const int XTableIndexIndex = 15; +static const int StopConditionsIndex = 16; +static const int TextIndex = 17; +static const int TextStyleIndex = 18; +static const int LeftMarginIndex = 19; +static const int RightMarginIndex = 20; +static const int FontIndex = 21; +static const int LineIndex = 22; +static const int RunStopIndexIndex = 23; +static const int SpaceCountIndex = 24; +static const int SpaceWidthIndex = 25; +static const int OutputMediumIndex = 26; + +class CharacterScanner: public BitBlt +{ +public: + CharacterScanner(ObjectMemory &memory, + int destForm, + int sourceForm, + int halftoneForm, + int combinationRule, + int destX, + int destY, + int width, + int height, + int sourceX, + int sourceY, + int clipX, + int clipY, + int clipWidth, + int clipHeight, + + + int xTable, + int lastIndex, + int stopConditions) : + BitBlt(memory, + destForm, + sourceForm, + halftoneForm, + combinationRule, + destX, + destY, + width, + height, + sourceX, + sourceY, + clipX, + clipY, + clipWidth, + clipHeight), + xTable(xTable), + lastIndex(lastIndex), + stopConditions(stopConditions) + { + } + + + // After scanning, internal state is updated for 3 variables which must be + // written back to the object store. Here they are: + int updateDestX() { return destX; } + int updatedWidth() { return width; } + int updatedSourceX() { return sourceX; } + int updatedLastIndex() { return lastIndex; } + + int scanCharactersFrom_to_in_rightX_stopConditions_displaying( + int startIndex, + int stopIndex, + int sourceString, + int rightX, + int stop, + bool displaying); + + int stopConditions; + int xTable; + int lastIndex; + + +}; + diff --git a/vm/filesystem.h b/vm/filesystem.h @@ -0,0 +1,62 @@ +// +// filesystem.h +// Smalltalk-80 +// +// Created by Dan Banay on 5/3/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#pragma once +#include <functional> +#include <cstdint> + +class IFileSystem +{ +public: + // File oriented operations + virtual int create_file(const char *name) = 0; + virtual int open_file(const char *name) = 0; + virtual int close_file(int file_handle) = 0; + + virtual int seek_to(int file_handle, int position) = 0; + virtual int tell(int file_handle) = 0; + virtual int read(int file_handle, char *buffer, int bytes) = 0; + virtual int write(int file_handle, const char *buffer, int bytes) = 0; + + + virtual bool truncate_to(int file_handle, int length) = 0; + virtual int file_size(int file_handle) = 0; + virtual bool file_flush(int file_handle) = 0; + + // Directory orientated operations + virtual void enumerate_files(const std::function <void (const char *) >& each) = 0; + + virtual bool rename_file(const char *old_name, const char *new_name) = 0; + virtual bool delete_file(const char* file_name) = 0; + + // Error handling + virtual const int last_error() = 0; + virtual const char *error_text(int code) = 0; +}; + + diff --git a/vm/hal.h b/vm/hal.h @@ -0,0 +1,79 @@ +// +// hal.h +// Smalltalk-80 +// +// Created by Dan Banay on 4/13/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#pragma once +#include <cstdint> + +class IHardwareAbstractionLayer +{ +public: + // Specify the semaphore to signal on input + virtual void set_input_semaphore(int semaphore) = 0; + + // The number of seconds since 00:00 in the morning of January 1, 1901 + virtual std::uint32_t get_smalltalk_epoch_time() = 0; + + // the number of milliseconds since the millisecond clock was + // last reset or rolled over (a 32-bit unsigned number) + virtual std::uint32_t get_msclock() = 0; + + // Schedule a semaphore to be signaled at a time. Only one outstanding + // request may be scheduled at anytime. When called any outstanding + // request will be replaced (or canceled if semaphore is 0). + // Will signal immediate if scheduled time has passed. + virtual void signal_at(int semaphore, std::uint32_t msClockTime) = 0; + + // Set the cursor image + // (a 16 word form) + virtual void set_cursor_image(std::uint16_t *image) = 0; + + // Set the mouse cursor location + virtual void set_cursor_location(int x, int y) = 0; + virtual void get_cursor_location(int *x, int *y) = 0; + virtual void set_link_cursor(bool link) = 0; + + // Set the display size + virtual bool set_display_size(int width, int height) = 0; + + // Notify that screen contents changed + virtual void display_changed(int x, int y, int width, int height) = 0; + + // Input queue + virtual bool next_input_word(std::uint16_t *word) = 0; + + // Report catastrophic failure + virtual void error(const char *message) = 0; + + // Lifetime + virtual void signal_quit() = 0; + virtual void exit_to_debugger() = 0; + + // Snapshot name + virtual const char *get_image_name() = 0; + virtual void set_image_name(const char *new_name) = 0; +}; diff --git a/vm/interpreter.cpp b/vm/interpreter.cpp @@ -0,0 +1,5502 @@ +// +// interpreter.cpp +// Smalltalk-80 +// +// Created by Dan Banay on 3/31/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#include <cstdint> +#include <cassert> +#include <cstdlib> +#include <cmath> +#include <limits> +#include "oops.h" +#include "interpreter.h" +#include "bitblt.h" + + +inline bool between_and(int value, int min, int max ) +{ + return value >= min && value <= max; +} + +Interpreter::Interpreter(IHardwareAbstractionLayer *halInterface, IFileSystem *fileSystemInterface) : hal(halInterface), fileSystem(fileSystemInterface), +#ifdef GC_MARK_SWEEP + memory(halInterface, this) +#else + memory(halInterface) +#endif +{ +} + +bool Interpreter::init() +{ + initializeMethodCache(); + semaphoreIndex = -1; + if (!memory.loadSnapshot(fileSystem, hal->get_image_name())) + return false; + /* + When Smalltalk is started up, the initial active context is found through the scheduler's active Process. + (G&R pg. 644) + */ + activeContext = firstContext(); + memory.increaseReferencesTo(activeContext); + fetchContextRegisters(); + checkLowMemory = false; + memoryIsLow = false; + lowSpaceSemaphore = NilPointer; + oopsLeftLimit = 0; + wordsLeftLimit = 0; + currentDisplay = 0; + currentCursor = 0; + currentDisplayWidth = 0; + currentDisplayHeight = 0; + return true; +} + +void Interpreter::error(const char *message) +{ + hal->error(message); +} + + +#ifdef GC_MARK_SWEEP +void Interpreter::prepareForCollection() +{ + storeContextRegisters(); + memory.addRoot(SmalltalkPointer); + memory.addRoot(activeContext); + if (newProcess != NilPointer) + { + memory.addRoot(newProcess); + } + +} +void Interpreter::collectionCompleted() +{ + memory.increaseReferencesTo(activeContext); + fetchContextRegisters(); + if (newProcessWaiting) + { + memory.increaseReferencesTo(newProcess); + } +} +#endif + +// primitiveAtEnd +void Interpreter::primitiveAtEnd() +{ +#ifndef IMPLEMENT_PRIMITIVE_AT_END + primitiveFail(); +#else + int stream; + int array; + int arrayClass; + int length; + int index; + int limit; + + /* "source" + stream <- self popStack. + array <- memory fetchPointer: StreamArrayIndex + ofObject: stream. + arrayClass <- memory fetchClassOf: array. + length <- self lengthOf: array. + index <- self fetchInteger: StreamIndexIndex + ofObject: stream. + limit <- self fetchInteger: StreamReadLimitIndex + ofObject: stream. "ERROR dbanay : was Stream" + self success: + (arrayClass=ClassArrayPointer) | (arrayClass=ClassStringPointer). + self success + ifTrue: [(index >= limit) | (index >= length) + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 1] + */ + stream = popStack(); + array = memory.fetchPointer_ofObject(StreamArrayIndex, stream); + arrayClass = memory.fetchClassOf(array); + length = lengthOf(array); + index = fetchInteger_ofObject(StreamIndexIndex, stream); + limit = fetchInteger_ofObject(StreamReadLimitIndex, stream); + success(arrayClass == ClassArrayPointer || arrayClass == ClassStringPointer); + if (success()) + { + if (index >= limit || index >= length) + push(TruePointer); + else + push(FalsePointer); + } + else + { + unPop(1); + } +#endif +} + + +// checkIndexableBoundsOf:in: +void Interpreter::checkIndexableBoundsOf_in(int index, int array) +{ + + /* "source" + "dbanay - this is totally wrong" + class <- memory fetchClassOf: array. + self success: index >= 1. + self success: index + (self fixedFieldsOf: class) <= (self lengthOf: array) + */ + /* "source corrected" + self success: index >= 1. + self success: index <= (self lengthOf: array) + */ + success(index >= 1); + success(index <= lengthOf(array)); +} + + +// primitiveNextPut +void Interpreter::primitiveNextPut() +{ +#ifndef IMPLEMENT_PRIMITIVE_NEXT_PUT + primitiveFail(); + +#else + int value; + int stream; + int index; + int limit; + int array; + int arrayClass; + int ascii; + + /* "source" + value <- self popStack. + stream <- self popStack. + array <- memory fetchPointer: StreamArrayIndex + ofObject: stream. + arrayClass <- memory fetchClassOf: array. + index <- self fetchInteger: StreamIndexIndex + ofObject: stream. + limit <- self fetchInteger: StreamWriteLimitIndex + ofObject: stream. + self success: index < limit. + self success: + (arrayClass=ClassArrayPointer) | (arrayClass=ClassStringPointer). + self checkIndexableBoundsOf: index + 1 + in: array. + self success + ifTrue: [index <- index + 1. + arrayClass = ClassArrayPointer + ifTrue: [self subscript: array + with: index + storing: value] + ifFalse: [ascii <- memory fetchPointer: CharacterValueIndex + ofObject: value. + self subscript: array + with: index + storing: ascii]]. + self success + ifTrue: [self storeInteger: StreamIndexIndex + ofObject: stream + withValue: index]. + self success + ifTrue: [self push: value] + ifFalse: [self unPop: 2] + */ + + + value = popStack(); + stream = popStack(); + array = memory.fetchPointer_ofObject(StreamArrayIndex, stream); + arrayClass = memory.fetchClassOf(array); + index = fetchInteger_ofObject(StreamIndexIndex, stream); + limit = fetchInteger_ofObject(StreamWriteLimitIndex,stream); + success(index < limit); + success(arrayClass==ClassArrayPointer || arrayClass==ClassStringPointer); + checkIndexableBoundsOf_in(index + 1, array); + if (success()) + { + index = index + 1; + if (arrayClass == ClassArrayPointer) + { + subscript_with_storing(array, index, value); + } + else + { + ascii = memory.fetchPointer_ofObject(CharacterValueIndex, value); + subscript_with_storing(array, index, ascii); + } + } + if (success()) + storeInteger_ofObject_withValue(StreamIndexIndex, stream, index); + if (success()) + push(value); + else + unPop(2); +#endif +} + + +// lengthOf: +int Interpreter::lengthOf(int array) +{ + /* "source" + (self isWords: (memory fetchClassOf: array)) + ifTrue: [^memory fetchWordLengthOf: array] + ifFalse: [^memory fetchByteLengthOf: array] + */ + + return isWords(memory.fetchClassOf(array)) + ? memory.fetchWordLengthOf(array) : + memory.fetchByteLengthOf(array); +} + + +// primitiveNext +void Interpreter::primitiveNext() +{ +#ifndef IMPLEMENT_PRIMITIVE_NEXT + primitiveFail(); + +#else + int stream; + int index; + int limit; + int array; + int arrayClass; + int result = 0; + int ascii; + + /* "source" + stream <- self popStack. + array <- memory fetchPointer: StreamArrayIndex + ofObject: stream. + arrayClass <- memory fetchClassOf: array. + index <- self fetchInteger: StreamIndexIndex + ofObject: stream. + limit <- self fetchInteger: StreamReadLimitIndex + ofObject: stream. + self success: index < limit. + self success: + (arrayClass=ClassArrayPointer) | (arrayClass=ClassStringPointer). + self checkIndexableBoundsOf: index + 1 + in: array. + self success + ifTrue: [index <- index + 1. + result <- self subscript: array + with: index]. + self success + ifTrue: [self storeInteger: StreamIndexIndex + ofObject: stream + withValue: index]. + self success + ifTrue: [arrayClass = ClassArrayPointer + ifTrue: [self push: result] + ifFalse: [ascii <- memory integerValueOf: result. + self push: (memory fetchPointer: ascii + ofObject: CharacterTablePointer)]] + ifFalse: [self unPop: 1] + */ + stream = popStack(); + array = memory.fetchPointer_ofObject(StreamArrayIndex, stream); + arrayClass = memory.fetchClassOf(array); + index = fetchInteger_ofObject(StreamIndexIndex, stream); + limit = fetchInteger_ofObject(StreamReadLimitIndex, stream); + success(index < limit); + success(arrayClass == ClassArrayPointer || arrayClass == ClassStringPointer); + checkIndexableBoundsOf_in(index + 1, array); + if (success()) + { + index = index + 1; + result = subscript_with(array, index); + } + if (success()) + { + storeInteger_ofObject_withValue(StreamIndexIndex, stream, index); + } + if (success()) + { + if (arrayClass == ClassArrayPointer) + { + push(result); + } + else + { + ascii = memory.integerValueOf(result); + push(memory.fetchPointer_ofObject(ascii, CharacterTablePointer)); + } + } + else + unPop(1); +#endif +} + + +// dispatchSubscriptAndStreamPrimitives +void Interpreter::dispatchSubscriptAndStreamPrimitives() +{ + /* "source" + primitiveIndex = 60 ifTrue: [^self primitiveAt]. + primitiveIndex = 61 ifTrue: [^self primitiveAtPut]. + primitiveIndex = 62 ifTrue: [^self primitiveSize]. + primitiveIndex = 63 ifTrue: [^self primitiveStringAt]. + primitiveIndex = 64 ifTrue: [^self primitiveStringAtPut]. + primitiveIndex = 65 ifTrue: [^self primitiveNext]. + primitiveIndex = 66 ifTrue: [^self primitiveNextPut]. + primitiveIndex = 67 ifTrue: [^self primitiveAtEnd] + */ + switch (primitiveIndex) + { + case 60: primitiveAt(); break; + case 61: primitiveAtPut(); break; + case 62: primitiveSize(); break; + case 63: primitiveStringAt(); break; + case 64: primitiveStringAtPut(); break; + case 65: primitiveNext(); break; + case 66: primitiveNextPut(); break; + case 67: primitiveAtEnd(); break; + } +} + + +// primitiveStringAt +void Interpreter::primitiveStringAt() +{ + int index; + int array; + int ascii; + int character = 0; + + /* "source" + index <- self positive16BitValueOf: self popStack. + array <- self popStack. + self checkIndexableBoundsOf: index + in: array. + self success + ifTrue: [ascii <- memory integerValueOf: (self subscript: array + with: index). + character <- memory fetchPointer: ascii + ofObject: CharacterTablePointer]. + self success + ifTrue: [self push: character] + ifFalse: [self unPop: 2] + */ + + index = positive16BitValueOf(popStack()); + array = popStack(); + checkIndexableBoundsOf_in(index, array); + if (success()) + { + ascii = memory.integerValueOf(subscript_with(array, index)); + character = memory.fetchPointer_ofObject(ascii, CharacterTablePointer); + } + + if (success()) + { + push(character); + } + else + unPop(2); +} + + +// primitiveAt +void Interpreter::primitiveAt() +{ + int index; + int array; + int arrayClass; + int result = 0; + + /* "source" + index <- self positive16BitValueOf: self popStack. + array <- self popStack. + arrayClass <- memory fetchClassOf: array. + self checkIndexableBoundsOf: index + in: array. + self success + ifTrue: [index <- index + (self fixedFieldsOf: arrayClass). + result <- self subscript: array + with: index]. + self success + ifTrue: [self push: result] + ifFalse: [self unPop: 2] + */ + index = positive16BitValueOf(popStack()); + array = popStack(); + arrayClass = memory.fetchClassOf(array); + checkIndexableBoundsOf_in(index, array); + + if (success()) + { + index = index + fixedFieldsOf(arrayClass); + result = subscript_with(array, index); + } + + if (success()) + { + push(result); + } + else + unPop(2); +} + + +// primitiveSize +void Interpreter::primitiveSize() +{ + int array; + int cls; + int length = 0; + + /* "source" + array <- self popStack. + "dbanay ERROR make sure it is a pointer!" + self success: memory isIntegerObject: array. + self success ifTrue: [ class <- memory fetchClassOf: array. + length <- self positive16BitIntegerFor: + (self lengthOf: array) - (self fixedFieldsOf: class)]. + self success + ifTrue: [self push: length] + ifFalse: [self unPop: 1] + */ + + array = popStack(); + success(!memory.isIntegerObject(array)); + if (success()) + { + cls = memory.fetchClassOf(array); + length = positive16BitIntegerFor(lengthOf(array) - fixedFieldsOf(cls)); + } + if (success()) + push(length); + else + unPop(1); +} + + +// primitiveStringAtPut +void Interpreter::primitiveStringAtPut() +{ + int index; + int array; + int ascii; + int character; + + /* "source" + character <- self popStack. + index <- self positive16BitValueOf: self popStack. + array <- self popStack. + self checkIndexableBoundsOf: index + in: array. + self success: (memory fetchClassOf: character) = ClassCharacterPointer. + self success + ifTrue: [ascii <- memory fetchPointer: CharacterValueIndex + ofObject: character. + self subscript: array + with: index + storing: ascii]. + self success + ifTrue: [self push: character] + ifFalse: [self unPop: 2] "dbanay ERROR should be 3" + */ + character = popStack(); + index = positive16BitValueOf(popStack()); + array = popStack(); + checkIndexableBoundsOf_in(index, array); + success(memory.fetchClassOf(character) == ClassCharacterPointer); + if (success()) + { + ascii = memory.fetchPointer_ofObject(CharacterValueIndex, character); + subscript_with_storing(array, index, ascii); + } + if (success()) + push(character); + else + unPop(3); +} + + +// subscript:with: +int Interpreter::subscript_with(int array, int index) +{ + int cls; + int value; + + /* "source" + class <- memory fetchClassOf: array. + (self isWords: class) + ifTrue: [(self isPointers: class) + ifTrue: [^memory fetchPointer: index - 1 + ofObject: array] + ifFalse: [value <- memory fetchWord: index - 1 + ofObject: array. + ^self positive16BitIntegerFor: value]] + ifFalse: [value <- memory fetchByte: index - 1 + ofObject: array. + ^memory integerObjectOf: value] + */ + cls = memory.fetchClassOf(array); + if (isWords(cls)) + { + if (isPointers(cls)) + { + return memory.fetchPointer_ofObject(index - 1, array); + } + else + { + value = memory.fetchWord_ofObject(index - 1, array); + return positive16BitIntegerFor(value); + } + } + + value = memory.fetchByte_ofObject(index - 1, array); + return memory.integerObjectOf(value); +} + + +// primitiveAtPut +void Interpreter::primitiveAtPut() +{ + int array; + int index; + int arrayClass; + int value; + + /* "source" + value <- self popStack. + index <- self positive16BitValueOf: self popStack. + array <- self popStack. + arrayClass <- memory fetchClassOf: array. + self checkIndexableBoundsOf: index. + in: array. + self success + ifTrue: [index <- index + (self fixedFieldsOf: arrayClass). + self subscript: array + with: index + storing: value]. + self success + ifTrue: [self push: value] + ifFalse: [self unPop: 3] + */ + value = popStack(); + index = positive16BitValueOf(popStack()); + array = popStack(); + arrayClass = memory.fetchClassOf(array); + checkIndexableBoundsOf_in(index, array); + if (success()) + { + index = index + fixedFieldsOf(arrayClass); + subscript_with_storing(array, index, value); + } + + if (success()) + push(value); + else + unPop(3); +} + + +// subscript:with:storing: +void Interpreter::subscript_with_storing(int array, int index, int value) +{ + int cls; + + /* "source" + class <- memory fetchClassOf: array. + (self isWords: class) + ifTrue: [(self isPointers: class) + ifTrue: [^memory storePointer: index - 1 + ofObject: array + withValue: value] + ifFalse: [self success: (memory isIntegerObject: value). + self success: ifTrue: + [^memory + storeWord: index-1 + ofObject: array + withValue: (self positive16BitValueOf: + value)]]] + ifFalse: [self success: (memory isIntegerObject: value). "ERROR: dbanay check for large pos as well" + self success ifTrue: + [^memory storeByte: index - 1 + ofObject: array + withValue: (self lowByteOf: + (memory integerValueOf: + value))]] + */ + + cls = memory.fetchClassOf(array); + if (isWords(cls)) + { + if (isPointers(cls)) + { + memory.storePointer_ofObject_withValue(index - 1, array, value); + } + else + { + success(memory.isIntegerObject(value) || memory.fetchClassOf(value) == ClassLargePositiveIntegerPointer); + if (success()) + { + memory.storeWord_ofObject_withValue(index - 1, array, positive16BitValueOf(value)); + } + } + } + else + { + success(memory.isIntegerObject(value)); + if (success()) + { + memory.storeByte_ofObject_withValue(index - 1, array, lowByteOf(memory.integerValueOf(value))); + } + } +} + + +/* + The instruction pointer stored in a context is a one-relative index to the method's fields because subscripting in Smalltalk (i.e., the at: message) takes one-relative indices. The memory, however, uses zero-relative indices; so the fetchContextRegisters routine subtracts one to convert it to a memory index and the storeContextRegisters routine adds the one back in. +*/ +// storeContextRegisters +void Interpreter::storeContextRegisters() +{ + /* "source" + self storeInstructionPointerValue: instructionPointer + 1 + inContext: activeContext. + self storeStackPointerValue: stackPointer - TempFrameStart + 1 + inContext: activeContext + */ + + storeInstructionPointerValue_inContext(instructionPointer + 1, activeContext); + storeStackPointerValue_inContext(stackPointer - TempFrameStart + 1, activeContext); +} + +// isBlockContext: +bool Interpreter::isBlockContext(int contextPointer) +{ + int methodOrArguments; + + /* "source" + methodOrArguments <- memory fetchPointer: MethodIndex + ofObject: contextPointer. + ^memory isIntegerObject: methodOrArguments + */ + methodOrArguments = memory.fetchPointer_ofObject(MethodIndex, + contextPointer); + return memory.isIntegerObject(methodOrArguments); + +} + +// newActiveContext: +void Interpreter::newActiveContext(int aContext) +{ + /* "source" + self storeContextRegisters. + memory decreaseReferencesTo: activeContext. + activeContext <- aContext. + memory increaseReferencesTo: activeContext. + self fetchContextRegisters + */ + + storeContextRegisters(); + memory.decreaseReferencesTo(activeContext); + activeContext = aContext; + memory.increaseReferencesTo(activeContext); + fetchContextRegisters(); +} + +/* + The instruction pointer stored in a context is a one-relative index to the method's fields because subscripting in Smalltalk (i.e., the at: message)takes one-relative indices. The memory, however, uses zero-relative indices; so the fetchContextRegisters routine subtracts one to convert it to a memory index and the storeContextRegisters routine adds the one back in. +*/ + +// fetchContextRegisters +void Interpreter::fetchContextRegisters() +{ + /* "source" + (self isBlockContext: activeContext) + ifTrue: [homeContext <- memory fetchPointer: HomeIndex + ofObject: activeContext] + ifFalse: [homeContext <- activeContext]. + receiver <- memory fetchPointer: ReceiverIndex + ofObject: homeContext. + method <- memory fetchPointer: MethodIndex + ofObject: homeContext. + instructionPointer <- (self instructionPointerOfContext: activeContext) - 1. + stackPointer <- + (self stackPointerOfContext: activeContext) + TempFrameStart - 1 + */ + + if (isBlockContext(activeContext)) + homeContext = memory.fetchPointer_ofObject(HomeIndex, activeContext); + else + homeContext = activeContext; + receiver = memory.fetchPointer_ofObject(ReceiverIndex, homeContext); + method = memory.fetchPointer_ofObject(MethodIndex, homeContext); + instructionPointer = instructionPointerOfContext(activeContext) - 1; + stackPointer = stackPointerOfContext(activeContext) + TempFrameStart - 1; +} + +// dispatchInputOutputPrimitives +void Interpreter::dispatchInputOutputPrimitives() +{ + /* "source" + primitiveIndex = 90 ifTrue: [^self primitiveMousePoint]. + primitiveIndex = 91 ifTrue: [^self primitiveCursorLocPut]. + primitiveIndex = 92 ifTrue: [^self primitiveCursorLink]. + primitiveIndex = 93 ifTrue: [^self primitiveInputSemaphore]. + primitiveIndex = 94 ifTrue: [^self primitiveSampleInterval]. + primitiveIndex = 95 ifTrue: [^self primitiveInputWord]. + primitiveIndex = 96 ifTrue: [^self primitiveCopyBits]. + primitiveIndex = 97 ifTrue: [^self primitiveSnapshot]. + primitiveIndex = 98 ifTrue: [^self primitiveTimeWordsInto]. + primitiveIndex = 99 ifTrue: [^self primitiveTickWordsInto]. + primitiveIndex = 100 ifTrue: [^self primitiveSignalAtTick]. + primitiveIndex = 101 ifTrue: [^self primitiveBeCursor]. + primitiveIndex = 102 ifTrue: [^self primitiveBeDisplay]. + primitiveIndex = 103 ifTrue: [^self primitiveScanCharacters]. + primitiveIndex = 104 ifTrue: [^self primitiveDrawLoop]. + primitiveIndex = 105 ifTrue: [^self primitiveStringReplace] + */ + + switch (primitiveIndex) + { + case 90: primitiveMousePoint(); break; + case 91: primitiveCursorLocPut(); break; + case 92: primitiveCursorLink(); break; + case 93: primitiveInputSemaphore(); break; + case 94: primitiveSampleInterval(); break; + case 95: primitiveInputWord(); break; + case 96: primitiveCopyBits(); break; + case 97: primitiveSnapshot(); break; + case 98: primitiveTimeWordsInto(); break; + case 99: primitiveTickWordsInto(); break; + case 100: primitiveSignalAtTick(); break; + case 101: primitiveBeCursor(); break; + case 102: primitiveBeDisplay(); break; + case 103: primitiveScanCharacters(); break; + case 104: primitiveDrawLoop(); break; + case 105: primitiveStringReplace(); break; + } +} + +void Interpreter::primitiveMousePoint() +{ + /* + Poll the mouse to find out its position. Return a Point. Fail if event-driven + tracking is used instead of polling. + */ + int mouseX, mouseY; + + pop(1); // remove receiver + hal->get_cursor_location(&mouseX, &mouseY); + int pointResult = memory.instantiateClass_withPointers(ClassPointPointer, ClassPointSize); + storeInteger_ofObject_withValue(XIndex, pointResult, mouseX); + storeInteger_ofObject_withValue(YIndex, pointResult, mouseY); + push(pointResult); +} + +void Interpreter::primitiveCursorLocPut() +{ + /* + Move the cursor to the screen location specified by the argument. Fail if + the argument is not a Point. + */ + int point = popStack(); + success(memory.fetchClassOf(point) == ClassPointPointer); + if (success()) + { + int x = fetchInteger_ofObject(XIndex, point); + int y = fetchInteger_ofObject(YIndex, point); + hal->set_cursor_location(x, y); + } + else + unPop(1); +} + +void Interpreter::primitiveCursorLink() +{ + /* + Cause the cursor to track the pointing device location if the argument is true. + Decouple the cursor from the pointing device if the argument is false. + */ + int flag = popStack(); + hal->set_link_cursor(flag == TruePointer); +} + +void Interpreter::primitiveInputSemaphore() +{ + /* + Install the argument (a Semaphore) as the object to be signalled whenever + an input event occurs. The semaphore will be signaled once for every + word placed in the input buffer by an I/O device. Fail if the argument is + neither a Semaphore nor nil. + */ + int semaphore = popStack(); + success(semaphore == NilPointer || memory.fetchClassOf(semaphore) == ClassSemaphorePointer); + if (success()) + hal->set_input_semaphore(semaphore); + else + unPop(1); +} + +void Interpreter::primitiveSampleInterval() +{ + /* + Set the minimum time span between event driven mouse position + samples. The argument is a number of milliseconds. Fail if the argument + is not a SmallInteger. + */ + //Not actually used! + primitiveFail(); + +} + +void Interpreter::primitiveInputWord() +{ + /* + Return the next word from the input buffer and remove the word from the + buffer. This message should be sent just after the input semaphore + finished a wait (was sent a signal by an I/O device). Fail if the input + buffer is empty. + */ + + std::uint16_t word; + bool result = hal->next_input_word(&word); + if (result) + { + pop(1); // remove receiver + push(positive16BitIntegerFor(word)); + } + else + { + primitiveFail(); + } +} + + +// Return a oop to the display bitmap +// Reference may become invalid on the next cycle of the interpreter... +int Interpreter::getDisplayBits(int width, int height) +{ + // Return oop of display bits object + // sanity checking display width/height + if (currentDisplay == 0) return 0; // No display yet + int displayBits = memory.fetchPointer_ofObject(BitsInForm, currentDisplay); + int computedSize = currentDisplayHeight * ((currentDisplayWidth + 15)/16); + int actualSize = memory.fetchWordLengthOf(displayBits); + // The sizes do not match... + // Smalltalk shrinks the display bitmap to a height of 100 behind our back + // when saving for example. + if (computedSize != actualSize) + return 0; + return displayBits; // ok then... +} + +void Interpreter::updateDisplay(int destForm, int updatedX, int updatedY, int updatedWidth, int updatedHeight) +{ + int width = fetchInteger_ofObject(WidthInForm, currentDisplay); + int height = fetchInteger_ofObject(HeightInForm, currentDisplay); + + if (currentDisplayWidth != width || currentDisplayHeight != height) + { + // Display bits changed... possibly due to screen size change... + if (height <= 100) + return; // See note in primitiveBeDisplay... + hal->set_display_size(width, height); + currentDisplayWidth = width; + currentDisplayHeight = height; + } + + if (updatedWidth > 0 && updatedHeight > 0) + hal->display_changed(updatedX, updatedY, updatedWidth, updatedHeight); +} + +void Interpreter::primitiveCopyBits() +{ + + int bitBltPointer = stackTop(); + int destForm = memory.fetchPointer_ofObject(DestFormIndex, bitBltPointer); + int sourceForm = memory.fetchPointer_ofObject(SourceFormIndex, bitBltPointer); + int destX = fetchInteger_ofObject(DestXIndex, bitBltPointer); + int destY = fetchInteger_ofObject(DestYIndex, bitBltPointer); + int clipX = fetchInteger_ofObject(ClipXIndex, bitBltPointer); + int clipY = fetchInteger_ofObject(ClipYIndex, bitBltPointer); + int clipWidth = fetchInteger_ofObject(ClipWidthIndex, bitBltPointer); + int clipHeight = fetchInteger_ofObject(ClipHeightIndex, bitBltPointer); + int sourceX = fetchInteger_ofObject(SourceXIndex, bitBltPointer); + int sourceY = fetchInteger_ofObject(SourceYIndex, bitBltPointer); + int width = fetchInteger_ofObject(WidthIndex, bitBltPointer); + int height = fetchInteger_ofObject(HeightIndex, bitBltPointer); + int rule = fetchInteger_ofObject(CombinationRuleIndex, bitBltPointer); + + success(between_and(rule, 0, 15)); + if (success()) + { + BitBlt bitBlt(memory, + destForm, + sourceForm, + memory.fetchPointer_ofObject(HalftoneFormIndex, bitBltPointer), + rule, + destX, + destY, + width, + height, + sourceX, + sourceY, + clipX, + clipY, + clipWidth, + clipHeight); + + int updatedX, updatedY, updatedWidth, updatedHeight; + bitBlt.copyBits(); + if (destForm == currentDisplay) + { + bitBlt.getUpdatedBounds(&updatedX, &updatedY, &updatedWidth, &updatedHeight); + if (updatedWidth > 0 && updatedHeight > 0) + updateDisplay(destForm, updatedX, updatedY, updatedWidth, updatedHeight); + + } + } +} + +void Interpreter::primitiveSnapshot() +{ + /* + The primitiveSnapshot routine writes the current state of the + object memory on a file of the same format as the Smalltalk-80 release file. + This file can be resumed in exactly the same way that the release file was + originally started. Note that the pointer of the active context at + the time of the primitive call must be stored in the active Process on the file. + (G&R) pg 651. + */ + + int activeProcess = memory.fetchPointer_ofObject(ActiveProcessIndex, schedulerPointer()); + memory.storePointer_ofObject_withValue(SuspendedContextIndex, activeProcess, activeContext); + storeContextRegisters(); + + memory.garbageCollect(); + memory.saveSnapshot(fileSystem, hal->get_image_name()); + + /* This is poorly documented by the Bluebook. There is an actual return value that is important. + see snapshotAs:thenQuit: in the Smalltalk sources. When the system resumes a snapshot the interpreter will be + back at the point of the save, and 'self' will be at the top of the stack. But after saving we + return nil to tell the caller that we just wrote a snapshot. This is how we can distinguish + the case were we save a session (to be continued potentially followed by an exit) or we are + resuming a saved session. + */ + pop(1); // DO NOT POP BEFORE WRITING IMAGE. + push(NilPointer); // return of nil signals we just saved +} + +void Interpreter::primitiveTimeWordsInto() +{ + /* + The argument is a byte indexable object of length at least four. Store + into the first four bytes of the argument the number of seconds since + 00:00 in the morning of January 1, 1901 (a 32-bit unsigned number). + The low-order 8-bits are stored in the byte indexed by 1 and the high- + order 8-bits in the byte indexed 4. + */ + std::uint32_t time = hal->get_smalltalk_epoch_time(); + int byteIndexObject = popStack(); + memory.storeByte_ofObject_withValue(0, byteIndexObject, time & 0xff); + memory.storeByte_ofObject_withValue(1, byteIndexObject, (time >> 8) & 0xff); + memory.storeByte_ofObject_withValue(2, byteIndexObject, (time >> 16) & 0xff); + memory.storeByte_ofObject_withValue(3, byteIndexObject, (time >> 24) & 0xff); +} + +void Interpreter::primitiveTickWordsInto() +{ + /* + The argument is a byte indexable object of length at least four (a + LargePositiveInteger). Store into the first four bytes of the argument the + number of milliseconds since the millisecond clock was last reset or rolled + over (a 32-bit unsigned number). The low-order 8-bits are stored in + the byte indexed by 1 and the high-order 8-bits in the byte indexed 4. + */ + std::uint32_t time = hal->get_msclock(); + int byteIndexObject = popStack(); + memory.storeByte_ofObject_withValue(0, byteIndexObject, time & 0xff); + memory.storeByte_ofObject_withValue(1, byteIndexObject, (time >> 8) & 0xff); + memory.storeByte_ofObject_withValue(2, byteIndexObject, (time >> 16) & 0xff); + memory.storeByte_ofObject_withValue(3, byteIndexObject, (time >> 24) & 0xff); +} + +void Interpreter::primitiveSignalAtTick() +{ + /* + + + The primitiveSignalAtTick routine is associated with the signal:atTick: + messages in ProcessorScheduler. his message takes a Semaphore as the first + argument and a byte indexable object of at least four bytes as the second + argument. The first four bytes of the second argument are interpreted as an + unsigned 32-bit integer of the type stored by the primitiveTickWordsInto + routine. The interpreter should signal the Semaphore argument when the + millisecond clock reaches the value specified by the second argument. + If the specified time has passed,the Semaphore is signaled immediately. + This primitive signals the last Semaphore to be passed to it. If a new + call is made on it before the last timer value has been reached the last + Semaphore will not be signaled. If the first argument is not a Semaphore + any currently waiting Semaphore will be forgotten. (pg. 652 G&R) + + Signal the semaphore when the millisecond clock reaches the value of + the second argument. The second argument is a byte indexable object at + least four bytes long (a 32-bit unsigned number with the low order + 8-bits stored in the byte with the lowest index). Fail if the first + argument is neither a Semaphore nor nil. + + + */ + + int timePointer = popStack(); + int semaphore = popStack(); + + success(semaphore == NilPointer || memory.fetchClassOf(semaphore) == ClassSemaphorePointer); + if (success()) + { + if (semaphore == NilPointer) + semaphore = 0; // Tells HAL to cancel outstanding request + + std::uint32_t time = + memory.fetchByte_ofObject(0, timePointer) | + (memory.fetchByte_ofObject(1, timePointer) << 8) | + (memory.fetchByte_ofObject(2, timePointer) << 16) | + (memory.fetchByte_ofObject(3, timePointer) << 24); + + hal->signal_at(semaphore, time); + } + else + unPop(2); +} + +void Interpreter::primitiveBeCursor() +{ + /* + Tell the interpreter to use the receiver as the current cursor image. Fail if the + receiver does not match the size expected by the hardware. + */ + if (currentCursor != stackTop()) + { + currentCursor = stackTop(); + int cursorBitmap = memory.fetchPointer_ofObject(BitsInForm, currentCursor); + std::uint16_t bits[16]; + for(int i = 0; i < 16; i++) + { + bits[i] = memory.fetchWord_ofObject(i, cursorBitmap); + } + hal->set_cursor_image(bits); + } + + } + +void Interpreter::primitiveBeDisplay() +{ + /* + Tell the interpreter to use the receiver as the current display image. Fail if the + form is too wide to fit on the physical display + */ + int newDisplay = stackTop(); + if (currentDisplay != newDisplay) + { + int width = fetchInteger_ofObject(WidthInForm, newDisplay); + int height = fetchInteger_ofObject(HeightInForm, newDisplay); + // Intersting fact: In order to save space when writing the object image + // Smalltalk resizes the display to the current width x 100 just before saving. + // When the system resumes, it will be resized to the last actual size. + // Here we ignore the change to the height of 100. + if (height > 100) + { + if (!hal->set_display_size(width, height)) + { + primitiveFail(); + } + currentDisplay = newDisplay; + currentDisplayWidth = width; + currentDisplayHeight = height; + } + else + currentDisplay = 0; + } +} + +// scanCharactersFrom: startIndex to: stopIndex in: sourceString rightX: rightX stopConditions: stops displaying: display + +void Interpreter::primitiveScanCharacters() +{ +#ifdef IMPLEMENT_PRIMITIVE_SCANCHARS + bool displaying = popStack() == TruePointer; + int stops = popStack(); + int rightX = popInteger(); + int sourceString = popStack(); + int stopIndex = popInteger(); + int startIndex = popInteger(); + int scannerPointer = popStack(); + int destForm = memory.fetchPointer_ofObject(DestFormIndex, scannerPointer); + int sourceForm = memory.fetchPointer_ofObject(SourceFormIndex, scannerPointer); + int destX = fetchInteger_ofObject(DestXIndex, scannerPointer); + int destY; + int clipX; + int clipY; + int clipWidth; + int clipHeight; + int sourceX = 0; // uninitialized... assigned during scanning + int sourceY; + int rule; + int width = 0; + int height; + int xTable = memory.fetchPointer_ofObject(XTableIndexIndex, scannerPointer); + int lastIndex = fetchInteger_ofObject(LastIndexIndex, scannerPointer); + int stopConditions = memory.fetchPointer_ofObject(StopConditionsIndex, scannerPointer); + + // If not displaying, some of the fields are nil, so only + // fetch integers that are actually used... + if (displaying) + { + destY = fetchInteger_ofObject(DestYIndex, scannerPointer); + clipX = fetchInteger_ofObject(ClipXIndex, scannerPointer); + clipY = fetchInteger_ofObject(ClipYIndex, scannerPointer); + clipWidth = fetchInteger_ofObject(ClipWidthIndex, scannerPointer); + clipHeight = fetchInteger_ofObject(ClipHeightIndex, scannerPointer); + sourceY = fetchInteger_ofObject(SourceYIndex, scannerPointer); + rule = fetchInteger_ofObject(CombinationRuleIndex, scannerPointer); + height = fetchInteger_ofObject(HeightIndex, scannerPointer); + } + else + { + destY = 0; + clipX = 0; + clipY = 0; + clipWidth = 0; + clipHeight = 0; + sourceY = 0; + rule = 0; + height = 0; + } + + if (success()) + { + + CharacterScanner scanner(memory, + destForm, + sourceForm, + memory.fetchPointer_ofObject(HalftoneFormIndex, scannerPointer), + rule, + destX, + destY, + width, + height, + sourceX, + sourceY, + clipX, + clipY, + clipWidth, + clipHeight, + xTable, + lastIndex, + stopConditions + ); + + + int result = scanner.scanCharactersFrom_to_in_rightX_stopConditions_displaying(startIndex, stopIndex, sourceString, rightX, stops, displaying); + /* + Need to pull out the following modified values and store them back into the scanner: + destX, width, sourceX in BitBlt fields + lastIndex in CharacterScanner + */ + + storeInteger_ofObject_withValue(DestXIndex, scannerPointer, scanner.updateDestX()); + storeInteger_ofObject_withValue(WidthIndex, scannerPointer, scanner.updatedWidth()); + storeInteger_ofObject_withValue(SourceXIndex, scannerPointer, scanner.updatedSourceX()); + storeInteger_ofObject_withValue(LastIndexIndex, scannerPointer, scanner.updatedLastIndex()); + + if (destForm == currentDisplay && displaying) + { + updateDisplay(destForm, clipX, clipY, clipWidth, clipHeight); + } + push(result); + } + else + { + unPop(7); + } +#else + primitiveFail(); +#endif + +} + +void Interpreter::primitiveDrawLoop() +{ + // optional + primitiveFail(); +} + +void Interpreter::primitiveStringReplace() +{ + // optional + primitiveFail(); + +} + +// lookupMethodInDictionary: +bool Interpreter::lookupMethodInDictionary(int dictionary) +{ + int length; + int index; + int mask; + bool wrapAround; + int nextSelector; + int methodArray; + + /* "source" + length <- memory fetchWordLengthOf: dictionary. + mask <- length - SelectorStart - 1. + index <- (mask bitAnd: (self hash: messageSelector)) + SelectorStart. + wrapAround <- false. + [true] whileTrue: + [nextSelector <- memory fetchPointer: index + ofObject: dictionary. + nextSelector=NilPointer ifTrue: [^false]. + nextSelector=messageSelector + ifTrue: [methodArray <- memory fetchPointer: MethodArrayIndex + ofObject: dictionary. + newMethod <- memory fetchPointer: index - SelectorStart + ofObject: methodArray. + primitiveIndex <- self primitiveIndexOf: newMethod. + ^true]. + index <- index + 1. + index = length + ifTrue: [wrapAround ifTrue: [^false]. + wrapAround <- true. + index <- SelectorStart]] + */ + length = memory.fetchWordLengthOf(dictionary); + mask = length - SelectorStart - 1; + index = (mask & hash(messageSelector)) + SelectorStart; + wrapAround = false; + for(;;) + { + nextSelector = memory.fetchPointer_ofObject(index, dictionary); + if (nextSelector == NilPointer) return false; + if (nextSelector == messageSelector) + { + methodArray = memory.fetchPointer_ofObject(MethodArrayIndex, dictionary); + newMethod = memory.fetchPointer_ofObject(index - SelectorStart, methodArray); + primitiveIndex = primitiveIndexOf(newMethod); + return true; + } + index = index + 1; + if (index == length) + { + if (wrapAround) return false; + wrapAround = true; + index = SelectorStart; + } + } +} + +// createActualMessage +void Interpreter::createActualMessage() +{ + int argumentArray; + int message; + + /* "source" + argumentArray <- memory instantiateClass: ClassArrayPointer + withPointers: argumentCount. + "ERROR: messageSize misspelled, self inserted" + message <- memory instantiateClass: ClassMessagePointer + withPointers: MessageSize. + memory storePointer: MessageSelectorIndex + ofObject: message + withValue: messageSelector. + memory storePointer: MessageArgumentsIndex + ofObject: message + withValue: argumentArray. + self transfer: argumentCount + "ERROR in selector in next line and next but one after" + fromIndex: stackPointer - (argumentCount - 1) + ofObject: activeContext + toIndex: 0 + ofObject: argumentArray. + self pop: argumentCount. + self push: message. + argumentCount <- 1 + */ + + argumentArray = memory.instantiateClass_withPointers(ClassArrayPointer, argumentCount); + message = memory.instantiateClass_withPointers(ClassMessagePointer, MessageSize); + memory.storePointer_ofObject_withValue(MessageSelectorIndex, message, messageSelector); + memory.storePointer_ofObject_withValue(MessageArgumentsIndex, message, argumentArray); + transfer_fromIndex_ofObject_toIndex_ofObject(argumentCount, + stackPointer - (argumentCount - 1), + activeContext, + 0, + argumentArray); + + pop(argumentCount); + push(message); + argumentCount = 1; +} + + +// lookupMethodInClass: +bool Interpreter::lookupMethodInClass(int cls) +{ + int currentClass; + int dictionary; + + /* "source" + currentClass <- class. + [currentClass~=NilPointer] whileTrue: + [dictionary <- memory fetchPointer: MessageDictionaryIndex + ofObject: currentClass. + (self lookupMethodInDictionary: dictionary) + ifTrue: [^true]. + currentClass <- self superclassOf: currentClass]. + messageSelector = DoesNotUnderstandSelector. + ifTrue: [self error: 'Recursive not understood error encountered']. + self createActualMessage. + messageSelector <- DoesNotUnderstandSelector. + ^self lookupMethodInClass: class + */ + + currentClass = cls; + while (currentClass != NilPointer) + { + dictionary = memory.fetchPointer_ofObject(MessageDictionaryIndex, currentClass); + if (lookupMethodInDictionary(dictionary)) return true; + currentClass = superclassOf(currentClass); + } + if (messageSelector == DoesNotUnderstandSelector) + error("Recursive not understood error encountered'"); + createActualMessage(); + messageSelector = DoesNotUnderstandSelector; + return lookupMethodInClass(cls); +} + + +// returnBytecode +void Interpreter::returnBytecode() +{ + /* "source" + currentBytecode = 120 + ifTrue: [^self returnValue: receiver + to: self sender]. + currentBytecode = 121 + ifTrue: [^self returnValue: TruePointer + to: self sender]. + currentBytecode = 122 + ifTrue: [^self returnValue: FalsePointer + to: self sender]. + currentBytecode = 123 + ifTrue: [^self returnValue: NilPointer + to: self sender]. + currentBytecode = 124 + ifTrue: [^self returnValue: self popStack + to: self sender]. + currentBytecode = 125 + ifTrue: [^self returnValue: self popStack + to: self caller] + */ + switch (currentBytecode) + { + case 120: returnValue_to(receiver, sender()); break; + case 121: returnValue_to(TruePointer, sender()); break; + case 122: returnValue_to(FalsePointer, sender()); break; + case 123: returnValue_to(NilPointer, sender()); break; + case 124: returnValue_to(popStack(), sender()); break; + case 125: returnValue_to(popStack(), caller()); break; + } +} + + +// nilContextFields +void Interpreter::nilContextFields() +{ + /* "source" + memory storePointer: SenderIndex + ofObject: activeContext + withValue: NilPointer. + memory storePointer: InstructionPointerIndex + ofObject: activeContext + withValue: NilPointer + */ + + memory.storePointer_ofObject_withValue(SenderIndex, activeContext, NilPointer); + memory.storePointer_ofObject_withValue(InstructionPointerIndex, activeContext, NilPointer); + +} + +// returnToActiveContext: +void Interpreter::returnToActiveContext(int aContext) +{ + /* "source" + memory increaseReferencesTo: aContext. + self nilContextFields. + memory decreaseReferencesTo: activeContext. + activeContext <- aContext. + self fetchContextRegisters + */ + + memory.increaseReferencesTo(aContext); + nilContextFields(); + memory.decreaseReferencesTo(activeContext); + activeContext = aContext; + fetchContextRegisters(); +} + + +// returnValue:to: +void Interpreter::returnValue_to(int resultPointer, int contextPointer) +{ + int sendersIP; + + /* "source" + contextPointer = NilPointer + ifTrue: [self push: activeContext. + self push: resultPointer. + ^self sendSelector: CannotReturnSelector + argumentCount: 1]. + sendersIP <- memory fetchPointer: InstructionPointerIndex + ofObject: contextPointer. + sendersIP = NilPointer + ifTrue: [self push: activeContext. + self push: resultPointer. + ^self sendSelector: CannotReturnSelector + argumentCount: 1]. + memory increaseReferencesTo: resultPointer. + self returnToActiveContext: contextPointer. + self push: resultPointer. + memory decreaseReferencesTo: resultPointer + */ + if (contextPointer == NilPointer) + { + push(activeContext); + push(resultPointer); + sendSelector_argumentCount(CannotReturnSelector, 1); + return; + } + sendersIP = memory.fetchPointer_ofObject(InstructionPointerIndex, contextPointer); + if (sendersIP == NilPointer) + { + push(activeContext); + push(resultPointer); + sendSelector_argumentCount(CannotReturnSelector, 1); + return; + } + memory.increaseReferencesTo(resultPointer); + returnToActiveContext(contextPointer); + push(resultPointer); + memory.decreaseReferencesTo(resultPointer); +} + + +// synchronousSignal: +void Interpreter::synchronousSignal(int aSemaphore) +{ + int excessSignals; + + /* "source" + (self isEmptyList: aSemaphore) + ifTrue: [excessSignals <- self fetchInteger: ExcessSignalsIndex + ofObject: aSemaphore. + self storeInteger: ExcessSignalsIndex + ofObject: aSemaphore + withValue: excessSignals + 1] + ifFalse: [ "dbanay: ref counting issue: removeFirstLinkOfList" + aProcess <- self removeFirstLinkOfList: aSemaphore. + self resume: aProcess. + memory decreaseReferencesTo: aProcess] + */ + + if (isEmptyList(aSemaphore)) + { + excessSignals = fetchInteger_ofObject(ExcessSignalsIndex, aSemaphore); + storeInteger_ofObject_withValue(ExcessSignalsIndex, aSemaphore, excessSignals + 1); + } + else + { + // removeFirstLinkOfList returns pointer that must be released + int aProcess = removeFirstLinkOfList(aSemaphore); + resume(aProcess); + memory.decreaseReferencesTo(aProcess); + } +} + + +// primitiveBlockCopy +void Interpreter::primitiveBlockCopy() +{ + int context; + int methodContext; + int blockArgumentCount; + int newContext; + int initialIP; + int contextSize; + + + /* "source" + blockArgumentCount <- self popStack. + context <- self popStack. + (self isBlockContext: context) + ifTrue: [methodContext <- memory fetchPointer: HomeIndex + ofObject: context] + ifFalse: [methodContext <- context]. + contextSize <- memory fetchWordLengthOf: methodContext. + newContext <- memory instantiateClass: ClassBlockContextPointer + withPointers: contextSize. + initialIP <- memory integerObjectOf: instructionPointer + 3. + memory storePointer: InitialIPIndex + ofObject: newContext + withValue: initialIP. + memory storePointer: InstructionPointerIndex + ofObject: newContext + withValue: initialIP. + self storeStackPointerValue: 0 + inContext: newContext. + memory storePointer: BlockArgumentCountIndex + ofObject: newContext + withValue: blockArgumentCount. + memory storePointer: HomeIndex + ofObject: newContext + withValue: methodContext. + self push: newContext + */ + + blockArgumentCount = popStack(); + context = popStack(); + if (isBlockContext(context)) + methodContext = memory.fetchPointer_ofObject(HomeIndex, context); + else + methodContext = context; + contextSize = memory.fetchWordLengthOf(methodContext); + newContext = memory.instantiateClass_withPointers(ClassBlockContextPointer, contextSize); + initialIP = memory.integerObjectOf(instructionPointer + 3); + memory.storePointer_ofObject_withValue(InitialIPIndex, newContext, initialIP); + memory.storePointer_ofObject_withValue(InstructionPointerIndex, newContext, initialIP); + storeStackPointerValue_inContext(0, newContext); + memory.storePointer_ofObject_withValue(BlockArgumentCountIndex, newContext, blockArgumentCount); + memory.storePointer_ofObject_withValue(HomeIndex, newContext, methodContext); + push(newContext); +} + + +// primitiveResume +void Interpreter::primitiveResume() +{ + /* "source" + self resume: self stackTop + */ + resume(stackTop()); +} + + +// primitivePerformWithArgs +void Interpreter::primitivePerformWithArgs() +{ + int thisReceiver; + int performSelector; + int argumentArray; + int arrayClass; + int arraySize; + int index; + + /* "source" + argumentArray <- self popStack. + arraySize <- memory fetchWordLengthOf: argumentArray. + arrayClass <- memory fetchClassOf: argumentArray. + self success: (stackPointer + arraySize) + < (memory fetchWordLengthOf: activeContext). + self success: (arrayClass = ClassArrayPointer). + self success + ifTrue: [performSelector <- messageSelector. + messageSelector <- self popStack. + thisReceiver <- self stackTop. + argumentCount <- arraySize. + index <- 1. + [index <= argumentCount] + whileTrue: [self push: (memory fetchPointer: index - 1 + ofObject: argumentArray). + index <- index + 1]. + self lookupMethodInClass: + (memory fetchClassOf: thisReceiver). + self success: (self argumentCountOf: newMethod) + = argumentCount. + self success + ifTrue: [self executeNewMethod] + ifFalse: [self unPop: argumentCount. + self push: messageSelector. + self push: argumentArray. + argumentCount <- 2. + messageSelector <- performSelector]] + ifFalse: [self unPop: 1] + */ + + argumentArray = popStack(); + arraySize = memory.fetchWordLengthOf(argumentArray); + arrayClass = memory.fetchClassOf(argumentArray); + success((stackPointer + arraySize) + < memory.fetchWordLengthOf(activeContext)); + success(arrayClass == ClassArrayPointer); + if (success()) + { + performSelector = messageSelector; + messageSelector = popStack(); + thisReceiver = stackTop(); + argumentCount = arraySize; + index = 1; + while (index <= argumentCount) + { + push(memory.fetchPointer_ofObject(index - 1, argumentArray)); + index = index + 1; + } + lookupMethodInClass(memory.fetchClassOf(thisReceiver)); + success(argumentCountOf(newMethod) == argumentCount); + if (success()) + executeNewMethod(); + else + { + unPop(argumentCount); + push(messageSelector); + push(argumentArray); + argumentCount = 2; + messageSelector = performSelector; + } + } + else + unPop(1); + +} + + +// wakeHighestPriority +//NOTE: Returns a referenced increased pointer that must be decreased by caller +int Interpreter::wakeHighestPriority() +{ + int priority; + int processLists; + int processList; + + /* "source" + processLists <- memory fetchPointer: ProcessListsIndex + ofObject: self schedulerPointer. + priority <- memory fetchWordLengthOf: processLists. + [processList <- memory fetchPointer: priority - 1 + ofObject: processLists. + self isEmptyList: processList] whileTrue: [priority <- priority - 1]. + ^self removeFirstLinkOfList: processList + */ + + processLists = memory.fetchPointer_ofObject(ProcessListsIndex, schedulerPointer()); + priority = memory.fetchWordLengthOf(processLists); + for(;;) + { + assert(priority > 0); + processList = memory.fetchPointer_ofObject(priority - 1, processLists); + if (!isEmptyList(processList)) break; + priority = priority - 1; + } + + return removeFirstLinkOfList(processList); +} + + +// primitivePerform +void Interpreter::primitivePerform() +{ + int performSelector; + int newReceiver; + int selectorIndex; + + + /* "source" + performSelector <- messageSelector. + messageSelector <- self stackValue: argumentCount - 1. + newReceiver <- self stackValue: argumentCount. + self lookupMethodInClass: (memory fetchClassOf: newReceiver). + self success: (self argumentCountOf: newMethod) = (argumentCount - 1). + self success + ifTrue: [selectorIndex <- stackPointer - argumentCount + 1. + self transfer: argumentCount - 1 + fromIndex: selectorIndex + 1 + ofObject: activeContext + toIndex: selectorIndex + ofObject: activeContext. + self pop: 1. + argumentCount <- argumentCount - 1. + self executeNewMethod] + ifFalse: [messageSelector <- performSelector] + */ + + performSelector = messageSelector; + messageSelector = stackValue(argumentCount - 1); + newReceiver = stackValue(argumentCount); + lookupMethodInClass(memory.fetchClassOf(newReceiver)); + success(argumentCountOf(newMethod) == argumentCount - 1); + if (success()) + { + selectorIndex = stackPointer - argumentCount + 1; + transfer_fromIndex_ofObject_toIndex_ofObject( argumentCount - 1, + selectorIndex + 1, + activeContext, + selectorIndex, + activeContext); + pop(1); + argumentCount = argumentCount - 1; + executeNewMethod(); + } + else + { + messageSelector = performSelector; + } +} + + +// primitiveValueWithArgs +void Interpreter::primitiveValueWithArgs() +{ + int argumentArray; + int blockContext; + int blockArgumentCount; + int arrayClass; + int arrayArgumentCount = 0; + int initialIP; + + /* "source" + argumentArray <- self popStack. + blockContext <- self popStack. + blockArgumentCount <- self argumentCountOfBlock: blockContext. + arrayClass <- memory fetchClassOf: argumentArray. + self success: (arrayClass = ClassArrayPointer). + self success + ifTrue: [arrayArgumentCount <- memory fetchWordLengthOf: argumentArray. + self success: arrayArgumentCount = blockArgumentCount]. + self success + ifTrue: [self transfer: arrayArgumentCount + fromIndex: 0 + ofObject: argumentArray + toIndex: TempFrameStart + ofObject: blockContext. + initialIP <- memory fetchPointer: InitialIPIndex + ofObject: blockContext. + memory storePointer: InstructionPointerIndex + ofObject: blockContext + withValue: initialIP. + self storeStackPointerValue: arrayArgumentCount + inContext: blockContext. + memory storePointer: CallerIndex + ofObject: blockContext + withValue: activeContext. + self newActiveContext: blockContext] + ifFalse: [self unPop: 2] + */ + + argumentArray = popStack(); + blockContext = popStack(); + blockArgumentCount = argumentCountOfBlock(blockContext); + arrayClass = memory.fetchClassOf(argumentArray); + success(arrayClass == ClassArrayPointer); + if (success()) + { + arrayArgumentCount = memory.fetchWordLengthOf(argumentArray); + success(arrayArgumentCount == blockArgumentCount); + } + if (success()) + { + transfer_fromIndex_ofObject_toIndex_ofObject(arrayArgumentCount, + 0, + argumentArray, + TempFrameStart, + blockContext); + initialIP = memory.fetchPointer_ofObject(InitialIPIndex, blockContext); + memory.storePointer_ofObject_withValue(InstructionPointerIndex, blockContext, initialIP); + storeStackPointerValue_inContext(arrayArgumentCount, blockContext); + memory.storePointer_ofObject_withValue(CallerIndex, blockContext, activeContext); + newActiveContext(blockContext); + } + else + unPop(2); +} + + +// removeFirstLinkOfList: +int Interpreter::removeFirstLinkOfList(int aLinkedList) +{ + int firstLink; + int lastLink; + int nextLink; + + /* "source" + firstLink <- memory fetchPointer: FirstLinkIndex + ofObject: aLinkedList. + memory increaseReferencesTo: firstLink. "dbanay: protect it in case lastLink = firstLink" + lastLink <- memory fetchPointer: LastLinkIndex + ofObject: aLinkedList. + lastLink = firstLink + ifTrue: [memory storePointer: FirstLinkIndex + ofObject: aLinkedList + withValue: NilPointer. + memory storePointer: LastLinkIndex + ofObject: aLinkedList + withValue: NilPointer] + ifFalse: [nextLink <- memory fetchPointer: NextLinkIndex + ofObject: firstLink. + memory storePointer: FirstLinkIndex + ofObject: aLinkedList + withValue: nextLink]. + memory storePointer: NextLinkIndex + ofObject: firstLink + withValue: NilPointer. + ^firstLink + */ + /* + The routines listed here ignore the reference-counting problem in the interest of clarity. (pg. 644 G&R). + Found and fixed. -dbanay + */ + + firstLink = memory.fetchPointer_ofObject(FirstLinkIndex, aLinkedList); + + // When the link list is updated the references to fistLink + // will drop to zero. So, we need to return an increased pointer that + // must be decreased by the caller. + // Calls: + // suspendActive->wakeHighestPriority->removeFirstLinkOfList + // synchronousSignal->removeFirstLinkOfList + memory.increaseReferencesTo(firstLink); + + lastLink = memory.fetchPointer_ofObject(LastLinkIndex, aLinkedList); + if (lastLink == firstLink) + { + memory.storePointer_ofObject_withValue(FirstLinkIndex, aLinkedList, NilPointer); + memory.storePointer_ofObject_withValue(LastLinkIndex, aLinkedList, NilPointer); + } + else + { + nextLink = memory.fetchPointer_ofObject(NextLinkIndex, firstLink); + memory.storePointer_ofObject_withValue(FirstLinkIndex, aLinkedList, nextLink); + } + memory.storePointer_ofObject_withValue(NextLinkIndex, firstLink, NilPointer); + return firstLink; +} + + +// addLastLink:toList: +void Interpreter::addLastLink_toList(int aLink, int aLinkedList) +{ + int lastLink; + + /* "source" + (self isEmptyList: aLinkedList) + ifTrue: [memory storePointer: FirstLinkIndex + ofObject: aLinkedList + withValue: aLink] + ifFalse: [lastLink <- memory fetchPointer: LastLinkIndex + ofObject: aLinkedList. + memory storePointer: NextLinkIndex + ofObject: lastLink + withValue: aLink]. + memory storePointer: LastLinkIndex + ofObject: aLinkedList + withValue: aLink. + memory storePointer: MyListIndex + ofObject: aLink + withValue: aLinkedList + */ + + + if (isEmptyList(aLinkedList)) + { + memory.storePointer_ofObject_withValue(FirstLinkIndex, aLinkedList, aLink); + } + else + { + lastLink = memory.fetchPointer_ofObject(LastLinkIndex, aLinkedList); + memory.storePointer_ofObject_withValue(NextLinkIndex, lastLink, aLink); + } + memory.storePointer_ofObject_withValue(LastLinkIndex, aLinkedList, aLink); + memory.storePointer_ofObject_withValue(MyListIndex, aLink, aLinkedList); + +} + +// primitiveWait +void Interpreter::primitiveWait() +{ + int thisReceiver; + int excessSignals; + + /* "source" + thisReceiver <- self stackTop. + excessSignals <- self fetchInteger: ExcessSignalsIndex + ofObject: thisReceiver. + excessSignals > 0 + ifTrue: [self storeInteger: ExcessSignalsIndex + ofObject: thisReceiver + withValue: excessSignals - 1] + ifFalse: [self addLastLink: self activeProcess + toList: thisReceiver. + self suspendActive] + */ + + thisReceiver = stackTop(); + excessSignals = fetchInteger_ofObject(ExcessSignalsIndex, thisReceiver); + if (excessSignals > 0) + { + storeInteger_ofObject_withValue(ExcessSignalsIndex, thisReceiver, excessSignals - 1); + } + else + { + addLastLink_toList(activeProcess(), thisReceiver); + suspendActive(); + } +} + + +// primitiveFlushCache +void Interpreter::primitiveFlushCache() +{ + /* "source" + self initializeMethodCache + */ + initializeMethodCache(); +} + + +// suspendActive +void Interpreter::suspendActive() +{ + /* "source" + "dbanay: ref counting issue - wakeHighestPriority" + aProcess = self wakeHighestPriority. + self transferTo: self wakeHighestPriority. + memory decreaseReferencesTo: aProcess + */ + + //Note: wakeHighestPriority returns a pointer that must be decreased by caller + int aProcess = wakeHighestPriority(); + transferTo(aProcess); + memory.decreaseReferencesTo(aProcess); +} + + +// activeProcess +int Interpreter::activeProcess() +{ + /* "source" + newProcessWaiting + ifTrue: [^newProcess] + ifFalse: [^memory fetchPointer: ActiveProcessIndex + ofObject: self schedulerPointer] + */ + + if (newProcessWaiting) + { + return newProcess; + } + + return memory.fetchPointer_ofObject(ActiveProcessIndex, schedulerPointer()); +} + + +// dispatchControlPrimitives +void Interpreter::dispatchControlPrimitives() +{ + /* "source" + primitiveIndex = 80 ifTrue: [^self primitiveBlockCopy]. + primitiveIndex = 81 ifTrue: [^self primitiveValue]. + primitiveIndex = 82 ifTrue: [^self primitiveValueWithArgs]. + primitiveIndex = 83 ifTrue: [^self primitivePerform]. + primitiveIndex = 84 ifTrue: [^self primitivePerformWithArgs]. + primitiveIndex = 85 ifTrue: [^self primitiveSignal]. + primitiveIndex = 86 ifTrue: [^self primitiveWait]. + primitiveIndex = 87 ifTrue: [^self primitiveResume]. + primitiveIndex = 88 ifTrue: [^self primitiveSuspend]. + primitiveIndex = 89 ifTrue: [^self primitiveFlushCache] + */ + switch (primitiveIndex) + { + case 80: primitiveBlockCopy(); break; + case 81: primitiveValue(); break; + case 82: primitiveValueWithArgs(); break; + case 83: primitivePerform(); break; + case 84: primitivePerformWithArgs(); break; + case 85: primitiveSignal(); break; + case 86: primitiveWait(); break; + case 87: primitiveResume(); break; + case 88: primitiveSuspend(); break; + case 89: primitiveFlushCache(); break; + } + +} + + +bool Interpreter::isInLowMemoryCondition() +{ + return oopsLeftLimit > 0 && wordsLeftLimit > 0 && + (memory.oopsLeft() < oopsLeftLimit || + memory.coreLeft() < wordsLeftLimit); +} + + +// checkProcessSwitch +void Interpreter::checkProcessSwitch() +{ + int theActiveProcess; + + /* "source" + [semaphoreIndex > 0] + whileTrue: + [self synchronousSignal: (semaphoreList at: semaphoreIndex). + semaphoreIndex <- semaphoreIndex - 1]. + newProcessWaiting + ifTrue: [newProcessWaiting <- false. + activeProcess <- self activeProcess. + memory storePointer: SuspendedContextIndex + ofObject: activeProcess + withValue: activeContext. + memory storePointer: ActiveProcessIndex + ofObject: self schedulerPointer + withValue: newProcess. + self newActiveContext: + (memory fetchPointer: SuspendedContextIndex + ofObject: newProcess). + "dbanay: Need to remove reference" + memory decreaseReferencesTo: newProcess. + newProcess <- nil] + */ + + + //dbanay -- warn about low memory -- once + if (checkLowMemory) + { + bool memoryWasLow = memoryIsLow; + memoryIsLow = false; + // the Smalltalk system treat oops or words limits being zero as don't check + if (lowSpaceSemaphore != NilPointer && oopsLeftLimit > 0 && wordsLeftLimit > 0) + { + if (isInLowMemoryCondition()) + { + memory.garbageCollect(); // Try to get some memory back... + if (isInLowMemoryCondition()) + { + memoryIsLow = true; + if (!memoryWasLow) + asynchronousSignal(lowSpaceSemaphore); + } + } + } + checkLowMemory = false; + } + + + while (semaphoreIndex >= 0) + { + synchronousSignal(semaphoreList[semaphoreIndex]); + semaphoreIndex = semaphoreIndex - 1; + } + if (newProcessWaiting) + { + newProcessWaiting = false; + theActiveProcess = activeProcess(); + memory.storePointer_ofObject_withValue(SuspendedContextIndex, theActiveProcess, activeContext); + memory.storePointer_ofObject_withValue(ActiveProcessIndex, schedulerPointer(), newProcess); + newActiveContext(memory.fetchPointer_ofObject(SuspendedContextIndex, newProcess)); + memory.decreaseReferencesTo(newProcess); + newProcess = NilPointer; + } +} + + +// primitiveSignal +void Interpreter::primitiveSignal() +{ + /* "source" + self synchronousSignal: self stackTop + */ + synchronousSignal(stackTop()); +} + + +// isEmptyList: +int Interpreter::isEmptyList(int aLinkedList) +{ + /* "source" + ^(memory fetchPointer: FirstLinkIndex + ofObject: aLinkedList) + = NilPointer + */ + + return memory.fetchPointer_ofObject(FirstLinkIndex, aLinkedList) == NilPointer; +} + + +// primitiveSuspend +void Interpreter::primitiveSuspend() +{ + /* "source" + self success: self stackTop = self activeProcess. + self success + ifTrue: [self popStack. + self push: NilPointer. + self suspendActive] + */ + success(stackTop() == activeProcess()); + if (success()) + { + popStack(); + push(NilPointer); + suspendActive(); + } + +} + + +// primitiveValue +void Interpreter::primitiveValue() +{ + int blockContext; + int blockArgumentCount; + int initialIP; + + /* "source" + blockContext <- self stackValue: argumentCount. + blockArgumentCount <- self argumentCountOfBlock: blockContext. + self success: argumentCount = blockArgumentCount. + self success + ifTrue: [self transfer: argumentCount + fromIndex: stackPointer - argumentCount + 1 + ofObject: activeContext + toIndex: TempFrameStart + ofObject: blockContext. + self pop: argumentCount + 1. + initialIP <- memory fetchPointer: InitialIPIndex + ofObject: blockContext. + memory storePointer: InstructionPointerIndex + ofObject: blockContext + withValue: initialIP. + self storeStackPointerValue: argumentCount + inContext: blockContext. + memory storePointer: CallerIndex + ofObject: blockContext + withValue: activeContext. + self newActiveContext: blockContext] + */ + + blockContext = stackValue(argumentCount); + blockArgumentCount = argumentCountOfBlock(blockContext); + success(argumentCount == blockArgumentCount); + if (success()) + { + transfer_fromIndex_ofObject_toIndex_ofObject(argumentCount, + stackPointer - argumentCount + 1, + activeContext, + TempFrameStart, + blockContext); + pop(argumentCount + 1); + initialIP = memory.fetchPointer_ofObject(InitialIPIndex, blockContext); + memory.storePointer_ofObject_withValue(InstructionPointerIndex, blockContext, initialIP); + storeStackPointerValue_inContext(argumentCount, blockContext); + memory.storePointer_ofObject_withValue(CallerIndex, blockContext, activeContext); + newActiveContext(blockContext); + } + +} + + +// firstContext +int Interpreter::firstContext() +{ + /* "source" + newProcessWaiting <- false. + newProcess <- nil. "dbanay: need to initialize" + ^memory fetchPointer: SuspendedContextIndex + ofObject: self activeProcess + */ + + newProcessWaiting = false; + newProcess = NilPointer; + return memory.fetchPointer_ofObject(SuspendedContextIndex, activeProcess()); +} + + +// asynchronousSignal: +void Interpreter::asynchronousSignal(int aSemaphore) +{ + /* "source" + semaphoreIndex <- semaphoreIndex + 1. + semaphoreList at: semaphoreIndex put: aSemaphore + */ + semaphoreIndex = semaphoreIndex + 1; + if (semaphoreIndex == sizeof(semaphoreList)/sizeof(semaphoreList[0])) + error("overflow semaphore list"); + semaphoreList[semaphoreIndex] = aSemaphore; + +} + + +// transferTo: +void Interpreter::transferTo(int aProcess) +{ + /* "source" + newProcessWaiting <- true. + "dbanay needs ref count newProcess" + newProcess ~~ NilPointer ifTrue: [ memory decreaseReferencesTo: newProcess ]. + newProcess <- aProcess + */ + newProcessWaiting = true; + if (newProcess != NilPointer) + memory.decreaseReferencesTo(newProcess); + newProcess = aProcess; + memory.increaseReferencesTo(newProcess); + +} + + +// resume: +void Interpreter::resume(int aProcess) +{ + int theActiveProcess; + int activePriority; + int newPriority; + + /* "source" + activeProcess <- self activeProcess. + activePriority <- self fetchInteger: PriorityIndex + ofObject: activeProcess. + newPriority <- success fetchInteger: PriorityIndex + ofObject: aProcess. + newPriority > activePriority + ifTrue: [self sleep: activeProcess + self transferTo: aProcess] + ifFalse: [self sleep: aProcess] + */ + theActiveProcess = activeProcess(); + activePriority = fetchInteger_ofObject(PriorityIndex, theActiveProcess); + newPriority = fetchInteger_ofObject(PriorityIndex, aProcess); + if (newPriority > activePriority) + { + sleep(theActiveProcess); + transferTo(aProcess); + } + else + { + sleep(aProcess); + } +} + + +// sleep: +void Interpreter::sleep(int aProcess) +{ + int priority; + int processLists; + int processList; + + /* "source" + priority <- self fetchInteger: PriorityIndex + ofObject: aProcess. + processLists <- memory fetchPointer: ProcessListsIndex + ofObject: self schedulerPointer. + processList <- memory fetchPointer: priority - 1 + ofObject: processLists. + self addLastLink: aProcess + toList: processList + */ + priority = fetchInteger_ofObject(PriorityIndex, aProcess); + processLists = memory.fetchPointer_ofObject(ProcessListsIndex, schedulerPointer()); + processList = memory.fetchPointer_ofObject(priority - 1, processLists); + addLastLink_toList(aProcess, processList); +} + + +// primitiveClass +void Interpreter::primitiveClass() +{ + int instance; + + /* "source" + instance <- self popStack. + self push: (memory fetchClassOf: instance) + */ + instance = popStack(); + push(memory.fetchClassOf(instance)); +} + + +void Interpreter::primitiveCoreLeft() +{ + pop(1); // remove receiver + push(positive32BitIntegerFor(memory.coreLeft())); + } + +void Interpreter::primitiveQuit() +{ + hal->signal_quit(); + +} + +void Interpreter::primitiveExitToDebugger() +{ + hal->exit_to_debugger(); +} + +void Interpreter::primitiveOopsLeft() +{ + pop(1); // remove receiver + push(positive16BitIntegerFor(memory.oopsLeft())); +} + +void Interpreter::primitiveSignalAtOopsLeftWordsLeft() +{ + /* + (from the sources) + Tell the object memory to signal the Semaphore when either the number + of object pointers remaining drops below numOops, or the number of + words in the object space remaining drops below numWords. Fail if the + first argument is neither a Semaphore nor nil. Fail if numOops is not a + 16-bit Integer, or if numWords is not a 32-bit LargePositiveInteger. + */ + + std::uint32_t numWords = positive32BitValueOf(popStack()); + int numOops = positive16BitValueOf(popStack()); + int semaphore = popStack(); + // sempahore must either be nil or an instance of Semaphore + success(semaphore == NilPointer || memory.fetchClassOf(semaphore) == ClassSemaphorePointer); + if (success()) + { + // Don't need to take reference since Smalltalk is waiting on it someplace else + lowSpaceSemaphore = semaphore; + oopsLeftLimit = numOops; + wordsLeftLimit = numWords; + } + else + unPop(3); + +} + + +// dispatchSystemPrimitives +void Interpreter::dispatchSystemPrimitives() +{ + /* "source" + primitiveIndex = 110 ifTrue: [^self primitiveEquivalent]. + primitiveIndex = 111 ifTrue: [^self primitiveClass]. + primitiveIndex = 112 ifTrue: [^self primitiveCoreLeft]. + primitiveIndex = 113 ifTrue: [^self primitiveQuit]. + primitiveIndex = 114 ifTrue: [^self primitiveExitToDebugger]. + primitiveIndex = 115 ifTrue: [^self primitiveOopsLeft]. + primitiveIndex = 116 ifTrue: [^self primitiveSignalAtOopsLeftWordsLeft] + */ + + switch (primitiveIndex) + { + case 110: primitiveEquivalent(); break; + case 111: primitiveClass(); break; + case 112: primitiveCoreLeft(); break; + case 113: primitiveQuit(); break; + case 114: primitiveExitToDebugger(); break; + case 115: primitiveOopsLeft(); break; + case 116: primitiveSignalAtOopsLeftWordsLeft(); break; + } +} + + +// primitiveEquivalent +void Interpreter::primitiveEquivalent() +{ + int thisObject; + int otherObject; + + /* "source" + otherObject <- self popStack. + thisObject <- self popStack. + thisObject = otherObject + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer] + */ + + otherObject = popStack(); + thisObject = popStack(); + if (thisObject == otherObject) + push(TruePointer); + else + push(FalsePointer); +} + + +// dispatchPrimitives +void Interpreter::dispatchPrimitives() +{ + /* "source" + primitiveIndex < 60 + ifTrue: [^self dispatchArithmeticPrimitives]. + primitiveIndex < 68 + ifTrue: [^self dispatchSubscriptAndStreamPrimitives]. + primitiveIndex < 80 + ifTrue: [^self dispatchStorageManagementPrimitives]. + primitiveIndex < 90 + ifTrue: [^self dispatchControlPrimitives]. + primitiveIndex < 110 + ifTrue: [^self dispatchInputOutputPrimitives]. + primitiveIndex < 128 + ifTrue: [^self dispatchSystemPrimitives]. + primitiveIndex < 256 + ifTrue: [^self dispatchPrivatePrimitives] + */ + if (primitiveIndex < 60) + dispatchArithmeticPrimitives(); + else if (primitiveIndex < 68) + dispatchSubscriptAndStreamPrimitives(); + else if (primitiveIndex < 80) + dispatchStorageManagementPrimitives(); + else if (primitiveIndex < 90) + dispatchControlPrimitives(); + else if (primitiveIndex < 110) + dispatchInputOutputPrimitives(); + else if (primitiveIndex < 128) + dispatchSystemPrimitives(); + else if (primitiveIndex < 256) + { + dispatchPrivatePrimitives(); + } +} + +// dispatchPrivatePrimitives +void Interpreter::dispatchPrivatePrimitives() +{ + switch (primitiveIndex) + { + case 128: // beSnapshot + primitiveBeSnapshotFile(); + break; + case 130: // Posix File primitives + primitivePosixFileOperation(); + break; + case 131: // Posix Directory primitives + primitivePosixDirectoryOperation(); + break; + case 132: // Posix error + primitivePosixLastErrorOperation(); + break; + case 133: // Posix error string + primitivePosixErrorStringOperation(); + break; + default: + primitiveFail(); + break; + } +} + +void Interpreter::primitiveBeSnapshotFile() +{ + + int fileObjectPointer = stackTop(); + int fileNamePointer = memory.fetchPointer_ofObject(FileNameIndex, fileObjectPointer); // fileName field + std::string fileName = stringFromObject(fileNamePointer); + + hal->set_image_name(fileName.c_str()); +} + +void Interpreter::primitivePosixLastErrorOperation() +{ + pop(1); + pushInteger(fileSystem->last_error()); +} + +void Interpreter::primitivePosixErrorStringOperation() +{ + int code = popInteger(); + pop(1); // pop receiver + if (success()) + push(stringObjectFor(fileSystem->error_text(code))); + else + unPop(2); +} + +void Interpreter::primitivePosixFileOperation() +{ + // command id, name, page, file + /* + can get file descriptor from file ('fd' field) + ID Return Remarks + ---- ------- ---------- + 0 true/false read page (stores size in bytesInPage) + 1 true/false write page (uses bytesInPage) + 2 true/false truncate after page or entire file if page is nil + 3 size of file/nil file size + 4 true/false open file -- sets fd in file + 5 true/false close file -- sets fd to -1 + */ + + int page = popStack(); + int name = popStack(); + int code = popInteger(); + int file = popStack(); + + const int DescriptorIndex = 8; // fd field of PosixFile + const int PageNumberIndex = 3; // pageNumber field in PosixFilePage + + const int PageInPageIndex = 1; // ByteArray contents in PosixFilePage + const int BytesInPageIndex = 4; // bytesInPage field in PosixFilePage + + const int PageSize = 512; // MUST match page size of PosixFilePage + + static std::uint8_t pageBuffer[PageSize]; + + // Code must be legit + success(code >= 0 && code <= 6); + success(file != NilPointer); + + if (success()) + { + switch (code) + { + case 0: // Read page + { + success(memory.fetchPointer_ofObject(DescriptorIndex, file) != NilPointer); + success(page != NilPointer); + if (success()) + { + int fd = (int) positive32BitValueOf(memory.fetchPointer_ofObject(DescriptorIndex, file)); + int pageNumber = fetchInteger_ofObject(PageNumberIndex, page); + assert(pageNumber >= 1); + + int byteArray = memory.fetchPointer_ofObject(PageInPageIndex, page); + + int position = (pageNumber - 1)*PageSize; + + if (fileSystem->seek_to(fd, position) != position) + { + push(FalsePointer); + return; + } + + // No direct pointer access! Read full page and store byte by byte + int bytesInPage = fileSystem->read(fd, (char *) &pageBuffer, PageSize); + + for(int i = 0; i < bytesInPage; i++) + memory.storeByte_ofObject_withValue(i, byteArray, pageBuffer[i]); + + storeInteger_ofObject_withValue(BytesInPageIndex, page, bytesInPage); + push(TruePointer); + } + } + break; + + case 1: // Write page + { + success(memory.fetchPointer_ofObject(DescriptorIndex, file) != NilPointer); + success(page != NilPointer); + if (success()) + { + int fd = (int) positive32BitValueOf(memory.fetchPointer_ofObject(DescriptorIndex, file)); + int pageNumber = fetchInteger_ofObject(PageNumberIndex, page); + assert(pageNumber >= 1); + + int byteArray = memory.fetchPointer_ofObject(PageInPageIndex, page); + + int position = (pageNumber - 1)*PageSize; + + if (fileSystem->seek_to(fd, position) != position) + { + push(FalsePointer); + return; + } + + // No direct pointer access! Read bytes by byte into staging buffer + int bytesInPage = fetchInteger_ofObject(BytesInPageIndex, page); + // Fill buffer with page data + for(int i = 0; i < bytesInPage; i++) + pageBuffer[i] = memory.fetchByte_ofObject(i, byteArray); + + // blast it out + if (fileSystem->write(fd, (char *) pageBuffer, bytesInPage) == bytesInPage) + push(TruePointer); + else + push(FalsePointer); + } + } + break; + + case 2: // truncate page (make it the last page). A nil page means truncate to zero bytes + { + success(memory.fetchPointer_ofObject(DescriptorIndex, file) != NilPointer); + success(page != NilPointer); + if (success()) + { + + int result; + int fd = (int) positive32BitValueOf(memory.fetchPointer_ofObject(DescriptorIndex, file)); + if (page != NilPointer) + { + int pageNumber = fetchInteger_ofObject(PageNumberIndex, page); + assert(pageNumber >= 1); + + int bytesInPage = fetchInteger_ofObject(BytesInPageIndex, page); + int newSize = (pageNumber-1)*PageSize + bytesInPage; + result = fileSystem->truncate_to(fd, newSize); + } + else + result = fileSystem->truncate_to(fd, 0); + push(result != -1 ? TruePointer : FalsePointer); + } + + } + break; + + case 3: // File size + { + success(memory.fetchPointer_ofObject(DescriptorIndex, file) != NilPointer); + if (success()) + { + int fd = (int) positive32BitValueOf(memory.fetchPointer_ofObject(DescriptorIndex, file)); + int size = fileSystem->file_size(fd); + if (size >= 0) + push(positive32BitIntegerFor(size)); + else + push(NilPointer); + } + } + break; + + case 4: // Open File + { + success(memory.fetchClassOf(name) == ClassStringPointer); + if (success()) + { + std::string fileName = stringFromObject(name); + int fd = fileSystem->open_file(fileName.c_str()); + if (fd != -1) + { + memory.storePointer_ofObject_withValue(DescriptorIndex, file, positive32BitIntegerFor(fd)); + push(TruePointer); + } + else + push(FalsePointer); + } + } + + break; + + case 5: // Close file + { + int fd = (int) positive32BitValueOf(memory.fetchPointer_ofObject(DescriptorIndex, file)); + int result = fileSystem->close_file(fd); + memory.storePointer_ofObject_withValue(DescriptorIndex, file, NilPointer); + push(result != -1 ? TruePointer : FalsePointer); + } + break; + } + } + + if (!success()) + unPop(4); + +} + +void Interpreter::primitivePosixDirectoryOperation() +{ + /* + If you allocate an array and then allocate more objects to put into that array, the array pointer has no reference and can go away if GC happens. Be sure to push it on the stack after alloc to protect it. + + */ + /* + ID ARG1 ARG2 Return Remarks + ---- -------- ------- ------ ----------- + 0 name fd/nil create file (replacing existing one) + 1 name true/false delete file + 2 new name PosixFile true/false rename file + 3 nil Array of strings Array of file names in directory + */ + + const int DescriptorIndex = 8; // fd field of PosixFile + + + int arg2 = popStack(); + int arg1 = popStack(); + int code = popInteger(); + pop(1); // remove receiver + + success(code >= 0 && code <= 3); + success(arg1 == NilPointer || memory.fetchClassOf(arg1) == ClassStringPointer); + + if (success()) + { + switch (code) + { + case 0: // Create file + { + std::string s = stringFromObject(arg1); + int fd = fileSystem->create_file(s.c_str()); + if (fd != -1) + { + push(positive32BitIntegerFor(fd)); + } + else + push(NilPointer); + } + break; + + case 1: // Delete file + { + std::string s = stringFromObject(arg1); + push(fileSystem->delete_file(s.c_str()) ? TruePointer : FalsePointer); + } + break; + + case 2: // Rename file + { + int oldPos = 0; // silence uninitialized variable warning + int file = arg2; + int newNameObjectPointer = arg1; + int descriptorObjectPointer = memory.fetchPointer_ofObject(DescriptorIndex, file); + bool wasOpen = (descriptorObjectPointer != NilPointer); + if (wasOpen) + { + int fd = (int) positive32BitValueOf(descriptorObjectPointer); + oldPos = fileSystem->tell(fd); // Save position for restore after we open new file... + // Some operating systems don't let you rename an open file... + fileSystem->close_file(fd); + } + std::string newName = stringFromObject(newNameObjectPointer); + std::string oldName = stringFromObject(memory.fetchPointer_ofObject(FileNameIndex, file)); + if (fileSystem->rename_file(oldName.c_str(), newName.c_str())) + { + // Re-open and update descriptor of File object + if (wasOpen) + { + int fd = fileSystem->open_file(newName.c_str()); + if (fd != -1) + { + memory.storePointer_ofObject_withValue(DescriptorIndex, + file, positive32BitIntegerFor(fd)); + fileSystem->seek_to(fd, oldPos); // Restore position.... + } + else + memory.storePointer_ofObject_withValue(DescriptorIndex, file, NilPointer); + } + // Update with new name + memory.storePointer_ofObject_withValue(FileNameIndex, file, newNameObjectPointer); + push(TruePointer); + } + else + { + if (wasOpen) + { + // Something failed. Open the original file again...if possible + int fd = fileSystem->open_file(oldName.c_str()); + if (fd != -1) + { + memory.storePointer_ofObject_withValue(DescriptorIndex, + file, positive32BitIntegerFor(fd)); + fileSystem->seek_to(fd, oldPos); // Restore position.... + } + else + memory.storePointer_ofObject_withValue(DescriptorIndex, file, NilPointer); + } + push(FalsePointer); + } + } + break; + case 3: // Enumerate files + { + // One pass to get length... + int length = 0; + fileSystem->enumerate_files([&](const char *) { + length++; + }); + + int array = memory.instantiateClass_withPointers(ClassArrayPointer, length); + // Push the array first so there is a refernce on it just in case GC takes place when we add the + // entries + push(array); + + // A second pass to fetch and store values + int i = 0; + fileSystem->enumerate_files([&](const char *name) { + memory.storePointer_ofObject_withValue(i, array, stringObjectFor(name)); + i++; + }); + } + break; + } + } + else + unPop(4); + +} + + + +// positive16BitValueOf: +int Interpreter::positive16BitValueOf(int integerPointer) +{ + int value; + + /* "source" + (memory isIntegerObject: integerPointer) + ifTrue: [^memory integerValueOf: integerPointer]. + (memory fetchClassOf: integerPointer) = + ClassLargePositiveIntegerPointer + ifFalse: [^self primitiveFail]. + (memory fetchByteLengthOf: integerPointer) = 2 + ifFalse: [^self primitiveFail]. + value <- memory fetchByte: 1 + ofObject: integerPointer. + value <- value * 256 + (memory fetchByte: 0 + ofObject: integerPointer). + ^value + */ + if (memory.isIntegerObject(integerPointer)) + return memory.integerValueOf(integerPointer); + if (memory.fetchClassOf(integerPointer) != ClassLargePositiveIntegerPointer) + return primitiveFail(); + if (memory.fetchByteLengthOf(integerPointer) != 2) + return primitiveFail(); + + value = memory.fetchByte_ofObject(1, integerPointer); + value = value * 256 + memory.fetchByte_ofObject(0, integerPointer); + return value; +} + + +std::uint32_t Interpreter::positive32BitValueOf(int integerPointer) +{ + std::uint32_t value; + if (memory.isIntegerObject(integerPointer)) + return memory.integerValueOf(integerPointer); + if (memory.fetchClassOf(integerPointer) != ClassLargePositiveIntegerPointer) + return primitiveFail(); + + int bytes = memory.fetchByteLengthOf(integerPointer); + value = memory.fetchByte_ofObject(0, integerPointer); + if (bytes > 1) + value |= memory.fetchByte_ofObject(1, integerPointer) << 8; + if (bytes > 2) + value |= memory.fetchByte_ofObject(2, integerPointer) << 16; + if (bytes > 3) + value |= ((std::uint32_t) memory.fetchByte_ofObject(3, integerPointer)) << 24; + + return value; +} + +// primitiveResponse +bool Interpreter::primitiveResponse() +{ + int flagValue; + + /* "source" + primitiveIndex = 0 + ifTrue: [flagValue <- self flagValueOf: newMethod. + flagValue = 5 + ifTrue: [self quickReturnSelf. + ^true]. + flagValue = 6 + ifTrue: [self quickInstanceLoad. + ^true]. + ^false] + ifFalse: [self initPrimitive. + self dispatchPrimitives. + ^self success] + */ + + if (primitiveIndex == 0) + { + flagValue = flagValueOf(newMethod); + if (flagValue == 5) + { + quickReturnSelf(); + return true; + } + if (flagValue == 6) + { + quickInstanceLoad(); + return true; + } + return false; + } + initPrimitive(); + dispatchPrimitives(); + return success(); +} + + +// quickInstanceLoad +void Interpreter::quickInstanceLoad() +{ + int thisReceiver; + int fieldIndex; + + /* "source" + thisReceiver <- self popStack. + fieldIndex <- self fieldIndexOf: newMethod. + self push: (memory fetchPointer: fieldIndex + ofObject: thisReceiver) + */ + thisReceiver = popStack(); + fieldIndex = fieldIndexOf(newMethod); + push(memory.fetchPointer_ofObject(fieldIndex, thisReceiver)); +} + + +// arithmeticSelectorPrimitive +void Interpreter::arithmeticSelectorPrimitive() +{ + /* "source" + "ERROR: the next line is redundant" + "self success: (memory isIntegerObject: (self stackValue: 1))." + self success + ifTrue:[currentBytecode = 176 ifTrue: [^self primitiveAdd]. + currentBytecode = 177 ifTrue: [^self primitiveSubtract]. + currentBytecode = 178 ifTrue: [^self primitiveLessThan]. + currentBytecode = 179 ifTrue: [^self primitiveGreaterThan]. + currentBytecode = 180 ifTrue: [^self primitiveLessOrEqual]. + currentBytecode = 181 ifTrue: [^self primitiveGreaterOrEqual]. + currentBytecode = 182 ifTrue: [^self primitiveEqual]. + currentBytecode = 183 ifTrue: [^self primitiveNotEqual]. + currentBytecode = 184 ifTrue: [^self primitiveMultiply]. + currentBytecode = 185 ifTrue: [^self primitiveDivide]. + currentBytecode = 186 ifTrue: [^self primitiveMod]. + currentBytecode = 187 ifTrue: [^self primitiveMakePoint]. + currentBytecode = 188 ifTrue: [^self primitiveBitShift]. + currentBytecode = 189 ifTrue: [^self primitiveDiv]. + currentBytecode = 190 ifTrue: [^self primitiveBitAnd]. + currentBytecode = 191 ifTrue: [^self primitiveBitOr]] + */ + + //success(memory.isIntegerObject(stackValue(1))); + if (success()) + { + switch (currentBytecode) + { + case 176: primitiveAdd(); break; + case 177: primitiveSubtract(); break; + case 178: primitiveLessThan(); break; + case 179: primitiveGreaterThan(); break; + case 180: primitiveLessOrEqual(); break; + case 181: primitiveGreaterOrEqual(); break; + case 182: primitiveEqual(); break; + case 183: primitiveNotEqual(); break; + case 184: primitiveMultiply(); break; + case 185: primitiveDivide(); break; + case 186: primitiveMod(); break; + case 187: primitiveMakePoint(); break; + case 188: primitiveBitShift(); break; + case 189: primitiveDiv(); break; + case 190: primitiveBitAnd(); break; + case 191: primitiveBitOr(); break; + } + } +} + +// positive16BitIntegerFor: +int Interpreter::positive16BitIntegerFor(int integerValue) +{ + int newLargeInteger; + + /* "source" + integerValue < 0 + ifTrue: [^self primitiveFail]. + (memory isIntegerValue: integerValue) + ifTrue: [^memory integerObjectOf: integerValue]. + newLargeInteger <- memory instantiateClass: + ClassLargePositiveIntegerPointer + withBytes: 2. + memory storeByte: 0 + ofObject: newLargeInteger + withValue: (self lowByteOf: integerValue). + memory storeByte: 1 + ofObject: newLargeInteger + withValue: (self highByteOf: integerValue). + ^newLargeInteger + */ + + if (integerValue < 0) + { + return primitiveFail(); + } + if (memory.isIntegerValue(integerValue)) + return memory.integerObjectOf(integerValue); + newLargeInteger = memory.instantiateClass_withBytes(ClassLargePositiveIntegerPointer, 2); + memory.storeByte_ofObject_withValue(0, newLargeInteger, lowByteOf(integerValue)); + memory.storeByte_ofObject_withValue(1, newLargeInteger, highByteOf(integerValue)); + return newLargeInteger; +} + +int Interpreter::positive32BitIntegerFor(int integerValue) +{ + + if (memory.isIntegerValue(integerValue)) + return memory.integerObjectOf(integerValue); + int newLargeInteger; + + newLargeInteger = memory.instantiateClass_withBytes(ClassLargePositiveIntegerPointer, 4); + memory.storeByte_ofObject_withValue(0, newLargeInteger, lowByteOf(integerValue)); + memory.storeByte_ofObject_withValue(1, newLargeInteger, highByteOf(integerValue)); + memory.storeByte_ofObject_withValue(2, newLargeInteger, (integerValue >> 16) & 0xff); + memory.storeByte_ofObject_withValue(3, newLargeInteger, (integerValue >> 24) & 0xff); + return newLargeInteger; + +} + + +// popInteger +int Interpreter::popInteger() +{ + int integerPointer; + + /* "source" + integerPointer <- self popStack. + self success: (memory isIntegerObject: integerPointer). + self success + ifTrue: [^memory integerValueOf: integerPointer] + */ + integerPointer = popStack(); + success(memory.isIntegerObject(integerPointer)); + if (success()) + return memory.integerValueOf(integerPointer); + + return std::numeric_limits<int>::min(); +} + + +// specialSelectorPrimitiveResponse +int Interpreter::specialSelectorPrimitiveResponse() +{ + /* "source" + self initPrimitive. + (currentBytecode between: 176 and: 191) + ifTrue: [self arithmeticSelectorPrimitive]. + (currentBytecode between: 192 and: 207) + ifTrue: [self commonSelectorPrimitive]. + ^self success + */ + + initPrimitive(); + if (between_and(currentBytecode, 176, 191)) + arithmeticSelectorPrimitive(); + else if (between_and(currentBytecode, 192, 207)) + commonSelectorPrimitive(); + return success(); +} + + +// commonSelectorPrimitive +void Interpreter::commonSelectorPrimitive() +{ + int receiverClass; + + /* "source" + argumentCount <- self fetchInteger: (currentBytecode - 176)*2 + 1 + ofObject: SpecialSelectorsPointer. + receiverClass <- + memory fetchClassOf: (self stackValue: argumentCount). + currentBytecode = 198 ifTrue: [^self primitiveEquivalent]. + currentBytecode = 199 ifTrue: [^self primitiveClass]. + currentBytecode = 200 + ifTrue: [self success: + (receiverClass = ClassMethodContextPointer) + | (receiverClass = ClassBlockContextPointer). + ^self success ifTrue: [self primitiveBlockCopy]]. + (currentBytecode = 201) | (currentBytecode = 202) + ifTrue: [self success: receiverClass = ClassBlockContextPointer. + ^self success ifTrue: [self primitiveValue]]. + self primitiveFail + */ + + argumentCount = fetchInteger_ofObject((currentBytecode - 176)*2 + 1, SpecialSelectorsPointer); + receiverClass = memory.fetchClassOf(stackValue(argumentCount)); + if (currentBytecode == 198 ) + { + primitiveEquivalent(); + } + else if (currentBytecode == 199 ) + { + primitiveClass(); + } + else if (currentBytecode == 200) + { + success(receiverClass == ClassMethodContextPointer || receiverClass == ClassBlockContextPointer); + if (success()) + primitiveBlockCopy(); + } + else if (currentBytecode == 201 || currentBytecode == 202) + { + success(receiverClass == ClassBlockContextPointer); + if (success()) + primitiveValue(); + } + else + primitiveFail(); +} + + + +// initializeMethodCache +void Interpreter::initializeMethodCache() +{ + /* "source" + methodCacheSize <- 1024. + methodCache <- Array new: methodCacheSize + */ + for(int i = 0; i < sizeof(methodCache)/sizeof(methodCache[0]); i++) + methodCache[i] = NilPointer; +} + + +// primitiveMod +void Interpreter::primitiveMod() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; //silence warning + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success: integerArgument ~= 0. + self success + ifTrue: [integerResult <- integerReceiver \\ integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + success(integerArgument != 0); + if (success()) + { + integerResult = integerReceiver % integerArgument; + if (integerArgument < 0) + { + if (integerResult > 0) + { + integerResult += integerArgument; + } + } else + { + if (integerResult < 0) + { + integerResult += integerArgument; + } + } + success(memory.isIntegerValue(integerResult)); + } + if (success()) + pushInteger(integerResult); + else + unPop(2); +} + + +// dispatchArithmeticPrimitives +void Interpreter::dispatchArithmeticPrimitives() +{ + /* "source" + primitiveIndex < 20 + ifTrue: [^self dispatchIntegerPrimitives]. + primitiveIndex < 40 + ifTrue: [^self dispatchLargeIntegerPrimitives]. + primitiveIndex < 60 + ifTrue: [^self dispatchFloatPrimitives] + */ + if (primitiveIndex < 20) + { + dispatchIntegerPrimitives(); + } + else if (primitiveIndex < 40) + { + dispatchLargeIntegerPrimitives(); + } + else if (primitiveIndex < 60) + { + dispatchFloatPrimitives(); + } +} + + +// primitiveEqual +void Interpreter::primitiveEqual() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver = integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver == integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + { + unPop(2); + } +} + + +// primitiveBitOr +void Interpreter::primitiveBitOr() +{ + int integerReceiver; + int integerArgument; + int integerResult; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver bitOr: integerArgument]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver | integerArgument; + pushInteger(integerResult); + } + else + unPop(2); +} + + +// primitiveDivide +// The primitive routine for division (associated with the selector/) is different than +// the other three arithmetic primitives since it only produces a result if the division +// is exact, otherwise the primitive fails. +void Interpreter::primitiveDivide() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; // eliminate warning + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success: integerArgument ~= 0. + self success: integerReceiver \\ integerArgument = 0. + self success + ifTrue: [integerResult <- integerReceiver // integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [ self push: (memory integerObjectOf: integerResult)] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + success(integerArgument != 0); + success(integerReceiver % integerArgument == 0); + if (success()) + { + integerResult = integerReceiver / integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + push(memory.integerObjectOf(integerResult)); + else + unPop(2); +} + + +// primitiveMultiply +void Interpreter::primitiveMultiply() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver * integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver * integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + pushInteger(integerResult); + else + unPop(2); +} + +// primitiveBitAnd +void Interpreter::primitiveBitAnd() +{ + int integerReceiver; + int integerArgument; + int integerResult; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver bitAnd: integerArgument]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + + + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver & integerArgument; + pushInteger(integerResult); + } + else + unPop(2); +} + + +// primitiveSubtract +void Interpreter::primitiveSubtract() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver - integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver - integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + pushInteger(integerResult); + else + unPop(2); +} + + +// dispatchIntegerPrimitives +void Interpreter::dispatchIntegerPrimitives() +{ + /* "source" + primitiveIndex = 1 ifTrue: [^self primitiveAdd]. + primitiveIndex = 2 ifTrue: [^self primitiveSubtract]. + primitiveIndex = 3 ifTrue: [^self primitiveLessThan]. + primitiveIndex = 4 ifTrue: [^self primitiveGreaterThan]. + primitiveIndex = 5 ifTrue: [^self primitiveLessOrEqual]. + primitiveIndex = 6 ifTrue: [^self primitiveGreaterOrEqual]. + primitiveIndex = 7 ifTrue: [^self primitiveEqual]. + primitiveIndex = 8 ifTrue: [^self primitiveNotEqual]. + primitiveIndex = 9 ifTrue: [^self primitiveMultiply]. + primitiveIndex = 10 ifTrue: [^self primitiveDivide]. + primitiveIndex = 11 ifTrue: [^self primitiveMod]. + primitiveIndex = 12 ifTrue: [^self primitiveDiv]. + primitiveIndex = 13 ifTrue: [^self primitiveQuo]. + primitiveIndex = 14 ifTrue: [^self primitiveBitAnd]. + primitiveIndex = 15 ifTrue: [^self primitiveBitOr]. + primitiveIndex = 16 ifTrue: [^self primitiveBitXor]. + primitiveIndex = 17 ifTrue: [^self primitiveBitShift]. + primitiveIndex = 18 ifTrue: [^self primitiveMakePoint] + */ + + switch (primitiveIndex) + { + case 1: primitiveAdd(); break; + case 2: primitiveSubtract(); break; + case 3: primitiveLessThan(); break; + case 4: primitiveGreaterThan(); break; + case 5: primitiveLessOrEqual(); break; + case 6: primitiveGreaterOrEqual(); break; + case 7: primitiveEqual(); break; + case 8: primitiveNotEqual(); break; + case 9: primitiveMultiply(); break; + case 10: primitiveDivide(); break; + case 11: primitiveMod(); break; + case 12: primitiveDiv(); break; + case 13: primitiveQuo(); break; + case 14: primitiveBitAnd(); break; + case 15: primitiveBitOr(); break; + case 16: primitiveBitXor(); break; + case 17: primitiveBitShift(); break; + case 18: primitiveMakePoint(); break; + } +} + + +// primitiveGreaterOrEqual +void Interpreter::primitiveGreaterOrEqual() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver >= integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver >= integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + + +// primitiveAdd +void Interpreter::primitiveAdd() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver + integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver + integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + pushInteger(integerResult); + else + unPop(2); +} + + +// primitiveNotEqual +void Interpreter::primitiveNotEqual() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver ~= integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver != integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + + +// primitiveQuo +void Interpreter::primitiveQuo() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success: integerArgument ~= 0. + self success + ifTrue: [integerResult <- integerReceiver quo: integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + success(integerArgument != 0); + + if (success()) + { + integerResult = integerReceiver / integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + push(memory.integerObjectOf(integerResult)); + else + unPop(2); +} + + +// dispatchFloatPrimitives +void Interpreter::dispatchFloatPrimitives() +{ + /* "source" + primitiveIndex = 40 ifTrue: [^self primitiveAsFloat]. + primitiveIndex = 41 ifTrue: [^self primitiveFloatAdd]. + primitiveIndex = 42 ifTrue: [^self primitiveFloatSubtract]. + primitiveIndex = 43 ifTrue: [^self primitiveFloatLessThan]. + primitiveIndex = 44 ifTrue: [^self primitiveFloatGreaterThan]. + primitiveIndex = 45 ifTrue: [^self primitiveFloatLessOrEqual]. + primitiveIndex = 46 ifTrue: [^self primitiveFloatGreaterOrEqual]. + primitiveIndex = 47 ifTrue: [^self primitiveFloatEqual]. + primitiveIndex = 48 ifTrue: [^self primitiveFloatNotEqual]. + primitiveIndex = 49 ifTrue: [^self primitiveFloatMultiply]. + primitiveIndex = 50 ifTrue: [^self primitiveFloatDivide]. + primitiveIndex = 51 ifTrue: [^self primitiveTruncated]. + primitiveIndex = 52 ifTrue: [^self primitiveFractionalPart]. + primitiveIndex = 53 ifTrue: [^self primitiveExponent]. + primitiveIndex = 54 ifTrue: [^self primitiveTimesTwoPower] + */ + + switch (primitiveIndex) + { + case 40: primitiveAsFloat(); break; + case 41: primitiveFloatAdd(); break; + case 42: primitiveFloatSubtract(); break; + case 43: primitiveFloatLessThan(); break; + case 44: primitiveFloatGreaterThan(); break; + case 45: primitiveFloatLessOrEqual(); break; + case 46: primitiveFloatGreaterOrEqual(); break; + case 47: primitiveFloatEqual(); break; + case 48: primitiveFloatNotEqual(); break; + case 49: primitiveFloatMultiply(); break; + case 50: primitiveFloatDivide(); break; + case 51: primitiveTruncated(); break; + case 52: primitiveFractionalPart(); break; + case 53: primitiveExponent(); break; + case 54: primitiveTimesTwoPower(); break; + } + +} + +// The primitiveAsFloat routine converts its SmallInteger receiver into a Float. +void Interpreter::primitiveAsFloat() +{ + int integerArgument = popInteger(); + if (success()) + { + pushFloat((float) integerArgument); + } + else + unPop(1); +} + +void Interpreter::primitiveFloatAdd() +{ + float floatReceiver; + float floatArgument; + float floatResult; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + if (success()) + { + floatResult = floatReceiver + floatArgument; + pushFloat(floatResult); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatSubtract() +{ + float floatReceiver; + float floatArgument; + float floatResult; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + if (success()) + { + floatResult = floatReceiver - floatArgument; + pushFloat(floatResult); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatLessThan() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver < floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatGreaterThan() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver > floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatLessOrEqual() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver <= floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatGreaterOrEqual() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver >= floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatEqual() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver == floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatNotEqual() +{ + float floatReceiver; + float floatArgument; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + + if (success()) + { + if (floatReceiver != floatArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatMultiply() +{ + float floatReceiver; + float floatArgument; + float floatResult; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + if (success()) + { + floatResult = floatReceiver * floatArgument; + pushFloat(floatResult); + } + else + unPop(2); +} + +void Interpreter::primitiveFloatDivide() +{ + float floatReceiver; + float floatArgument; + float floatResult; + + floatArgument = popFloat(); + floatReceiver = popFloat(); + success(floatArgument != 0); + if (success()) + { + floatResult = floatReceiver / floatArgument; + pushFloat(floatResult); + } + else + unPop(2); +} + +void Interpreter::primitiveTruncated() +{ + float floatReceiver; + int integerResult = 0; + floatReceiver = popFloat(); + if (success()) + { + integerResult = (int) floatReceiver; + success(memory.isIntegerValue(integerResult)); + } + + if (success()) + { + pushInteger(integerResult); + } + else + unPop(1); +} + +void Interpreter::primitiveFractionalPart() +{ + float floatReceiver; + float floatResult; + floatReceiver = popFloat(); + if (success()) + { + floatResult = floatReceiver - (int) floatReceiver; + pushFloat(floatResult); + } + else + unPop(1); +} + +// primitiveLessOrEqual +void Interpreter::primitiveLessOrEqual() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver <= integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver <= integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + + +// primitiveMakePoint +void Interpreter::primitiveMakePoint() +{ + int integerReceiver; + int integerArgument; + int pointResult; + + /* "source" + + integerArgument <- self popStack. + integerReceiver <- self popStack. + self success: (memory isIntegerValue: integerReceiver). + self success: (memory isIntegerValue: integerArgument)." + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [pointResult <- memory instantiateClass: ClassPointPointer + withPointers: ClassPointSize. + "ERROR: dbanay next two changed to be storeInteger:ofObject:withValue" + self storeInteger: XIndex + ofObject: pointResult + withValue: integerReceiver. + self storeInteger: YIndex + ofObject: pointResult + withValue: integerArgument. + self push: pointResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + success(memory.isIntegerValue(integerReceiver)); + success(memory.isIntegerValue(integerArgument)); + if (success()) + { + pointResult = memory.instantiateClass_withPointers(ClassPointPointer, ClassPointSize); + storeInteger_ofObject_withValue(XIndex, pointResult, integerReceiver); + storeInteger_ofObject_withValue(YIndex, pointResult, integerArgument); + push(pointResult); + } + else + unPop(2); +} + + +// primitiveBitXor +void Interpreter::primitiveBitXor() +{ + int integerReceiver; + int integerArgument; + int integerResult; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver bitXor: integerArgument]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + integerResult = integerReceiver ^ integerArgument; + pushInteger(integerResult); + } + else + unPop(2); +} + + +// primitiveLessThan +void Interpreter::primitiveLessThan() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver < integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver < integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); + + +} + + +// primitiveBitShift +void Interpreter::primitiveBitShift() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerResult <- integerReceiver bitShift: integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + if (success()) + { + integerResult = integerArgument >= 0 ? integerReceiver << integerArgument : integerReceiver >> -integerArgument; + success(memory.isIntegerValue(integerResult)); + } + if (success()) + pushInteger(integerResult); + else + unPop(2); +} + + +// primitiveGreaterThan +void Interpreter::primitiveGreaterThan() +{ + int integerReceiver; + int integerArgument; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success + ifTrue: [integerReceiver > integerArgument + ifTrue: [self push: TruePointer] + ifFalse: [self push: FalsePointer]] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + + if (success()) + { + if (integerReceiver > integerArgument) + push(TruePointer); + else + push(FalsePointer); + } + else + unPop(2); +} + + +// primitiveDiv +void Interpreter::primitiveDiv() +{ + int integerReceiver; + int integerArgument; + int integerResult = 0; + + /* "source" + integerArgument <- self popInteger. + integerReceiver <- self popInteger. + self success: integerArgument ~= 0. + self success + ifTrue: [integerResult <- integerReceiver // integerArgument. + self success: (memory isIntegerValue: integerResult)]. + self success + ifTrue: [self pushInteger: integerResult] + ifFalse: [self unPop: 2] + */ + integerArgument = popInteger(); + integerReceiver = popInteger(); + success(integerArgument != 0); + if (success()) + { + integerResult = integerReceiver / integerArgument; + if (integerReceiver % integerArgument != 0) + { + // Smalltalk truncates to negative infinity ( -7 // 2 == -4 not -3) + if (integerResult < 0) + integerResult--; + } + success(memory.isIntegerValue(integerResult)); + } + if (success()) + push(memory.integerObjectOf(integerResult)); + else + unPop(2); + +} + +std::string Interpreter::stringFromObject(int stringOrSymbolPointer) +{ + + int len = memory.fetchByteLengthOf(stringOrSymbolPointer); + std::string s; + s.reserve(len); + + for(int i = 0; i < len; i++) + { + std::uint8_t ch = memory.fetchByte_ofObject(i, stringOrSymbolPointer); + s.append(1, ch); + } + return s; + } + +int Interpreter::stringObjectFor(const char *s) +{ + if (!s) + return NilPointer; + + const char *p = s; + while (*p) + p++; + int length = (int) (p - s); + int objectPointer = memory.instantiateClass_withBytes(ClassStringPointer, length); + p = s; + for(int i = 0; i < length; i++) + { + memory.storeByte_ofObject_withValue(i, objectPointer, *p++); + } + return objectPointer; +} + + +#ifdef DEBUGGING_SUPPORT + +std::string Interpreter::selectorName(int selector) +{ + return stringFromObject(selector); +} + +std::string Interpreter::classNameOfObject(int objectPointer) +{ + return className(memory.fetchClassOf(objectPointer)); +} + +std::string Interpreter::className(int classPointer) +{ + if (classPointer == ClassSmallInteger) + return "SmallInteger"; + + if (classPointer == NilPointer) + return "UndefinedObject"; + + int symbol = memory.fetchPointer_ofObject(6, classPointer); + if (memory.fetchClassOf(symbol) != ClassSymbolPointer) + return "<unknown>"; + + return stringFromObject(symbol); +} +#endif + +// sendSelector:argumentCount: +void Interpreter::sendSelector_argumentCount(int selector, int count) +{ + int newReceiver; + + /* "source" + messageSelector <- selector. + argumentCount <- count. + newReceiver <- self stackValue: argumentCount. + self sendSelectorToClass: (memory fetchClassOf: newReceiver) + */ + messageSelector = selector; + argumentCount = count; + newReceiver = stackValue(argumentCount); + +#if 0 +#ifdef DEBUGGING_SUPPORT + // Debugging aid that helped me figure out why stuff + // wasn't working - intercept show: and error: messages and + // display them + const int showSelector = 6640; // #show: + const int errorSelector = 282; // #error: +#if 0 + bool showSend = true; + + if (selector == showSelector) + { + int s = stackValue(argumentCount-1); + assert(memory.fetchClassOf(s) == ClassStringPointer); + std::string text = stringFromObject(s); + printf("Transcript: %s\n", text.c_str()); + showSend = false; + } + else if (selector == errorSelector) + { + int s = stackValue(argumentCount-1); + assert(memory.fetchClassOf(s) == ClassStringPointer); + std::string text = stringFromObject(s); + printf("ERROR: %s\n", text.c_str()); + showSend = false; + } + + if (showSend) + { + int cls = memory.fetchClassOf(newReceiver); + std::string className = classNameOfObject(newReceiver); + std::string sel = selectorName(selector); + printf("sendSelector %s [%d] (args = %d) to %d (%s) 0x%d\n", + sel.c_str(), selector, count, newReceiver, className.c_str(), cls); + } +#endif +#endif +#endif + sendSelectorToClass(memory.fetchClassOf(newReceiver)); +} + + +// findNewMethodInClass: +void Interpreter::findNewMethodInClass(int cls) +{ + int hash; + + /* "source" + hash <- (((messageSelector bitAnd: class) bitAnd: 16rFF) bitShift: 2) + 1. + ((methodCache at: hash) = messageSelector + and: [(methodCache at: hash + 1) = class]) + ifTrue: [newMethod <- methodCache at: hash + 2. + primitiveIndex <- methodCache at: hash + 3] + ifFalse: [self lookupMethodInClass: class. + methodCache at: hash put: messageSelector. + methodCache at: hash + 1 put: class. + methodCache at: hash + 2 put: newMethod. + methodCache at: hash + 3 put: primitiveIndex] + */ + + // This is not a great hash function + // Bits of History, pg.244 has a discussion and a better one + // hash = ((messageSelector ^ cls) & 0xff) << 2; + + hash = (messageSelector & cls & 0xff) << 2; // removed +1 since C arrays are zero based + if (methodCache[hash] == messageSelector && methodCache[hash+1] == cls) + { + newMethod = methodCache[hash+2]; + primitiveIndex = methodCache[hash+3]; + } + else + { + + lookupMethodInClass(cls); + methodCache[hash] = messageSelector; + methodCache[hash+1] = cls; + methodCache[hash+2] = newMethod; + methodCache[hash+3] = primitiveIndex; + } + +} + + +// activateNewMethod +void Interpreter::activateNewMethod() +{ + int contextSize; + int newContext; + + /* "source" + (self largeContextFlagOf: newMethod) = 1 + ifTrue: [contextSize <- 32 + TempFrameStart] + ifFalse: [contextSize <- 12 + TempFrameStart]. + newContext <- memory instantiateClass: ClassMethodContextPointer + withPointers: contextSize. + memory storePointer: SenderIndex + ofObject: newContext + withValue: activeContext. + self storeInstructionPointerValue: + (self initialInstructionPointerOfMethod: newMethod) + inContext: newContext. + self storeStackPointerValue: (self temporaryCountOf: newMethod) + inContext: newContext. + memory storePointer: MethodIndex + ofObject: newContext + withValue: newMethod. + self transfer: argumentCount + 1 + fromIndex: stackPointer - argumentCount + ofObject: activeContext + toIndex: ReceiverIndex + ofObject: newContext. + self pop: argumentCount + 1. + self newActiveContext: newContext + */ + + if (largeContextFlagOf(newMethod) == 1) + contextSize = 32 + TempFrameStart; + else + contextSize = 12 + TempFrameStart; + newContext = memory.instantiateClass_withPointers( + ClassMethodContextPointer, contextSize); + memory.storePointer_ofObject_withValue(SenderIndex, + newContext, activeContext); + storeInstructionPointerValue_inContext( + initialInstructionPointerOfMethod(newMethod), newContext); + storeStackPointerValue_inContext(temporaryCountOf(newMethod), newContext); + memory.storePointer_ofObject_withValue(MethodIndex, newContext, newMethod); + transfer_fromIndex_ofObject_toIndex_ofObject(argumentCount + 1, + stackPointer - argumentCount, + activeContext, + ReceiverIndex, + newContext); + pop(argumentCount + 1); + newActiveContext(newContext); +} + + +// sendSpecialSelectorBytecode +void Interpreter::sendSpecialSelectorBytecode() +{ + int selectorIndex; + int selector; + int count; + + /* "source" + self specialSelectorPrimitiveResponse + ifFalse: [selectorIndex <- (currentBytecode - 176) * 2. + selector <- memory fetchPointer: selectorIndex + ofObject: SpecialSelectorsPointer. + count <- self fetchInteger: selectorIndex + 1 + ofObject: SpecialSelectorsPointer. + self sendSelector: selector + argumentCount: count] + */ + + if (!specialSelectorPrimitiveResponse()) + { + selectorIndex = (currentBytecode - 176) * 2; + selector = memory.fetchPointer_ofObject(selectorIndex, SpecialSelectorsPointer); + count = fetchInteger_ofObject(selectorIndex + 1, SpecialSelectorsPointer); + sendSelector_argumentCount(selector, count); + } +} + + +// doubleExtendedSuperBytecode +void Interpreter::doubleExtendedSuperBytecode() +{ + int methodClass; + + /* "source" + argumentCount <- self fetchByte. + messageSelector <- self literal: self fetchByte. + methodClass <- self methodClassOf: method. + self sendSelectorToClass: (self superclassOf: methodClass) + */ + argumentCount = fetchByte(); + messageSelector = literal(fetchByte()); + methodClass = methodClassOf(method); + sendSelectorToClass(superclassOf(methodClass)); +} + + +// sendBytecode +void Interpreter::sendBytecode() +{ + /* "source" + (currentBytecode between: 131 and: 134) + ifTrue: [^self extendedSendBytecode]. + (currentBytecode between: 176 and: 207) + ifTrue: [^self sendSpecialSelectorBytecode]. + (currentBytecode between: 208 and: 255) + ifTrue: [^self sendLiteralSelectorBytecode] + */ + if (between_and(currentBytecode, 131, 134)) + extendedSendBytecode(); + else if (between_and(currentBytecode, 176, 207)) + sendSpecialSelectorBytecode(); + else if (between_and(currentBytecode, 208, 255)) + sendLiteralSelectorBytecode(); + +} + + +// doubleExtendedSendBytecode +void Interpreter::doubleExtendedSendBytecode() +{ + int count; + int selector; + + /* "source" + count <- self fetchByte. + selector <- self literal: self fetchByte. + self sendSelector: selector + argumentCount: count + */ + + count = fetchByte(); + selector = literal(fetchByte()); + sendSelector_argumentCount(selector, count); +} + + +// sendSelectorToClass: +void Interpreter::sendSelectorToClass(int classPointer) +{ + /* "source" + self findNewMethodInClass: classPointer. + self executeNewMethod + */ + findNewMethodInClass(classPointer); + executeNewMethod(); +} + + +// sendLiteralSelectorBytecode +void Interpreter::sendLiteralSelectorBytecode() +{ + int selector; + + /* "source" + selector <- self literal: (self extractBits: 12 to: 15 + of: currentBytecode). + self sendSelector: selector + argumentCount: (self extractBits: 10 to: 11 + of: currentBytecode) - 1 + */ + selector = literal(extractBits_to_of(12, 15, currentBytecode)); + sendSelector_argumentCount(selector, extractBits_to_of(10, 11, currentBytecode) - 1); +} + + +// singleExtendedSuperBytecode +void Interpreter::singleExtendedSuperBytecode() +{ + int descriptor; + int selectorIndex; + int methodClass; + + /* "source" + descriptor <- self fetchByte. + argumentCount <- self extractBits: 8 to: 10 + of: descriptor. + selectorIndex <- self extractBits: 11 to: 15 + of: descriptor. + messageSelector <- self literal: selectorIndex. + methodClass <- self methodClassOf: method. + self sendSelectorToClass: (self superclassOf: methodClass) + */ + + descriptor = fetchByte(); + argumentCount = extractBits_to_of(8, 10, descriptor); + selectorIndex = extractBits_to_of(11, 15, descriptor); + messageSelector = literal(selectorIndex); + methodClass = methodClassOf(method); + sendSelectorToClass(superclassOf(methodClass)); +} + + +// singleExtendedSendBytecode +void Interpreter::singleExtendedSendBytecode() +{ + int descriptor; + int selectorIndex; + + /* "source" + descriptor <- self fetchByte. + selectorIndex <- self extractBits: 11 to: 15 + of: descriptor. + self sendSelector: (self literal: selectorIndex) + argumentCount: (self extractBits: 8 to: 10 + of: descriptor) + */ + descriptor = fetchByte(); + selectorIndex = extractBits_to_of(11, 15, descriptor); + sendSelector_argumentCount(literal(selectorIndex), extractBits_to_of(8, 10, descriptor)); +} + + +// extendedSendBytecode +void Interpreter::extendedSendBytecode() +{ + /* "source" + currentBytecode = 131 ifTrue: [^self singleExtendedSendBytecode]. + currentBytecode = 132 ifTrue: [^self doubleExtendedSendBytecode]. + currentBytecode = 133 ifTrue: [^self singleExtendedSuperBytecode]. + currentBytecode = 134 ifTrue: [^self doubleExtendedSuperBytecode] + */ + + switch (currentBytecode) + { + case 131: singleExtendedSendBytecode(); break; + case 132: doubleExtendedSendBytecode(); break; + case 133: singleExtendedSuperBytecode(); break; + case 134: doubleExtendedSuperBytecode(); break; + } +} + + +// executeNewMethod +void Interpreter::executeNewMethod() +{ + /* "source" + self primitiveResponse + ifFalse: [self activateNewMethod] + */ + if (!primitiveResponse()) + activateNewMethod(); +} + + +// dispatchOnThisBytecode +void Interpreter::dispatchOnThisBytecode() +{ + /* "source" + (currentBytecode between: 0 and: 119) ifTrue: [^self stackBytecode]. + (currentBytecode between: 120 and: 127) ifTrue: [^self returnBytecode]. + (currentBytecode between: 128 and: 130) ifTrue: [^self stackBytecode]. + (currentBytecode between: 131 and: 134 ifTrue: [^self sendBytecode]. + (currentBytecode between: 135 and: 137) ifTrue: [^self stackBytecode]. + (currentBytecode between: 144 and: 175) ifTrue: [^self jumpBytecode]. + (currentBytecode between: 176 and: 255) ifTrue: [^self sendBytecode] + */ + if (between_and(currentBytecode, 0, 119)) { stackBytecode(); } + else if (between_and(currentBytecode, 120, 127)) { returnBytecode(); } + else if (between_and(currentBytecode, 128, 130)) { stackBytecode(); } + else if (between_and(currentBytecode, 131, 134)) { sendBytecode(); } + else if (between_and(currentBytecode, 135, 137)) { stackBytecode(); } + else if (between_and(currentBytecode, 144, 175)) { jumpBytecode(); } + else if (between_and(currentBytecode, 176, 255)) { sendBytecode(); } +} + + +// fetchByte +int Interpreter::fetchByte() +{ + int byte; + + /* "source" + byte <- memory fetchByte: instructionPointer + ofObject: method. + instructionPointer <- instructionPointer + 1. + ^byte + */ + + byte = memory.fetchByte_ofObject(instructionPointer, method); + instructionPointer = instructionPointer + 1; + return byte; +} + + +// cycle +void Interpreter::cycle() +{ + /* "source" + self checkProcessSwitch. + currentBytecode <- self fetchByte. + self dispatchOnThisBytecode + */ + + checkProcessSwitch(); + currentBytecode = fetchByte(); + dispatchOnThisBytecode(); +} + + + +// interpret +void Interpreter::interpret() +{ + /* "source" + [true] whileTrue: [self cycle] + */ + for(;;) + { + cycle(); + } +} + + +// primitiveIndexOf: +int Interpreter::primitiveIndexOf(int methodPointer) +{ + int flagValue; + + /* "source" + flagValue <- self flagValueOf: methodPointer. + flagValue=7 + ifTrue: [^self extractBits: 7 to: 14 + of: (self headerExtensionOf: methodPointer)] + ifFalse: [^0] + */ + flagValue = flagValueOf(methodPointer); + if (flagValue==7) + { + return extractBits_to_of(7, 14, headerExtensionOf(methodPointer)); + } + return 0; +} + + +// argumentCountOf: +int Interpreter::argumentCountOf(int methodPointer) +{ + int flagValue; + + /* "source" + flagValue <- self flagValueOf: methodPointer. + flagValue < 5 + ifTrue: [^flagValue]. + flagValue < 7 + ifTrue: [^0] + ifFalse: [^self extractBits: 2 to: 6 + of: (self headerExtensionOf: methodPointer)] + */ + flagValue = flagValueOf(methodPointer); + if (flagValue < 5) + return flagValue; + if (flagValue < 7) + return 0; + else + return extractBits_to_of(2, 6, headerExtensionOf(methodPointer)); +} + +// methodClassOf: +int Interpreter::methodClassOf(int methodPointer) +{ + int literalCount; + int association; + + /* "source" + literalCount <- self literalCountOf: methodPointer. + association <- self literal: literalCount - 1 + ofMethod: methodPointer. + ^memory fetchPointer: ValueIndex + ofObject: association + */ + literalCount = literalCountOf(methodPointer); + association = literal_ofMethod(literalCount - 1, methodPointer); + return memory.fetchPointer_ofObject(ValueIndex, association); +} + + +// storeAndPopReceiverVariableBytecode +void Interpreter::storeAndPopReceiverVariableBytecode() +{ + int variableIndex; + + /* "source" + variableIndex <- self extractBits: 13 to: 15 + of: currentBytecode. + memory storePointer: variableIndex + ofObject: receiver + withValue: self popStack + */ + + variableIndex = extractBits_to_of(13, 15, currentBytecode); + memory.storePointer_ofObject_withValue(variableIndex, receiver, popStack()); +} + + +// extendedStoreBytecode +void Interpreter::extendedStoreBytecode() +{ + int descriptor; + int variableType; + int variableIndex; + int association; + + /* "source" + descriptor <- self fetchByte. + variableType <- self extractBits: 8 to: 9 + of: descriptor. + variableIndex <- self extractBits: 10 to: 15 + of: descriptor. + variableType = 0 ifTrue: + [^memory storePointer: variableIndex + ofObject: receiver + withValue: self stackTop]. + variableType = 1 ifTrue: + [^memory storePointer: variableIndex + TempFrameStart + ofObject: homeContext + withValue: self stackTop]. + variableType = 2 ifTrue: + [^self error: 'illegal store']. + variableType = 3 ifTrue: + [association <- self literal: variableIndex. + ^memory storePointer: ValueIndex + ofObject: association + withValue: self stackTop] + */ + + descriptor = fetchByte(); + variableType = extractBits_to_of(8, 9, descriptor); + variableIndex = extractBits_to_of(10, 15, descriptor); + switch (variableType) + { + case 0: memory.storePointer_ofObject_withValue(variableIndex, receiver, stackTop()); break; + case 1: memory.storePointer_ofObject_withValue(variableIndex + TempFrameStart, homeContext, stackTop()); break; + case 2: error("illegal store"); break; + case 3: + association = literal(variableIndex); + memory.storePointer_ofObject_withValue(ValueIndex, association, stackTop()); + break; + } +} + + +// pushLiteralConstantBytecode +void Interpreter::pushLiteralConstantBytecode() +{ + int fieldIndex; + + /* "source" + fieldIndex <- self extractBits: 11 to: 15 + of: currentBytecode. + self pushLiteralConstant: fieldIndex + */ + + fieldIndex = extractBits_to_of(11, 15, currentBytecode); + pushLiteralConstant(fieldIndex); +} + + +// storeAndPopTemporaryVariableBytecode +void Interpreter::storeAndPopTemporaryVariableBytecode() +{ + int variableIndex; + + /* "source" + variableIndex <- self extractBits: 13 to: 15 + of: currentBytecode. + memory storePointer: variableIndex + TempFrameStart + ofObject: homeContext + withValue: self popStack + */ + variableIndex = extractBits_to_of(13, 15, currentBytecode); + memory.storePointer_ofObject_withValue(variableIndex + TempFrameStart, + homeContext, + popStack()); +} + + +// extendedStoreAndPopBytecode +void Interpreter::extendedStoreAndPopBytecode() +{ + /* "source" + self extendedStoreBytecode. + self popStackBytecode + */ + + extendedStoreBytecode(); + popStackBytecode(); +} + + +// stackBytecode +void Interpreter::stackBytecode() +{ + /* "source" + (currentBytecode between: 0 and: 15) + ifTrue: [^self pushReceiverVariableBytecode]. + (currentBytecode between: 16 and: 31) + ifTrue: [^self pushTemporaryVariableBytecode]. + (currentBytecode between: 32 and: 63) + ifTrue: [^self pushLiteralConstantBytecode]. + (currentBytecode between: 64 and: 95) + ifTrue: [^self pushLiteralVariableBytecode]. + (currentBytecode between: 96 and: 103) + ifTrue: [^self storeAndPopReceiverVariableBytecode]. + (currentBytecode between: 104 and: 111) + ifTrue: [^self storeAndPopTemporaryVariableBytecode]. + currentBytecode = 112 + ifTrue: [^self pushReceiverBytecode]. + currentBytecode between: 113 and: 119) + ifTrue: [^self pushConstantBytecode]. + currentBytecode = 128 + ifTrue: [^self extendedPushBytecode]. + currentBytecode = 129 + ifTrue: [^self extendedStoreBytecode]. + currentBytecode = 130 + ifTrue: [^self extendedStoreAndPopBytecode]. + currentBytecode = 135 + ifTrue: [^self popStackBytecode]. + currentBytecode = 136 + ifTrue: [^self duplicateTopBytecode]. + currentBytecode = 137 + ifTrue: [^self pushActiveContextBytecode] + */ + + if (between_and(currentBytecode, 0, 15)) pushReceiverVariableBytecode(); + else if (between_and(currentBytecode, 16, 31)) pushTemporaryVariableBytecode(); + else if (between_and(currentBytecode, 32, 63)) pushLiteralConstantBytecode(); + else if (between_and(currentBytecode, 64, 95)) pushLiteralVariableBytecode(); + else if (between_and(currentBytecode, 96, 103)) storeAndPopReceiverVariableBytecode(); + else if (between_and(currentBytecode, 104 ,111)) storeAndPopTemporaryVariableBytecode(); + else if (currentBytecode == 112) pushReceiverBytecode(); + else if (between_and(currentBytecode, 113, 119)) pushConstantBytecode(); + else if (currentBytecode == 128) extendedPushBytecode(); + else if (currentBytecode == 129) extendedStoreBytecode(); + else if (currentBytecode == 130) extendedStoreAndPopBytecode(); + else if (currentBytecode == 135) popStackBytecode(); + else if (currentBytecode == 136) duplicateTopBytecode(); + else if (currentBytecode == 137) pushActiveContextBytecode(); +} + + +// extendedPushBytecode +void Interpreter::extendedPushBytecode() +{ + int descriptor; + int variableType; + int variableIndex; + + /* "source" + descriptor <- self fetchByte. + variableType <- self extractBits: 8 to: 9 + of: descriptor. + variableIndex <- self extractBits: 10 to: 15 + of: descriptor. + variableType=0 ifTrue: [^self pushReceiverVariable: variableIndex]. + variableType=1 ifTrue: [^self pushTemporaryVariable: variableIndex]. + variableType=2 ifTrue: [^self pushLiteralConstant: variableIndex]. + variableType=3 ifTrue: [^self pushLiteralVariable: variableIndex] + */ + descriptor = fetchByte(); + variableType = extractBits_to_of(8, 9, descriptor); + variableIndex = extractBits_to_of(10, 15, descriptor); + switch (variableType) + { + case 0: pushReceiverVariable(variableIndex); break; + case 1: pushTemporaryVariable(variableIndex); break; + case 2: pushLiteralConstant(variableIndex); break; + case 3: pushLiteralVariable(variableIndex); break; + } +} + +// pushConstantBytecode +void Interpreter::pushConstantBytecode() +{ + /* "source" + currentBytecode = 113 ifTrue: [^self push: TruePointer]. + currentBytecode = 114 ifTrue: [^self push: FalsePointer]. + currentBytecode = 115 ifTrue: [^self push: NilPointer]. + currentBytecode = 116 ifTrue: [^self push: MinusOnePointer]. + currentBytecode = 117 ifTrue: [^self push: ZeroPointer]. + currentBytecode = 118 ifTrue: [^self push: OnePointer]. + currentBytecode = 119 ifTrue: [^self push: TwoPointer] + */ + switch (currentBytecode) + { + case 113: push(TruePointer); break; + case 114: push(FalsePointer); break; + case 115: push(NilPointer); break; + case 116: push(MinusOnePointer); break; + case 117: push(ZeroPointer); break; + case 118: push(OnePointer); break; + case 119: push(TwoPointer); break; + } +} + + +// jumpIf:by: +void Interpreter::jumpIf_by(int condition, int offset) +{ + int boolean; + + /* "source" + boolean <- self popStack. + boolean = condition + ifTrue: [self jump: offset] + ifFalse: [(boolean=TruePointer) | (boolean=FalsePointer) + ifFalse: [self unPop: 1. + self sendMustBeBoolean]] + */ + + boolean = popStack(); + if (boolean == condition) + { + jump(offset); + } + else + { + if (!(boolean == TruePointer || boolean == FalsePointer)) + { + unPop(1); + sendMustBeBoolean(); + } + } +} + + +// longConditionalJump +void Interpreter::longConditionalJump() +{ + int offset; + + /* "source" + offset <- self extractBits: 14 to: 15 + of: currentBytecode. + offset <- offset * 256 + self fetchByte. + (currentBytecode between: 168 and: 171) + ifTrue: [^self jumpIf: TruePointer + by: offset]. + (currentBytecode between: 172 and: 175) + ifTrue: (^self jumpIf: FalsePointer + by: offset] + */ + offset = extractBits_to_of(14, 15, currentBytecode); + offset = offset * 256 + fetchByte(); + if (between_and(currentBytecode, 168, 171)) + { + jumpIf_by(TruePointer, offset); + } + else if (between_and(currentBytecode, 172, 175)) + { + jumpIf_by(FalsePointer, offset); + } +} + +// jumpBytecode +void Interpreter::jumpBytecode() +{ + /* "source" + (currentBytecode between: 144 and: 151) + ifTrue: [^self shortUnconditionalJump]. + (currentBytecode between: 152 and: 159) + ifTrue: [^self shortConditionalJump]. + (currentBytecode between: 160 and: 167) + ifTrue: [^self longUnconditionalJump]. + (currentBytecode between: 168 and: 175) + ifTrue: [^self longConditionalJump] + */ + + if (between_and( currentBytecode, 144, 151)) shortUnconditionalJump(); + else if (between_and( currentBytecode, 152, 159)) shortConditionalJump(); + else if (between_and( currentBytecode, 160, 167)) longUnconditionalJump(); + else if (between_and( currentBytecode, 168, 175)) longConditionalJump(); +} + +// storeInteger:ofObject:withValue: +void Interpreter::storeInteger_ofObject_withValue(int fieldIndex, int objectPointer, int integerValue) +{ + int integerPointer; + + /* "source" + (memory isIntegerValue: integerValue) + ifTrue: [integerPointer <- memory integerObjectOf: integerValue. + memory storePointer: fieldIndex + ofObject: objectPointer + withValue: integerPointer] + ifFalse: [^self primitiveFail] + */ + if (memory.isIntegerValue(integerValue)) + { + integerPointer = memory.integerObjectOf(integerValue); + memory.storePointer_ofObject_withValue(fieldIndex, objectPointer, integerPointer); + } + else + primitiveFail(); +} + + +// transfer:fromIndex:ofObject:toIndex:ofObject: +void Interpreter::transfer_fromIndex_ofObject_toIndex_ofObject( + int count, + int firstFrom, + int fromOop, + int firstTo, + int toOop + ) +{ + int fromIndex; + int toIndex; + int lastFrom; + int oop; + + /* "source" + fromIndex <- firstFrom. + lastFrom <- firstFrom + count. + toIndex <- firstTo. + [fromIndex < lastFrom] whileTrue: + [oop <- memory fetchPointer: fromIndex + ofObject: fromOop. + memory storePointer: toIndex + ofObject: toOop + withValue: oop. + memory storePointer: fromIndex + ofObject: fromOop + withValue: NilPointer. + fromIndex <- fromIndex + 1. + toIndex <- toIndex + 1] + */ + + fromIndex = firstFrom; + lastFrom = firstFrom + count; + toIndex = firstTo; + while (fromIndex < lastFrom) + { + oop = memory.fetchPointer_ofObject(fromIndex, fromOop); + memory.storePointer_ofObject_withValue(toIndex, toOop, oop); + memory.storePointer_ofObject_withValue(fromIndex, fromOop, NilPointer); + fromIndex = fromIndex + 1; + toIndex = toIndex + 1; + } +} + +// fetchInteger:ofObject: +int Interpreter::fetchInteger_ofObject(int fieldIndex, int objectPointer) +{ + int integerPointer; + + /* "source" + integerPointer <- memory fetchPointer: fieldIndex + ofObject: objectPointer. + (memory isIntegerObject: integerPointer) + ifTrue: [^memory integerValueOf: integerPointer] + ifFalse: [^self primitiveFail] + */ + integerPointer = memory.fetchPointer_ofObject(fieldIndex, objectPointer); + if (memory.isIntegerObject(integerPointer)) + return memory.integerValueOf(integerPointer); + else + return primitiveFail(); +} + +// primitiveNewMethod +void Interpreter::primitiveNewMethod() +{ + int header; + int bytecodeCount; + int cls; + int size; + + /* "source" + header <- self popStack. + bytecodeCount <- self popInteger. + class <- self popStack. + size <- (self literalCountOfHeader: header) + 1 * 2 + bytecodeCount. + "ERROR: dbanay - need tp initialize literal frame" + self push: (memory instantiateClass: class + withBytes: size) + */ + + header = popStack(); + bytecodeCount = popInteger(); + cls = popStack(); + int literalCount = literalCountOfHeader(header); + size = (literalCount + 1) * 2 + bytecodeCount; + int newMethod = memory.instantiateClass_withBytes(cls, size); + for(int i = 0; i < literalCount; i++) + { + memory.storeWord_ofObject_withValue(LiteralStart + i, newMethod, NilPointer); + } + // Note: using storeWord vs storePointer because it memory with + // initialized with zeros and this break ref counting + memory.storeWord_ofObject_withValue(HeaderIndex, newMethod, header); + push(newMethod); +} + + +// primitiveAsOop +void Interpreter::primitiveAsOop() +{ + int thisReceiver; + + /* "source" + thisReceiver <- self popStack. + self success: (memory isIntegerObject: thisReceiver) == false. + self success + ifTrue: [self push: (thisReceiver bitOr: 1)] + ifFalse: [self unPop: 1] + */ + thisReceiver = popStack(); + success(memory.isIntegerObject(thisReceiver) == false); + if (success()) + push(thisReceiver | 1); + else + unPop(1); +} + + +// primitiveSomeInstance +void Interpreter::primitiveSomeInstance() +{ + int cls; + int instance; + + + /* "source" + class <- self popStack. + "ERROR: instancesOf not defined in G&R, body of + method has been changed completely from: + (memory instancesOf: class) + ifTrue: [self push: (memory initialInstanceOf: class)] + ifFalse: [self primitiveFail] + to:" + + instance <- memory initialInstanceOf: class. + instance = NilPointer + ifTrue: [self primitiveFail] + ifFalse: [self push: instance] + */ + + cls = popStack(); + instance = memory.initialInstanceOf(cls); + if (instance == NilPointer) + primitiveFail(); + else + push(instance); +} + + +// primitiveObjectAt +void Interpreter::primitiveObjectAt() +{ + int thisReceiver; + int index; + + /* "source" + index <- self popInteger. + thisReceiver <- self popStack. + self success: index > 0. + self success: index <= (self objectPointerCountOf: thisReceiver). + self success + ifTrue: [self push: (memory fetchPointer: index - 1 + ofObject: thisReceiver)] + ifFalse: [self unPop: 2] + */ + index = popInteger(); + thisReceiver = popStack(); + success(index > 0); + success(index <= objectPointerCountOf(thisReceiver)); + if (success()) + { + push(memory.fetchPointer_ofObject(index - 1, thisReceiver)); + } + else + unPop(2); + +} + + +// primitiveNextInstance +void Interpreter::primitiveNextInstance() +{ + int object; + int instance; + + /* "source" + object <- self popStack. + "ERROR: isLastInstance: not defined in G&R, body of + method has been changed completely from: + (memory isLastInstance: object) + ifTrue: [self primitiveFail] + ifFalse: [self push: (memory instanceAfter: object)] + to:" + + instance <- memory instanceAfter: object. + instance = NilPointer + ifTrue: [self primitiveFail] + ifFalse: [self push: instance] + */ + object = popStack(); + instance = memory.instanceAfter(object); + if (instance == NilPointer) + primitiveFail(); + else + push(instance); +} + + +// primitiveNew +void Interpreter::primitiveNew() +{ + int cls; + int size; + + /* "source" + class <- self popStack. + size <- self fixedFieldsOf: class. + self success: (self isIndexable: class) == false. + self success + ifTrue: [(self isPointers: class) + ifTrue: [self push: (memory instantiateClass: class + withPointers: size)] + ifFalse: [self push: (memory instantiateClass: class + withWords: size)]] + ifFalse: [self unPop: 1] + */ + + cls = popStack(); + size = fixedFieldsOf(cls); + success(isIndexable(cls) == false); + if (success()) + { + if (isPointers(cls)) + { + push(memory.instantiateClass_withPointers(cls, size)); + } + else + { + push(memory.instantiateClass_withWords(cls, size)); + } + } + else + unPop(1); +} + + +// primitiveAsObject +void Interpreter::primitiveAsObject() +{ + int thisReceiver; + int newOop; + + /* "source" + thisReceiver <- self popStack. + newOop <- thisReceiver bitAnd: 16rFFFE. + "ERROR: hasObject not defined" + self success: (memory hasObject: newOop). + self success + ifTrue: [self push: newOop] + ifFalse: [self unPop: 1] + */ + + thisReceiver = popStack(); + newOop = thisReceiver & 0xFFFE; + success(memory.hasObject(newOop)); + if (success()) + push(newOop); + else + unPop(1); + +} + + +// primitiveNewWithArg +void Interpreter::primitiveNewWithArg() +{ + int size; + int cls; + + /* "source" + size <- self positive16BitValueOf: self popStack. + self success: size <= 65533. "dbanay: ERROR check max size" + class <- self popStack. + self success: (self isIndexable: class). + self success + ifTrue: [size <- size + (self fixedFieldsOf: class). + (self isPointers: class) + ifTrue: [self push: (memory instantiateClass: class + withPointers: size)] + ifFalse: [(self isWords: class) + ifTrue: [self push: (memory + instantiateClass: class + withWords: size)] + ifFalse: [self push: (memory + instantiateClass: class + withBytes: size)]]] + ifFalse: [self unPop: 2] + */ + + size = positive16BitValueOf(popStack()); + success(size <= 65533); + + cls = popStack(); + success(isIndexable(cls)); + if (success()) + { + size = size + fixedFieldsOf(cls); + if (isPointers(cls)) + { + push(memory.instantiateClass_withPointers(cls, size)); + } + else + { + if (isWords(cls)) + { + push(memory.instantiateClass_withWords(cls, size)); + } + else + { + push(memory.instantiateClass_withBytes(cls, size)); + } + } + } + else + unPop(2); +} + + +// primitiveInstVarAtPut +void Interpreter::primitiveInstVarAtPut() +{ + int thisReceiver; + int index; + int newValue; + + /* "source" + "ERROR: realValue is not used in the method" + newValue <- self popStack. + index <- self popInteger. + thisReceiver <- self popStack. + self checkInstanceVariableBoundsOf: index + in: thisReceiver. + self success + ifTrue: [self subscript: thisReceiver + with: index + storing: newValue]. + self success + ifTrue: [self push: newValue] + ifFalse: [self unPop: 3] + */ + + newValue = popStack(); + index = popInteger(); + thisReceiver = popStack(); + checkIndexableBoundsOf_in(index, thisReceiver); + if (success()) + { + subscript_with_storing(thisReceiver, index, newValue); + } + if (success()) + push(newValue); + else + unPop(3); +} + + +// primitiveObjectAtPut +void Interpreter::primitiveObjectAtPut() +{ + int thisReceiver; + int index; + int newValue; + + /* "source" + newValue <- self popStack. + index <- self popInteger. + thisReceiver <- self popStack. + self success: index > 0. + self success: index <= (self objectPointerCountOf: thisReceiver). + self success + ifTrue: [memory storePointer: index - 1 + ofObject: thisReceiver + withValue: newValue. + self push: newValue] + ifFalse: [self unPop: 3] + */ + + newValue = popStack(); + index = popInteger(); + thisReceiver = popStack(); + success(index > 0); + success(index <= objectPointerCountOf(thisReceiver)); + if (success()) + { + memory.storePointer_ofObject_withValue(index - 1, thisReceiver, newValue); + push(newValue); + } + else + unPop(3); + +} + + +// primitiveInstVarAt +void Interpreter::primitiveInstVarAt() +{ + int thisReceiver; + int index; + int value = 0; + + /* "source" + index <- self popInteger. + thisReceiver <- self popStack. + self checkInstanceVariableBoundsOf: index + in: thisReceiver. + self success + ifTrue: [value <- self subscript: thisReceiver + with: index]. + self success + ifTrue: [self push: value] + ifFalse: [self unPop: 2] + */ + + index = popInteger(); + thisReceiver = popStack(); + checkInstanceVariableBoundsOf_in(index, thisReceiver); + if (success()) + value = subscript_with(thisReceiver, index); + if (success()) + push(value); + else + unPop(2); + +} + + +// primitiveBecome +void Interpreter::primitiveBecome() +{ + int thisReceiver; + int otherPointer; + + /* "source" + otherPointer <- self popStack. + thisReceiver <- self popStack. + self success: (memory isIntegerObject: otherPointer) not. + self success: (memory isIntegerObject: thisReceiver) not. + self success + ifTrue: [memory swapPointersOf: thisReceiver and: otherPointer. + self push: thisReceiver] + ifFalse: [self unPop: 2] + */ + otherPointer = popStack(); + thisReceiver = popStack(); + success(!memory.isIntegerObject(otherPointer)); + success(!memory.isIntegerObject(thisReceiver)); + if (success()) + { + memory.swapPointersOf_and(thisReceiver, otherPointer); + push(thisReceiver); + } + else + unPop(2); +} + + +// dispatchStorageManagementPrimitives +void Interpreter::dispatchStorageManagementPrimitives() +{ + /* "source" + primitiveIndex = 68 ifTrue: [^self primitiveObjectAt]. + primitiveIndex = 69 ifTrue: [^self primitiveObjectAtPut]. + primitiveIndex = 70 ifTrue: [^self primitiveNew]. + primitiveIndex = 71 ifTrue: [^self primitiveNewWithArg]. + primitiveIndex = 72 ifTrue: [^self primitiveBecome]. + primitiveIndex = 73 ifTrue: [^self primitiveInstVarAt]. + primitiveIndex = 74 ifTrue: [^self primitiveInstVarAtPut]. + primitiveIndex = 75 ifTrue: [^self primitiveAsOop]. + primitiveIndex = 76 ifTrue: [^self primitiveAsObject]. + primitiveIndex = 77 ifTrue: [^self primitiveSomeInstance]. + primitiveIndex = 78 ifTrue: [^self primitiveNextInstance]. + primitiveIndex = 79 ifTrue: [^self primitiveNewMethod] + */ + switch (primitiveIndex) + { + case 68: primitiveObjectAt(); break; + case 69: primitiveObjectAtPut(); break; + case 70: primitiveNew(); break; + case 71: primitiveNewWithArg(); break; + case 72: primitiveBecome(); break; + case 73: primitiveInstVarAt(); break; + case 74: primitiveInstVarAtPut(); break; + case 75: primitiveAsOop(); break; + case 76: primitiveAsObject(); break; + case 77: primitiveSomeInstance(); break; + case 78: primitiveNextInstance(); break; + case 79: primitiveNewMethod(); break; + } +} + +void Interpreter::pushFloat(float f) +{ + std::uint32_t uint32 = *(std::uint32_t *) &f; + int objectPointer = memory.instantiateClass_withWords(ClassFloatPointer, 2); + memory.storeWord_ofObject_withValue(0, objectPointer, uint32 & 0xffff); + memory.storeWord_ofObject_withValue(1, objectPointer, uint32 >> 16); + + push(objectPointer); +} + +float Interpreter::popFloat() +{ + int objectPointer = popStack(); + success(memory.fetchClassOf(objectPointer) == ClassFloatPointer); + if (success()) + { + return extractFloat(objectPointer); + } + + return std::nanf(""); +} + + diff --git a/vm/interpreter.h b/vm/interpreter.h @@ -0,0 +1,1453 @@ +// +// interpreter.h +// Smalltalk-80 +// +// Created by Dan Banay on 3/31/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +#pragma once +#include <string> +#include "objmemory.h" +#include "filesystem.h" +#include "hal.h" + +// Add some helpful methods if defined +//#define DEBUGGING_SUPPORT + +// implement optional primitiveNext +#define IMPLEMENT_PRIMITIVE_NEXT + +// implement optional primitiveAtEnd +#define IMPLEMENT_PRIMITIVE_AT_END + +// implement optional primitiveNextPut +#define IMPLEMENT_PRIMITIVE_NEXT_PUT + +// implement optional primitiveScanCharacters +#define IMPLEMENT_PRIMITIVE_SCANCHARS + +class Interpreter +#ifdef GC_MARK_SWEEP + : IGCNotification +#endif +{ +public: + + Interpreter(IHardwareAbstractionLayer *halInterface, IFileSystem *fileSystemInterface); + + bool init(); + + + // cycle + void cycle(); + + inline void checkLowMemoryConditions() + { + checkLowMemory = true; + } + + // asynchronousSignal: + void asynchronousSignal(int aSemaphore); + + + // Debug/testing + int lastBytecode() { return currentBytecode; } + + + int getDisplayBits(int width, int height); + + // Allow read-only access to display form data + inline int fetchWord_ofDislayBits(int wordIndex, int displayBits) + { + return memory.fetchWord_ofObject(wordIndex, displayBits); + } + + + +private: + + void error(const char *message); + + // --- ArrayStrmPrims --- + + // primitiveAtEnd + void primitiveAtEnd(); + + // checkIndexableBoundsOf:in: + void checkIndexableBoundsOf_in(int index, int array); + + // primitiveNextPut + void primitiveNextPut(); + + // lengthOf: + int lengthOf(int array); + + // primitiveNext + void primitiveNext(); + + // dispatchSubscriptAndStreamPrimitives + void dispatchSubscriptAndStreamPrimitives(); + + // primitiveStringAt + void primitiveStringAt(); + + // primitiveAt + void primitiveAt(); + + // primitiveSize + void primitiveSize(); + + // primitiveStringAtPut + void primitiveStringAtPut(); + + // subscript:with: + int subscript_with(int array, int index); + + // primitiveAtPut + void primitiveAtPut(); + + // subscript:with:storing: + void subscript_with_storing(int array, int index, int value); + + + // --- Contexts --- + + // storeContextRegisters + void storeContextRegisters(); + + // unPop: + inline void unPop(int number) + { + /* "source" + stackPointer <- stackPointer + number + */ + + stackPointer = stackPointer + number; + } + + // isBlockContext: + bool isBlockContext(int contextPointer); + + // push: + inline void push(int object) + { + /* "source" + stackPointer <- stackPointer + 1. + memory storePointer: stackPointer + ofObject: activeContext + withValue: object + */ + + stackPointer = stackPointer + 1; + memory.storePointer_ofObject_withValue(stackPointer, activeContext, object); + + } + + // instructionPointerOfContext: + inline int instructionPointerOfContext(int contextPointer) + { + /* "source" + ^self fetchInteger: InstructionPointerIndex + ofObject: contextPointer + */ + + return fetchInteger_ofObject(InstructionPointerIndex, contextPointer); + } + + // newActiveContext: + void newActiveContext(int aContext); + + // argumentCountOfBlock: + inline int argumentCountOfBlock(int blockPointer) + { + /* "source" + ^self fetchInteger: BlockArgumentCountIndex + ofObject: blockPointer + */ + + return fetchInteger_ofObject(BlockArgumentCountIndex, blockPointer); + } + + // literal: + inline int literal(int offset) + { + /* "source" + ^self literal: offset + ofMethod: method + */ + + return literal_ofMethod(offset, method); + } + + // sender + inline int sender() + { + /* "source" + ^memory fetchPointer: SenderIndex + ofObject: homeContext + */ + + return memory.fetchPointer_ofObject(SenderIndex, homeContext); + } + + // temporary: + inline int temporary(int offset) + { + /* "source" + ^memory fetchPointer: offset + TempFrameStart + ofObject: homeContext + */ + + return memory.fetchPointer_ofObject(offset + TempFrameStart, homeContext); + } + + // caller + inline int caller() + { + /* "source" + ^memory fetchPointer: SenderIndex + ofObject: activeContext + */ + return memory.fetchPointer_ofObject(SenderIndex, activeContext); + } + + // pop: + inline void pop(int number) + { + /* "source" + stackPointer <- stackPointer - number + */ + + stackPointer = stackPointer - number; + } + + // storeStackPointerValue:inContext: + inline void storeStackPointerValue_inContext(int value, int contextPointer) + { + /* "source" + self storeInteger: StackPointerIndex + ofObject: contextPointer + withValue: value + */ + + storeInteger_ofObject_withValue(StackPointerIndex, contextPointer, value); + } + + // stackValue: + inline int stackValue(int offset) + { + /* "source" + ^memory fetchPointer: stackPointer - offset + ofObject: activeContext + */ + return memory.fetchPointer_ofObject(stackPointer - offset, activeContext); + } + + // stackTop + inline int stackTop() + { + /* "source" + ^memory fetchPointer: stackPointer + ofObject: activeContext + */ + + return memory.fetchPointer_ofObject(stackPointer, activeContext); + } + + // popStack + inline int popStack() + { + int stackTop; + + /* "source" + stackTop <- memory fetchPointer: stackPointer + ofObject: activeContext. + stackPointer <- stackPointer - 1. + ^stackTop + */ + + stackTop = memory.fetchPointer_ofObject(stackPointer, activeContext); + stackPointer = stackPointer - 1; + return stackTop; + } + + // fetchContextRegisters + void fetchContextRegisters(); + + // storeInstructionPointerValue:inContext: + inline void storeInstructionPointerValue_inContext(int value, int contextPointer) + { + /* "source" + self storeInteger: InstructionPointerIndex + ofObject: contextPointer + withValue: value + */ + + storeInteger_ofObject_withValue(InstructionPointerIndex, contextPointer, value); + } + + // stackPointerOfContext: + inline int stackPointerOfContext(int contextPointer) + { + /* "source" + ^self fetchInteger: StackPointerIndex + ofObject: contextPointer + */ + + return fetchInteger_ofObject(StackPointerIndex, contextPointer); + } + + + // --- IOPrims --- + + // dispatchInputOutputPrimitives + void dispatchInputOutputPrimitives(); + + void primitiveMousePoint(); + void primitiveCursorLocPut(); + void primitiveCursorLink(); + void primitiveInputSemaphore(); + void primitiveSampleInterval(); + void primitiveInputWord(); + void updateDisplay(int destForm, int updatedHeight, int updatedWidth, int updatedX, int updatedY); + + void primitiveCopyBits(); + void primitiveSnapshot(); + void primitiveTimeWordsInto(); + void primitiveTickWordsInto(); + void primitiveSignalAtTick(); + void primitiveBeCursor(); + void primitiveBeDisplay(); + void primitiveScanCharacters(); + void primitiveDrawLoop(); + void primitiveStringReplace(); + + + // --- Classes --- + + // lookupMethodInDictionary: + bool lookupMethodInDictionary(int dictionary); + + // isPointers: + inline bool isPointers(int classPointer) + { + int pointersFlag; + + /* "source" + pointersFlag <- self extractBits: 0 to: 0 + of: (self instanceSpecificationOf: classPointer). + ^pointersFlag = 1 + */ + pointersFlag = extractBits_to_of(0, 0, instanceSpecificationOf(classPointer)); + return pointersFlag == 1; + } + + // superclassOf: + inline int superclassOf(int classPointer) + { + /* "source" + ^memory fetchPointer: SuperclassIndex + ofObject: classPointer + */ + return memory.fetchPointer_ofObject(SuperclassIndex, classPointer); + } + + // fixedFieldsOf: + inline int fixedFieldsOf(int classPointer) + { + /* "source" + ^self extractBits: 4 to: 14 + of: (self instanceSpecificationOf: classPointer) + */ + + return extractBits_to_of(4, 14, instanceSpecificationOf(classPointer)); + } + + // isWords: + inline bool isWords(int classPointer) + { + int wordsFlag; + + /* "source" + wordsFlag <- self extractBits: 1 to: 1 + of: (self instanceSpecificationOf: classPointer). + ^wordsFlag = 1 + */ + + wordsFlag = extractBits_to_of(1, 1, instanceSpecificationOf(classPointer)); + return wordsFlag == 1; + } + + // hash: + inline int hash(int objectPointer) + { + /* "source" + ^objectPointer bitShift: -1 + */ + + return objectPointer >> 1; + + } + + // isIndexable: + inline bool isIndexable(int classPointer) + { + int indexableFlag; + + /* "source" + indexableFlag <- self extractBits: 2 to: 2 + of: (self instanceSpecificationOf: classPointer). + ^indexableFlag = 1 + */ + + indexableFlag = extractBits_to_of(2, 2, instanceSpecificationOf(classPointer)); + return indexableFlag == 1; + } + + // instanceSpecificationOf: + inline int instanceSpecificationOf(int classPointer) + { + /* "source" + ^memory fetchPointer: InstanceSpecificationIndex + ofObject: classPointer + */ + + return memory.fetchPointer_ofObject(InstanceSpecificationIndex, classPointer); + } + + // createActualMessage + void createActualMessage(); + + // lookupMethodInClass: + bool lookupMethodInClass(int cls); + + + // --- ReturnBytecode --- + + // returnToActiveContext: + void returnToActiveContext(int aContext); + + // returnBytecode + void returnBytecode(); + + // nilContextFields + void nilContextFields(); + + // returnValue:to: + void returnValue_to(int resultPointer, int contextPointer); + + + // --- ControlPrims --- + + // synchronousSignal: + void synchronousSignal(int aSemaphore); + + // primitiveBlockCopy + void primitiveBlockCopy(); + + // primitiveResume + void primitiveResume(); + + // primitivePerformWithArgs + void primitivePerformWithArgs(); + + // wakeHighestPriority + int wakeHighestPriority(); + + // primitivePerform + void primitivePerform(); + + // primitiveValueWithArgs + void primitiveValueWithArgs(); + + // removeFirstLinkOfList: + int removeFirstLinkOfList(int aLinkedList); + + // primitiveWait + void primitiveWait(); + + // primitiveFlushCache + void primitiveFlushCache(); + + // suspendActive + void suspendActive(); + + // activeProcess + int activeProcess(); + + // schedulerPointer + inline int schedulerPointer() + { + /* "source" + ^memory fetchPointer: ValueIndex + ofObject: SchedulerAssociationPointer + */ + return memory.fetchPointer_ofObject(ValueIndex, SchedulerAssociationPointer); + } + + // addLastLink:toList: + void addLastLink_toList(int aLink, int aLinkedList); + + // dispatchControlPrimitives + void dispatchControlPrimitives(); + + // checkProcessSwitch + void checkProcessSwitch(); + + // primitiveSignal + void primitiveSignal(); + + // isEmptyList: + int isEmptyList(int aLinkedList); + + // primitiveSuspend + void primitiveSuspend(); + + // primitiveValue + void primitiveValue(); + + // firstContext + int firstContext(); + + + // transferTo: + void transferTo(int aProcess); + + // resume: + void resume(int aProcess); + + // sleep: + void sleep(int aProcess); + + + // --- SystemPrims --- + + // primitiveClass + void primitiveClass(); + + // dispatchSystemPrimitives + void dispatchSystemPrimitives(); + + // primitiveEquivalent + void primitiveEquivalent(); + + void primitiveCoreLeft(); + void primitiveQuit(); + void primitiveExitToDebugger(); + void primitiveOopsLeft(); + void primitiveSignalAtOopsLeftWordsLeft(); + + + // Vendor specific + void dispatchPrivatePrimitives(); + + // Posix filesystem primitives -- dbanay + void primitiveBeSnapshotFile(); + void primitivePosixFileOperation(); + void primitivePosixDirectoryOperation(); + void primitivePosixLastErrorOperation(); + void primitivePosixErrorStringOperation(); + + + // --- PrimitiveTest --- + + // success: + inline void success(bool successValue) + { + /* "source" + success <- successValue & success + */ + successFlag = successFlag && successValue; + } + + // dispatchPrimitives + void dispatchPrimitives(); + + // positive16BitValueOf: + int positive16BitValueOf(int integerPointer); + std::uint32_t positive32BitValueOf(int integerPointer); + + // initPrimitive + inline void initPrimitive() + { + /* "source" + success <- true + */ + + successFlag = true; + } + + // success + inline bool success() + { + /* "source" + ^success + */ + + return successFlag; + } + + // primitiveResponse + bool primitiveResponse(); + + // quickInstanceLoad + void quickInstanceLoad(); + + // arithmeticSelectorPrimitive + void arithmeticSelectorPrimitive(); + + // primitiveFail + int primitiveFail() + { + /* "source" + success <- false + */ + + successFlag = false; + return 0; // invalid oop + } + + // pushInteger: + inline void pushInteger(int integerValue) + { + /* "source" + self push: (memory integerObjectOf: integerValue) + */ + push(memory.integerObjectOf(integerValue)); + } + + // quickReturnSelf + inline void quickReturnSelf() + { + /* "source" + */ + + // self is on stack top + } + + // positive16BitIntegerFor: + int positive16BitIntegerFor(int integerValue); + int positive32BitIntegerFor(int integerValue); + + // popInteger + int popInteger(); + + // specialSelectorPrimitiveResponse + int specialSelectorPrimitiveResponse(); + + // commonSelectorPrimitive + void commonSelectorPrimitive(); + + + // --- Initialization --- + + + // initializeMethodCache + void initializeMethodCache(); + + + // --- ArithmeticPrim --- + + // primitiveMod + void primitiveMod(); + + // dispatchArithmeticPrimitives + void dispatchArithmeticPrimitives(); + + // primitiveEqual + void primitiveEqual(); + + // primitiveBitOr + void primitiveBitOr(); + + // primitiveDivide + void primitiveDivide(); + + // primitiveMultiply + void primitiveMultiply(); + + // dispatchLargeIntegerPrimitives + inline void dispatchLargeIntegerPrimitives() + { + /* "source" + self primitiveFail + */ + + primitiveFail(); + } + + // primitiveBitAnd + void primitiveBitAnd(); + + // primitiveSubtract + void primitiveSubtract(); + + // dispatchIntegerPrimitives + void dispatchIntegerPrimitives(); + + // primitiveGreaterOrEqual + void primitiveGreaterOrEqual(); + + // primitiveAdd + void primitiveAdd(); + + // primitiveNotEqual + void primitiveNotEqual(); + + // primitiveQuo + void primitiveQuo(); + + // dispatchFloatPrimitives + void dispatchFloatPrimitives(); + + void primitiveAsFloat(); + void primitiveFloatAdd(); + void primitiveFloatSubtract(); + void primitiveFloatLessThan(); + void primitiveFloatGreaterThan(); + void primitiveFloatLessOrEqual(); + void primitiveFloatGreaterOrEqual(); + void primitiveFloatEqual(); + void primitiveFloatNotEqual(); + void primitiveFloatMultiply(); + void primitiveFloatDivide(); + void primitiveTruncated(); + void primitiveFractionalPart(); + inline void primitiveExponent() + { + primitiveFail(); // optional + } + inline void primitiveTimesTwoPower() + { + primitiveFail(); // optional + } + + // primitiveLessOrEqual + void primitiveLessOrEqual(); + + // primitiveMakePoint + void primitiveMakePoint(); + + // primitiveBitXor + void primitiveBitXor(); + + // primitiveLessThan + void primitiveLessThan(); + + // primitiveBitShift + void primitiveBitShift(); + + // primitiveGreaterThan + void primitiveGreaterThan(); + + // primitiveDiv + void primitiveDiv(); + + + // --- SendBytecodes --- + + // sendSelector:argumentCount: + void sendSelector_argumentCount(int selector, int count); + + // findNewMethodInClass: + void findNewMethodInClass(int cls); + + // activateNewMethod + void activateNewMethod(); + + // sendSpecialSelectorBytecode + void sendSpecialSelectorBytecode(); + + // doubleExtendedSuperBytecode + void doubleExtendedSuperBytecode(); + + // sendBytecode + void sendBytecode(); + + // doubleExtendedSendBytecode + void doubleExtendedSendBytecode(); + + // sendSelectorToClass: + void sendSelectorToClass(int classPointer); + + // sendLiteralSelectorBytecode + void sendLiteralSelectorBytecode(); + + // singleExtendedSuperBytecode + void singleExtendedSuperBytecode(); + + // singleExtendedSendBytecode + void singleExtendedSendBytecode(); + + // extendedSendBytecode + void extendedSendBytecode(); + + // executeNewMethod + void executeNewMethod(); + + + // --- MainLoop --- + + // dispatchOnThisBytecode + void dispatchOnThisBytecode(); + + // fetchByte + int fetchByte(); + + // interpret + void interpret(); + +private: + // --- CompiledMethod --- + + // headerOf: + inline int headerOf(int methodPointer) + { + /* "source" + ^memory fetchPointer: HeaderIndex + ofObject: methodPointer + */ + + return memory.fetchPointer_ofObject(HeaderIndex, methodPointer); + } + + // literalCountOf: + inline int literalCountOf(int methodPointer) + { + /* "source" + ^self literalCountOfHeader: (self headerOf: methodPointer) + */ + + return literalCountOfHeader(headerOf(methodPointer)); + } + + // primitiveIndexOf: + int primitiveIndexOf(int methodPointer); + + // argumentCountOf: + int argumentCountOf(int methodPointer); + + // literalCountOfHeader: + inline int literalCountOfHeader(int headerPointer) + { + /* "source" + ^self extractBits: 9 to: 14 + of: headerPointer + */ + + return extractBits_to_of(9, 14, headerPointer); + } + + // fieldIndexOf: + inline int fieldIndexOf(int methodPointer) + { + /* "source" + ^self extractBits: 3 to: 7 + of: (self headerOf: methodPointer) + */ + return extractBits_to_of(3, 7, headerOf(methodPointer)); + } + + // methodClassOf: + int methodClassOf(int methodPointer); + + // literal:ofMethod: + inline int literal_ofMethod(int offset, int methodPointer) + { + /* "source" + ^memory fetchPointer: offset + LiteralStart + ofObject: methodPointer + */ + + return memory.fetchPointer_ofObject(offset + LiteralStart, methodPointer); + } + + // temporaryCountOf: + inline int temporaryCountOf(int methodPointer) + { + /* "source" + ^self extractBits: 3 to: 7 + of: (self headerOf: methodPointer) + */ + + return extractBits_to_of(3, 7, headerOf(methodPointer)); + } + + // largeContextFlagOf: + inline int largeContextFlagOf(int methodPointer) + { + /* "source" + ^self extractBits: 8 to: 8 + of: (self headerOf: methodPointer) + */ + + return extractBits_to_of(8, 8, headerOf(methodPointer)); + } + + // objectPointerCountOf: + inline int objectPointerCountOf(int methodPointer) + { + /* "source" + ^(self literalCountOf: methodPointer) + LiteralStart + */ + + return literalCountOf(methodPointer) + LiteralStart; + } + + // headerExtensionOf: + inline int headerExtensionOf(int methodPointer) + { + int literalCount; + + /* "source" + literalCount <- self literalCountOf: methodPointer. + ^self literal: literalCount - 2 + ofMethod: methodPointer + */ + + literalCount = literalCountOf(methodPointer); + return literal_ofMethod(literalCount - 2, methodPointer); + } + + // flagValueOf: + inline int flagValueOf(int methodPointer) + { + /* "source" + ^self extractBits: 0 to: 2 + of: (self headerOf: methodPointer) + */ + + return extractBits_to_of(0, 2, headerOf(methodPointer)); + } + + // initialInstructionPointerOfMethod: + inline int initialInstructionPointerOfMethod(int methodPointer) + { + /* "source" + ^((self literalCountOf: methodPointer) + LiteralStart) * 2 + 1 + */ + + return (literalCountOf(methodPointer) + LiteralStart) * 2 + 1; + } + + + // --- StackBytecodes --- + + // pushLiteralVariableBytecode + inline void pushLiteralVariableBytecode() + { + int fieldIndex; + + /* "source" + fieldIndex <- self extractBits: 11 to: 15 + of: currentBytecode. + self pushLiteralVariable: fieldIndex + */ + fieldIndex = extractBits_to_of(11, 15, currentBytecode); + pushLiteralVariable(fieldIndex); + } + + // pushLiteralConstant: + inline void pushLiteralConstant(int literalIndex) + { + /* "source" + self push: (self literal: literalIndex) + */ + + push(literal(literalIndex)); + } + + // popStackBytecode + inline void popStackBytecode() + { + /* "source" + self popStack + */ + popStack(); + } + + // storeAndPopReceiverVariableBytecode + void storeAndPopReceiverVariableBytecode(); + + // extendedStoreBytecode + void extendedStoreBytecode(); + + // pushLiteralConstantBytecode + void pushLiteralConstantBytecode(); + + // storeAndPopTemporaryVariableBytecode + void storeAndPopTemporaryVariableBytecode(); + + // extendedStoreAndPopBytecode + void extendedStoreAndPopBytecode(); + + // pushReceiverBytecode + inline void pushReceiverBytecode() + { + /* "source" + self push: receiver + */ + + push(receiver); + } + + // duplicateTopBytecode + inline void duplicateTopBytecode() + { + /* "source" + ^self push: self stackTop + */ + + push(stackTop()); + } + + // pushReceiverVariableBytecode + inline void pushReceiverVariableBytecode() + { + int fieldIndex; + + /* "source" + fieldIndex <- self extractBits: 12 to: 15 + of: currentBytecode. + self pushReceiverVariable: fieldIndex + */ + + fieldIndex = extractBits_to_of(12, 15, currentBytecode); + pushReceiverVariable(fieldIndex); + } + + // pushActiveContextBytecode + inline void pushActiveContextBytecode() + { + /* "source" + self push: activeContext + */ + push(activeContext); + } + + // stackBytecode + void stackBytecode(); + + // extendedPushBytecode + void extendedPushBytecode(); + + // pushTemporaryVariable: + inline void pushTemporaryVariable(int temporaryIndex) + { + /* "source" + self push: (self temporary: temporaryIndex) + */ + + push(temporary(temporaryIndex)); + } + + // pushReceiverVariable: + inline void pushReceiverVariable(int fieldIndex) + { + /* "source" + self push: (memory fetchPointer: fieldIndex + ofObject: receiver) + */ + push(memory.fetchPointer_ofObject(fieldIndex, receiver)); + } + + // pushConstantBytecode + void pushConstantBytecode(); + + // pushTemporaryVariableBytecode + inline void pushTemporaryVariableBytecode() + { + int fieldIndex; + + /* "source" + fieldIndex <- self extractBits: 12 to: 15 + of: currentBytecode. + self pushTemporaryVariable: fieldIndex + */ + + fieldIndex = extractBits_to_of(12, 15, currentBytecode); + pushTemporaryVariable(fieldIndex); + } + + // pushLiteralVariable: + inline void pushLiteralVariable(int literalIndex) + { + int association; + + /* "source" + association <- self literal: literalIndex. + self push: (memory fetchPointer: ValueIndex + ofObject: association) + */ + association = literal(literalIndex); + push(memory.fetchPointer_ofObject(ValueIndex, association)); + } + + + // --- JumpBytecodes --- + + // sendMustBeBoolean + inline void sendMustBeBoolean() + { + /* "source" + self sendSelector: MustBeBooleanSelector + argumentCount: 0 + */ + + sendSelector_argumentCount(MustBeBooleanSelector, 0); + } + + // shortUnconditionalJump + inline void shortUnconditionalJump() + { + int offset; + + /* "source" + offset <- self extractBits: 13 to: 15 + of: currentBytecode. + self jump: offset + 1 + */ + + offset = extractBits_to_of(13, 15, currentBytecode); + jump(offset + 1); + } + + // jump: + inline void jump(int offset) + { + /* "source" + instructionPointer <- instructionPointer + offset + */ + + instructionPointer = instructionPointer + offset; + } + + // jumpIf:by: + void jumpIf_by(int condition, int offset); + + // longConditionalJump + void longConditionalJump(); + + // longUnconditionalJump + inline void longUnconditionalJump() + { + int offset; + + /* "source" + offset <- self extractBits: 13 to: 15 + of: currentBytecode. + self jump: offset - 4 * 256 + self fetchByte + */ + offset = extractBits_to_of(13, 15, currentBytecode); + jump((offset - 4) * 256 + fetchByte()); + } + + // jumpBytecode + void jumpBytecode(); + + // shortConditionalJump + inline void shortConditionalJump() + { + int offset; + + /* "source" + offset <- self extractBits: 13 to: 15 + of: currentBytecode. + self jumpIf: FalsePointer + by: offset + 1 + */ + + offset = extractBits_to_of(13, 15, currentBytecode); + jumpIf_by(FalsePointer, offset + 1); + } + + + // --- IntegerAccess --- + + // storeInteger:ofObject:withValue: + void storeInteger_ofObject_withValue(int fieldIndex, int objectPointer, int integerValue); + + // extractBits:to:of: + inline int extractBits_to_of(int firstBitIndex, int lastBitIndex, int anInteger) + { + /* "source" + ^(anInteger bitShift: lastBitIndex - 15) + bitAnd: (2 raisedTo: lastBitIndex - firstBitIndex + 1) - 1 + */ + + std::uint16_t mask = (1 << (lastBitIndex - firstBitIndex + 1)) - 1; + std::uint16_t shift = anInteger >> (15-lastBitIndex); + return shift & mask; + + } + + // transfer:fromIndex:ofObject:toIndex:ofObject: + void transfer_fromIndex_ofObject_toIndex_ofObject( + int count, + int firstFrom, + int fromOop, + int firstTo, + int toOop + ); + + // lowByteOf: + inline int lowByteOf(int anInteger) + { + /* "source" + ^self extractBits: 8 to: 15 + of: anInteger + */ + + return extractBits_to_of(8, 15, anInteger); + } + + // fetchInteger:ofObject: + int fetchInteger_ofObject(int fieldIndex, int objectPointer); + + // highByteOf: + inline int highByteOf(int anInteger) + { + /* "source" + ^self extractBits: 0 to: 7 + of: anInteger + */ + return extractBits_to_of(0, 7, anInteger); + } + + + // --- StoreMgmtPrims --- + + // checkInstanceVariableBoundsOf:in: + inline void checkInstanceVariableBoundsOf_in(int index, int object) + { + /* "source" + class <- memory fetchClassOf: object. + self success: index >= 1. + self success: index <= (self lengthOf: object) + */ + //cls = memory.fetchClassOf(object); + success(index >= 1); + success(index <= lengthOf(object)); + } + + // primitiveNewMethod + void primitiveNewMethod(); + + // primitiveAsOop + void primitiveAsOop(); + + // primitiveSomeInstance + void primitiveSomeInstance(); + + // primitiveObjectAt + void primitiveObjectAt(); + + // primitiveNextInstance + void primitiveNextInstance(); + + // primitiveNew + void primitiveNew(); + + // primitiveAsObject + void primitiveAsObject(); + + // primitiveNewWithArg + void primitiveNewWithArg(); + + // primitiveInstVarAtPut + void primitiveInstVarAtPut(); + + // primitiveObjectAtPut + void primitiveObjectAtPut(); + + // primitiveInstVarAt + void primitiveInstVarAt(); + + // primitiveBecome + void primitiveBecome(); + + // dispatchStorageManagementPrimitives + void dispatchStorageManagementPrimitives(); + + // --Float Access-- + void pushFloat(float f); + + inline float extractFloat(int objectPointer) + { + std::uint32_t uint32 = (memory.fetchWord_ofObject(1, objectPointer) << 16) | memory.fetchWord_ofObject(0, objectPointer); + return * (float *) &uint32; + } + + float popFloat(); + + + bool isInLowMemoryCondition(); + +#ifdef GC_MARK_SWEEP + void prepareForCollection(); + void collectionCompleted(); +#endif + +private: + // initializePointIndices + static const int XIndex = 0; + static const int YIndex = 1; + static const int ClassPointSize = 2; + + // initializeStreamIndices + static const int StreamArrayIndex = 0; + static const int StreamIndexIndex = 1; + static const int StreamReadLimitIndex = 2; + static const int StreamWriteLimitIndex = 3; + + // initializeSchedulerIndices + // Class ProcessorScheduler + static const int ProcessListsIndex = 0; + static const int ActiveProcessIndex = 1; + // Class LinkedList + static const int FirstLinkIndex = 0; + static const int LastLinkIndex = 1; + // Class Semaphore + static const int ExcessSignalsIndex = 2; + // Class Link + static const int NextLinkIndex = 0; + // Class Process + static const int SuspendedContextIndex = 1; + static const int PriorityIndex = 2; + static const int MyListIndex = 3; + + // initializeMessageIndices + static const int MessageSelectorIndex = 0; + static const int MessageArgumentsIndex = 1; + static const int MessageSize = 2; + + // initializeClassIndices + // Class Class + static const int SuperclassIndex = 0; + static const int MessageDictionaryIndex = 1; + static const int InstanceSpecificationIndex = 2; + // Fields of a message dictionary + static const int MethodArrayIndex = 1; + static const int SelectorStart = 2; + + // initializeSmallIntegers + // SmallIntegers" + static const int MinusOnePointer = 65535; + static const int ZeroPointer = 1; + static const int OnePointer = 3; + static const int TwoPointer = 5; + + // initializeContextIndices + // Class MethodContext + static const int SenderIndex = 0; + static const int InstructionPointerIndex = 1; + static const int StackPointerIndex = 2; + static const int MethodIndex = 3; + static const int ReceiverIndex = 5; + static const int TempFrameStart = 6; + // Class BlockContext + static const int CallerIndex = 0; + static const int BlockArgumentCountIndex = 3; + static const int InitialIPIndex = 4; + static const int HomeIndex = 5; + + // initializeAssociationIndex + static const int ValueIndex = 1; + + // initializeCharacterIndex + static const int CharacterValueIndex = 0; + + // initializeMethodIndices + // Class CompiledMethod + static const int HeaderIndex = 0; + static const int LiteralStart = 1; + + // Forms + static const int BitsInForm = 0; + static const int WidthInForm = 1; + static const int HeightInForm = 2; + static const int OffsetInForm = 3; + + // Files + static const int FileNameIndex = 1; // fileName field of File + + // "Registers" + int activeContext; + int homeContext; + int method; + int receiver; + int instructionPointer; + int stackPointer; + int currentBytecode; + bool successFlag; + + // Class related registers + int messageSelector; + int argumentCount; + int newMethod; + int primitiveIndex; + + + // Process-related Registers (pg 642) + bool newProcessWaiting; // The newProcessWaiting register will be true if a process switch is called for and false otherwise. + int newProcess; // If newProcessWaiting is true then the newProcess register will point to the Process to be transferred to. + /* + The semaphoreList register points to an Array used by the interpreter to buffer Semaphores that should be signaled. This is an Array in Interpreter, not in the object memory. It will be a table in a machine-language interpreter. + */ + + int semaphoreList[4096]; + + int semaphoreIndex; // The semaphoreIndex register hold the index of the last Semaphore in the semaphoreList buffer. + + // Using an array of int for method cache to remain faithful as possible to the bluebook + // Any size change will require changes to hash function in findNewMethodInClass + int methodCache[1024]; + + ObjectMemory memory; + + // dbanay - primitiveSignalAtOopsLeftWordsLeft support + bool checkLowMemory; + bool memoryIsLow; + int lowSpaceSemaphore; + int oopsLeftLimit; + std::uint32_t wordsLeftLimit; + + IHardwareAbstractionLayer *hal; + IFileSystem *fileSystem; + int currentDisplay; + int currentDisplayWidth; + int currentDisplayHeight; + int currentCursor; + + // Return a std::string for a string or symbol oop + std::string stringFromObject(int strOop); + int stringObjectFor(const char *s); + +#ifdef DEBUGGING_SUPPORT + std::string selectorName(int selector); + std::string classNameOfObject(int objectPointer); + std::string className(int classPointer); +#endif + +}; + diff --git a/vm/main.cpp b/vm/main.cpp @@ -0,0 +1,1099 @@ +// +// main.cpp +// Smalltalk-80 +// +// Created by Dan Banay on 2/20/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +// If defined, the mouse cursor is rendered by the application rather than the system. +// System rendering is preferred, but on Windows, the cursor didn't always change +// if the left mouse button was being held down. In addition, I found that (again) +// on Windows, on high resolution displays the mouse cursor was tiny +// (it wasn't respecting the display scaling setting). +// + +#ifdef _WIN32 +#define SOFTWARE_MOUSE_CURSOR +#endif + +#include <iostream> +#include <fstream> +#include <sstream> +#include <cassert> +#include <stdlib.h> +#include <time.h> +#ifdef _WIN32 +#define SDL_MAIN_HANDLED +#include "SDL.h" +#else +#include "SDL2/SDL.h" +#endif +#include "interpreter.h" +#include "posixfilesystem.h" +#include "hal.h" +#include <queue> + +#ifdef __EMSCRIPTEN__ +// Port navigateur (st80.schurger.org) : la boucle principale est découpée en trames, +// les caractères viennent de SDL_TEXTINPUT (disposition du clavier respectée) et la page +// pilote la vitesse par les fonctions st80_* exportées (voir web/app.js). +#include <emscripten.h> +static volatile double st80_budget_ms = 10; // temps d'interprétation par trame +static volatile int st80_paused = 0; +static double st80_cycles = 0; // bytecodes exécutés depuis le départ +class VirtualMachine; +static VirtualMachine *st80_vm = 0; +extern "C" { + EMSCRIPTEN_KEEPALIVE void st80_set_budget(double ms) { st80_budget_ms = ms; } + EMSCRIPTEN_KEEPALIVE void st80_set_paused(int paused) { st80_paused = paused; } + EMSCRIPTEN_KEEPALIVE double st80_cycle_count() { return st80_cycles; } + EMSCRIPTEN_KEEPALIVE const char *st80_image_name(); +} +#endif + + +typedef std::uint16_t Pixel; +static const SDL_PixelFormatEnum TextureFormat = SDL_PIXELFORMAT_RGB565; + + +static inline void expand_pixel(Pixel *destPixel, std::uint16_t srcWord, int srcBit) +{ + *destPixel = -((srcWord & (1<<srcBit) ) == 0); +} + +struct options +{ + std::string root_directory; + std::string snapshot_name; + bool three_buttons; + int cycles_per_frame; + int display_scale; + bool vsync; + Uint32 novsync_delay; +}; + + +class VirtualMachine: public IHardwareAbstractionLayer +{ +public: + VirtualMachine(struct options& vm_options) : + vm_options(vm_options), + fileSystem(vm_options.root_directory), + interpreter(this, &fileSystem), + window(0), renderer(0), texture(0), +#ifdef SOFTWARE_MOUSE_CURSOR + mouse_texture(0), +#else + cursor(0), +#endif + display_width(0), display_height(0), + scheduled_semaphore(0), input_semaphore(0), scheduled_time(0), + event_count(0), last_event_time(0), + quit_signalled(false), texture_needs_update(false), + image_name(vm_options.snapshot_name) + { + } + + ~VirtualMachine() + { +#ifdef SOFTWARE_MOUSE_CURSOR + if (mouse_texture) + SDL_DestroyTexture(mouse_texture); +#else + if (cursor) + SDL_FreeCursor(cursor); + +#endif + if (texture) + SDL_DestroyTexture(texture); + if (renderer) + SDL_DestroyRenderer(renderer); + if (window) + SDL_DestroyWindow(window); + } + + + void set_input_semaphore(int semaphore) + { + input_semaphore = semaphore; + } + + // the number of seconds since 00:00 in the morning of January 1, 1901 + std::uint32_t get_smalltalk_epoch_time() + { + // Seconds between 1/1/1901 00:00 and 1/1/1970 00:00 + + const std::uint32_t TIME_OFFSET = 2177452800; + time_t unix_epoch_time = time(0); + return (std::uint32_t) unix_epoch_time + TIME_OFFSET; + } + + // the number of milliseconds since the millisecond clock was + // last reset or rolled over (a 32-bit unsigned number) + std::uint32_t get_msclock() + { + return SDL_GetTicks(); + } + + void check_scheduled_semaphore() + { + if( scheduled_semaphore && SDL_TICKS_PASSED(SDL_GetTicks(), scheduled_time)) + { + interpreter.asynchronousSignal(scheduled_semaphore); + scheduled_semaphore = 0; + } + } + + // Schedule a semaphore to be signaled at a time. Only one outstanding + // request may be scheduled at anytime. When called any outstanding + // request will be replaced (or canceled if semaphore is 0). + // Will signal immediate if scheduled time has passed. + void signal_at(int semaphore, std::uint32_t msClockTime) + { + scheduled_semaphore = semaphore; + scheduled_time = msClockTime; + if (semaphore) + { + // Just in case the time passed + check_scheduled_semaphore(); + } + } + + SDL_Cursor *create_cursor(const Uint8* cursor_bits) + { + // Maps a nibble to a byte where each bit is repeated + // e.g. 1010 -> 11001100 + static int expandedNibbleToByte[] = + { + 0b00000000, // 0000 + 0b00000011, // 0001 + 0b00001100, // 0010 + 0b00001111, // 0011 + 0b00110000, // 0100 + 0b00110011, // 0101 + 0b00111100, // 0110 + 0b00111111, // 0111 + 0b11000000, // 1000 + 0b11000011, // 1001 + 0b11001100, // 1010 + 0b11001111, // 1011 + 0b11110000, // 1100 + 0b11110011, // 1101 + 0b11111100, // 1110 + 0b11111111 // 1111 + + }; + + SDL_Cursor* new_cursor = 0; + + + if (vm_options.display_scale == 1) + { + new_cursor = SDL_CreateCursor((const Uint8 *) cursor_bits, (const Uint8 *) cursor_bits, 16, 16, 0, 0); + + } + else if (vm_options.display_scale == 2) + { + std::uint8_t image[128]; + std::uint8_t *src = (std::uint8_t *) cursor_bits; + int dest = 0; + + // 4 bytes (32-bits) x 32 rows + for(int h = 0; h < 16; h++) + { + image[dest] = expandedNibbleToByte[*(src) >> 4]; + image[dest+1] = expandedNibbleToByte[*(src) & 0xf]; + image[dest+2] = expandedNibbleToByte[*(src+1) >> 4]; + image[dest+3] = expandedNibbleToByte[*(src+1) & 0xf]; + + image[dest+4] = image[dest]; + image[dest+5] = image[dest+1]; + image[dest+6] = image[dest+2]; + image[dest+7] = image[dest+3]; + dest += 8; + src += 2; + } + + new_cursor = SDL_CreateCursor((const Uint8 *) image, (const Uint8 *) image, 32, 32, 0, 0); + } + if (!new_cursor) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Create Cursor failed: %s", SDL_GetError()); + + } + + return new_cursor; + } + +#ifdef SOFTWARE_MOUSE_CURSOR + void update_mouse_cursor(const std::uint16_t* cursor_bits) + { + int dest_pitch; + std::uint8_t* pixels; + + int code = SDL_LockTexture(mouse_texture, 0, (void **)&pixels, &dest_pitch); + if (code < 0) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK MOUSE TEXTURE SDL: %s", SDL_GetError()); + return; + } + + std::uint8_t* dest_row = pixels; + std::uint16_t* source_pixel = (std::uint16_t *) cursor_bits; + for(int h = 0; h < 16; h++) + { + std::uint16_t* dest_pixel = (Pixel *) dest_row; + for(int b = 15; b >= 0; b--) + { + // Low order bit of a 5551 pixel is alpha + *dest_pixel = (*source_pixel & (1 << b)) != 0; + dest_pixel++; + } + source_pixel++; + dest_row += dest_pitch; + + } + SDL_UnlockTexture(mouse_texture); + } +#endif + + // Set the cursor image + // (a 16 word form) + void set_cursor_image(std::uint16_t *image) + { +#ifdef SOFTWARE_MOUSE_CURSOR + + if (!mouse_texture) + { + mouse_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA5551, SDL_TEXTUREACCESS_STREAMING, 16, 16); + SDL_SetTextureBlendMode(mouse_texture, SDL_BLENDMODE_BLEND); + } + + update_mouse_cursor(image); +#else + std::uint16_t cursor_bits[16]; + + // SDL uses a MSB format, so swap the bytes + for(int i = 0; i < 16; i++) + { + cursor_bits[i] = ((image[i] & 0xff) << 8) | (image[i] >> 8); + } + + SDL_Cursor* old_cursor = cursor; + + cursor = create_cursor((const Uint8 *) cursor_bits); + + SDL_SetCursor(cursor); + + if (old_cursor) + { + SDL_FreeCursor(old_cursor); + } +#endif + + } + + // Set the mouse cursor location + void set_cursor_location(int x, int y) + { + SDL_WarpMouseInWindow(window, x * vm_options.display_scale, y * vm_options.display_scale); + } + + void get_cursor_location(int *x, int *y) + { + SDL_GetMouseState(x, y); + *x = *x / vm_options.display_scale; + *y = *y / vm_options.display_scale; + } + + void set_link_cursor(bool link) + { + } + + + void initialize_texture() + { + std::uint8_t* dest_row; + int dest_pitch; + + int code = SDL_LockTexture(texture, 0, (void **)&dest_row, &dest_pitch); + if (code < 0) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK SDL: %s", SDL_GetError()); + return; + } + + // There may be many frames before Smalltalk renders, so initialize the screen texture + // with something that looks like the Smalltalk desktop pattern + for(int h = 0; h < display_height; h++) + { + Pixel* dest_pixel = (Pixel *) dest_row; + + for(int i = 0; i < display_width; i++) + { + *dest_pixel++ = (h & 1) ^ (i & 1) ? 0 : ~0; + } + dest_row += dest_pitch; + } + SDL_UnlockTexture(texture); + } + + bool set_display_size(int width, int height) + { + if (display_width != width || display_height != height) + { + display_width = width; + display_height = height; + dirty_rect.x = 0; + dirty_rect.y = 0; + dirty_rect.w = width; + dirty_rect.h = height; + + if (window) + { + SDL_SetWindowSize(window, vm_options.display_scale*display_width, vm_options.display_scale*display_height); + SDL_DestroyTexture(texture); + } + else + { + window = SDL_CreateWindow("Smalltalk-80", + SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, + vm_options.display_scale*display_width, vm_options.display_scale*display_height, + 0); + + Uint32 flags = SDL_RENDERER_ACCELERATED | (vm_options.vsync ? SDL_RENDERER_PRESENTVSYNC : 0); + + renderer = SDL_CreateRenderer(window, -1, flags ); + if (!renderer) // pas de WebGL (ou pas d'accélération) : rendu logiciel + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); + + + } + + texture = SDL_CreateTexture(renderer, TextureFormat, SDL_TEXTUREACCESS_STREAMING, display_width, display_height); + initialize_texture(); + + } + return true; + } + + void update_texture() + { + int source_word_left = dirty_rect.x / 16; + int source_word_right = ( dirty_rect.x + dirty_rect.w - 1) / 16; + int display_width_words = (display_width + 15) / 16; + + int source_index_row = source_word_left + (dirty_rect.y * display_width_words); + int update_word_width = source_word_right - source_word_left + 1; + + // We transfer pixels in groups of WORDS from the display form, + // so we need to set texture update rectangle so the left and right edges are on + // a word boundary + SDL_Rect update_rect; + update_rect.x = source_word_left * 16; + update_rect.y = dirty_rect.y; + update_rect.w = update_word_width * 16; + update_rect.h = dirty_rect.h; + + int displayBitmap = interpreter.getDisplayBits(display_width, display_height); + + if (displayBitmap == 0) return; // bail + + std::uint8_t* pixels; + int dest_pitch; + int code = SDL_LockTexture(texture, &update_rect, (void **)&pixels, &dest_pitch); + if (code < 0) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK SDL: %s", SDL_GetError()); + return; + } + + std::uint8_t* dest_row = pixels; + + + for(int h = 0; h < update_rect.h; h++) + { + Pixel* dest_pixel = (Pixel *) dest_row; + int source_index = source_index_row; + for(int i = 0; i < update_word_width; i++) + { + std::uint16_t source_pixel = interpreter.fetchWord_ofDislayBits(source_index, displayBitmap); + expand_pixel(dest_pixel++, source_pixel, 15); + expand_pixel(dest_pixel++, source_pixel, 14); + expand_pixel(dest_pixel++, source_pixel, 13); + expand_pixel(dest_pixel++, source_pixel, 12); + expand_pixel(dest_pixel++, source_pixel, 11); + expand_pixel(dest_pixel++, source_pixel, 10); + expand_pixel(dest_pixel++, source_pixel, 9); + expand_pixel(dest_pixel++, source_pixel, 8); + expand_pixel(dest_pixel++, source_pixel, 7); + expand_pixel(dest_pixel++, source_pixel, 6); + expand_pixel(dest_pixel++, source_pixel, 5); + expand_pixel(dest_pixel++, source_pixel, 4); + expand_pixel(dest_pixel++, source_pixel, 3); + expand_pixel(dest_pixel++, source_pixel, 2); + expand_pixel(dest_pixel++, source_pixel, 1); + expand_pixel(dest_pixel++, source_pixel, 0); + + source_index++; + } + dest_row += dest_pitch; + source_index_row += display_width_words; + } + + SDL_UnlockTexture(texture); + } + + + void display_changed(int x, int y, int width, int height) + { + texture_needs_update = true; + assert(x >= 0 && x < display_width); + assert(y >= 0 && y < display_height); + assert(x + width <= display_width); + assert(y + height <= display_height); + + if (SDL_RectEmpty(&dirty_rect)) + { + dirty_rect.x = x; + dirty_rect.y = y; + dirty_rect.w = width; + dirty_rect.h = height; + } + else + { + SDL_Rect update_rect {x, y, width, height}; + SDL_UnionRect(&dirty_rect, &update_rect, &dirty_rect); + } + } + + + + void error(const char *message) + { + std::cerr << message << std::endl; + abort(); + } + + //Input queue + bool next_input_word(std::uint16_t *word) + { + if (input_queue.size() == 0) + return false; + + *word = input_queue.front(); + input_queue.pop(); + + return true; + } + + // lifetime + void signal_quit() + { + quit_signalled = true; + } + + const char *get_image_name() + { + return image_name.c_str(); + } + + void set_image_name(const char *new_name) + { + image_name = new_name; + } + + + void exit_to_debugger() + { + abort(); + } + + bool init() + { +#ifdef __EMSCRIPTEN__ + // Le clavier n'est capturé que lorsque le canevas a le focus (la page reste utilisable) + SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, "#canvas"); +#endif + if (SDL_Init(SDL_INIT_VIDEO) < 0) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError()); + return false; + } +#ifdef __EMSCRIPTEN__ + SDL_StartTextInput(); +#endif + +#ifdef SOFTWARE_MOUSE_CURSOR + SDL_ShowCursor(0); // We show our own... + +#endif + + + texture_needs_update = false; + quit_signalled = false; + return interpreter.init(); + } + + void queue_input_word(std::uint16_t word) + { + assert(input_semaphore); + input_queue.push(word); + interpreter.asynchronousSignal(input_semaphore); +} + + void queue_input_word(std::uint16_t type, std::uint16_t parameter) + { + queue_input_word(((type & 0xf) << 12) | (parameter & 0xfff)); + } + + void queue_input_time_words() + { + std::uint32_t delta_time; + std::uint32_t now = get_msclock(); + if (event_count++ == 0) + { + delta_time = 0; + } + else + { + delta_time = now - last_event_time; + } + + if (delta_time <= 4095) + { + // can fit in 12 bits + queue_input_word(0, delta_time); + } + else + { + std::uint32_t abs_time = get_smalltalk_epoch_time(); + // too large, use type 5 with absolute time + queue_input_word(5, 0); // parameter is ignored + queue_input_word((abs_time>>16) & 0xffff); // high word first + queue_input_word(abs_time & 0xffff); // low word next + + } + + last_event_time = now; + } + +#if 0 + void paste_clipboard() + { + + if (SDL_HasClipboardText()) + { + queue_input_time_words(); + for(const char *text = SDL_GetClipboardText(); *text; text++) + { + int ch = *text; + if (ch == '\n') ch = '\r'; + queue_input_word(3, ch); + queue_input_word(4, ch); + } + } + } +#endif + + /* + decoded keyboard: + + A decoded keyboard consists of some independent keys and some “meta" keys (shift and escape) + that cannot be detected on their own, but that change the value of the other keys. The keys + on a decoded keyboard only indicate their down transition, not their up transition. + For a decoded keyboard, the full shifted and “controlled" ASCII should be used as a parameter + and successive type 3 and 4 words should be produced for each keystroke. + + undecoded keyboard: + + (independent keys with up/down detection) + On an undecoded keyboard, the standard keys produce parameters that are the ASCII code + of the character on the keytop without shift or control information (i.e., the key with “A” + on it produces the ASCII for “a” and the key with “2” and “@“ on it produces the ASCII for “2”). + */ + void handle_keyboard_event(const SDL_KeyboardEvent& key) + { + + // Map between a key scan code and it's shifted key value (if any) + static char shift_map[128] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, ' ', '!', '"', '#', '$', '%', '&', '"', '(', + ')', '*', '+', '<', '_', '>', '?', ')', '!', '@', + '#', '$', '%', '^', '&', '*', '(', ':', ':', '<', + '+', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + '{', '|', '}', '^', '_', '~', 'A', 'B', 'C', 'D', + 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', '{', '|', '}', '~', 127 + }; + + std::uint16_t type = key.type == SDL_KEYDOWN ? 3 : 4; + std::uint16_t param = 0; + /* + left shift 136 right shift 137 control 138 alpha-lock 139 + backspace 8 tab 9 line feed 10 return 13 escape 27 space 32 delete 127 + + */ +#if 0 + if (key.keysym.scancode == SDL_SCANCODE_V && key.keysym.mod == KMOD_LGUI) + { + if (type == 3) + paste_clipboard(); + return; + } +#endif + + // My initial plan was to use go unencoded for everything, but + // when I pressed shift 6, I saw a ~ appear!. It turns out the + // ALTO keyboard has ~ above 6! + // https://www.flickr.com/photos/walkingsf/31415192416 + + switch (key.keysym.scancode) + { + case SDL_SCANCODE_LCTRL: + case SDL_SCANCODE_RCTRL: + param = 138; break; + case SDL_SCANCODE_CAPSLOCK: param = 139; break; + case SDL_SCANCODE_DELETE: param = 127; break; + default: + if (key.keysym.sym > 127) + return; // Must be ascii +#ifdef __EMSCRIPTEN__ + // Les caractères imprimables arrivent par SDL_TEXTINPUT (handle_text_input), qui + // respecte la disposition du clavier ; ici on ne garde que les touches de commande + // et les combinaisons avec Ctrl, pour lesquelles le navigateur n'émet pas de texte. + if (key.keysym.sym >= ' ' && key.keysym.sym < 127 && !(key.keysym.mod & KMOD_CTRL)) + return; +#endif + param = key.keysym.sym & 0x7f; + break; + } + + if (param < 128) + { + if (type == 3) + { + if (key.keysym.mod & (KMOD_LGUI|KMOD_RGUI)) + return; // Ignore + + if (key.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) + param = shift_map[param]; + + /* + For a decoded keyboard, the full shifted and “controlled" ASCII should be + used as a parameter and successive type 3 and 4 words should be produced for each keystroke. + */ + queue_input_time_words(); + queue_input_word(3, param); + queue_input_word(4, param); + } + } + else + { + // send undecoded + queue_input_time_words(); + queue_input_word(type, param); + } + } + +#ifdef __EMSCRIPTEN__ + // Texte saisi (clavier « décodé » : un mot type 3 puis type 4 par caractère ASCII) + void handle_text_input(const SDL_TextInputEvent& text) + { + for (const char *p = text.text; *p; p++) + { + unsigned char ch = (unsigned char) *p; + if (ch >= 128) continue; // Smalltalk-80 ne connaît que l'ASCII + queue_input_time_words(); + queue_input_word(3, ch); + queue_input_word(4, ch); + } + } +#endif + + void handle_mouse_button_event(const SDL_MouseButtonEvent& mouse) + { + // The bluebook got these wrong! + const int RedButton = 130; // select + const int YellowButton = 129; // doit etc. + const int BlueButton = 128; // frame, close + + unsigned mods; + int smalltalk_button = 0; + int button_index; + + static unsigned button_down_mods[3] = {0}; // modifier state at button down + + switch(mouse.button) + { + case SDL_BUTTON_LEFT: smalltalk_button = RedButton; button_index = 0; break; + case SDL_BUTTON_MIDDLE: smalltalk_button = BlueButton; button_index = 1; break; + case SDL_BUTTON_RIGHT: smalltalk_button = YellowButton; button_index = 2; break; + default: + return; + } + + if (mouse.type == SDL_MOUSEBUTTONDOWN) + { + // Save mod state when the button went down + // when the button is released we will use these rather than active one + mods = SDL_GetModState(); + button_down_mods[button_index] = mods; + } + else + mods = button_down_mods[button_index]; + + + if (vm_options.three_buttons) + { + // Real 3 button mouse + switch(mouse.button) + { + case SDL_BUTTON_LEFT: smalltalk_button = RedButton; break; + case SDL_BUTTON_MIDDLE: smalltalk_button = YellowButton; break; + case SDL_BUTTON_RIGHT: smalltalk_button = BlueButton; break; + default: + return; + } + } + else + { + #ifdef __APPLE__ + const Uint32 BlueFlags = KMOD_RGUI|KMOD_LGUI; + #else + const Uint32 BlueFlags = KMOD_RALT|KMOD_LALT; + + #endif + + /* + Left = Red + Right/Ctrl+Left = Yellow + Alt+Left(win+linux) /Command+Left(mac) = Blue + */ + switch(mouse.button) + { + case SDL_BUTTON_LEFT: + if (mods & BlueFlags) + smalltalk_button = BlueButton; + else if (mods & (KMOD_RCTRL|KMOD_LCTRL)) + smalltalk_button = YellowButton; + else + smalltalk_button = RedButton; + break; + case SDL_BUTTON_RIGHT: + smalltalk_button = YellowButton; + break; +#ifdef __EMSCRIPTEN__ + case SDL_BUTTON_MIDDLE: // molette cliquée = bouton bleu (fenêtres) + smalltalk_button = BlueButton; + break; +#endif + default: + return; /* Don't care about this button */ + } + } + + if (mouse.type == SDL_MOUSEBUTTONDOWN) + { + queue_input_time_words(); + queue_input_word(3, smalltalk_button); + } + else if (mouse.type == SDL_MOUSEBUTTONUP) + { + button_down_mods[button_index] = 0; + queue_input_time_words(); + queue_input_word(4, smalltalk_button); + } + } + + void handle_mouse_movement_event(const SDL_MouseMotionEvent& motion) + { + queue_input_time_words(); + queue_input_word(1, (std::uint16_t) motion.x); + queue_input_time_words(); + queue_input_word(1, (std::uint16_t) motion.y); + } + + + void render() + { + if (renderer) + { + if (texture_needs_update) + { + update_texture(); + texture_needs_update = false; + } + // SDL_RenderClear(renderer); + if (texture) + SDL_RenderCopy(renderer, texture, NULL, NULL); + +#ifdef SOFTWARE_MOUSE_CURSOR + if (mouse_texture) + { + static SDL_Rect mouse_src_rect{0,0,16,16}; + int mouseX, mouseY; + SDL_GetMouseState(&mouseX, &mouseY); + + SDL_Rect dst = {mouseX, mouseY, 16*vm_options.display_scale, 16*vm_options.display_scale}; + SDL_RenderCopy(renderer, mouse_texture, &mouse_src_rect, &dst); + } +#endif + + SDL_RenderPresent(renderer); + dirty_rect.x = 0; + dirty_rect.y = 0; + dirty_rect.w = 0; + dirty_rect.h = 0; + } + } + + void process_events() + { + SDL_Event event; + + while (SDL_PollEvent(&event)) + { + if(event.type == SDL_QUIT) + { + quit_signalled = true; + break; + } + if (input_semaphore) + { + if (event.type == SDL_KEYUP || event.type == SDL_KEYDOWN) + handle_keyboard_event(event.key); + else if (event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN) + handle_mouse_button_event(event.button); + else if (event.type == SDL_MOUSEMOTION) + handle_mouse_movement_event(event.motion); +#ifdef __EMSCRIPTEN__ + else if (event.type == SDL_TEXTINPUT) + handle_text_input(event.text); +#endif + } + } + } + +#ifdef __EMSCRIPTEN__ + // Une trame du navigateur : événements, puis des cycles d'interprétation jusqu'à + // épuisement du budget de temps, puis affichage. Le navigateur appelle frame() par + // requestAnimationFrame ; rien ne bloque jamais. + static void frame_callback(void *arg) { static_cast<VirtualMachine *>(arg)->frame(); } + + void frame() + { + process_events(); + check_scheduled_semaphore(); + interpreter.checkLowMemoryConditions(); + + if (!st80_paused) + { + double start = emscripten_get_now(); + do + { + for(int i = 0; i < vm_options.cycles_per_frame && !quit_signalled; i++) + interpreter.cycle(); + st80_cycles += vm_options.cycles_per_frame; + } + while (!quit_signalled && emscripten_get_now() - start < st80_budget_ms); + } + + if (quit_signalled) + { + emscripten_cancel_main_loop(); + EM_ASM({ if (Module.onQuit) Module.onQuit(); }); + return; + } + render(); + } + + void run() + { + st80_vm = this; + emscripten_set_main_loop_arg(frame_callback, this, 0, 1); + } +#else + void run() + { + for(;;) + { + process_events(); + + check_scheduled_semaphore(); + interpreter.checkLowMemoryConditions(); + + for(int i = 0; i < vm_options.cycles_per_frame && !quit_signalled; i++) + { + interpreter.cycle(); + } + + if (quit_signalled) break; + + render(); + + if (!vm_options.vsync && vm_options.novsync_delay > 0) + SDL_Delay(vm_options.novsync_delay); // Don't kill CPU + } + } +#endif + + struct options vm_options; + + PosixST80FileSystem fileSystem; + + SDL_Window *window; + SDL_Renderer *renderer; + SDL_Texture *texture; + + +#ifdef SOFTWARE_MOUSE_CURSOR + SDL_Texture *mouse_texture; +#else + SDL_Cursor *cursor; +#endif + + Interpreter interpreter; + + + std::queue<std::uint16_t> input_queue; + std::uint32_t last_event_time; + int event_count; + + int input_semaphore; + bool quit_signalled; + + + bool texture_needs_update; + int display_width, display_height; + + SDL_Rect dirty_rect; + + int scheduled_semaphore; + std::uint32_t scheduled_time; + std::string image_name; + +}; + + + +#ifdef __EMSCRIPTEN__ +const char *st80_image_name() { return st80_vm ? st80_vm->get_image_name() : ""; } +#endif + +static bool process_args(int argc, const char *argv[], struct options &options) +{ + if (argc < 3) + return false; + + int arg = 1; + while (arg < argc) + { + // directory option + if (strcmp(argv[arg], "-directory") == 0 && arg + 1 < argc) + { + arg++; + options.root_directory = argv[arg]; + + // Remove trailing directory separator (if any) -- Unix and Windows + if (options.root_directory[options.root_directory.size()-1] == '/' || options.root_directory[options.root_directory.size()-1] == '\\') + options.root_directory.pop_back(); + } + else if (strcmp(argv[arg], "-image") == 0 && arg + 1 < argc) + { + arg++; + options.snapshot_name = argv[arg]; + } + else if (strcmp(argv[arg], "-delay") == 0 && arg + 1 < argc) + { + arg++; + int delay = atoi(argv[arg]); + if (delay < 0) return false; + options.novsync_delay = delay; + } + else if (strcmp(argv[arg], "-cycles") == 0 && arg + 1 < argc) + { + arg++; + int cycles = atoi(argv[arg]); + if (cycles <= 0) return false; + options.cycles_per_frame = cycles; + } + else if (strcmp(argv[arg], "-2x") == 0) + { + options.display_scale = 2; + } + else if (strcmp(argv[arg], "-vsync") == 0) + { + options.vsync = true; + } + else if (strcmp(argv[arg], "-three") == 0) + { + options.three_buttons = true; + } + else + return false; + arg++; + } + + // Check for required args + return options.root_directory.size() > 0; +} + +int main(int argc, const char * argv[]) { + + struct options vm_options; + + vm_options.snapshot_name = "snapshot.im"; + vm_options.three_buttons = false; + vm_options.vsync = false; + vm_options.novsync_delay = 0; // Try -delay 8 arg if your CPU is unhappy + vm_options.cycles_per_frame = 1800; + vm_options.display_scale = 1; + + if (!process_args(argc, argv, vm_options)) + { + std::cerr << "usage: " << argv[0] << + " -directory root-directory [-vsync] [-delay ms] [-cycles cycles-per-frame] [-2x] [-image snapshot]" + << std::endl; + exit(-1); + } + + VirtualMachine *vm = new VirtualMachine(vm_options); + if (vm->init()) + { + vm->run(); + } + else + { + std::cerr << "VM failed to initialize (invalid/missing directory or snapshot?)" << std::endl; + } + delete vm; + + return 0; +} diff --git a/vm/objmemory.cpp b/vm/objmemory.cpp @@ -0,0 +1,1732 @@ +// +// objmemory.cpp +// Smalltalk-80 +// +// Created by Dan Banay on 2/20/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#include <cstdint> +#include <algorithm> +#include "objmemory.h" +#include "oops.h" + +#ifndef GC_REF_COUNT +#ifndef GC_MARK_SWEEP +#error "must define GC_REF_COUNT and/or GC_MARK_SWEEP" +#endif +#endif + + +ObjectMemory::ObjectMemory( + IHardwareAbstractionLayer *halInterface +#ifdef GC_MARK_SWEEP + , IGCNotification *notification +#endif +) : currentSegment(-1), freeWords(0), freeOops(0) +{ +#ifdef GC_MARK_SWEEP + gcNotification = notification; +#endif + hal = halInterface; +} + + + +bool ObjectMemory::loadObjectTable(IFileSystem *fileSystem, int fd) +{ + // First two 32-bit values have the object space length and object table lengths in words + std::int32_t objectTableLength; + + if (fileSystem->seek_to(fd, 4) == -1) // Skip over object space length + return false; + if (fileSystem->read(fd, (char *)&objectTableLength, sizeof(objectTableLength)) != sizeof(objectTableLength)) + return false; + int fileSize = fileSystem->file_size(fd); + + if (fileSystem->seek_to(fd, fileSize - objectTableLength*2) == -1) // Reposition to start of object table + return false; + + for(int objectPointer = 0; objectPointer < objectTableLength; objectPointer+=2) + { + std::uint16_t words[2]; + if (fileSystem->read(fd, (char *)&words, sizeof(words)) != sizeof(words)) + return false; + ot_put(objectPointer, words[0]); + locationBitsOf_put(objectPointer, words[1]); + } + + headOfFreePointerListPut(NonPointer); + + // Initialize the remaining entries as free + for(int objectPointer = objectTableLength; objectPointer < ObjectTableSize; objectPointer += 2) + { + ot_put(objectPointer, 0); + freeBitOf_put(objectPointer, 1); + locationBitsOf_put(objectPointer, 0); + } + + // Build the OT entry free list, Go backwards so we have lower entries first on free list. + // Why? Makes the OT easier to see in debugger. + // Note we skip oop 0, which is considered reserved and invalid. (page 2, Xerox Virtual Image booklet) + for(int objectPointer = ObjectTableSize-2; objectPointer >= 2; objectPointer -= 2) + if (freeBitOf(objectPointer)) + toFreePointerListAdd(objectPointer); + + freeOops = auditFreeOops(); + + return true; +} + +bool ObjectMemory::loadObjects(IFileSystem *fileSystem, int fd) +{ + static const int SegmentHeapSpaceSize = HeapSpaceStop + 1; + + // Track amount of free space available for objects in each segment + int heapSpaceRemaining[HeapSegmentCount]; + + for(int segment = FirstHeapSegment; segment <= LastHeapSegment; segment++) + heapSpaceRemaining[segment - FirstHeapSegment] = SegmentHeapSpaceSize; + + // Load objects from the virtual image into the heap segments + // being careful to not split an object across a segment boundary + int destinationSegment = FirstHeapSegment, destinationWord = 0; + + for(int objectPointer = 2; objectPointer < ObjectTableSize; objectPointer += 2) + { + if (freeBitOf(objectPointer)) continue; + // A free chunk has it's COUNT field set to zero but the free bit is clear + assert (countBitsOf(objectPointer) != 0); // SANITY Make sure a freeChunk wasn't saved! + + // On disk objects are stored contiguously as if a large 20-bit WORD addressed space + // In this scheme, the OT segment and locations combine to form a WORD address + const int objectImageWordAddress = (segmentBitsOf(objectPointer) << 16) + + locationBitsOf(objectPointer); + + fileSystem->seek_to(fd, ObjectSpaceBaseInImage + objectImageWordAddress * sizeof(std::uint16_t)); + + std::uint16_t objectSize; + fileSystem->read(fd, (char *) &objectSize, sizeof(objectSize)); + + + // Account for the extra word used by HugeSize objects + int extraSpace = objectSize < HugeSize || pointerBitOf(objectPointer) == 0 ? 0 : 1; + int space = objectSize + extraSpace; // space in memory + + if (space > heapSpaceRemaining[destinationSegment - FirstHeapSegment]) + { + // No room left in the current segment, move to next + destinationSegment++; + if (destinationSegment == HeapSegmentCount) return false; // Full + destinationWord = 0; + } + + // Update OT entry so that it references the object location in ObjectMemory vs the disk image + segmentBitsOf_put(objectPointer, destinationSegment); + locationBitsOf_put(objectPointer, destinationWord); + + // Store the object in the image into word memory + // First comes the size... + + sizeBitsOf_put(objectPointer, objectSize ); + + // Next is the class... + std::uint16_t classBits; + fileSystem->read(fd,(char *) &classBits, sizeof(classBits)); + + classBitsOf_put(objectPointer, classBits); + + // Followed by the fields... + for(int wordIndex = 0; wordIndex < objectSize-HeaderSize; wordIndex++) + { + std::uint16_t word; + fileSystem->read(fd,(char *) &word, sizeof(word)); + // use heap chunk + storeWord_ofObject_withValue(wordIndex, objectPointer, word); + } + + destinationWord += space; + + heapSpaceRemaining[destinationSegment - FirstHeapSegment] -= space; + } + + // Initialize the free chunk lists for each heap segment with the sentinel + for(int segment = FirstHeapSegment; segment <= LastHeapSegment; segment++) + { + for(int size = HeaderSize; size <= BigSize; size++) + resetFreeChunkList_inSegment(size, segment); + } + + freeWords = 0; + // Place any remaining space in each segment onto it's free chunk list, which is + // is a linked list of object pointers. + // The chunks are linked using the class field of an object. The size field of + // the object contains the actual size of the free chunk. + for(int segment = FirstHeapSegment; segment <= LastHeapSegment; segment++) + { + int freeChunkSize = heapSpaceRemaining[segment - FirstHeapSegment]; + freeWords += freeChunkSize; + if (freeChunkSize >= HeaderSize) + { + int freeChunkLocation = SegmentHeapSpaceSize - freeChunkSize; + // G&R pg 665 - each free chunk has an OT entry + currentSegment = segment; // Set special segment register + int objectPointer = obtainPointer_location(freeChunkSize, freeChunkLocation); + toFreeChunkList_add(std::min(freeChunkSize, (int) BigSize), objectPointer); + } + } + + currentSegment = FirstHeapSegment; + + return true; + +} + +bool ObjectMemory::loadSnapshot(IFileSystem *fileSystem, const char *fileName) +{ + int fd = fileSystem->open_file(fileName); + if (fd == -1) + return false; + + bool succeeded = loadObjectTable(fileSystem, fd) && loadObjects(fileSystem, fd); + + fileSystem->close_file(fd); + + return succeeded; +} + + +bool ObjectMemory::padToPage(IFileSystem *fileSystem, int fd) +{ + int pos = fileSystem->tell(fd); + int desired = ((pos + 512 - 1) / 512) * 512; + std::uint16_t word = 0; + int pad = (desired - pos) / sizeof(word); + while (pad-- > 0) + { + if (fileSystem->write(fd, (char *) &word, sizeof(word)) != sizeof(word)) + return false; + } + + return true; + } + +bool ObjectMemory::saveSnapshot(IFileSystem *fileSystem, const char *imageFileName) +{ + + int fd = fileSystem->create_file(imageFileName); + if (fd == -1) + return false; + bool success = saveObjects(fileSystem, fd); + + fileSystem->close_file(fd); + return success; + +} + +bool ObjectMemory::saveObjects(IFileSystem *fileSystem, int fd) +{ + // Avoid dumping out the entire object table -- we only need to write entries up until + // the last OT entry that references an object + int lastUsedObjectPointer = NonPointer; + for(int objectPointer = 2; objectPointer < ObjectTableSize; objectPointer += 2) + { + if (hasObject(objectPointer)) + lastUsedObjectPointer = objectPointer; + } + + int storedObjectTableLength = lastUsedObjectPointer + 2; + + std::int32_t placeHolder[2] = {0}; + + // Write place holder value for object space length and object table length + if (fileSystem->write(fd, (char *) &placeHolder, sizeof(placeHolder)) != sizeof(placeHolder)) + return false; + + // Write two zero bytes indicating interchange format + std::uint8_t interchange[2] = {0}; + if (fileSystem->write(fd, (char *) &interchange, sizeof(interchange)) != sizeof(interchange)) + return false; + + if (!padToPage(fileSystem, fd)) // Advance to next page before writing objects + return false; + + // Write objects + std::int32_t objectSpaceLength = 0; + for(int objectPointer = 2; objectPointer < storedObjectTableLength; objectPointer += 2) + { + if (!hasObject(objectPointer)) continue; + + // Write object to file... N.B. we do not store the extra word for HugeSize objects + std::uint16_t header[2]; + std::uint16_t objectSize = sizeBitsOf(objectPointer); + header[0] = objectSize; + header[1] = (std::uint16_t) fetchClassOf(objectPointer); + if (fileSystem->write(fd, (char *) &header, sizeof(header)) != sizeof(header)) + return false; + int wordLengthOfObject = fetchWordLengthOf(objectPointer); + for(int wordIndex = 0; wordIndex < wordLengthOfObject; wordIndex++ ) + { + std::uint16_t word = (std::uint16_t) fetchWord_ofObject(wordIndex, objectPointer); + if (fileSystem->write(fd, (char *) &word, sizeof(word)) != sizeof(word)) + return false; + } + + objectSpaceLength += objectSize; + } + + + if (!padToPage(fileSystem, fd)) // Advance to next page before writing object table + return false; + + // Write object table + int objectImageWordAddress = 0; + for(int objectPointer = 0; objectPointer < storedObjectTableLength; objectPointer += 2) + { + std::uint16_t oldOTValue = ot(objectPointer); + std::uint16_t oldOTLocation = locationBitsOf(objectPointer); + + if (objectPointer >= 2) + { + if (!freeBitOf(objectPointer) && countBitsOf(objectPointer) == 0) + { + // This entry was for a free chunk of memory, but we don't save + // free space in the image. Store as a + // an available OT entry by setting free bit + freeBitOf_put(objectPointer, 1); + } + + if (freeBitOf(objectPointer)) + { + // manual.pdf - page 3: free entries have freeBit set and other bits in both + // words are 0. + ot_put(objectPointer, 0); + freeBitOf_put(objectPointer, 1); + locationBitsOf_put(objectPointer, 0); + } + else + { + std::uint16_t objectSize = (std::uint16_t) sizeBitsOf(objectPointer); + + // Modify the location of the object table entry... we do this once we no longer + // process this object table entry + segmentBitsOf_put(objectPointer, objectImageWordAddress >> 16); + locationBitsOf_put(objectPointer, objectImageWordAddress & 0xffff); + objectImageWordAddress += objectSize; + } + } + + // Assemble object table entry + std::uint16_t words[2]; + words[0] = ot(objectPointer); + words[1] = locationBitsOf(objectPointer); + + // Restore OT entry + ot_put(objectPointer, oldOTValue); + locationBitsOf_put(objectPointer, oldOTLocation); + + // Write this entry + if (fileSystem->write(fd, (char *) &words, sizeof(words)) != sizeof(words)) + return false; + + } + + // Now we can go back fill in the values for the image header. + fileSystem->seek_to(fd, 0); + fileSystem->write(fd, (char *) &objectSpaceLength, sizeof(objectSpaceLength)); + fileSystem->write(fd, (char *) &storedObjectTableLength, sizeof(storedObjectTableLength)); + + return true; +} + +// sweepCurrentSegmentFrom: +int ObjectMemory::sweepCurrentSegmentFrom(int lowWaterMark) +{ + int si; + int di; + int objectPointer; + int size; + + + /* "source" + "ERROR dbanay - unused local 'space'" + si <- di <- lowWaterMark. + [si < HeapSpaceStop] + whileTrue: "for each object, si" + [(wordMemory segment: currentSegment word: si + 1) = NonPointer + ifTrue: "unallocated, so skip it" + [size <- wordMemory segment: currentSegment word: si. + si <- si + size] + ifFalse: "allocated, so keep it, but move it to compact storage" + [objectPointer + <- wordMemory segment: currentSegment word: si. + size <- self locationBitsOf: objectPointer. + "the reversed size" + self locationBitsOf: objectPointer + put: di. "point object table at new location" + self sizeBitsOf: objectPointer + put: size. "restore the size to its proper place" + si <- si + 1. "skip the size" + di <- di + 1. "skip the size" + 2 to: (self spaceOccupiedBy: objectPointer) do: + "move the rest of the object" + [ :i | + wordMemory segment: currentSegment + word: di + put: (wordMemory segment: + currentSegment + word: si). + si <- si + 1. + di <- di + 1]]]. + ^di + */ + + si = di = lowWaterMark; + while (si < HeapSpaceStop) // for each object, si + { + if (wordMemory.segment_word(currentSegment, si + 1) == NonPointer) + { + // Unallocated, so skip it (see abandonFreeChunksInSegment) + size = wordMemory.segment_word(currentSegment, si); + si = si + size; + } + else + { + // allocated, so keep it, but move it to compact storage + objectPointer = wordMemory.segment_word(currentSegment, si); // reversed pointer! + size = locationBitsOf(objectPointer); // the reversed size (stored during pointer reversal step) + locationBitsOf_put(objectPointer, di); // point object table at new location (di) + sizeBitsOf_put(objectPointer, size); // restore the size to its proper place + si++; // skip the size header + di++; // skip the size header (size we wrote to di via sizeBitsOf_put) + int limit = spaceOccupiedBy(objectPointer); + for(int i = 2; i <= limit; i++) // move the rest of the object (already wrote size via sizeBitsOf_put) + { + wordMemory.segment_word_put(currentSegment, di, + wordMemory.segment_word(currentSegment, si)); + si++; + di++; + + } + } + } + + return di; + +} + + +// compactCurrentSegment +void ObjectMemory::compactCurrentSegment() +{ + int lowWaterMark; + int bigSpace; + + /* "source" + lowWaterMark <- self abandonFreeChunksInSegment: currentSegment. + lowWaterMark < HeapSpaceStop + ifTrue: [self reverseHeapPointersAbove: lowWaterMark. + bigSpace <- self sweepCurrentSegmentFrom: lowWaterMark. + self deallocate: (self obtainPointer: + (HeapSpaceStop + 1 - bigSpace) + location: bigSpace)] + */ + + RUNTIME_CHECK(currentSegment >= FirstHeapSegment && currentSegment <= LastHeapSegment); + + lowWaterMark = abandonFreeChunksInSegment(currentSegment); + if (lowWaterMark < HeapSpaceStop) + { + reverseHeapPointersAbove(lowWaterMark); + bigSpace = sweepCurrentSegmentFrom(lowWaterMark); + deallocate(obtainPointer_location(HeapSpaceStop + 1 - bigSpace, bigSpace)); + } +} + +// Force a garbage collection +void ObjectMemory::garbageCollect() +{ +#ifdef GC_MARK_SWEEP + reclaimInaccessibleObjects(); +#endif +} + + +// releasePointer: +void ObjectMemory::releasePointer(int objectPointer) +{ + /* "source" + self freeBitOf: objectPointer put: 1. + self toFreePointerListAdd: objectPointer + */ + freeBitOf_put(objectPointer, 1); + toFreePointerListAdd(objectPointer); +} + + +// reverseHeapPointersAbove: +void ObjectMemory::reverseHeapPointersAbove(int lowWaterMark) +{ + int size; + + /* "source" + 0 to: ObjectTableSize-2 by: 2 do: + [ :objectPointer | + (self freeBitOf: objectPointer) = 0 + ifTrue: "the Object Table entry is in use" + [(self segmentBitsOf: objectPointer) = currentSegment + ifTrue: "the object is in this segment" + [(self locationBitsOf: objectPointer) < lowWaterMark + ifFalse: "the object will be swept" + [size <- self sizeBitsOf: objectPointer. + "rescue the size" + self sizeBitsOf: objectPointer + put: objectPointer. + "reverse the pointer" + self locationBitsOf: objectPointer + put: size "save the size"]]]] + */ + + /* pg. 673 G&R */ + for(int objectPointer = 0; objectPointer <= ObjectTableSize-2; objectPointer += 2) + { + if (freeBitOf(objectPointer) == 0) // the Object Table entry is in use + { + // the object is in this segment + if (segmentBitsOf(objectPointer) == currentSegment) + { + // the object will be swept + if (locationBitsOf(objectPointer) >= lowWaterMark) + { + size = sizeBitsOf(objectPointer); // rescue the size + sizeBitsOf_put(objectPointer, objectPointer); // reverse pointer + locationBitsOf_put(objectPointer, size); // save the size + } + } + } + } +} + + +// abandonFreeChunksInSegment: +int ObjectMemory::abandonFreeChunksInSegment(int segment) +{ + int lowWaterMark; // Location in the segment of the first free chunk + int objectPointer; + int nextPointer; + + /* "source" + lowWaterMark <- HeapSpaceStop. "first assume that no chunk is free" + HeaderSize to: BigSize do: "for each free-chunk list" + [ :size | + objectPointer <- self headOfFreeChunkList: size + inSegment: segment. + [objectPointer = NonPointer] whileFalse: + [lowWaterMark <- lowWaterMark min: + (self locationBitsOf: objectPointer). + nextPointer <- self classBitsOf: objectPointer. + "link to next free chunk" + self classBitsOf: objectPointer put: NonPointer. + "distinguish for sweep" + self releasePointer: objectPointer. + "add entry to free-pointer list" + objectPointer <- nextPointer]. + self resetFreeChunkList: size inSegment: segment]. + ^lowWaterMark + */ + + // This computes the low water mark and sets the class field of free chunks to NonPointer + // so that are identified as such and can be combined into one free block after compaction + lowWaterMark = HeapSpaceStop; // first assume that no chunk is free + for(int size = HeaderSize; size <= BigSize; size++) + { + objectPointer = headOfFreeChunkList_inSegment(size, segment); + while (objectPointer != NonPointer) + { + lowWaterMark = std::min(lowWaterMark, locationBitsOf(objectPointer)); + nextPointer = classBitsOf(objectPointer); // link to next free chunk + classBitsOf_put(objectPointer, NonPointer); // distinguish for sweep + releasePointer(objectPointer); // Add entry to free (object table) pointer list + objectPointer = nextPointer; + } + resetFreeChunkList_inSegment(size, segment); + } + return lowWaterMark; +} + + +#ifdef GC_MARK_SWEEP + +// reclaimInaccessibleObjects +void ObjectMemory::reclaimInaccessibleObjects() +{ + + /* "source" + self zeroReferenceCounts. + self markAccessibleObjects. + self rectifyCountsAndDeallocateGarbage + */ + + zeroReferenceCounts(); + markAccessibleObjects(); + rectifyCountsAndDeallocateGarbage(); +} + + +// markObjectsAccessibleFrom: +int ObjectMemory::markObjectsAccessibleFrom(int rootObjectPointer) +{ + /* "source" + ^self forAllObjectsAccessibleFrom: rootObjectPointer + suchThat: "the predicate tests for an unmarked object and marks it" + [ :objectPointer | + unmarked <- (self countBitsOf: objectPointer) = 0. + unmarked ifTrue: [self countBitsOf: objectPointer put: 1]. + unmarked] + do: "the action restores the mark to count=1" + [ :objectPointer | + self countBitsOf: objectPointer put: 1] + */ + return forAllObjectsAccessibleFrom_suchThat_do(rootObjectPointer, + [this](int objectPointer) { // the predicate tests for an unmarked object and marks it + bool unmarked = countBitsOf(objectPointer) == 0; + if (unmarked) + { + countBitsOf_put(objectPointer, 1); + } + return unmarked; + }, + [this](int objectPointer) { // the action restores the mark to count=1 + countBitsOf_put(objectPointer, 1); + }); + + } + + +// markAccessibleObjects +void ObjectMemory::markAccessibleObjects() +{ + /* "source" + "ERROR: rootObjectPointers not defined" + rootObjectPointers do: + [ :rootObjectPointer | + self markObjectsAccessibleFrom: rootObjectPointer] + */ + + for(int i = 0; i <= LastSpecialOop; i += 2) + { + addRoot(i); + } + + if (gcNotification) + gcNotification->prepareForCollection(); + +} +#endif + + +void ObjectMemory::outOfMemoryError() +{ + assert(0); + hal->error("Out of memory"); +} + +// allocateChunk: +int ObjectMemory::allocateChunk(int size) +{ + int objectPointer; + + /* "source" + "marking collector" + objectPointer <- self attemptToAllocateChunk: size. + objectPointer isNil ifFalse: [^objectPointer]. + self reclaimInaccessibleObjects. "garbage collect and try again" + objectPointer <- self attemptToAllocateChunk: size. + objectPointer isNil ifFalse: [^objectPointer]. + self outOfMemoryError "give up" + */ + + objectPointer = attemptToAllocateChunk(size); +#ifdef GC_MARK_SWEEP + if (objectPointer == NilPointer) + { + reclaimInaccessibleObjects(); + objectPointer = attemptToAllocateChunk(size); + } +#endif + if (objectPointer != NilPointer) + { + if (freeWords >= size) + freeWords -= size; + + return objectPointer; + } + outOfMemoryError(); // give up + return NilPointer; +} + +#ifdef GC_MARK_SWEEP + +// rectifyCountsAndDeallocateGarbage +void ObjectMemory::rectifyCountsAndDeallocateGarbage() +{ + int count; + + /* "source" + "reset heads of free-chunk lists" + FirstHeapSegment to: LastHeapSegment do: "for every segment" + [ :segment | + HeaderSize to: BigSize do: "for every free chunk list" + [ :size | "reset the list head" + self resetFreeChunkList: size inSegment: segment]]. + "rectify counts, and deallocate garbage" + 0 to: ObjectTableSize-2 by: 2 do: "for every object table entry" + [ :objectPointer | + (self freeBitOf: objectPointer) = 0 + ifTrue: "if it is not a free entry" + [(count <- self countBitsOf: objectPointer) = 0 + ifTrue: "it is unmarked so deallocate it" + [self deallocate: objectPointer] + ifFalse: "it is marked so rectify reference counts" + [count < 128 + ifTrue: "subtract 1 to compensate for the mark" + [self countBitsOf: objectPointer put: count-1]. + 1 to: (self lastPointerOf: objectPointer)-1 do: + [ :offset | "increment the reference count + of each pointer" + self countUp: + (self heapChunkOf: objectPointer + word: offset)]]]]. + "be sure the root objects don't disappear" + "ERROR: rootObjectPointers not defined" + rootObjectPointers do: + [ :rootObjectPointer | self countUp: rootObjectPointer]. + self countBitsOf: NilPointer put: 128 + */ + // reset heads of free-chunk lists + for(int segment = FirstHeapSegment; segment <= LastHeapSegment; segment++) + { + // for every free chunk list + for(int size = HeaderSize; size <= BigSize; size++) + { + // reset the list head + resetFreeChunkList_inSegment(size, segment); + } + } + + // rectify counts, and deallocate garbage + for(int objectPointer = 0; objectPointer <= ObjectTableSize-2; objectPointer += 2) + { + if (freeBitOf(objectPointer) == 0) // if it is not a free entry + { + count = countBitsOf(objectPointer); + if (count == 0) + { + // unmarked, so deallocate it + freeWords += spaceOccupiedBy(objectPointer); //dbanay + deallocate(objectPointer); + } + else + { + // it is marked so rectify reference counts + if (count < 128) + { + // subtract 1 to compensate for the mark + countBitsOf_put(objectPointer, count - 1); + } + + int limit = lastPointerOf(objectPointer)-1; + // increment the reference count of each pointer + // NB start at offset 1, which is the class + for(int offset = 1; offset <= limit; offset++) + { + countUp(heapChunkOf_word(objectPointer, offset)); + } + } + } + } + + countBitsOf_put(NilPointer, 128); + + freeOops = auditFreeOops(); + + if (gcNotification) gcNotification->collectionCompleted(); + + +} + + +// zeroReferenceCounts +void ObjectMemory::zeroReferenceCounts() +{ + /* "source" + 0 to: ObjectTableSize-2 by: 2 do: + [ :objectPointer | + self countBitsOf: objectPointer put: 0] + */ + + for(int objectPointer = 0; objectPointer <= ObjectTableSize-2; objectPointer += 2) + { + countBitsOf_put(objectPointer, 0); + } +} +#endif + +// lastPointerOf: +// This returns the size of object up to the last pointer in it +int ObjectMemory::lastPointerOf(int objectPointer) +{ + // MethodClass is the object table index of CompiledMethod. + static const int MethodClass = ClassCompiledMethod; + int methodHeader; + + /* "source" + "ERROR - dbanay this is WRONG." + (self pointerBitOf: objectPointer) = 0 + ifTrue: [^HeaderSize] + "ERROR: MethodClass not defined" + ifFalse: [(self classBitsOf: objectPointer) = MethodClass + ifTrue: [methodHeader <- self heapChunkOf: objectPointer + word: HeaderSize. + ^HeaderSize + 1 + ((methodHeader bitAnd: 126) + bitShift: -1)] + ifFalse: [^self sizeBitsOf: objectPointer]] + */ + + /* "source" + "Fixed in July 1985 Ed of G&R" + (self pointerBitOf: objectPointer) = 0 + ifTrue: [(self classBitsOf: objectPointer) = MethodClass + ifTrue: [methodHeader <- self heapChunkOf: objectPointer + word: HeaderSize. + ^HeaderSize + 1 + ((methodHeader bitAnd: 126) bitShift: -1)] + ifFalse: [^HeaderSize]] + ifFalse: + [^self sizeBitsOf: objectPointer] + + */ + + if (pointerBitOf(objectPointer) == 0) + { // Not pointer object + // CompiledMethods are special in that they are marked as having no pointers but actually do + if (classBitsOf(objectPointer) == MethodClass) + { + methodHeader = heapChunkOf_word(objectPointer, HeaderSize); + // Header Size + Method Header Size + Literal Count + return HeaderSize + 1 + ((methodHeader & 126) >> 1); + } + else + return HeaderSize; // Class field is last pointer in the object + } + + return sizeBitsOf(objectPointer); + +} + + +// spaceOccupiedBy: +int ObjectMemory::spaceOccupiedBy(int objectPointer) +{ + int size; + + /* "source" + size <- self sizeBitsOf: objectPointer. + (size < HugeSize or: [(self pointerBitOf: objectPointer) = 0]) + ifTrue: [^size] + ifFalse: [^size + 1] + */ + size = sizeBitsOf(objectPointer); + if (size < HugeSize || pointerBitOf(objectPointer) == 0) + return size; + return size+1; // Account for extra word used for traversal algorithm (G&R pg. 679) +} + + +// allocate:odd:pointer:extra:class: +int ObjectMemory::allocate_odd_pointer_extra_class( + int size, + int oddBit, + int pointerBit, + int extraWord, + int classPointer + ) +{ + int objectPointer; + int defaultValue; + + /* "source" + self countUp: classPointer. + objectPointer <- self allocateChunk: size + extraWord. + self oddBitOf: objectPointer put: oddBit. + self pointerBitOf: objectPointer put: pointerBit. + self classBitsOf: objectPointer put: classPointer. + default <- pointerBit=0 ifTrue: [0] ifFalse: [NilPointer]. + HeaderSize to: size-1 do: + [ :i | self heapChunkOf: objectPointer word: i put: default]. + self sizeBitsOf: objectPointer put: size. + ^objectPointer + */ + countUp(classPointer); + objectPointer = allocateChunk(size + extraWord); + oddBitOf_put(objectPointer, oddBit); + pointerBitOf_put(objectPointer, pointerBit); + classBitsOf_put(objectPointer, classPointer); + defaultValue = (pointerBit == 0) ? 0 : NilPointer; + for(int i = HeaderSize; i <= size-1; i++) + { + heapChunkOf_word_put(objectPointer, i, defaultValue); + } + sizeBitsOf_put(objectPointer, size); + freeOops--; // dbanay + return objectPointer; +} + +// headOfFreePointerList +int ObjectMemory::headOfFreePointerList() +{ + /* "source" + ^wordMemory segment: ObjectTableSegment + word: FreePointerList + */ + + return wordMemory.segment_word(ObjectTableSegment, + FreePointerList); +} + +// toFreeChunkList:add: +void ObjectMemory::toFreeChunkList_add(int size, int objectPointer) +{ + int segment; + + /* "source" + segment <- self segmentBitsOf: objectPointer. + self classBitsOf: objectPointer + put: (self headOfFreeChunkList: size inSegment: segment). + self headOfFreeChunkList: size + inSegment: segment + put: objectPointer + */ + + segment = segmentBitsOf(objectPointer); + classBitsOf_put(objectPointer, + headOfFreeChunkList_inSegment(size, segment)); + headOfFreeChunkList_inSegment_put(size, segment, objectPointer); + +} + + +// headOfFreeChunkList:inSegment:put: +int ObjectMemory::headOfFreeChunkList_inSegment_put(int size, int segment, int objectPointer) +{ + /* "source" + ^wordMemory segment: segment + word: FirstFreeChunkList + size + put: objectPointer + */ + + RUNTIME_CHECK(size >= HeaderSize && size <= BigSize); + + return wordMemory.segment_word_put(segment, + FirstFreeChunkList + size, + objectPointer); +} + + +// removeFromFreePointerList +int ObjectMemory::removeFromFreePointerList() +{ + int objectPointer; + + /* "source" + objectPointer <- self headOfFreePointerList. + objectPointer = NonPointer ifTrue: [^nil]. + self headOfFreePointerListPut: (self locationBitsOf: objectPointer). + ^objectPointer + */ + + objectPointer = headOfFreePointerList(); + if (objectPointer == NonPointer) + return NilPointer; + headOfFreePointerListPut(locationBitsOf(objectPointer)); + return objectPointer; +} + +// toFreePointerListAdd: +void ObjectMemory::toFreePointerListAdd(int objectPointer) +{ + /* "source" + self locationBitsOf: objectPointer + put: (self headOfFreePointerList). + self headOfFreePointerListPut: objectPointer + */ + + locationBitsOf_put(objectPointer, headOfFreePointerList()); + headOfFreePointerListPut(objectPointer); + +} + + +// removeFromFreeChunkList: +int ObjectMemory::removeFromFreeChunkList(int size) +{ + int objectPointer; + int secondChunk; + + + /* "source" + objectPointer <- self headOfFreeChunkList: size + inSegment: currentSegment. + objectPointer = NonPointer ifTrue: [^nil]. + secondChunk <- self classBitsOf: objectPointer. + self headOfFreeChunkList: size + inSegment: currentSegment + put: secondChunk. + ^objectPointer + */ + + RUNTIME_CHECK(currentSegment >= FirstHeapSegment && currentSegment <= LastHeapSegment); + + objectPointer = headOfFreeChunkList_inSegment(size, currentSegment); + if (objectPointer == NonPointer) return NilPointer; + secondChunk = classBitsOf(objectPointer); + headOfFreeChunkList_inSegment_put(size, + currentSegment, + secondChunk); + return objectPointer; + +} + + +// resetFreeChunkList:inSegment: +void ObjectMemory::resetFreeChunkList_inSegment(int size, int segment) +{ + /* "source" + self headOfFreeChunkList: size + inSegment: segment + put: NonPointer + */ + RUNTIME_CHECK(size >= 2 && size <= BigSize); + headOfFreeChunkList_inSegment_put(size, segment, NonPointer); +} + + +// headOfFreeChunkList:inSegment: +int ObjectMemory::headOfFreeChunkList_inSegment(int size, int segment) +{ + /* "source" + ^wordMemory segment: segment + word: FirstFreeChunkList + size + */ + RUNTIME_CHECK(size >= 2 && size <= BigSize); + return wordMemory.segment_word(segment, + FirstFreeChunkList + size); +} + + +// headOfFreePointerListPut: +int ObjectMemory::headOfFreePointerListPut(int objectPointer) +{ + /* "source" + ^wordMemory segment: ObjectTableSegment + word: FreePointerList + put: objectPointer + */ + + return wordMemory.segment_word_put(ObjectTableSegment, + FreePointerList, + objectPointer); +} + + +// countDown: +int ObjectMemory::countDown(int rootObjectPointer) +{ + + /* "source" + (self isIntegerObject: rootObjectPointer) + ifTrue: [^rootObjectPointer] + ifFalse: "this is a pointer, so decrement its reference count" + [^self forAllObjectsAccessibleFrom: rootObjectPointer + suchThat: + "the predicate decrements the count and tests for zero" + [ :objectPointer | + count <- (self countBitsOf: objectPointer) - 1. + count < 127 + ifTrue: [self countBitsOf: objectPointer + put: count]. + count = 0] + do: "the action zeroes the count and deallocates the object" + [ :objectPointer | + self countBitsOf: objectPointer put: 0. + self deallocate: objectPointer]] + */ + + if (isIntegerObject(rootObjectPointer)) + return rootObjectPointer; + + RUNTIME_CHECK(countBitsOf(rootObjectPointer)>0); + + // this is a pointer, so decrement its reference count + return forAllObjectsAccessibleFrom_suchThat_do(rootObjectPointer, + [this](int objectPointer) { // predicate + int count = countBitsOf(objectPointer) - 1; + RUNTIME_CHECK(count >= 0); + if (count < 127) + countBitsOf_put(objectPointer, count); + return count == 0; + }, + [this](int objectPointer) { // action + // std::cout << "reference count zero. freeing " << objectPointer << " (" << classNameOfObject(fetchClassOf(objectPointer)) << ") free oops = " << freeOops << "\n"; + countBitsOf_put(objectPointer, 0); + freeWords += spaceOccupiedBy(objectPointer); //dbanay + freeOops++; + deallocate(objectPointer); + }); + +} + + +// countUp: +int ObjectMemory::countUp(int objectPointer) +{ + int count; + + /* "source" + (self isIntegerObject: objectPointer) + ifFalse: [count <- (self countBitsOf: objectPointer) + 1. + count < 129 ifTrue: [self countBitsOf: objectPointer put: count]]. + ^objectPointer + */ + if (!isIntegerObject(objectPointer)) + { + count = countBitsOf(objectPointer) + 1; + if (count < 129) // Count sticks at 128 + countBitsOf_put(objectPointer, count); + } + + return objectPointer; +} + + +// deallocate: +void ObjectMemory::deallocate(int objectPointer) +{ + int space; + + /* "source" + space <- self spaceOccupiedBy: objectPointer. + self sizeBitsOf: objectPointer put: space. + self toFreeChunkList: (space min: BigSize) add: objectPointer + */ + + space = spaceOccupiedBy(objectPointer); + sizeBitsOf_put(objectPointer, space); + toFreeChunkList_add(std::min(space, (int) BigSize), objectPointer); +} + +#ifdef RECURSIVE_MARKING +// recursive version -- stack hungry +// forAllOtherObjectsAccessibleFrom:suchThat:do: +int ObjectMemory::forAllOtherObjectsAccessibleFrom_suchThat_do( + int objectPointer, + const std::function <bool (int)>& predicate, + const std::function <void (int)>& action + ) +{ + int next; + + /* "source" + 1 to: (self lastPointerOf: objectPointer) - 1 do: + [ :offset | + next <- self heapChunkOf: objectPointer word: offset. + ((self isIntegerObject: next)==false and: [predicate value: next]) + ifTrue: "it's a non-immediate object and it should be processed" + [self forAllOtherObjectsAccessibleFrom: next + suchThat: predicate + do: action]]. + "all pointers have been followed; now perform the action" + action value: objectPointer. + ^objectPointer + */ + + int limit = lastPointerOf(objectPointer) - 1; + //N.B. start at offset 1, which is class field + for(int offset = 1; offset <= limit; offset++) + { + next = heapChunkOf_word(objectPointer, offset); + if (!isIntegerObject(next) && predicate(next)) + { + // it's a non-immediate object and it should be processed + forAllOtherObjectsAccessibleFrom_suchThat_do(next, + predicate, + action); + } + } + + // all pointers have been followed; now perform the action + action(objectPointer); + return objectPointer; +} +#else +// forAllOtherObjectsAccessibleFrom:suchThat:do: +int ObjectMemory::forAllOtherObjectsAccessibleFrom_suchThat_do( + int objectPointer, + const std::function <bool (int)>& predicate, + const std::function <void (int)>& action +) +{ + int prior; + int current; + int offset; + int size; + int next; + + /* "source" + "compute prior, current, offset, and size to begin processing objectPointer" + prior <- NonPointer. + current <- objectPointer. + offset <- size <- self lastPointerOf: objectPointer. + [true] whileTrue: "for all pointers in all objects traversed" + [(offset <- offset - 1) > 0 "decrement the field index" + ifTrue: "the class hasn't been passed yet" + [next <- self heapChunkOf: current word: offset. + "one of the pointers" + ((self isIntegerObject: next)==false and: [predicate value: next]) + ifTrue: "it's a non-immediate object and it should be processed" + ["reverse the pointer chain" + self heapChunkOf: current word: offset put: prior. + "save the offset either in the count field or in the extra word" + size < HugeSize + ifTrue: [self countBitsOf: current put: offset] + ifFalse: [self heapChunkOf: current + word: size+1 put: offset]. "ERROR dbanay size not size + 1" + "compute prior, current, offset, and size to begin processing next" + prior <- current. + current <- next. + offset <- size <- self lastPointerOf: current]] + ifFalse: ["all pointers have been followed; now perform the action" + action value: objectPointer. "ERROR dbanay - should be current" + "did we get here from another object?" + prior = NonPointer + ifTrue: "this was the root object, so we are done" + [^objectPointer]. + "restore next, current and size to resume processing prior" + next <- current. + current <- prior. + size <- self lastPointerOf: current. + "restore offset either from the count field or from the extra word" + size < HugeSize + ifTrue: [offset <- self countBitsOf: current] + ifFalse: [offset <- self heapChunkOf: current word: size+1]. "ERROR dbanay size not size + 1" + "restore prior from the reversed pointer chain" + prior <- self heapChunkOf: current word: offset. + "restore (un-reverse) the pointer chain" + self heapChunkOf: current word: offset put: next]] + */ + + prior = NonPointer; + current = objectPointer; + offset = size = lastPointerOf(objectPointer); + for(;;) + { + // for all pointers in all objects traversed + offset--; // decrement the field index + if (offset > 0) // the class hasn't been passed yet + { + next = heapChunkOf_word(current, offset); // one of the pointers + if (!isIntegerObject(next) && predicate(next)) + { + // it's a non-immediate object and it should be processed + // reverse pointer chain + heapChunkOf_word_put(current, offset, prior); + // save the offset either in the count field or in the extra word + if (size < HugeSize) + countBitsOf_put(current, offset); + else + heapChunkOf_word_put(current, size, offset); + // compute prior, current, offset, and size to begin processing next + prior = current; + current = next; + offset = size = lastPointerOf(current); + } + } + else + { + // all pointers have been followed; now perform the action + action(current); + // did we get here from another object? + if (prior == NonPointer) // this was the root object, so we are done + return objectPointer; + // restore next, current and size to resume processing prior + next = current; + current = prior; + size = lastPointerOf(current); + // restore offset either from the count field or from the extra word + if (size < HugeSize) + offset = countBitsOf(current); + else + offset = heapChunkOf_word(current, size); + // restore prior from the reversed pointer chain + prior = heapChunkOf_word(current, offset); + // restore (un-reverse) the pointer chain + heapChunkOf_word_put(current, offset, next); + } + } + } +#endif + + +// forAllObjectsAccessibleFrom:suchThat:do: +int ObjectMemory::forAllObjectsAccessibleFrom_suchThat_do(int objectPointer, + const std::function <bool (int)>& predicate, + const std::function <void (int)>& action) +{ + /* "source" + (predicate value: objectPointer) + ifTrue: [^self forAllOtherObjectsAccessibleFrom: objectPointer + suchThat: predicate + do: action] + */ + + if (predicate(objectPointer)) + { + return forAllOtherObjectsAccessibleFrom_suchThat_do(objectPointer, + predicate, + action); + } + + return NilPointer; + +} + + +// storePointer:ofObject:withValue: +int ObjectMemory::storePointer_ofObject_withValue(int fieldIndex, int objectPointer, int valuePointer) +{ + int chunkIndex; + + /* "source" + chunkIndex <- HeaderSize + fieldIndex. + self countUp: valuePointer. + self countDown: (self heapChunkOf: objectPointer word: chunkIndex). + ^self heapChunkOf: objectPointer word: chunkIndex put: valuePointer + */ + + RUNTIME_CHECK(fieldIndex >= 0 && fieldIndex < fetchWordLengthOf(objectPointer)); + RUNTIME_CHECK(valuePointer > 0); + + chunkIndex = HeaderSize + fieldIndex; + +#ifdef GC_REF_COUNT + countUp(valuePointer); + countDown(heapChunkOf_word(objectPointer, chunkIndex)); +#endif + return heapChunkOf_word_put(objectPointer, chunkIndex, valuePointer); +} + + +// storeWord:ofObject:withValue: +int ObjectMemory::storeWord_ofObject_withValue(int wordIndex, int objectPointer, int valueWord) +{ + /* "source" + ^self heapChunkOf: objectPointer word: HeaderSize + wordIndex + put: valueWord + */ + RUNTIME_CHECK(wordIndex >= 0 && wordIndex < fetchWordLengthOf(objectPointer)); + return heapChunkOf_word_put(objectPointer, HeaderSize + wordIndex, + valueWord); +} + + +// initialInstanceOf: +int ObjectMemory::initialInstanceOf(int classPointer) +{ + // Mario checks for the count bit not being zero. This is necessary + // because an OT entry with a clear free bit but a ZERO count marks + // an allocated chunk of memory available for use + /* "source" + 0 to: ObjectTableSize-2 by: 2 do: + [ :pointer | + "ERROR in next line, second part of test omitted" + ((self freeBitOf: pointer) = 0 and: [(self countBitOf: pointer) ~= 0]) + ifTrue: [(self fetchClassOf: pointer) = classPointer + ifTrue: [^pointer]]]. + ^NilPointer + */ + + for(int pointer = 0; pointer <= ObjectTableSize-2; pointer += 2) + { + // Only consider non-free entries that are not free chunks + if (freeBitOf(pointer) == 0 && countBitsOf(pointer) != 0) + { + if (fetchClassOf(pointer) == classPointer) + return pointer; + } + } + return NilPointer; +} + + + +// swapPointersOf:and: +void ObjectMemory::swapPointersOf_and(int firstPointer, int secondPointer) +{ + + int firstSegment; + int firstLocation; + int firstPointerBit; /* dbanay - ERROR was named firstPointer */ + int firstOdd; + + /* "source" + "ERROR in next line, firstPointer redefined" + "dbanay - should have been called firstPointerBit (FYI - NOT FIXED IN July 1985 ed)" + firstSegment <- self segmentBitsOf: firstPointer. + firstLocation <- self locationBitsOf: firstPointer. + "dbanay ERROR - next should be: firstPointerBit <- self pointerBitOf: firstPointer. + firstPointer <- self pointerBitOf: firstPointer. + firstOdd <- self oddBitOf: firstPointer. + self segmentBitsOf: firstPointer put: (self segmentBitsOf: secondPointer). + self locationBitsOf: firstPointer put: (self locationBitsOf: secondPointer). + self pointerBitOf: firstPointer put: (self pointerBitOf: secondPointer). + self oddBitOf: firstPointer put: (self oddBitOf: secondPointer). + self segmentBitsOf: secondPointer put: firstSegment. + self locationBitsOf: secondPointer put: firstLocation. + "ERROR dbanay - should be firstPointerBit" + self pointerBitOf: secondPointer put: firstPointer. + self oddBitOf: secondPointer put: firstOdd + */ + + firstSegment = segmentBitsOf(firstPointer); + firstLocation = locationBitsOf(firstPointer); + firstPointerBit = pointerBitOf(firstPointer); + firstOdd = oddBitOf(firstPointer); + + segmentBitsOf_put(firstPointer, segmentBitsOf(secondPointer)); + locationBitsOf_put(firstPointer, locationBitsOf(secondPointer)); + pointerBitOf_put(firstPointer, pointerBitOf(secondPointer)); + oddBitOf_put(firstPointer, oddBitOf(secondPointer)); + + segmentBitsOf_put(secondPointer, firstSegment); + locationBitsOf_put(secondPointer, firstLocation); + pointerBitOf_put(secondPointer, firstPointerBit); + oddBitOf_put(secondPointer, firstOdd); +} + + +// instantiateClass:withWords: +int ObjectMemory::instantiateClass_withWords(int classPointer, int length) +{ + int size; + + /* "source" + size <- HeaderSize + length. + ^self allocate: size odd: 0 pointer: 0 extra: 0 class: classPointer + */ + size = HeaderSize + length; + return allocate_odd_pointer_extra_class(size, 0, 0, 0, classPointer); +} + + +// instantiateClass:withBytes: +int ObjectMemory::instantiateClass_withBytes(int classPointer, int length) +{ + int size; + + /* "source" + size <- HeaderSize + ((length + 1)/2). + ^self allocate: size odd: length\\2 pointer: 0 extra: 0 class: classPointer + */ + size = HeaderSize + ((length + 1)/2); + return allocate_odd_pointer_extra_class(size, length % 2, 0, 0, classPointer); +} + + +// hasObject: +bool ObjectMemory::hasObject(int objectPointer) +{ + /* "source" + "is objectPointer pointing to a valid object ?" + ^(self freeBitOf: objectPointer) = 0 + "not sure that the first clause is necessary" + and: [(self countBitsOf: objectPointer) ~= 0] + */ + cantBeIntegerObject(objectPointer); // dbanay + return freeBitOf(objectPointer) == 0 && countBitsOf(objectPointer) != 0; +} + +int ObjectMemory::auditFreeOops() +{ + int count = 0; + for(int objectPointer = 2; objectPointer < ObjectTableSize; objectPointer+=2) + { + if (!hasObject(objectPointer)) + count++; + } + + return count; +} + + + +// instantiateClass:withPointers: +int ObjectMemory::instantiateClass_withPointers(int classPointer, int length) +{ + int size; + int extra; + + /* "source" + size <- HeaderSize + length. + extra <- size < HugeSize ifTrue: [0] ifFalse: [1]. + ^self allocate: size odd: 0 pointer: 1 extra: extra class: classPointer + */ + + size = HeaderSize + length; + extra = size < HugeSize ? 0 : 1; + return allocate_odd_pointer_extra_class(size, 0, 1, extra, classPointer); +} + + +// instanceAfter: +int ObjectMemory::instanceAfter(int objectPointer) +{ + int classPointer; + + /* "source" + "July 1985 ed also got this wrong" + "ERROR: next line omitted by G&R" + classPointer <- self fetchClassOf: objectPointer. + "dbanay - ERROR - was 'objectPointer to: ObjectTableSize-2 by: 2 do:' should start at objectPointer+2'" + "dbanay - ERROR - should also check count bits to skip free Chunk entries" + objectPointer to: ObjectTableSize-2 by: 2 do: + [ :pointer | + (self freeBitOf: pointer) = 0 + ifTrue: [(self fetchClassOf: pointer) = classPointer + ifTrue: [^pointer]]]. + ^NilPointer + */ + + classPointer = fetchClassOf(objectPointer); + + for(int pointer = objectPointer+2; pointer <= ObjectTableSize-2; pointer += 2) + { + if (hasObject(pointer)) + { + if (fetchClassOf(pointer) == classPointer) + return pointer; + } + } + return NilPointer; + +} + + + +// cantBeIntegerObject: +void ObjectMemory::cantBeIntegerObject(int objectPointer) +{ + /* "source" + (self isIntegerObject: objectPointer) + "ERROR: Sensor and notify: not defined" + ifTrue: [Sensor notify: 'A small integer has no object table entry'] + */ + + assert(!isIntegerObject(objectPointer)); + if (isIntegerObject(objectPointer)) + hal->error("A small integer has no object table entry"); +} + + + +// obtainPointer:location: +int ObjectMemory::obtainPointer_location(int size, int location) +{ + int objectPointer; + + /* "source" + objectPointer <- self removeFromFreePointerList. + objectPointer isNil ifTrue: [^nil]. + self ot: objectPointer put: 0. + self segmentBitsOf: objectPointer put: currentSegment. + self locationBitsOf: objectPointer put: location. + self sizeBitsOf: objectPointer put: size. + ^objectPointer + */ + RUNTIME_CHECK(currentSegment >= FirstHeapSegment && currentSegment <= LastHeapSegment); + objectPointer = removeFromFreePointerList(); + if (objectPointer == NilPointer) + return NilPointer; + ot_put(objectPointer, 0); + segmentBitsOf_put(objectPointer, currentSegment); + locationBitsOf_put(objectPointer, location); + sizeBitsOf_put(objectPointer, size); + return objectPointer; +} + + +// attemptToAllocateChunk: +int ObjectMemory::attemptToAllocateChunk(int size) +{ + int objectPointer; + + /* "source" + objectPointer <- self attemptToAllocateChunkInCurrentSegment: size. + objectPointer isNil ifFalse: [^objectPointer]. + 1 to: HeapSegmentCount do: + [ :i | + currentSegment <- currentSegment + 1. + currentSegment > LastHeapSegment + ifTrue: [currentSegment <- FirstHeapSegment]. + self compactCurrentSegment. + objectPointer + <- self attemptToAllocateChunkInCurrentSegment: size. + objectPointer isNil ifFalse: [^objectPointer]]. + ^nil + */ + + RUNTIME_CHECK(currentSegment >= FirstHeapSegment && currentSegment <= LastHeapSegment); + objectPointer = attemptToAllocateChunkInCurrentSegment(size); + if (objectPointer != NilPointer) return objectPointer; + for(int i = 1; i <= HeapSegmentCount; i++) + { + currentSegment++; + if (currentSegment > LastHeapSegment) + currentSegment = FirstHeapSegment; + compactCurrentSegment(); + objectPointer = attemptToAllocateChunkInCurrentSegment(size); + if (objectPointer != NilPointer) + return objectPointer; + + } + return NilPointer; +} + + +// attemptToAllocateChunkInCurrentSegment: +int ObjectMemory::attemptToAllocateChunkInCurrentSegment(int size) +{ + int objectPointer = NilPointer; + int predecessor; + int next; + int availableSize; + int excessSize; + int newPointer; + + /* "source" + ERROR dbanay - LastFreeChunkList is a LOCATION and not a size. Should use BigSize + size < BigSize + ifTrue: [objectPointer <- self removeFromFreeChunkList: size]. + objectPointer notNil + ifTrue: [^objectPointer]. "small chunk of exact size handy so use it" + predecessor <- NonPointer. + "remember predecessor of chunk under consideration" + objectPointer <- self headOfFreeChunkList: LastFreeChunkList + inSegment: currentSegment. + "the search loop stops when the end of the linked list is encountered" + [objectPointer = NonPointer] whileFalse: + [availableSize <- self sizeBitsOf: objectPointer. + availableSize = size + ifTrue: "exact fit - remove from free chunk list and return" + [next <- self classBitsOf: objectPointer. + "the link to the next chunk" + predecessor = NonPointer + ifTrue: "it was the head of the list; make the next item the head" + [self headOfFreeChunkList: LastFreeChunkList + inSegment: currentSegment + put: next] + ifFalse: "it was between two chunks; link them together" + [self classBitsOf: predecessor + put: next]. + ^objectPointer]. + "this chunk was either too big or too small; inspect the amount of variance" + excessSize <- availableSize - size. + excessSize >= HeaderSize + ifTrue: "can be broken into two usable parts: return the second part" + ["obtain an object table entry for the second part" + newPointer <- self obtainPointer: size + location: (self locationBitsOf: objectPointer) + + excessSize. + newPointer isNil ifTrue: [^nil]. + "correct the size of the first part (which remains on the free list)" + self sizeBitsOf: objectPointer put: excessSize. + ^newPointer] + ifFalse: "not big enough to use; try the next chunk on the list" + [predecessor <- objectPointer. + objectPointer <- self classBitsOf: objectPointer]]. + ^nil "the end of the linked list was reached and no fit was found" + */ + RUNTIME_CHECK(currentSegment >= FirstHeapSegment && currentSegment <= LastHeapSegment); + if (size < BigSize) + objectPointer = removeFromFreeChunkList(size); + + if (objectPointer != NilPointer) + { + return objectPointer; // small chunk of exact size handy so use it + } + predecessor = NonPointer; // remember predecessor of chunk under consideration + objectPointer = headOfFreeChunkList_inSegment(BigSize, currentSegment); + + // the search loop stops when the end of the linked list is encountered + while (objectPointer != NonPointer) + { + availableSize = sizeBitsOf(objectPointer); + if (availableSize == size) + { + // exact fit - remove from free chunk list and return + next = classBitsOf(objectPointer); // the link to the next chunk + if (predecessor == NonPointer) + { + // it was the head of the list; make the next item the head + headOfFreeChunkList_inSegment_put(BigSize, currentSegment, next); + } + else + { + // it was between two chunks; link them together + classBitsOf_put(predecessor, next); + } + return objectPointer; + } + + // this chunk was either too big or too small; inspect the amount of variance + excessSize = availableSize - size; + if (excessSize >= HeaderSize) + { + // can be broken into two usable parts: return the second part + // obtain an object table entry for the second part + newPointer = obtainPointer_location(size, locationBitsOf(objectPointer) + excessSize); + if (newPointer == NilPointer) + return NilPointer; + // correct the size of the first part (which remains on the free list) + sizeBitsOf_put(objectPointer, excessSize); + return newPointer; + } + else + { + // not big enough to use; try the next chunk on the list + predecessor = objectPointer; + objectPointer = classBitsOf(objectPointer); + } + } + + return NilPointer; // the end of the linked list was reached and no fit was found +} + diff --git a/vm/objmemory.h b/vm/objmemory.h @@ -0,0 +1,858 @@ +// +// objmemory.h +// Smalltalk-80 +// +// Created by Dan Banay on 2/20/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +#pragma once + +#include <cstdint> +#include <cassert> +#include <functional> +#include "hal.h" +#include "filesystem.h" +#include "realwordmemory.h" +#include "oops.h" + +// The Smalltalk-80 VM generates a tremendous amount of circular references as it runs +// -- primarily a MethodContext that references a BlockContext (from a temp field) that +// has a back reference to that MethodContext (the sender field). If a reference counting only +// scheme is used, then free object table entries will eventually be consumed. If, on the other hand, +// a GC only approach is used then memory will fill up with contexts and GC will happen fairly +// frequently. Therefore, the hybrid reference counting approach with full garbage collection +// when too much circular garbage accumulates is recommended. + +// GM_MARK_SWEEP and GC_REF_COUNT are not mutually exclusive! +// You can define *BOTH* for a hybrid collector which ref counts until +// memory is exhausted (cyclical data) and then does a full GC + +// Mark and sweep collection when memory full +#define GC_MARK_SWEEP + +// Ref counting +#define GC_REF_COUNT + + +// Define to use recursive marking for ref counting/GC +// If undefined the stack space efficient pointer reversal approach described +// on page 678 of G&R is used. Not recommended, and only included for completeness. +//#define RECURSIVE_MARKING + +// Perform range checks etc. at runtime +#define RUNTIME_CHECKING + +#ifdef RUNTIME_CHECKING +#define RUNTIME_CHECK2(c,f,l) runtime_check(c, "RUNTIME ERROR: (" #c ") at: " f "(" #l ")") +#define RUNTIME_CHECK1(c,f,l) RUNTIME_CHECK2(c,f,l) +#define RUNTIME_CHECK(cond) RUNTIME_CHECK1(cond, __FILE__, __LINE__) +#else +#define RUNTIME_CHECK(cond) ((void)0) +#endif + +#ifdef GC_MARK_SWEEP +class IGCNotification +{ +public: + // About to garbage collect. Client should call addRoot to specify roots of the world + virtual void prepareForCollection() = 0; + // Garbage collection has been completed + virtual void collectionCompleted() = 0; +}; + +#endif + +class ObjectMemory +{ +public: +#ifdef GC_MARK_SWEEP + ObjectMemory(IHardwareAbstractionLayer *halInterface, IGCNotification *notification = 0); +#else + ObjectMemory(IHardwareAbstractionLayer *halInterface); +#endif + + bool loadSnapshot(IFileSystem *fileSystem, const char *imageFileName); + bool saveSnapshot(IFileSystem *fileSystem, const char *imageFileName); + + + // --- BCIInterface --- + + inline int oopsLeft() + { + return freeOops; + } + + inline std::uint32_t coreLeft() + { + return freeWords; + } + + + void garbageCollect(); + + // storePointer:ofObject:withValue: + int storePointer_ofObject_withValue(int fieldIndex, int objectPointer, int valuePointer); + + // storeWord:ofObject:withValue: + int storeWord_ofObject_withValue(int wordIndex, int objectPointer, int valueWord); + + // increaseReferencesTo: + inline void increaseReferencesTo(int objectPointer) + { + /* "source" + self countUp: objectPointer + */ +#ifdef GC_REF_COUNT + countUp(objectPointer); +#endif + } + + // initialInstanceOf: + int initialInstanceOf(int classPointer); + + // decreaseReferencesTo: + inline void decreaseReferencesTo(int objectPointer) + { + /* "source" + self countDown: objectPointer + */ +#ifdef GC_REF_COUNT + countDown(objectPointer); +#endif + } + + + // isIntegerValue: + inline bool isIntegerValue(int valueWord) + { + /* "source" + "ERROR: G&R really cock this up" + "dbanay - still broken in July 1985 ed!" + ^valueWord >= -16384 and: [valueWord <= 16383] + */ + + return valueWord >= -16384 && valueWord <= 16383; + } + + + // fetchWord:ofObject: + inline int fetchWord_ofObject(int wordIndex, int objectPointer) + { + /* "source" + ^self heapChunkOf: objectPointer word: HeaderSize + wordIndex + */ + + RUNTIME_CHECK(wordIndex >= 0 && wordIndex < fetchWordLengthOf(objectPointer)); + return heapChunkOf_word(objectPointer, HeaderSize + wordIndex); + } + + + // integerValueOf: + inline int integerValueOf(int objectPointer) + { + /* "source" + ^objectPointer/2 + */ + + + return (std::int16_t)(objectPointer & 0xfffe)/2; + // Right shifting a negative number is undefined according to the standard. + // return ((std::int16_t) objectPointer) >> 1; + } + + // swapPointersOf:and: + void swapPointersOf_and(int firstPointer, int secondPointer); + + // fetchWordLengthOf: + inline int fetchWordLengthOf(int objectPointer) + { + /* "source" + ^(self sizeBitsOf: objectPointer) - HeaderSize + */ + + return sizeBitsOf(objectPointer) - HeaderSize; + } + + // instantiateClass:withWords: + int instantiateClass_withWords(int classPointer, int length); + + // isIntegerObject: + inline bool isIntegerObject(int objectPointer) + { + /* "source" + ^(objectPointer bitAnd: 1) = 1 + */ + + return (objectPointer & 1) == 1; + } + + + // instantiateClass:withBytes: + int instantiateClass_withBytes(int classPointer, int length); + + // hasObject: + bool hasObject(int objectPointer); + + // instantiateClass:withPointers: + int instantiateClass_withPointers(int classPointer, int length); + + // fetchByte:ofObject: + inline int fetchByte_ofObject(int byteIndex, int objectPointer) + { + /* "source" + ^self heapChunkOf: objectPointer byte: (HeaderSize*2 + byteIndex) + */ + return heapChunkOf_byte(objectPointer, (HeaderSize*2 + byteIndex)); + } + + // fetchPointer:ofObject: + inline int fetchPointer_ofObject(int fieldIndex, int objectPointer) + { + /* "source" + ^self heapChunkOf: objectPointer word: HeaderSize + fieldIndex + */ + RUNTIME_CHECK(fieldIndex >= 0 && fieldIndex < fetchWordLengthOf(objectPointer)); + return heapChunkOf_word(objectPointer, HeaderSize + fieldIndex); + } + + // fetchClassOf: + inline int fetchClassOf(int objectPointer) + { + /* Note that fetchClassOf:objectPointer returns IntegerClass (the object table index of SmallInteger) + if its argument is an immediate integer. G&R pg 686 */ + /* "source" + (self isIntegerObject: objectPointer) + ifTrue: [^IntegerClass] "ERROR IntegerClass not defined" + ifFalse: [^self classBitsOf: objectPointer] + */ + + if (isIntegerObject(objectPointer)) + return ClassSmallInteger; + + return classBitsOf(objectPointer); + + } + + // integerObjectOf: + inline int integerObjectOf(int value) + { + /* "source" + ^(value bitShift: 1) + 1 + */ + return (std::uint16_t) ((value << 1) | 1); + } + + // fetchByteLengthOf: + inline int fetchByteLengthOf(int objectPointer) + { + /* "source" + "ERROR in selector of next line" + ^(self fetchWordLengthOf: objectPointer)*2 - (self oddBitOf: objectPointer) + */ + return fetchWordLengthOf(objectPointer)*2 - oddBitOf(objectPointer); + } + + + // instanceAfter: + int instanceAfter(int objectPointer); + + // storeByte:ofObject:withValue: + inline int storeByte_ofObject_withValue(int byteIndex, int objectPointer, int valueByte) + { + /* "source" + ^self heapChunkOf: objectPointer + byte: (HeaderSize*2 + byteIndex) + put: valueByte + */ + + return heapChunkOf_byte_put(objectPointer, + HeaderSize*2 + byteIndex, + valueByte); + } + + + // --- ObjectPointers --- + + // cantBeIntegerObject: + void cantBeIntegerObject(int objectPointer); + + #ifdef GC_MARK_SWEEP + void addRoot(int rootObjectPointer) //dbanay + { + markObjectsAccessibleFrom(rootObjectPointer); + } + #endif + +private: + + // --- Compaction --- + + // sweepCurrentSegmentFrom: + int sweepCurrentSegmentFrom(int lowWaterMark); + + // compactCurrentSegment + void compactCurrentSegment(); + + // releasePointer: + void releasePointer(int objectPointer); + + // reverseHeapPointersAbove: + void reverseHeapPointersAbove(int lowWaterMark); + + // abandonFreeChunksInSegment: + int abandonFreeChunksInSegment(int segment); + + // allocateChunk: + int allocateChunk(int size); + +#ifdef GC_MARK_SWEEP + // --- MarkingGarbage --- + + // reclaimInaccessibleObjects + void reclaimInaccessibleObjects(); + + // markObjectsAccessibleFrom: + int markObjectsAccessibleFrom(int rootObjectPointer); + + // markAccessibleObjects + void markAccessibleObjects(); + + // rectifyCountsAndDeallocateGarbage + void rectifyCountsAndDeallocateGarbage(); + + // zeroReferenceCounts + void zeroReferenceCounts(); + +#endif + + // --- NonpointerObjs --- + + // lastPointerOf: + int lastPointerOf(int objectPointer); + + // spaceOccupiedBy: + int spaceOccupiedBy(int objectPointer); + + // allocate:odd:pointer:extra:class: + int allocate_odd_pointer_extra_class( + int size, + int oddBit, + int pointerBit, + int extraWord, + int classPointer + ); + + + // --- UnallocatedSpc --- + + // headOfFreePointerList + int headOfFreePointerList(); + + // toFreeChunkList:add: + void toFreeChunkList_add(int size, int objectPointer); + + // headOfFreeChunkList:inSegment:put: + int headOfFreeChunkList_inSegment_put(int size, int segment, int objectPointer); + + // removeFromFreePointerList + int removeFromFreePointerList(); + + // toFreePointerListAdd: + void toFreePointerListAdd(int objectPointer); + + // removeFromFreeChunkList: + int removeFromFreeChunkList(int size); + + // resetFreeChunkList:inSegment: + void resetFreeChunkList_inSegment(int size, int segment); + + // headOfFreeChunkList:inSegment: + int headOfFreeChunkList_inSegment(int size, int segment); + + // headOfFreePointerListPut: + int headOfFreePointerListPut(int objectPointer); + + + // --- RefCntGarbage --- + + // countDown: + int countDown(int rootObjectPointer); + + // countUp: + int countUp(int objectPointer); + + // deallocate: + void deallocate(int objectPointer); + + // forAllOtherObjectsAccessibleFrom:suchThat:do: + int forAllOtherObjectsAccessibleFrom_suchThat_do( + int objectPointer, + const std::function <bool (int)>& predicate, + const std::function <void (int)>& action + ); + + // forAllObjectsAccessibleFrom:suchThat:do: + int forAllObjectsAccessibleFrom_suchThat_do(int objectPointer, + const std::function <bool (int)>& predicate, + const std::function <void (int)>& action); + + + // --- ObjectTableEnt --- + + // segmentBitsOf: + inline int segmentBitsOf(int objectPointer) + { + /* "source" + ^self ot: objectPointer bits: 12 to: 15 + */ + + return ot_bits_to(objectPointer, 12, 15); + } + + // heapChunkOf:byte:put: + inline int heapChunkOf_byte_put(int objectPointer, int offset, int value) + { + /* "source" + ^wordMemory segment: (self segmentBitsOf: objectPointer) + word: ((self locationBitsOf: objectPointer) + (offset//2)) + byte: (offset\\2) put: value + */ + + return wordMemory.segment_word_byte_put(segmentBitsOf(objectPointer), + locationBitsOf(objectPointer) + (offset/2), + offset % 2, value); + } + + + // pointerBitOf:put: + inline int pointerBitOf_put(int objectPointer, int value) + { + /* "source" + ^self ot: objectPointer bits: 9 to: 9 put: value + */ + + return ot_bits_to_put(objectPointer, 9, 9, value); + } + + + // heapChunkOf:word: + inline int heapChunkOf_word(int objectPointer, int offset) + { + /* "source" + ^wordMemory segment: (self segmentBitsOf: objectPointer) + word: ((self locationBitsOf: objectPointer) + offset) + */ + return wordMemory.segment_word(segmentBitsOf(objectPointer), + locationBitsOf(objectPointer) + offset); + } + + // segmentBitsOf:put: + inline int segmentBitsOf_put(int objectPointer, int value) + { + /* "source" + ^self ot: objectPointer bits: 12 to: 15 put: value + */ + + return ot_bits_to_put(objectPointer, 12, 15, value); + } + + // heapChunkOf:word:put: + inline int heapChunkOf_word_put(int objectPointer, int offset, int value) + { + /* "source" + ^wordMemory segment: (self segmentBitsOf: objectPointer) + word: ((self locationBitsOf: objectPointer) + offset) + put: value + */ + return wordMemory.segment_word_put(segmentBitsOf(objectPointer), + locationBitsOf(objectPointer) + offset, + value); + } + + // oddBitOf: + inline int oddBitOf(int objectPointer) + { + /* "source" + ^self ot: objectPointer bits: 8 to: 8 + */ + + return ot_bits_to(objectPointer, 8, 8); + } + + + // freeBitOf: + inline int freeBitOf(int objectPointer) + { + /* "source" + ^self ot: objectPointer bits: 10 to: 10 + */ + + return ot_bits_to(objectPointer, 10, 10); + } + + // locationBitsOf: + inline int locationBitsOf(int objectPointer) + { + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + 1 + */ + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word(ObjectTableSegment, + ObjectTableStart + objectPointer + 1); + } + + // ot: + inline int ot(int objectPointer) + { + + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + */ + + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word(ObjectTableSegment, + ObjectTableStart + objectPointer); + } + + // freeBitOf:put: + inline int freeBitOf_put(int objectPointer, int value) + { + /* "source" + ^self ot: objectPointer bits: 10 to: 10 put: value + */ + + return ot_bits_to_put(objectPointer, 10, 10, value); + } + + // classBitsOf:put: + inline int classBitsOf_put(int objectPointer, int value) + { + /* "source" + ^self heapChunkOf: objectPointer word: 1 put: value + */ + + return heapChunkOf_word_put(objectPointer, 1, value); + } + + // heapChunkOf:byte: + inline int heapChunkOf_byte(int objectPointer, int offset) + { + /* "source" + ^wordMemory segment: (self segmentBitsOf: objectPointer) + word: ((self locationBitsOf: objectPointer) + (offset//2)) + byte: (offset\\2) + */ + + return wordMemory.segment_word_byte(segmentBitsOf(objectPointer), + locationBitsOf(objectPointer) + offset/2, + offset % 2); + } + + + // locationBitsOf:put: + inline int locationBitsOf_put(int objectPointer, int value) + { + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + 1 + put: value + */ + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word_put(ObjectTableSegment, + ObjectTableStart + objectPointer + 1, + value); + } + + + // sizeBitsOf: + inline int sizeBitsOf(int objectPointer) + { + /* "source" + ^self heapChunkOf: objectPointer word: 0 + */ + + return heapChunkOf_word(objectPointer, 0); + } + + + // oddBitOf:put: + inline int oddBitOf_put(int objectPointer, int value) + { + /* "source" + ^self ot: objectPointer bits: 8 to: 8 put: value + */ + return ot_bits_to_put(objectPointer, 8, 8, value); + } + + // ot:put: + inline int ot_put(int objectPointer, int value) + { + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + put: value + */ + + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word_put(ObjectTableSegment, + ObjectTableStart + objectPointer, + value); + } + + // countBitsOf:put: + inline int countBitsOf_put(int objectPointer, int value) + { + /* "source" + ^self ot: objectPointer bits: 0 to: 7 put: value + */ + + return ot_bits_to_put(objectPointer, 0, 7, value); + } + + // classBitsOf: + inline int classBitsOf(int objectPointer) + { + /* "source" + ^self heapChunkOf: objectPointer word: 1 + */ + return heapChunkOf_word(objectPointer, 1); + + } + + // countBitsOf: + inline int countBitsOf(int objectPointer) + { + /* "source" + ^self ot: objectPointer bits: 0 to: 7 + */ + + return ot_bits_to(objectPointer, 0, 7); + } + + // ot:bits:to:put: + inline int ot_bits_to_put( + int objectPointer, + int firstBitIndex, + int lastBitIndex, + int value + ) + { + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + bits: firstBitIndex + to: lastBitIndex + put: value + */ + + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word_bits_to_put(ObjectTableSegment, + ObjectTableStart + objectPointer, + firstBitIndex, + lastBitIndex, + value); + } + + // sizeBitsOf:put: + inline int sizeBitsOf_put(int objectPointer, int value) + { + /* "source" + ^self heapChunkOf: objectPointer word: 0 put: value + */ + + return heapChunkOf_word_put(objectPointer, 0, value); + } + + // ot:bits:to: + inline int ot_bits_to(int objectPointer, int firstBitIndex, int lastBitIndex) + { + /* "source" + self cantBeIntegerObject: objectPointer. + ^wordMemory segment: ObjectTableSegment + word: ObjectTableStart + objectPointer + bits: firstBitIndex + to: lastBitIndex + */ + + cantBeIntegerObject(objectPointer); + return wordMemory.segment_word_bits_to(ObjectTableSegment, + ObjectTableStart + objectPointer, + firstBitIndex, lastBitIndex); + + } + + // pointerBitOf: + inline int pointerBitOf(int objectPointer) + { + /* "source" + ^self ot: objectPointer bits: 9 to: 9 + */ + + return ot_bits_to(objectPointer, 9, 9); + } + + + // --- Allocation --- + + // obtainPointer:location: + int obtainPointer_location(int size, int location); + + // attemptToAllocateChunk: + int attemptToAllocateChunk(int size); + + // attemptToAllocateChunkInCurrentSegment: + int attemptToAllocateChunkInCurrentSegment(int size); + + void outOfMemoryError(); + + int auditFreeOops(); + +#ifdef RUNTIME_CHECKING + inline void runtime_check(bool condition, const char *errorMessage) + { + if (!condition) + { + assert(0); + hal->error(errorMessage); + } + } +#endif + +private: + RealWordMemory wordMemory; + // Special Register G&R pg. 667 + int currentSegment; // The index of the heap segment currently being used for allocation + + int freeWords; // free words remaining (make primitiveFreeCore "fast") + + // An a table entry with a free bit set OR that contains a reference to a free chunk + // (free bit clear but count field zero) of memory is counted as a free oop + int freeOops; // free OT entries (make primitiveFreeOops "fast") + + + // G&R pg. 664 - Object Table Related Constants + // Object Table Segment (last segment) contains the Object Table followed by the + // head of the OT free pointer list + // +-------------------------+ + // | | <--- ObjectTableStart + // | | + // | | + // | Object Table | + // | | + // | | + // +-------------------------+ + // | FreePointerList | + // +-------------------------+ + // |////// UNUSED WORD //////| + // +-------------------------+ + // + + static const int ObjectTableSegment = RealWordMemory::SegmentCount-1; + static const int ObjectTableStart = 0; + static const int ObjectTableSize = RealWordMemory::SegmentSize - 2; + // The smallest number that is too large to represent in an eight-bit count field; that is, 256. + static const int HugeSize = 256; // G&R pg 661 + + // The location of the head of the linked list of free object table entries + static const int FreePointerList = ObjectTableStart + ObjectTableSize; // G&R pg. 664 + + // G&R pg. 664 - Object Table Related Constants + // The smallest size of chunk that is not stored on a list whose chunk share the same size. + // (Theindex of the last free chunk list). + static const int BigSize = 20; + static const int FirstFreeChunkListSize = BigSize+1; + + + // Heap Constants G&R pg. 658 + + // The number of heaps segments used in the implementation. + // We reserve the last segment for the Object Table and use the remaining for the heap + static const int HeapSegmentCount = RealWordMemory::SegmentCount - 1; + + // Each heap segment is organized as follows: + // + // +-------------------------+ + // | | + // | | + // | Object Storage | + // | | + // | |<--- HeapSpaceStop (last word) + // +-------------------------+ + // | Array of BigSize+1 |<--- FirstFreeChunkList + // | Free Chunks Linked | + // | List Heads | + // | |<--- LastFreeChunkList + // +-------------------------+ + // + + // The index of the first memory segmentused to store the heap + static const int FirstHeapSegment = 0; + static const int LastHeapSegment = FirstHeapSegment + HeapSegmentCount - 1; + + // The address of the last location used in each heap segment. + static const int HeapSpaceStop = RealWordMemory::SegmentSize - FirstFreeChunkListSize - 1; + static const int HeaderSize = 2; // The number of words in an object header(2). + // If HeaderSize changes, revisit forAllOtherObjectsAccessibleFrom_suchThat_do + // where we test if the offset passes the class field... + + // The location of the head of the linked list of free chunks of size zero. Comes right + // after the last word for object storage. + static const int FirstFreeChunkList = HeapSpaceStop + 1; + + // The bluebook incorrectly uses LastFreeChunkList in all places it is used! The + // headOfFreeChunkList:inSegment: and headOfFreeChunkList:inSegment:put methods take + // a SIZE as the first parameter not a location. + // The location of the head of the linked list of free chunks of size BigSize or larger. + // static const int LastFreeChunkList = FirstFreeChunkList + BigSize; + + // Any sixteen-bit value that cannot be an object table index, e.g.,2**16~1. + static const int NonPointer = 65535; + // Last special oop + // (See SystemTracer in Smalltalk.sources) + static const int LastSpecialOop = 52; + + + // Snapshots + // Object space starts at offset 512 in the image + static const int ObjectSpaceBaseInImage = 512; + + bool loadObjectTable( IFileSystem *fileSystem, int fd); + static bool padToPage(IFileSystem *fileSystem, int fd); + bool loadObjects(IFileSystem *fileSystem, int fd); + bool saveObjects(IFileSystem *fileSystem, int fd); + +#ifdef GC_MARK_SWEEP + IGCNotification *gcNotification; +#endif + + // Interface to the host operating system + IHardwareAbstractionLayer *hal; +}; + diff --git a/vm/oops.h b/vm/oops.h @@ -0,0 +1,88 @@ +// +// oops.h +// Smalltalk-80 +// +// Created by Dan Banay on 3/5/20; +// Copyright © 2020 Dan Banay; All rights reserved; +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#pragma once + +// Well known oops for various objects in an image + +// initializeGuaranteedPointers G&R pg. 576 + +// UndefinedObject and Booleans +static const int NilPointer = 2; +static const int FalsePointer = 4; +static const int TruePointer = 6; + +// Root +static const int SchedulerAssociationPointer = 8; +static const int SmalltalkPointer = 25286; // SystemDictionary + +// Classes + +static const int ClassSmallInteger = 12; +static const int ClassStringPointer = 14; +static const int ClassArrayPointer = 16; +static const int ClassMethodContextPointer = 22; +static const int ClassBlockContextPointer = 24; +static const int ClassPointPointer = 26; +static const int ClassLargePositiveIntegerPointer = 28; +static const int ClassMessagePointer = 32; +static const int ClassCharacterPointer = 40; +static const int ClassCompiledMethod = 34; +static const int ClassSymbolPointer = 56; + +static const int ClassFloatPointer = 20; + +static const int ClassSemaphorePointer = 38; +static const int ClassDisplayScreenPointer = 834; +static const int ClassUndefinedObject = 25728; + +// Selectors +static const int DoesNotUnderstandSelector = 42; +static const int CannotReturnSelector = 44; +static const int MustBeBooleanSelector = 52; + +// Tables +static const int SpecialSelectorsPointer = 48; +static const int CharacterTablePointer = 50; + +/* + dbanay - first oops 2..52 are special oops... see this from SystemTracer: + + If using GC make sure these are roots + specialObjects _ + "1:" (Array with: nil with: false with: true with: (Smalltalk associationAt: #Processor)) + , "5:" (Array with: Symbol table with: SmallInteger with: String with: Array) + , "9:" (Array with: (Smalltalk associationAt: #Smalltalk) with: Float + with: MethodContext with: BlockContext) + , "13:" (Array with: Point with: LargePositiveInteger with: DisplayBitmap with: Message) + , "17:" (Array with: CompiledMethod with: #unusedOop18 with: Semaphore with: Character) + , "21:" (Array with: #doesNotUnderstand: with: #cannotReturn: + with: #monitor: with: Smalltalk specialSelectors) + , "25:" (Array with: Character characterTable with: #mustBeBoolean). + specialObjects size = 26 ifFalse: [self error: 'try again!!']. + */ diff --git a/vm/posixfilesystem.h b/vm/posixfilesystem.h @@ -0,0 +1,269 @@ +// +// posixfilesystem.h +// Smalltalk-80 +// +// Created by Dan Banay on 5/3/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + +#include "filesystem.h" +#include <string> +#include <stdlib.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <cassert> + +#ifndef _WIN32 +#include <unistd.h> +#include <dirent.h> +#include <errno.h> +#else +#include <windows.h> +#include <io.h> +#endif + +class PosixST80FileSystem: public IFileSystem +{ +public: + + PosixST80FileSystem(const std::string& root) : root_directory(root) + { + } + + std::string path_for_file(const char *name) + { + return root_directory + "/" + name; + } + + // File oriented operations + int open_file(const char *name) + { + int fd; + std::string path = path_for_file(name); +#ifdef _WIN32 + + errno_t code = _sopen_s(&fd, path.c_str(), _O_RDWR | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE); + +#else + fd = open(path.c_str(), O_RDWR ); + +#endif + return fd; + } + + int create_file(const char *name) + { + int fd; + std::string path = path_for_file(name); +#ifdef _WIN32 + errno_t code = _sopen_s(&fd, path.c_str(), _O_RDWR | _O_BINARY | _O_CREAT | _O_TRUNC, _SH_DENYNO, _S_IREAD | _S_IWRITE); +#else + fd = open(path.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644); +#endif + return fd; + } + + + int close_file(int file_handle) + { +#ifdef _WIN32 + if (file_handle == -1) return -1; + return _close(file_handle); +#else + return close(file_handle); +#endif + } + + int read(int file_handle, char *buffer, int bytes) + { +#ifdef _WIN32 + return _read(file_handle, buffer, bytes); +#else + return (int) ::read(file_handle, buffer, bytes); +#endif + } + + int write(int file_handle, const char *buffer, int bytes) + { +#ifdef _WIN32 + return _write(file_handle, buffer, bytes); +#else + return (int) ::write(file_handle, buffer, bytes); +#endif + } + + + bool truncate_to(int file_handle, int length) + { +#ifdef _WIN32 + return _chsize(file_handle, length) != -1; +#else + return ftruncate(file_handle, length) != -1; +#endif + } + + int file_size(int file_handle) + { +#ifdef _WIN32 + if (file_handle == -1) return -1; + + struct _stat s; + if (_fstat(file_handle, &s) != -1) + { + return (int) s.st_size; + } + + return -1; +#else + struct stat s; + if (fstat(file_handle, &s) != -1) + { + return (int) s.st_size; + } + + return -1; +#endif + } + + bool file_flush(int file_handle) + { +#ifndef _WIN32 + return fsync(file_handle) != -1; +#else + return true; +#endif + } + +#ifndef _WIN32 + bool is_diretory(const char *name) + { + std::string path = path_for_file(name); + struct stat statbuf; + if (stat(path.c_str(), &statbuf) != 0) + return 0; + return S_ISDIR(statbuf.st_mode); + } +#endif + + // Directory orientated operations + void enumerate_files(const std::function <void (const char *) >& each) + { +#ifndef _WIN32 + DIR *dir = opendir(root_directory.c_str()); + struct dirent *entry; + + while ((entry = readdir(dir))) + { + // skip hidden files and ., and .. + if (entry->d_name[0] != '.' && !is_diretory(entry->d_name)) + { + each(entry->d_name); + } + } + + closedir(dir); +#else + HANDLE hFind = INVALID_HANDLE_VALUE; + _WIN32_FIND_DATAA findFileData; + + std::string pattern = root_directory + "\\*"; + + hFind = FindFirstFileA(pattern.c_str(), &findFileData); + if (hFind != INVALID_HANDLE_VALUE) + { + do + { + if (findFileData.cFileName[0] != '.') + { + if ((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + { + each(findFileData.cFileName); + } + } + } + while (FindNextFileA(hFind, &findFileData) != 0); + FindClose(hFind); + + } +#endif + } + + bool rename_file(const char *old_name, const char *new_name) + { + std::string old_path = path_for_file(old_name); + std::string new_path = path_for_file(new_name); + + return rename(old_path.c_str(), new_path.c_str()) != -1; + } + + bool delete_file(const char* file_name) + { + std::string path = path_for_file(file_name); + +#ifdef _WIN32 + return _unlink(path.c_str()) != -1; + +#else + return unlink(path.c_str()) != -1; +#endif + } + + int seek_to(int file_handle, int position) + { +#ifdef _WIN32 + return (int) _lseek(file_handle, position, SEEK_SET); +#else + return (int) lseek(file_handle, position, SEEK_SET); +#endif + + } + + int tell(int file_handle) + { +#ifdef _WIN32 + return (int) _lseek(file_handle, 0, SEEK_CUR); +#else + return (int) lseek(file_handle, 0, SEEK_CUR); +#endif + } + + // Error handling + const int last_error() + { + return errno; + } + + const char *error_text(int code) + { +#ifdef _WIN32 + static char errmsg[512]; + strerror_s(errmsg, sizeof(errmsg), code); + return errmsg; +#else + return strerror(code); +#endif + } + +private: + std::string root_directory; + +}; diff --git a/vm/realwordmemory.h b/vm/realwordmemory.h @@ -0,0 +1,120 @@ +// +// realwordmemory.h +// Smalltalk-80 +// +// Created by Dan Banay on 2/25/20. +// Copyright © 2020 Dan Banay. All rights reserved. +// +// MIT License +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// + + +#pragma once + +#include <cstdint> +#include <cassert> + +// Segmented Memory Model as described in G&R pg. 656 +class RealWordMemory +{ +public: + static const int SegmentCount = 16; + static const int SegmentSize = 65536; /* in words */ + + RealWordMemory() + { + } + + inline int segment_word(int s, int w) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + return memory[s][w]; + } + + inline int segment_word_put(int s, int w, int value) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + assert(value >= 0 && value < 65536); + memory[s][w] = value; + return value; + } + + inline int segment_word_byte(int s, int w, int byteNumber) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + assert(byteNumber == 1 || byteNumber == 0); + + // byteNumber 0 is the byte of the word that appears first in member, 1 is the next + /* big endian */ + //return (memory[s][w] >> (8*byteNumber)) & 0xff; + return ((std::uint8_t *) &memory[s][w])[byteNumber]; + /* little endian */ + //return ((std::uint8_t *) &memory[s][w])[1-byteNumber]; + + } + + inline int segment_word_byte_put(int s, int w, int byteNumber, int value) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + assert(value >= 0 && value < 65536); + assert(byteNumber == 1 || byteNumber == 0); + + // byteNumber 0 is the byte of the word that appears first in member, 1 is the next + /* big endian */ + ((std::uint8_t *) &memory[s][w])[byteNumber] = value; + /* little endian */ + //((std::uint8_t *) &memory[s][w])[1-byteNumber] = value; + + return value; + } + + // The most significant bit in a word will be referred to with the index 0 and the least significant with the index 15. G&R 657 + inline int segment_word_bits_to(int s, int w, int firstBitIndex, int lastBitIndex) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + + std::uint16_t shift = memory[s][w] >> (15-lastBitIndex); + std::uint16_t mask = (1 << (lastBitIndex - firstBitIndex + 1)) - 1; + + return shift & mask; + } + + inline int segment_word_bits_to_put(int s, int w, int firstBitIndex, int lastBitIndex, int value) + { + assert(s >= 0 && s < SegmentCount); + assert(w >= 0 && w < SegmentSize); + assert(value >= 0 && value < 65536); + + std::uint16_t mask = (1 << (lastBitIndex - firstBitIndex + 1)) - 1; + assert((value & mask) == value); // make sure it fits + memory[s][w] = (memory[s][w] & ~(mask << (15-lastBitIndex))) | (value << (15 - lastBitIndex)); + return value; + } + +private: + std::uint16_t memory[SegmentCount][SegmentSize]; + +}; + diff --git a/web/app.js b/web/app.js @@ -0,0 +1,122 @@ +// Smalltalk-80 dans le navigateur : charge l'image choisie dans le système de fichiers en mémoire +// d'Emscripten, puis lance la VM (vm/main.cpp compilée en WebAssembly, voir Makefile). +// Fonctions C exportées : st80_set_budget(ms), st80_set_paused(0|1), st80_cycle_count(), st80_image_name(). + +const IMAGES = { + xerox: { + file: 'xerox-v2.im', + files: [], + label: 'Image Xerox du 1er avril 1983, telle que livrée', + }, + banay: { + file: 'banay-2020.im', + files: ['Smalltalk-80.sources', 'Smalltalk-80.changes'], + label: 'Image Xerox + classes PosixFile de Dan Banay (2020) : sources visibles', + }, +}; +const ROOT = '/st80'; + +const params = new URLSearchParams(location.search); +const imageKey = IMAGES[params.get('image')] ? params.get('image') : 'xerox'; +const image = IMAGES[imageKey]; + +const canvas = document.getElementById('canvas'); +const statusEl = document.getElementById('status'); +const imageSel = document.getElementById('image'); +const speedSel = document.getElementById('speed'); +const pauseBtn = document.getElementById('btn-pause'); +const saveBtn = document.getElementById('btn-save'); +const resetBtn = document.getElementById('btn-reset'); + +const status = (text) => { statusEl.textContent = text; }; +imageSel.value = imageKey; + +let module = null; +let paused = false; +let lastCycles = 0; +let lastTime = performance.now(); + +async function fetchBytes(name) { + const r = await fetch(`images/${name}`); + if (!r.ok) throw new Error(`${name} : HTTP ${r.status}`); + return new Uint8Array(await r.arrayBuffer()); +} + +async function boot() { + status(`Chargement de ${image.file}…`); + const files = [image.file, ...image.files]; + const [data, mod] = await Promise.all([ + Promise.all(files.map(fetchBytes)), + createST80({ + canvas, + noInitialRun: true, + print: (t) => console.log(t), + printErr: (t) => console.error(t), + onQuit: () => { status('Smalltalk a quitté (quitPrimitive). Rechargez la page pour recommencer.'); module = null; }, + }), + ]); + module = mod; + module.FS.mkdir(ROOT); + files.forEach((name, i) => module.FS.writeFile(`${ROOT}/${name}`, data[i])); + speed(); + status('Démarrage de la machine virtuelle…'); + module.callMain(['-directory', ROOT, '-image', image.file]); + lastTime = performance.now(); + setInterval(tick, 1000); +} + +function tick() { + if (!module) return; + const cycles = module.ccall('st80_cycle_count', 'number'); + const now = performance.now(); + const rate = (cycles - lastCycles) / ((now - lastTime) / 1000); + lastCycles = cycles; lastTime = now; + status(paused ? 'En pause' : `${image.label} — ${(rate / 1e6).toFixed(2)} M bytecodes/s`); +} + +function speed() { + if (module) module.ccall('st80_set_budget', null, ['number'], [Number(speedSel.value)]); +} + +speedSel.addEventListener('change', speed); + +pauseBtn.addEventListener('click', () => { + paused = !paused; + pauseBtn.classList.toggle('on', paused); + pauseBtn.textContent = paused ? 'Reprendre' : 'Pause'; + if (module) module.ccall('st80_set_paused', null, ['number'], [paused ? 1 : 0]); + tick(); +}); + +// Télécharge l'image courante telle qu'elle est dans le système de fichiers en mémoire +// (après « save » dans le menu système de Smalltalk, c'est l'instantané sauvegardé). +saveBtn.addEventListener('click', () => { + if (!module) return; + const name = module.ccall('st80_image_name', 'string') || image.file; + let bytes; + try { bytes = module.FS.readFile(`${ROOT}/${name}`); } catch { status(`Pas de fichier ${name}`); return; } + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' })); + a.download = name; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 10000); +}); + +resetBtn.addEventListener('click', () => location.reload()); + +imageSel.addEventListener('change', () => { + const u = new URL(location.href); + u.searchParams.set('image', imageSel.value); + location.href = u.toString(); +}); + +// Le bouton droit est le bouton jaune de Smalltalk : pas de menu contextuel du navigateur. +canvas.addEventListener('contextmenu', (e) => e.preventDefault()); +canvas.addEventListener('mousedown', () => canvas.focus()); + +window.st80 = { + cycles: () => (module ? module.ccall('st80_cycle_count', 'number') : 0), + get module() { return module; }, +}; + +boot().catch((e) => { console.error(e); status(`Erreur : ${e.message}`); }); diff --git a/web/images/Smalltalk-80.changes b/web/images/Smalltalk-80.changes @@ -0,0 +1 @@ +'From Smalltalk-80, version 2, of April 1, 1983 on 15 May 2020 at 11:05:34 am'!!PosixFilePage methodsFor: 'file/page/directory implementation'!pageNumber: pn pageNumber _ pn! !!PosixFilePage methodsFor: 'accessing'!serialNumber: n ^self!size: size bytesInPage _ size! !!PosixFile methodsFor: 'private'!doCommand: command name: name page: page error: e | result | result _ self doPrimCommand: command name: name page: page. (result == false or: [ result isNil] ) ifTrue: [ e isNil ifFalse: [ error _ self errorString: self lastError. self error: e]]. ^result!doPrimCommand: command name: name page: page <primitive: 130>!findLastPageNumber |bytes| "pages are numbered 1..N" bytes _ self sizeOnDisk. ^ lastPageNumber _ ((bytes + self pageSize - 1) // self pageSize) max: 1! !!PosixFile methodsFor: 'file/page/directory implementation'!fd: descriptor fd _ descriptor! !!PosixFile methodsFor: 'error handling'!errorString: anInteger <primitive: 133>!lastError <primitive: 132>! !!PosixFile methodsFor: 'file status'!close fd isNil ifFalse: [ ^self doCommand: 5 name: nil page: nil error:nil ]!open self doCommand: 4 name: fileName page: nil error: 'open:'. readWrite _ Read. self findLastPageNumber! !!PosixFile methodsFor: 'file accessing'!beSnapshotFile <primitive: 128>!endFile: aPage | nextPage | "Make the file end with aFilePage, i.e., remove all file pages after aFilePage, and answer the result of writing aFilePage (File|write:). If the argument is nil, delete all of the receiver's pages." aPage isNil ifFalse: [ nextPage _ self write: aPage ] ifTrue: [ nextPage _ nil ]. "truncate" self doCommand: 2 name: nil page: aPage error:'endFile:'. self findLastPageNumber. ^nextPage! !!PosixFile methodsFor: 'nonhomogenous accessing'!read: page "Read aFilePage if it exists, else answer false. aFilePage contains a pageNumber and other information, e.g., a serialNumber necessary to obtain the page. It is possible that aFilePage pageNumber = 0 may or may not exist in some file systems. The pageNumber may be used to compute a byte range to be read, or to lookup a disk address in a table. In a file system where pages are linked, aFilePage may contain the address of the next page and may help reveal lastPageNumber." (self doCommand: 0 name: nil page: page error:'read:') ifFalse: [^nil]. ^page!write: page | returnPage | self doCommand: 1 name: nil page: page error:'write:'. returnPage _ page. ((page lastPage) and: [page isFull]) ifTrue: ["last page can't be full, so glue on another page" returnPage _ self initPageNumber: 0. returnPage reinitialize. returnPage pageNumber: (lastPageNumber _ page pageNumber + 1)]. readWrite _ Read + Write. ^returnPage! !!PosixFileDirectory methodsFor: 'private'!doPrimitive: code arg1: arg1 arg2: arg2 <primitive: 131>! !!PosixFileDirectory methodsFor: 'enumerating'!do: aBlock | files | files _ (self fileNames collect: [ : aFileName | self initFileName: aFileName ]). (ReadStream on:files) do: aBlock! !!PosixFileDirectory methodsFor: 'removing'!removeOld: aFile self doPrimitive: 1 arg1: aFile fileName arg2: nil! !!PosixFileDirectory methodsFor: 'adding'!add: aFile ^self addNew: aFile!addNew: aFile | fd | fd _ self doPrimitive: 0 arg1: aFile fileName arg2: nil. aFile fd: fd. aFile readWrite: Write. ^aFile! !!PosixFileDirectory methodsFor: 'file accessing'!rename: aFile newName: newFileName self doPrimitive: 2 arg1: newFileName arg2: aFile! !Smalltalk condenseChanges!'----SNAPSHOT----'!'----SNAPSHOT----'! +\ No newline at end of file diff --git a/web/images/Smalltalk-80.sources b/web/images/Smalltalk-80.sources @@ -0,0 +1 @@ +'From Smalltalk-80, version 2, of April 1, 1983 on 31 May 1983 at 9:10:35 am'!PopUpMenu subclass: #ActionMenu instanceVariableNames: 'selectors ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!ActionMenu comment:'ActionMenus carry an array of selectors which correspond to the listed menu items. This allows a menu to stand alone in parameterizing a controller, since the controller just sends the selector to its model.ActionMenus allow the pluggable views experiment (TextView, SelectionInListView) tohandle menus much easier than having pairs of variables for the menu and its associatedselectors. Obviously these menus eagerly await a proper objectification of protocol.'!!ActionMenu methodsFor: 'action symbols'!selectorAt: index ^ selectors at: index!setSelectors: selArray selectors _ selArray! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ActionMenu class instanceVariableNames: ''!ActionMenu class comment:'This subclass of PopUpMenu carries a list of selectors corresponding to the various menu items.Therefore, with only the menu as a parameter, a controller can display the menu and thentell its model to perform the associated selector. This saves maintaining two parallel structures,one for the names in the menu, and one for the selectors to be performed.'!!ActionMenu class methodsFor: 'instance creation'!labels: aString lines: anArray selectors: selArray | aMenu | aMenu _ self labels: aString lines: anArray. aMenu setSelectors: selArray. ^ aMenu!labels: aString selectors: selArray ^ self labels: aString lines: nil selectors: selArray! !!ActionMenu class methodsFor: 'confirmation'!confirm "ActionMenu confirm" ^ (ActionMenu labels: 'confirm\abort' withCRs selectors: nil) startUp = 1! ! File subclass: #AltoFile instanceVariableNames: 'writeTime pageAddresses leader ' classVariableNames: '' poolDictionaries: 'AltoFilePool ' category: 'Files-Xerox Alto'!AltoFile comment:'A concrete example of class File.Instance Variables: writeTime <Time> pageAddresses <RunArray> of page addresses leader <Integer> address of the page where the leader information is stored '!!AltoFile methodsFor: 'nonhomogeneous accessing'!read: page | pn p fp palen oldCursor | pn _ page pageNumber. pageAddresses isNil ifTrue: [pn = 0 ifTrue: [palen _ 0] ifFalse: [^nil]] ifFalse: [palen _ pageAddresses size]. fp _ palen min: pn. "set address of first page. next addresses are set later" page address: (fp = 0 ifTrue: [leader] ifFalse: [pageAddresses at: fp]). oldCursor _ Cursor currentCursor. pn-fp > 10 ifTrue: [Cursor wait show]. "this may take a while..." fp to: pn do: [:p | "set up page for checking" page pageNumber: p. "set by machine code: page headerWordAt: Nextp put: (p < palen ifTrue: [pageAddresses at: (p+1)] ifFalse: [0]). page headerWordAt: backp put: (p=0 ifTrue: [0] ifFalse: [p=1 ifTrue: [leader] ifFalse: [pageAddresses at: (p-1)]]). page size: (p < palen ifTrue: [page dataSize] ifFalse: [0])." page doCommand: CCR error: 'read:'. page lastPage ifTrue: [lastPageNumber _ p. p < pn ifTrue: [oldCursor show. ^nil] ifFalse: [oldCursor show. ^page]]. (pageAddresses ~~ nil and: [p >= palen]) ifTrue: ["save address of next page if there is a page address table and address not already stored" pageAddresses addLast: (page headerWordAt: Nextp)]. p < pn ifTrue: ["set address of next page" page address: (page headerWordAt: Nextp)]]. oldCursor show. ^page!readOrAdd: aPage | page p pn | page _ aPage. pn _ page pageNumber. (self read: page) notNil ifTrue: [^page]. "page now contains last page" (lastPageNumber to: pn - 1) do: [:p | page pageNumber: p. page size: page dataSize. "this writes current and allocates next (empty) page" page _ self write: page]. ^page!write: page | nextPage labelDirty returnPage | ((labelDirty _ page lastPage) and: [page isFull]) ifTrue: ["last page can't be full, so glue on another page" returnPage _ nextPage _ self initPageNumber: 0. fileDirectory allocate: nextPage after: (fileDirectory realToVirtual: page address). nextPage reinitialize. nextPage headerWordAt: Backp put: page address. nextPage pageNumber: (lastPageNumber _ page pageNumber + 1). nextPage serialNumber: serialNumber. nextPage doCommand: CWW error: 'write: (allocate)'. "link to current page" page headerWordAt: Nextp put: nextPage address. pageAddresses ~~ nil ifTrue: [pageAddresses addLast: nextPage address]] ifFalse: [returnPage _ page]. "whenever a last (or second last) page is written, write label also" self doCommand: (labelDirty ifTrue: [CWW] ifFalse: [CCW]) page: page error: 'write:'. readWrite _ Read + Write. ^returnPage! !!AltoFile methodsFor: 'file accessing'!beSnapshotFile ^self beSnapshotSerialNumber: (self serialNumber) leaderVirtualDiskAddr: (fileDirectory realToVirtual: self leader)!endFile: aPage | page nextPage pn | page _ aPage. page isNil ifTrue: [pn _ -1 "free all of file"] ifFalse: [page isFull ifTrue: [nextPage _ self write: page. "if page was a full last page, next is an empty (and now last) page" nextPage lastPage ifTrue: [^nextPage]. page _ self readPageNumber: page pageNumber + 1. page isEmpty ifTrue: [^page]. page size: 0]. page headerWordAt: Nextp put: 0. self write: page. "free rest of file" pn _ page pageNumber]. lastPageNumber _ nil "reset by read:". [lastPageNumber isNil and: [ (nextPage _ self readPageNumber: (pn _ pn + 1)) notNil]] whileTrue: [nextPage reinitialize. nextPage freePage. nextPage doCommand: CWW error: 'endFile:'. fileDirectory deallocate: nextPage]. page notNil ifTrue: [pageAddresses shortenTo: (lastPageNumber _ page pageNumber)]. ^page! !!AltoFile methodsFor: 'file status'!close "fix up leader page, and remember create time" self updateLeader: (self readPageNumber: 0)!open "don't find last page immediately. for later close" readWrite _ Read!reinitialize super reinitialize. pageAddresses _ AltoFileAddressArray new directory: fileDirectory!release! !!AltoFile methodsFor: 'error handling'!errorString: status "see Alto hardware manual for details on error word format" | s | status = -1 ifTrue: [^'primitive failure, bad args?']. s _ WriteStream on: (String new: 50). s nextPutAll: (#('' 'hardware error or sector overflow' 'check error' 'disk command specified illegal sector' ) at: 1 + (status bitAnd: 3)). 1 to: 6 do: [:t | (status allMask: (128 bitShift: 1 - t)) ifTrue: [s nextPut: $ . s nextPutAll: (#('seek failed, possible illegal track' 'seek in progress' 'disk unit not ready' 'hardware late' 'hardware not transferring' 'checksum' ) at: t)]]. s nextPut: $ . s nextPutAll: (status storeStringRadix: 8). ^s contents! !!AltoFile methodsFor: 'file/page/directory implementation'!doCommand: command page: filePage error: e | done | done _ Semaphore new. self dskprim: fileDirectory diskNumber address: filePage address command: command page: filePage page semaphore: done. error<0 ifFalse: [done wait]. error ~= 0 ifTrue: [e isNil ifTrue: [^nil]. error _ self errorString: error. self error: e] ifFalse: [error _ ''. ^filePage]! !!AltoFile methodsFor: 'private'!beSnapshotSerialNumber: aByteArray leaderVirtualDiskAddr: anInteger <primitive: 135> self primitiveFailed!dskprim: diskNumber address: diskAddress command: diskCommand page: buffer semaphore: aSemaphore "Transfer a single record (page) to or from the Alto File System. Fail if integer arguments are not 16-bit positive Integers. Fail if a disk transfer is already in progress. Fail if the buffer is not large enough or is pointer containing. Fail if the last argument is not a Semaphore. Xerox specific primitive. See Object documentation what IsAPrimitive. diskNumber is 0 or 1, diskAddress is the starting Alto disk address (Integer), diskCommand is the disk command (usually CCR, CCW, CWW) (Integer), buffer is the string containing label and data, aSemaphore is signalled when the transfer completes. If disk primitive encounters an error, the receiver's instance variable named error is set to the DCB status. This Integer is greater than 0 and is interpreted by errorString:. Normally error is set to 0." <primitive: 128> error _ -1 "set error when the primitive fails"!findLastPageNumber self readPageNumber: 20000. ^lastPageNumber!leader ^leader!leader: pageAddress leader _ pageAddress!pageAddresses: anArrayOrNil pageAddresses _ anArrayOrNil!pageClass ^AltoFilePage!readFromDirectory: aFileStream "read file description from SysDir" serialNumber _ aFileStream next: 4. aFileStream skip: 4. leader _ fileDirectory virtualToReal: aFileStream nextWord. fileName _ String new: aFileStream next. 1 to: fileName size do: [:i | fileName at: i put: aFileStream next asCharacter]. aFileStream padToNextWord!sameAsStoredFile | page s tname | page _ self initPageNumber: 0. page binary. page address: leader. "if any of the following tests fail, File will be reinitialized" (((page doCommand: CCR error: nil) notNil and: [page pageNumber = 0]) and: [s _ page asFileStream: ExternalStream new. s skip: 4. writeTime = (s next: 4) and: [s skip: 4. tname _ String new: s next. 1 to: tname size do: [:i | tname at: i put: s next asCharacter]. fileName sameAs: tname]]) ifTrue: [(lastPageNumber notNil and: [pageAddresses notNil]) ifTrue: [page pageNumber: lastPageNumber. page address: (pageAddresses at: lastPageNumber). (page doCommand: CCR error: nil) isNil ifTrue: ["wrong file or page number" ^false]. page lastPage ifFalse: ["not last page anymore" lastPageNumber _ nil]. ^true]. ^true]. ^false!storeOnDirectory: aFileStream aFileStream nextPutAll: serialNumber. aFileStream nextWordPut: 1. aFileStream nextWordPut: 0. aFileStream nextWordPut: (fileDirectory realToVirtual: leader). aFileStream nextPut: fileName size. fileName do: [:char | aFileStream nextPut: char asciiValue]. aFileStream padToNextWordPut: 0!updateLeader: page "see <Alto>AltoFileSys.D, (p.3 leader page) for further info" | aFileStream time lastwrite | page binary. aFileStream _ page asFileStream: ExternalStream new. time _ Time timeWords. (readWrite bitAnd: Write) = Write ifTrue: [fileDirectory flush. "set creation/write/read date and file name" writeTime _ time. aFileStream nextPutAll: time. aFileStream nextPutAll: time. aFileStream nextPutAll: time. fileName isEmpty ifFalse: [aFileStream nextPut: fileName size. fileName do: [:char | aFileStream nextPut: char asciiValue]]] ifFalse: ["skip creation, remember write, update read date" aFileStream skip: 4. writeTime _ aFileStream next: 4. aFileStream nextPutAll: time]. page fromFileStream: aFileStream. self write: page!writeTime ^writeTime! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!AltoFile class instanceVariableNames: ''!!AltoFile class methodsFor: 'class initialization'!initialize | readStream | AltoFilePool at: #(CRR CCR CCW CWW ) put: #(18496 18512 18520 18536 ). readStream _ ReadStream on: #(1024 32 'SysDir.' ). #(Dfmask Boffset Dirname ) do: [:each | AltoFilePool at: each put: readStream next]. readStream _ ReadStream on: #(1 2 3 4 5 6 7 8 ). #(Nextp Backp Unused Numch Pagen Vn Sn1 Sn2 ) do: [:each | AltoFilePool at: each put: readStream next]! !AltoFile initialize! RunArray subclass: #AltoFileAddressArray instanceVariableNames: 'directory ' classVariableNames: '' poolDictionaries: '' category: 'Files-Xerox Alto'!AltoFileAddressArray comment:'I am a RunArray where each run represents the virtual addresses of a block of contiguous pages. Indexed by page numbers, my instance holds the virtual disk addresses of the pages. Attributes inherited from RunArray are: runs, an array of starting indicies; and values, an array of the first virtual address in each block. Instance Variables: directory <FileDirectory>'!!AltoFileAddressArray methodsFor: 'initialize-release'!directory: aDirectory "Set the receiver's directory to be the argument, aDirectory." directory _ aDirectory!shortenTo: newSize "Shortens the receiver to be size, newSize (for file shorten). Create an error if newSize is greater than the old size." | oldSize short | oldSize _ self size. newSize > oldSize ifTrue: [^self error: 'invalid extension']. newSize < oldSize ifTrue: [short _ self copyFrom: 1 to: newSize. runs _ short runs. values _ short values]! !!AltoFileAddressArray methodsFor: 'accessing'!at: index | run offset value | super at: index setRunOffsetAndValue: [:run :offset :value | ^directory virtualToReal: value + offset]! !!AltoFileAddressArray methodsFor: 'adding'!addLast: val | virt | virt _ directory realToVirtual: val. (runs size = 0 or: [virt ~= ((values at: values size) + (runs at: runs size))]) ifTrue: [super addLast: virt] "create new run" ifFalse: [runs at: runs size put: (runs at: runs size) + 1]. "stretch last run" ^val! ! FileDirectory subclass: #AltoFileDirectory instanceVariableNames: 'dirFile bitsFile diskPages totalPages nSectors ' classVariableNames: '' poolDictionaries: 'AltoFilePool ' category: 'Files-Xerox Alto'!AltoFileDirectory comment:'A concrete example of a FileDirectory class. Implements the Xerox Alto File System. See the Alto Operating System Reference Manual section about Disks. Note that the Alto file address format is bits 0-3 sector number (0 - 8r15, i.e., 12 or 14 sectors) 4-12 cylinder number (0 - 8r312, Model 31; 0-8r625, Model 44) 13 head number (0-1) 14 disk number (0-1) 15 restore bit.Instance Variables: dirFile <File> or nil bitsFile <File> or nil diskPages <Integer> totalPages <Integer> nSectors <Integer> '!!AltoFileDirectory methodsFor: 'adding'!addNew: aFile | sn page | sn _ self allocateSN: aFile. aFile serialNumber: sn. "allocate a new page (more success after O.S. stuff, bittable etc.)" self allocate: (page _ aFile initPageNumber: 0) after: 800. "write 0th -- leader, in the process filling it in and then creating first page". page reinitialize. page serialNumber: sn. page size: page dataSize. aFile leader: page address. aFile readWrite: Write. aFile updateLeader: page. self addEntry: aFile. ^aFile! !!AltoFileDirectory methodsFor: 'removing'!remove: aFile ifAbsentDo: aBlock (self findFileOrHole: aFile) ifFalse: [^aBlock value: aFile]. self removeOld: aFile!removeOld: file | aFile | aFile _ self deleteEntry: file. aFile open. aFile endFile: nil. bitsFile flush! !!AltoFileDirectory methodsFor: 'accessing'!next ^self nextFile: self fileClass new!realToVirtual: address "Convert the argument, address, from a real address to a virtual address." ^(( address bitShift: -12) bitAnd: 8r17) "sector: field" + (nSectors * ((address bitAnd: 8r7774) bitShift: -2)) "cylinder and head: field*" + "disk: field*pages per disk" ((address bitAnd: 2) = 2 "diskPages*(address bitAnd: 2)//2" ifTrue: [diskPages] ifFalse: [0])! !!AltoFileDirectory methodsFor: 'enumerating'!reset dirFile == nil ifTrue: [self open] ifFalse: [self flush]. dirFile readOnly. dirFile reset! !!AltoFileDirectory methodsFor: 'file accessing'!checkName: aString "Answer whether aString is a valid file name." ^self checkName: aString fixErrors: false!checkName: fname fixErrors: fixing "Check file name for correct length and characters." | char len i newName special period | fname isEmpty ifTrue: [fixing ifTrue: [^'$']. self error: 'empty file name']. special _ '.-+$!!?'. period _ $.. len _ fname size. (len > 39 or: [len = 39 and: [(fname at: len) ~= period]]) ifTrue: [fixing ifTrue: ["truncate name" len _ 38] ifFalse: [self error: 'name too long']]. newName _ WriteStream on: (String new: len + 1). 1 to: len do: [:i | char _ fname at: i. "check characters: alphanumeric or 6 special" (char isLetter or: [(special includes: char) or: [char isDigit]]) ifTrue: [newName nextPut: char] ifFalse: [ fixing ifTrue: [newName nextPut: $-] ifFalse: [self error: ('illegal character ' copyWith: char)]]]. "make sure last character is period (isn't period when fixing)" (fname at: len) = period ifTrue: [fixing ifTrue: [newName skip: -1]] ifFalse: [fixing ifFalse: [newName nextPut: period]]. ^newName contents!checkNameOfFile: aString "Answer whether aString is a valid file name." ^self checkNameOfFile: aString fixErrors: false!fileClass ^AltoFile!filesMatching: pattern ^super filesMatching: (pattern last = $. ifTrue: [pattern] ifFalse: [pattern , '.'])!rename: aFile newName: newFileName | holesize pos newFile newName file | (self findFileOrHole: (newFile _ self initFileName: newFileName)) ifTrue: [^newFile error: 'rename: new name already exists']. newName _ newFile fileName. "a possible insertion place" pos _ dirFile position. (self findFileOrHole: (file _ self initFile: aFile)) ifFalse: [^file error: 'rename: old name does not exist']. holesize _ dirFile nextWord bitAnd: Dfmask - 1. dirFile skip: -2. file fileName: newName. (self fileSize: file) "new size of entry" <= holesize ifTrue: ["new entry will fit in current entry" "read and save entry" pos _ dirFile position. file _ self next] ifFalse: ["delete and save entry" file _ self deleteEntry: file]. "position to same entry or hole discovered earlier" dirFile position: pos. file fileName: newName. self addEntry: file. file readWrite: Write. file writeTime isNil ifTrue: ["close file: updating name in leader page" file close] "otherwise, file is open. defer leader page change until someone closes it"! !!AltoFileDirectory methodsFor: 'file status'!close closed ifFalse: [dirFile close. bitsFile == nil ifFalse: ["an interrupted open?" bitsFile close]. super close]!flush bitsFile == nil ifFalse: [bitsFile flush]!open | f s a page len elen type | closed ifTrue: ["assume some defaults in case DSHAPE is not in SysDir leader page. these should only be needed if the disk is old (and not scavenged). they will not work if a 14 sector system is missing DSHAPE (unlikely) since addresses of first page of SysDir and DiskDescriptor might be computed incorrectly" nSectors _ 12. diskPages _ 812 * nSectors. totalPages _ 2 * diskPages. "read SysDir leader page to find out file system configuration. see AltoFileSys.D". f _ self findKey: Dirname. f binary. "to prevent address of page 1 from being stored". f pageAddresses: nil. page _ f readPageNumber: 0. "length of property list, in words" len _ page at: 494. len = 210 ifTrue: ["scan file properties for DSHAPE" s _ page asFileStream: ExternalStream new. s skipWords: (page at: 493). [len > 0] whileTrue: [type _ s next. type = 0 ifTrue: [ "0 terminates list. property not found. try to read it later from DiskDescriptor" len _ 0] ifFalse: [elen _ s next. (type = 1 and: [elen = 5]) ifTrue: ["DSHAPE. read property" self configure: s. "set flags so configure and loop are not done again" s _ false. len _ 0] ifFalse: ["skip over other property" len _ len - elen. s skipWords: elen - 1]]]]. "now, with the correct (or default) file system configuration, store the virtual address of next page (1), and create a FileStream on SysDir" a _ AltoFileAddressArray new directory: self. a addLast: (page headerWordAt: Nextp). f pageAddresses: a. dirFile _ f asFileStream. dirFile readOnly. bitsFile _ self oldFile: 'DiskDescriptor'. bitsFile binary. bitsFile readWrite. closed _ false. s ifTrue: ["configuration not read from SysDir. this will work for 12 sector systems. 14 sector systems should have had the DSHAPE property" self configure: bitsFile]. super open]!release dirFile _ bitsFile _ nil. closed _ true! !!AltoFileDirectory methodsFor: 'page accessing'!allocate: nextPage after: address | index stop ch m vadr oldCursor | index _ nil. [true] whileTrue: ["go around bittable from address to end, and beginning to address. we start over again if the table appears full or bitsFile is out of sync" (index notNil and: [stop >= totalPages]) ifTrue: ["wrap around to where we started" stop _ address. index _ 0] ifFalse: [index isNil ifFalse: ["disk probably full" Smalltalk releaseExternalViews. self error: 'YOUR DISK IS FULL (abort or make space and proceed)']. self open. "index by bits rather than bytes? close enough for now" index _ address bitAnd: 8r177770. stop _ totalPages]. bitsFile position: index // 8 + Boffset. [index notNil and: [(index _ index + 8) <= stop]] whileTrue: [(ch _ bitsFile next) = 8r377 ifFalse: ["check that bitsFile position is correct -- possibly out of sync with index if growSmalltalkBy: occurred?" bitsFile position ~= (index // 8 + Boffset) ifTrue: [index _ nil] ifFalse: [m _ 8r200. index - 8 to: index - 1 do: [:vadr | (ch bitAnd: m) = 0 ifTrue: ["page appears free. first update DiskDescriptor" bitsFile skip: -1. bitsFile nextPut: (ch _ ch bitOr: m). "then check if page is really free" vadr = 0 ifFalse: "O.S. boot" [nextPage reinitialize. nextPage freePage. nextPage address: (self virtualToReal: vadr). (nextPage doCommand: CCR error: nil) notNil ifTrue: [oldCursor notNil ifTrue: [oldCursor show]. ^vadr] ifFalse: "otherwise, page not really free" [oldCursor isNil ifTrue: [oldCursor _ Cursor currentCursor. Cursor wait show. "this may take a while"]]]]. "page not free according to bit" m _ m bitShift: -1]]]]]!allocateSN: file | sn i | "get last serial number used, a ByteArray" bitsFile position: 8. sn _ bitsFile next: 4. "Add 1 to 4-byte SN, handling overflow" i _ 4. [(sn at: i) = 255] whileTrue: [sn at: i put: 0. i _ i-1]. sn at: i put: ((sn at: i) + 1). "store new serial number, and return it" bitsFile skip: -4. bitsFile nextPutAll: sn. ^sn!deallocate: page | index byte m | closed ifTrue: [self open]. index _ self realToVirtual: page address. "byte position" bitsFile position: index // 8 + Boffset. byte _ bitsFile next. "bit position" m _ 8r200 bitShift: 0 - (index bitAnd: 7). "make page free by turning off bit in DiskDescriptor" (byte bitAnd: m) = m ifTrue: [bitsFile skip: -1. bitsFile nextPut: byte - m] ifFalse: [Transcript cr. Transcript show: 'page already free (deallocate:)']!freePages | npages byte | self open. bitsFile position: Boffset. npages _ 0. 1 to: totalPages by: 8 do: [:i | (byte _ bitsFile next) = 255 ifFalse: ["possibly up to 8 unused" npages _ npages + 8. [byte = 0] whileFalse: [npages _ npages - (byte bitAnd: 1). byte _ byte bitShift: -1] "all used"]]. ^npages! !!AltoFileDirectory methodsFor: 'private'!addEntry: file "called only by Insert: and rename:newName:" | entrysize holesize | dirFile atEnd ifTrue: [holesize _ nil] ifFalse: [ "either a deleted entry or rename entry" holesize _ dirFile nextWord bitAnd: Dfmask - 1. dirFile skip: -2]. dirFile readWrite. entrysize _ (self fileSize: file) // 2. dirFile nextWordPut: Dfmask + entrysize. file storeOnDirectory: dirFile. (holesize notNil and: [entrysize < holesize]) ifTrue: ["mark remaining hole" dirFile nextWordPut: holesize - entrysize]. dirFile readOnly. bitsFile flush!configure: s "read disk configuration from a Stream: either leader page of SysDir or beginning of DiskDescriptor" | nDisks nHeads nTracks | nDisks _ s nextWord . nTracks _ s nextWord. nHeads _ s nextWord. nSectors _ s nextWord. diskPages _ nTracks * nHeads * nSectors. totalPages _ nDisks * diskPages!deleteEntry: file "called only by Delete: and rename:newName: read and save" | p nextFile | p _ dirFile position. nextFile _ self next. dirFile position: p. "delete it from directory (turn off bit in entry length word)" p _ dirFile nextWord bitAnd: Dfmask - 1. dirFile skip: -2. dirFile readWrite. dirFile nextWordPut: p. dirFile readOnly. dirFile skip: -2. ^nextFile!diskID "return user name and disk name installed in O.S. login name is stored somewhere else???" | f userName diskName len | f _ self oldFile: 'Sys.Boot'. f text. f readOnly. f position: 512. len _ f next asciiValue. userName _ f next: len. f padToNextWord. len _ f next asciiValue. diskName _ f next: len. f close. ^Array with: userName with: diskName!diskNumber ^directoryName!fileSize: file "return size in characters of a directory entry entry format 1 n (length in words, including this one) + undeleted bit (dfmask) 2-3 serialNumber 4 version 5 file number (0?) 6 virtual address of page 0 7-n name as Bcpl string (extra 0 if length even)" ^13 "header word, sn, version, fn, leader, name" + (file fileName size bitOr: 1)!find: aFile ifAbsentDo: aBlock | sn | (aFile fileName sameAs: Dirname) ifTrue: ["return system directory file. known serialNumber and leader" sn _ ByteArray new: 4. sn wordAt: 1 put: 8r100000. sn wordAt: 2 put: 8r144. aFile serialNumber: sn. aFile leader: 8r10000 "(self virtualToReal: 1)". ^aFile]. "^super find: aFile ifAbsent: aBlock" (self findFileOrHole: aFile) ifFalse: [^aBlock value: aFile]. ^self nextFile: aFile!findFileOrHole: t1 | t2 t3 t4 t5 t6 t7 t8 t9 t10 | t2 _ self checkNameOfFile: t1. t1 fileName: t2. t8 _ t2 size. self reset. t5 _ nil. t6 _ Dfmask. t7 _ (self fileSize: t1) // 2. [dirFile atEnd] whileFalse: [t4 _ dirFile nextWord. t3 _ t4 bitAnd: Dfmask - 1. t7 > t3 ifTrue: [t9 _ -2] ifFalse: [t4 = t3 ifTrue: [t9 _ -2. t3 < t6 ifTrue: [t6 _ t3. t5 _ dirFile position]] ifFalse: [dirFile skip: 10. t9 _ -13. t8 = dirFile next ifTrue: [t10 _ 1. [t10 <= t8 and: [(t2 at: t10) asLowercase = dirFile next asCharacter asLowercase]] whileTrue: [t10 _ t10 + 1]. t10 > t8 ifTrue: [dirFile skip: t9 - t8. ^true]. t9 _ t9 - t10]]]. dirFile skip: t3 * 2 + t9]. t5 notNil ifTrue: [dirFile position: t5 - 2]. ^false!nextFile: aFile | w elen | [dirFile atEnd] whileFalse: ["header word of directory" w _ dirFile nextWord. elen _ w bitAnd: Dfmask - 1. (w bitAnd: Dfmask) = Dfmask ifTrue: ["normal entry. create file instance" aFile directory: self. aFile reinitialize. "initialize from directory" aFile readFromDirectory: dirFile. "skip to end of partially read entry" dirFile skip: elen * 2 - (self fileSize: aFile). ^aFile]. "deleted entry" dirFile skipWords: elen - 1]. ^nil!virtualToReal: vadr "inverse of realToVirtual:" | sec d | vadr < diskPages ifTrue: [d _ 0. sec _ vadr] "d _ (vadr // diskPages) bitShift: 1" ifFalse: [d _ 2. sec _ vadr \\ diskPages]. ^"disk" d + "cylinder & head" (sec // nSectors bitShift: 2) + "(sec \\ nSectors) bitShift: 12" "sector" (#(0 8r10000 8r20000 8r30000 8r40000 8r50000 8r60000 8r70000 8r100000 8r110000 8r120000 8r130000 8r140000 8r150000 8r160000 8r170000) at: (sec \\ nSectors + 1)) "Indexing is faster than LargeInteger arithmetic!!"! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!AltoFileDirectory class instanceVariableNames: ''!!AltoFileDirectory class methodsFor: 'instance creation'!directory: aFileDirectory directoryName: aString "Answer an instance of me in directory aFileDirectory whose name is aString." ^super new setDirectory: aFileDirectory directoryName: aString!new ^self directory: 0 directoryName: 0! ! FilePage subclass: #AltoFilePage instanceVariableNames: 'address ' classVariableNames: '' poolDictionaries: 'AltoFilePool ' category: 'Files-Xerox Alto'!AltoFilePage comment:'A FilePage from an AltoFile consists of an address (2 words), a label (8 words) and data (512 bytes). The instance variable "page" is a ByteArray which contains first the label and then the data.'!!AltoFilePage methodsFor: 'accessing'!size ^self headerWordAt: Numch! !!AltoFilePage methodsFor: 'file status'!reinitialize page == nil ifTrue: [super reinitialize] ifFalse: ["nextp, backp, lnused, numch, pn" page atAll: (1 to: 10) put: 0]! !!AltoFilePage methodsFor: 'page accessing'!address ^address!address: addressNumber address _ addressNumber!pageNumber ^self headerWordAt: Pagen!pageNumber: pn self headerWordAt: Pagen put: pn!serialNumber ^self label copyFrom: Sn1 * 2 - 1 to: Sn2 * 2!serialNumber: sn self headerWordAt: Sn1 put: (sn wordAt: 1). self headerWordAt: Sn2 put: (sn wordAt: 2). self headerWordAt: Vn put: 1 "fixed version"! !!AltoFilePage methodsFor: 'page testing'!headerSize ^16!lastPage ^(self headerWordAt: Nextp) = 0! !!AltoFilePage methodsFor: 'file/page/directory implementation'!size: size self headerWordAt: Numch put: size! !!AltoFilePage methodsFor: 'private'!freePage self headerWordAt: Sn1 put: -1. self headerWordAt: Sn2 put: -1. self headerWordAt: Vn put: -1!label ^page! ! CodeController subclass: #AlwaysAcceptCodeController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!AlwaysAcceptCodeController comment:'I am a code controller that will do an accept even if the text is the same.'!!AlwaysAcceptCodeController methodsFor: 'menu messages'!accept (model changeRequestFrom: view) ifFalse: [^view flash]. self controlTerminate. (view accept: self text from: self) ifTrue: [initialText _ paragraph text copy] ifFalse: [view flash]. self controlInitialize! ! Path subclass: #Arc instanceVariableNames: 'quadrant radius center ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!Arc comment: 'A quarter of a Circle, the quadrant is specified by 1, 2, 3 or 4 points which indicate which part of the circle is to be displayed. Quadrants are numbered 1 - 4 counter clockwise.'!!Arc methodsFor: 'accessing'!center "Answer the point at the center of the receiver." ^center!center: aPoint "Set aPoint to be the receiver's center." center _ aPoint!center: aPoint radius: anInteger "The receiver is defined by a point at the center and a radius. The quadrant is not reset." center _ aPoint. radius _ anInteger!center: aPoint radius: anInteger quadrant: section "The receiver is an Arc for the quadrant specified by section. The size of the arc is defined by the center and its radius." center _ aPoint. radius _ anInteger. quadrant _ section!quadrant "Answer the section of a circle represented by the receiver." ^quadrant!quadrant: section "Set section to be the part of the circle represented by the receiver." quadrant _ section!radius "Answer the receiver's radius." ^radius!radius: anInteger "Set anInteger to be the receiver's radius." radius _ anInteger! !!Arc methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm | nSegments line angle sin cos xn yn xn1 yn1 | nSegments _ 12.0. line _ Line new. line form: self form. angle _ 90.0 / nSegments. sin _ (angle * (2 * Float pi / 360.0)) sin. cos _ (angle * (2 * Float pi / 360.0)) cos. quadrant = 1 ifTrue: [xn _ radius asFloat. yn _ 0.0]. quadrant = 2 ifTrue: [xn _ 0.0. yn _ 0.0 - radius asFloat]. quadrant = 3 ifTrue: [xn _ 0.0 - radius asFloat. yn _ 0.0]. quadrant = 4 ifTrue: [xn _ 0.0. yn _ radius asFloat]. nSegments truncated timesRepeat: [xn1 _ xn * cos + (yn * sin). yn1 _ yn * cos - (xn * sin). line beginPoint: center + (xn truncated @ yn truncated). line endPoint: center + (xn1 truncated @ yn1 truncated). line displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm. xn _ xn1. yn _ yn1]!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm | newArc tempCenter | newArc _ Arc new. tempCenter _ aTransformation applyTo: self center. newArc center: tempCenter x truncated @ tempCenter y truncated. newArc quadrant: self quadrant. newArc radius: (self radius * aTransformation scale x) truncated. newArc form: self form. newArc displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRect rule: anInteger mask: aForm! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Arc class instanceVariableNames: ''!!Arc class methodsFor: 'examples'!example "Click the button somewhere on the screen. The designated point will be the center of an Arc with radius 50 in the 4th quadrant." | anArc aForm | aForm _ Form new extent: 1 @ 30. "make a long thin Form for display" aForm black. "turn it black" anArc _ Arc new. anArc form: aForm. "set the form for display" anArc radius: 50.0. anArc center: Sensor waitButton. anArc quadrant: 4. anArc displayOn: Display. Sensor waitButton "Arc example."! ! ArrayedCollection variableSubclass: #Array instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed'!Array comment:'I am an arrayed collection of pointers.'!!Array methodsFor: 'comparing'!hash "make sure = arrays hash =ly" self size = 0 ifTrue: [^17171]. ^(self at: 1) hash + (self at: self size) hash!hashMappedBy: map "Answer what my hash would be if oops changed according to map" self size = 0 ifTrue: [^ self hash]. ^ (self first hashMappedBy: map) + (self last hashMappedBy: map)! !!Array methodsFor: 'converting'!asArray "Answer with the receiver itself." ^self! !!Array methodsFor: 'printing'!isLiteral self detect: [:element | element isLiteral not] ifNone: [^true]. ^false!printOn: aStream | tooMany | tooMany _ aStream position + self maxPrint. aStream nextPut: $(. self do: [:element | aStream position > tooMany ifTrue: [aStream nextPutAll: '...etc...)'. ^self]. element printOn: aStream. aStream space]. aStream nextPut: $)!storeOn: aStream "Use the literal form if possible." self isLiteral ifTrue: [aStream nextPut: $#; nextPut: $(. self do: [:element | element printOn: aStream. aStream space]. aStream nextPut: $)] ifFalse: [super storeOn: aStream]! ! SequenceableCollection subclass: #ArrayedCollection instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Abstract'!ArrayedCollection comment:'I am an abstract collection of elements with integers as external keys. I re-implement several messages inherited from SequenceableCollection in order to obtain some performance gains. Subclasses are Array elements are pointers ByteArray elements are bytes RunArray elements are typically runs of the same thing String elements are characters Text elements are characters with style WordArray elements are words '!!ArrayedCollection methodsFor: 'accessing'!size "Answer the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Primitive is specified here to override SequenceableCollection size. Essential. See Object documentation whatIsAPrimitive. " <primitive: 62> ^self basicSize! !!ArrayedCollection methodsFor: 'adding'!add: newObject self shouldNotImplement! !!ArrayedCollection methodsFor: 'printing'!storeOn: aStream aStream nextPutAll: '(('. aStream nextPutAll: self class name. aStream nextPutAll: ' new: '. aStream store: self size. aStream nextPut: $). (self storeElementsFrom: 1 to: self size on: aStream) ifFalse: [aStream nextPutAll: '; yourself']. aStream nextPut: $)! !!ArrayedCollection methodsFor: 'private'!defaultElement ^nil!storeElementsFrom: firstIndex to: lastIndex on: aStream | noneYet defaultElement arrayElement | noneYet _ true. defaultElement _ self defaultElement. firstIndex to: lastIndex do: [:index | arrayElement _ self at: index. arrayElement = defaultElement ifFalse: [noneYet ifTrue: [noneYet _ false] ifFalse: [aStream nextPut: $;]. aStream nextPutAll: ' at: '. aStream store: index. aStream nextPutAll: ' put: '. aStream store: arrayElement]]. ^noneYet! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ArrayedCollection class instanceVariableNames: ''!!ArrayedCollection class methodsFor: 'instance creation'!new "Answer a new instance of me, with size = 0." ^self new: 0!new: size withAll: value "Answer a new instance of me, whose every element is equal to the argument, value." ^(self new: size) atAllPut: value!with: anObject "Answer a new instance of me, containing only anObject." | newCollection | newCollection _ self new: 1. newCollection at: 1 put: anObject. ^newCollection!with: firstObject with: secondObject "Answer a new instance of me, containing firstObject and secondObject." | newCollection | newCollection _ self new: 2. newCollection at: 1 put: firstObject. newCollection at: 2 put: secondObject. ^newCollection!with: firstObject with: secondObject with: thirdObject "Answer a new instance of me, containing only these three objects." | newCollection | newCollection _ self new: 3. newCollection at: 1 put: firstObject. newCollection at: 2 put: secondObject. newCollection at: 3 put: thirdObject. ^newCollection!with: firstObject with: secondObject with: thirdObject with: fourthObject "Answer a new instance of me, containing the four arguments as the elements." | newCollection | newCollection _ self new: 4. newCollection at: 1 put: firstObject. newCollection at: 2 put: secondObject. newCollection at: 3 put: thirdObject. newCollection at: 4 put: fourthObject. ^newCollection! ! ParseNode subclass: #AssignmentNode instanceVariableNames: 'variable value ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!AssignmentNode comment: 'I represent a (var_expr) construct.'!!AssignmentNode methodsFor: 'initialize-release'!variable: aVariable value: expression variable _ aVariable. value _ expression!variable: aVariable value: expression from: encoder "compile" (aVariable isMemberOf: MessageNode) ifTrue: [^aVariable store: expression from: encoder]. variable _ aVariable. value _ expression! !!AssignmentNode methodsFor: 'code generation'!emitForEffect: stack on: aStream value emitForValue: stack on: aStream. variable emitStorePop: stack on: aStream!emitForValue: stack on: aStream value emitForValue: stack on: aStream. variable emitStore: stack on: aStream!sizeForEffect: encoder ^(value sizeForValue: encoder) + (variable sizeForStorePop: encoder)!sizeForValue: encoder ^(value sizeForValue: encoder) + (variable sizeForStore: encoder)! !!AssignmentNode methodsFor: 'printing'!printOn: aStream indent: level variable printOn: aStream indent: level. aStream nextPutAll: ' _ '. value printOn: aStream indent: level + 2!printOn: aStream indent: level precedence: p p < 4 ifTrue: [aStream nextPutAll: '(']. self printOn: aStream indent: level. p < 4 ifTrue: [aStream nextPutAll: ')']! ! LookupKey subclass: #Association instanceVariableNames: 'value ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Support'!Association comment: 'I am a pair of associated objects--a key and a value. I can serve as an entry in a dictionary. Think of my key as the left-hand side of the dictionary and my value as the right-hand side.'!!Association methodsFor: 'accessing'!key: aKey value: anObject "Store the arguments as the variables of the receiver." key _ aKey. value _ anObject!value "Answer the value of the receiver." ^value!value: anObject "Store the argument, anObject, as the value of the receiver." value _ anObject! !!Association methodsFor: 'printing'!printOn: aStream super printOn: aStream. aStream nextPutAll: '->'. value printOn: aStream! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Association class instanceVariableNames: ''!!Association class methodsFor: 'instance creation'!key: newKey value: newValue "Answer a new instance of me with the arguments as the key and value of the association." ^(super key: newKey) value: newValue! ! Collection subclass: #Bag instanceVariableNames: 'contents ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Unordered'!Bag comment: 'I am an unordered collection of elements. I store these elements in a dictionary, tallying up occurrences of equal objects. Because I store an occurrence only once, my clients should beware that objects they store will not necessarily be retrieved such that == is true. If the client cares, a subclass of me should be created.'!!Bag methodsFor: 'accessing'!at: index self errorNotKeyed!at: index put: anObject self errorNotKeyed!size | tally | tally _ 0. contents do: [:each | tally _ tally + each]. ^tally!sortedCounts "Answer with a collection of counts with elements, sorted by decreasing count." | counts | counts _ SortedCollection sortBlock: [:x :y | x >= y]. contents associationsDo: [:assn | counts add: (Association key: assn value value: assn key)]. ^ counts!sortedElements "Answer with a collection of elements with counts, sorted by element." | elements | elements _ SortedCollection new. contents associationsDo: [:assn | elements add: assn]. ^ elements! !!Bag methodsFor: 'testing'!includes: anObject ^contents includesKey: anObject!occurrencesOf: anObject (self includes: anObject) ifTrue: [^contents at: anObject] ifFalse: [^0]! !!Bag methodsFor: 'adding'!add: newObject ^self add: newObject withOccurrences: 1!add: newObject withOccurrences: anInteger "Add the element newObject to the elements of the receiver. Do so as though the element were added anInteger number of times. Answer newObject." (self includes: newObject) ifTrue: [contents at: newObject put: anInteger + (contents at: newObject)] ifFalse: [contents at: newObject put: anInteger]. ^newObject! !!Bag methodsFor: 'removing'!remove: oldObject ifAbsent: exceptionBlock | count | (self includes: oldObject) ifTrue: [(count _ contents at: oldObject) = 1 ifTrue: [contents removeKey: oldObject] ifFalse: [contents at: oldObject put: count - 1]] ifFalse: [^exceptionBlock value]. ^oldObject! !!Bag methodsFor: 'enumerating'!do: aBlock contents associationsDo: [:assoc | assoc value timesRepeat: [aBlock value: assoc key]]! !!Bag methodsFor: 'private'!setDictionary contents _ Dictionary new! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Bag class instanceVariableNames: ''!!Bag class methodsFor: 'instance creation'!new ^super new setDictionary! ! Object subclass: #Behavior instanceVariableNames: 'superclass methodDict format subclasses ' classVariableNames: 'SelectorsOfConflictMethods SelectorsOfCopiedMethods SelectorsOfDirectedMethods ' poolDictionaries: '' category: 'Kernel-Classes'!Behavior comment:'Instance Variables: superclass <Behavior> links the chain of inheritance methodDict <IdentityDictionary> associates message names with methods format <Integer> encodes storage layout of instances subclasses <Set> back-pointers to the class'' subclassesBehavior provides the minimum state necessary for compiling methods, and creating and running instances. Most objects are created as instances of the more fully supported subclass, Class, but Behavior is a good starting point for providing instance-specific behavior (as in Metaclass).'!!Behavior methodsFor: 'initialize-release'!obsolete "Invalidate and recycle local messages. Remove the receiver from its superclass' subclass list." methodDict _ MethodDictionary new. self superclasses do: [:each | each removeSubclass: self]. self removeFromInheritanceTables! !!Behavior methodsFor: 'accessing'!format "Answer an Integer that encodes the kinds and numbers of variables of instances of the receiver." ^format! !!Behavior methodsFor: 'testing'!instSize "Answer the number of named instance variables (as opposed to indexed variables) of the receiver." ^format bitAnd: 255!isBits "Answer whether the receiver contains just bits (not pointers)." ^format noMask: -16384!isBytes "Answer whether the receiver has 8-bit instance variables." ^format noMask: 8192!isFixed "Answer whether the receiver does not have a variable (indexable) part." ^self isVariable not!isPointers "Answer whether the receiver contains just pointers (not bits)." ^self isBits not!isVariable "Answer whether the receiver has a variable (indexable) part." ^(format bitAnd: 4096) ~= 0!isWords "Answer whether the receiver has 16-bit instance variables." ^self isBytes not! !!Behavior methodsFor: 'copying'!copy "Make a copy of the receiver without a list of subclasses." | myCopy savedSubclasses | savedSubclasses _ subclasses. subclasses _ nil. myCopy _ self shallowCopy. subclasses _ savedSubclasses. ^myCopy methodDictionary: methodDict copy! !!Behavior methodsFor: 'printing'!printHierarchy "Answer a description containing the names and instance variable names of all of the subclasses and superclasses of the receiver." | aStream index supers | index _ 0. aStream _ WriteStream on: (String new: 16). self allDynamicSuperclasses reverseDo: [:aClass | aStream crtab: index. index _ index + 1. aStream nextPutAll: aClass name. aStream space. aStream print: aClass instVarNames. supers _ aClass superclasses. supers size>1 ifTrue: [aStream nextPutAll: ' [also a '. (supers copyFrom: 2 to: supers size) do: [:s | aStream space; nextPutAll: s name; space; print: s allInstVarNames]. aStream nextPut: $] ]]. aStream cr. self printSubclassesOn: aStream callingSuperclass: self dynamicSuperclass level: index. ^aStream contents!printOn: aStream aStream nextPutAll: 'a descendent of '. superclass printOn: aStream! !!Behavior methodsFor: 'creating class hierarchy'!addSubclass: aSubclass "Make the argument, aSubclass, be one of the subclasses of the receiver." (aSubclass superclasses includes: self) ifTrue: [subclasses == nil ifTrue: [subclasses _ Set with: aSubclass] ifFalse: [subclasses add: aSubclass]] ifFalse: [self error: aSubclass name , ' is not my subclass']!removeSubclass: aSubclass "If the argument, aSubclass, is one of the receiver's subclasses, remove it." subclasses == nil ifFalse: [subclasses remove: aSubclass ifAbsent: []. subclasses isEmpty ifTrue: [subclasses _ nil]]!superclass: aClass "Change the receiver's superclass to be aClass." (aClass isKindOf: Behavior) ifTrue: [superclass _ aClass] ifFalse: [self error: 'superclass must be a class-describing object']! !!Behavior methodsFor: 'creating method dictionary'!addSelector: selector withMethod: compiledMethod "Add the message selector with the corresponding compiled method to the receiver's method dictionary." | wasThere | wasThere _ methodDict includesKey: selector. methodDict at: selector put: compiledMethod. self flushCache. "if the selector is indexed in SelectorsOfConflictMethods or SelectorsOfCopiedMethods, remove it" ((SelectorsOfConflictMethods at: selector ifAbsent: [Array new]) includes: self) ifTrue: [self removeClass: self selector: selector in: SelectorsOfConflictMethods]. ((SelectorsOfCopiedMethods at: selector ifAbsent: [Array new]) includes: self) ifTrue: [self removeClass: self selector: selector in: SelectorsOfCopiedMethods]. wasThere ifTrue: [self checkChangeSelector: selector] ifFalse: [self subclasses do: [:sub | sub checkSuperAddSelector: selector]]!addSelectorUnchecked: selector withMethod: compiledMethod "Add the message selector with the corresponding compiled method to the receiver's method dictionary. Do not check for effect on (multiple) inheritance." methodDict at: selector put: compiledMethod. self flushCache!methodDictionary: aDictionary "Store the argument, aDictionary, as the method dictionary of the receiver." methodDict _ aDictionary!removeSelector: selector "Assuming that the message selector is in the receiver's method dictionary, remove it. If the selector is not in the method dictionary, create an error notification." methodDict removeKey: selector. self flushCache. self checkChangeSelector: selector!removeSelectorUnchecked: selector "Assuming that the message selector is in the receiver's method dictionary, remove it. If the selector is not in the method dictionary, create an error notification. Do not check for effect on (multiple) inheritance." methodDict removeKey: selector. self flushCache!tryCopyingCodeFor: selector "Check if 'selector' is compound, and if so, try to copy down the appropriate code. Return #OK if sucessful, #HierarchyViolation if the class part is not one of my immediate superclasses, or #NotFound if the class part is OK but the selector part is not found in the inheritance hierarchy." | classPart whichClass simpleSelector descr | selector isCompound ifFalse: [^#NotFound]. classPart _ selector classPart. simpleSelector _ selector selectorPart. "check for special class parts" classPart==#all ifTrue: [self compileBroadcastCodeFor: simpleSelector. self insertClass: self selector: simpleSelector in: SelectorsOfDirectedMethods. ^#OK]. classPart==#super ifTrue: [descr _ self superMethodDescriptionAt: simpleSelector] ifFalse: [whichClass _ Smalltalk at: classPart. "if I'm a metaclass, get the metaclass of whichClass" self isMeta ifTrue: [whichClass _ whichClass class]. "check that whichClass is one of my superclasses" (self inheritsFrom: whichClass) ifFalse: [^#HierarchyViolation]. descr _ whichClass methodDescriptionAt: simpleSelector]. descr isBad ifTrue: [^#NotFound]. self compileUnchecked: classPart , '.' , descr sourceCode. self insertClass: self selector: simpleSelector in: SelectorsOfDirectedMethods. ^#OK! !!Behavior methodsFor: 'instance creation'!basicNew "Answer a new instance of the receiver (which is a class) with no indexable variables. Fail if the class is indexable. Essential. See Object documentation whatIsAPrimitive." <primitive: 70> self isVariable ifTrue: [^self basicNew: 0]. self primitiveFailed!basicNew: anInteger "Answer a new instance of the receiver (which is a class) with the number of indexable variables specified by the argument, anInteger. Fail if the class is not indexable or if the argument is not a positive Integer. Essential. See Object documentation whatIsAPrimitive." <primitive: 71> self primitiveFailed!new "Answer a new instance of the receiver (which is a class) with no indexable variables. Fail if the class is indexable. Essential. See Object documentation whatIsAPrimitive. " <primitive: 70> self isVariable ifTrue: [^self new: 0]. self primitiveFailed!new: anInteger "Answer a new instance of the receiver (which is a class) with the number of indexable variables specified by the argument, anInteger. Fail if the class is not indexable or if the argument is not a positive Integer. Essential. See Object documentation whatIsAPrimitive." <primitive: 71> self primitiveFailed! !!Behavior methodsFor: 'accessing class hierarchy'!allDynamicSuperclasses "Answer an OrderedCollection of the receiver and the receiver's ancestor's dynamic superclasses; ordered with immediate superclass first." | temp | superclass == nil ifTrue: [^OrderedCollection new] ifFalse: [temp _ superclass allDynamicSuperclasses. temp addFirst: superclass. ^temp]!allSubclasses "Answer an OrderedCollection of the receiver's subclasses and the receiver's ancestor's subclasses in breadth-first order, with the immediate subclasses first." | coll | coll _ OrderedCollection new. coll addAll: self subclasses. self subclasses do: [:eachSubclass | coll addAll: eachSubclass allSubclasses]. ^coll!allSuperclasses "Answer an OrderedCollection of the receiver's superclasses and the receiver's ancestor's superclasses in breadth-first order, with the immediate superclasses first." | coll | coll _ OrderedCollection new. self allSuperclassesInto: coll. ^coll!allSuperclassesInto: orderedCollection "Add all my superclasses to orderedCollection if not already there. Use breadth-first order." | mysupers | mysupers _ self superclasses. mysupers do: [:each | each allSuperclassesInto: orderedCollection]. mysupers reverseDo: [:each | (orderedCollection includes: each) ifFalse: [orderedCollection addFirst: each]]!dynamicSuperclass "Answer the receiver's superclass. Only returns the first one - use 'superclasses' to find them all." ^superclass!hasMultipleSuperclasses ^false!subclasses "Answer the receiver's subclasses. Return a copy so that callers who add or delete subclasses won't get confused." subclasses == nil ifTrue: [^Set new] ifFalse: [^subclasses copy]!superclass "Answer the receiver's superclass. Only returns the first one - use 'superclasses' to find them all." ^superclass!superclasses "Answer with an array of all the receiver's superclasses." superclass == nil ifTrue: [^#()]. self hasMultipleSuperclasses ifTrue: [^ (Array with: superclass) , self class otherSuperclasses]. ^ Array with: superclass!withAllSubclasses "Answer an OrderedCollection of subclasses including this class in breadth first order." | subs | subs _ self allSubclasses. subs addFirst: self. ^subs!withAllSuperclasses "Answer an OrderedCollection of superclasses including this class in breadth first order." | subs | subs _ self allSuperclasses. subs addFirst: self. ^subs! !!Behavior methodsFor: 'accessing method dictionary'!allSelectors "Answer a set of all the message selectors that instances of the receiver can understand." | aSet | aSet _ Set new. self withAllSuperclasses do: [:each | aSet addAll: each selectors]. ^aSet "Point allSelectors."!checkChangeSelector: selector | descr classes class | "The method for selector has been changed or removed. Check all copied versions for the method in question." (SelectorsOfCopiedMethods at: selector ifAbsent: [Array new]) do: [:class | (class inheritsFrom: self) ifTrue: [(class checkMethodFor: selector) ifFalse: [Transcript cr; show: 'conflicting methods for ' , selector, ' in ', class name] ]]. "Remove all versions copied for directed access (eg Point.max) " (SelectorsOfDirectedMethods at: selector ifAbsent: [Array new]) do: [:class | (class inheritsFrom: self) ifTrue: [(class compoundSelectorsMatching: selector) do: [:sel | class removeSelectorUnchecked: sel]. self removeClass: class selector: selector in: SelectorsOfDirectedMethods]]!checkSuperAddSelector: selector | local | local _ self includesSelector: selector. self hasMultipleSuperclasses ifFalse: [local ifTrue: [^self]. ^ self subclasses do: [:sub | sub checkSuperAddSelector: selector]]. (self checkMethodFor: selector) ifFalse: "Copy or note conflict" [Transcript cr; show: 'conflicting methods for ' , selector, ' in ', self name]. local ifTrue: [^self]. "Was local before, so no change below" ^ self subclasses do: [:sub | sub checkSuperAddSelector: selector]!compiledMethodAt: selector "Answer the compiled method associated with the message selector in the receiver's method dictionary. If the selector is not in the dictionary, create an error notification." ^methodDict at: selector!dynamicMethodDescriptionAt: selector "return a method description for the method for 'selector' that would be found by dynamic lookup" (methodDict includesKey: selector) ifTrue: [^MethodDescription whichClass: self selector: selector]. superclass == nil ifTrue: [^MethodDescription makeMethodNotImplemented]. ^superclass dynamicMethodDescriptionAt: selector!methodDescriptionAt: selector "return a method description for the method for 'selector' " | local copied conflict | local _ methodDict includesKey: selector. copied _ (SelectorsOfCopiedMethods at: selector ifAbsent: [Array new]) includes: self. conflict _ (SelectorsOfConflictMethods at: selector ifAbsent: [Array new]) includes: self. local & copied not & conflict not ifTrue: [^MethodDescription whichClass: self selector: selector]. ^self superMethodDescriptionAt: selector!selectorAtMethod: method setClass: classResultBlock "Answer both the message selector associated with the compiled method and the class in which that selector is defined." | sel | sel _ methodDict keyAtValue: method ifAbsent: [superclass == nil ifTrue: [classResultBlock value: self. ^self defaultSelectorForMethod: method]. sel _ superclass selectorAtMethod: method setClass: classResultBlock. "Set class to be self, rather than that returned from superclass. " sel == (self defaultSelectorForMethod: method) ifTrue: [classResultBlock value: self]. ^sel]. classResultBlock value: self. ^sel!selectors "Answer a Set of all the message selectors specified in the receiver's method dictionary." ^methodDict keys "Point selectors."!sourceCodeAt: messageSelector "Answer the string corresponding to the source code for the argument." ^ self sourceCodeForMethod: (methodDict at: messageSelector) at: messageSelector!sourceCodeForMethod: method at: messageSelector "Answer the string corresponding to the source code for the argument." | newSource index| Sensor leftShiftDown ifTrue: [newSource _ (self decompilerClass new decompile: messageSelector in: self method: method) decompileString] ifFalse: [newSource _ method getSource. newSource == nil ifTrue: [newSource _ (self decompilerClass new decompile: messageSelector in: self method: method) decompileString] ifFalse: [((newSource at: newSource size) isSeparator) ifTrue: [index _ newSource size. "tidy up for file out" [((newSource at: index) isSeparator) and: [index > 1]] whileTrue: [index _ index - 1]. newSource _ newSource copyFrom: 1 to: index]]]. ^newSource!sourceMethodAt: selector "Answer the paragraph corresponding to the source code for the argument." ^(self sourceCodeAt: selector) asText makeSelectorBoldIn: self!superMethodDescriptionAt: selector "return a method description for the method for 'selector' inherited from my superclasses" | descr result | result _ MethodDescription makeMethodNotImplemented. self superclasses do: [: each | descr _ each methodDescriptionAt: selector. descr isMethodNotImplemented ifFalse: [result isMethodNotImplemented ifTrue: [result _ descr] ifFalse: [result=descr ifFalse: [^MethodDescription makeConflictingMethods]]]]. ^result! !!Behavior methodsFor: 'accessing instances and variables'!allClassVarNames "Answer a Set of the names of the receiver's and the receiver's ancestor's class variables." ^superclass allClassVarNames!allInstances "Answer a collection of all instances of this class." | aCollection | aCollection _ OrderedCollection new. self allInstancesDo: [:x | x == aCollection ifFalse: [aCollection add: x]]. ^aCollection!allInstVarNames "Answer an Array of the names of the receiver's instance variables." | names | names _ OrderedCollection new. self accumulateInstVarNames: names traversedClasses: Set new. ^names!allSharedPools "Answer a Set of the pools, dictionaries, that the receiver and the receiver's ancestors share. Subclasses, such as class Class, override this message." ^superclass allSharedPools!allVarNamesSelect: selectBlock "Answer a collection of all the static variable names defined for the receiver which satisfy the condition in selectBlock. Test class and pool variables, including superclass variables. Also include global variables." | set | set _ self classPool keys select: selectBlock. self sharedPools do: [:pool | set addAll: (pool keys select: selectBlock)]. superclass == nil ifTrue: [set addAll: (Smalltalk keys select: selectBlock)] ifFalse: [set addAll: (superclass allVarNamesSelect: selectBlock)]. ^set!classVarNames "Answer a Set of the receiver's class variable names. Since the receiver does not retain knowledge of class variables, the method fakes it by creating an empty set." ^Set new!instanceCount "Answer the number of instances of the receiver that are currently in use." | count | count _ 0. self allInstancesDo: [:x | count _ count + 1]. ^count!instVarNames "Answer an Array of the instance variable names. Behaviors must make up fake local instance variable names because Behaviors have instance variables for the purpose of compiling methods, but these are not named instance variables. " | mySize superSize | mySize _ self instSize. superSize _ superclass == nil ifTrue: [0] ifFalse: [superclass instSize]. mySize = superSize ifTrue: [^#()]. ^(superSize + 1 to: mySize) collect: [:i | 'inst' , i printString]!sharedPools "Answer a Set of the pools, dictionaries, that the receiver shares. Since the receiver does not retain knowledge of pool dictionaries, the method fakes it by creating an empty array. Subclasses, such as class Class, override this message." ^Set new!someInstance "Answer the first instance of this receiver. See Object nextInstance. Fails if there are none. Essential. See Object documentation whatIsAPrimitive." <primitive: 77> ^nil!subclassInstVarNames "Answer a Set of the names of the receiver's subclasses' instance variables." | vars | vars _ Set new. self allSubclasses do: [:aSubclass | vars addAll: aSubclass instVarNames]. ^vars! !!Behavior methodsFor: 'testing class hierarchy'!inheritsFrom: aClass "Answer whether the argument, aClass, is on the receiver's superclass chain." self superclasses do: [:each | (each==aClass or: [each inheritsFrom: aClass]) ifTrue: [^true]]. ^false!kindOfSubclass "Answer a string which is the keyword that describes the receiver's kind of subclass, either a regular subclass, a variableSubclass, a variableByteSubclass, or a variableWordSubclass." self isVariable ifTrue: [self isBits ifTrue: [self isBytes ifTrue: [^' variableByteSubclass: '] ifFalse: [^' variableWordSubclass: ']] ifFalse: [^' variableSubclass: ']] ifFalse: [^' subclass: ']! !!Behavior methodsFor: 'testing method dictionary'!canUnderstand: selector "Answer true if the receiver can respond to the message whose selector is the argument, false otherwise. The selector can be in the method dictionary of the receiver's class or any of its superclasses." (self includesSelector: selector) ifTrue: [^true]. superclass == nil ifTrue: [^false]. ^superclass canUnderstand: selector!hasMethods "Answer whether the receiver has any methods in its method dictionary." ^methodDict size > 0!includesSelector: aSymbol "Answer whether the message whose selector is the argument is in the method dictionary of the receiver's class." ^methodDict includesKey: aSymbol!scopeHas: varName ifTrue: assocBlock "Look up varName in this class, its superclasses, and Smalltalk. If it is there, pass the association to assocBlock, and answer true; else answer false." | assoc | self withAllSuperclasses do: [:sup | (sup poolHas: varName ifTrue: assocBlock) ifTrue: [^true]]. assoc _ Smalltalk associationAt: varName ifAbsent: []. assoc == nil ifFalse: [assocBlock value: assoc. ^true]. ^false!whichClassIncludesSelector: aSymbol "Answer the class on the receiver's superclass chain where the argument, aSymbol (a message selector), will be found." (methodDict includesKey: aSymbol) ifTrue: [^self]. superclass == nil ifTrue: [^nil]. ^superclass whichClassIncludesSelector: aSymbol "Rectangle whichClassIncludesSelector: #inspect."!whichSelectorsAccess: instVarName "Answer a set of selectors whose methods access the argument, instVarName, as a named instance variable." | instVarIndex | instVarIndex _ self allInstVarNames indexOf: instVarName ifAbsent: [^Set new]. ^methodDict keys select: [:sel | ((methodDict at: sel) readsField: instVarIndex) or: [(methodDict at: sel) writesField: instVarIndex]] "Point whichSelectorsAccess: 'x'."!whichSelectorsReferTo: literal "Answer a set of selectors whose methods access the argument as a literal." | special | special _ Smalltalk hasSpecialSelector: literal ifTrueSetByte: [:byte ]. ^self whichSelectorsReferTo: literal special: special byte: byte "Rectangle whichSelectorsReferTo: #+."!whichSelectorsReferTo: literal special: specialFlag byte: specialByte "Answer a collection of selectors whose methods access the argument as a literal." | who method methodArray index arraySize | who_ OrderedCollection new. methodArray _ methodDict methodArray. arraySize _ methodArray size. index _ 0. [(index _ index + 1) <= arraySize] whileTrue: [(method _ methodArray at: index) == nil ifFalse: [((method refersToLiteral: literal) or: [specialFlag and: [method scanFor: specialByte]]) ifTrue: [who add: (methodDict basicAt: index)]]]. ^who "Rectangle whichSelectorsReferTo: #+."! !!Behavior methodsFor: 'compiling'!compile: code notifying: requestor trailer: bytes "Compile the argument, code, as source code in the context of the receiver. Use the default fail code [^nil]. Does not save source code. The second argument, requestor, is to be notified if an error occurs. The argument code is either a string or an object that converts to a string or a PositionableStream on an object that converts to a string. The third argument, bytes, is a trailer, that is, an array of three bytes that should be added to the end of the compiled method. These point to the location of the source code (on a file)." ^self compile: code notifying: requestor trailer: bytes ifFail: [^nil]!compile: code notifying: requestor trailer: bytes ifFail: failBlock "Compile the argument, code, as source code in the context of the receiver and install the result in the receiver's method dictionary. The argument requestor is to be notified if an error occurs. The argument code is either a string or an object that converts to a string or a PositionableStream on an object that converts to a string. The trailer is an array of three bytes that should be added to the end of the compiled method. These point to the location of the source code (on a file). This method does not save the source code. Evaluate the failBlock if the compilation does not succeed." | methodNode selector | methodNode _ self compilerClass new compile: code in: self notifying: requestor ifFail: failBlock. selector _ methodNode selector. self addSelector: selector withMethod: (methodNode generate: bytes). ^selector!compileAll ^ self compileAllFrom: self!compileAllFrom: oldClass "Compile all the methods in oldClass's method dictionary. See recompile:from: regarding oldClass, which is normally just self." self selectors do: [:sel | self recompile: sel from: oldClass]!compileAllSubclasses "Compile all the methods in the receiver's subclasses. This does not modify code (re-install the compiled versions), just compiles the methods as a kind of static check." self allSubclasses do: [:aSubclass | aSubclass compileAll]!compileBroadcastCodeFor: selector "compile code that invokes ALL methods for 'selector' in my inheritance hierarchy" | implementors strm keywords argNames | implementors _ self withAllSuperclasses select: [:each | each includesSelector: selector]. argNames _ Array new: selector numArgs. 1 to: argNames size do: [:i | argNames at: i put: 'arg' , i printString]. strm _ WriteStream on: (String new: 500). strm nextPutAll: 'all.'. argNames size=0 ifTrue: [strm nextPutAll: selector] ifFalse: [keywords _ selector keywords. 1 to: argNames size do: [:i | strm nextPutAll: (keywords at: i); space; nextPutAll: (argNames at: i); space]]. implementors do: [:each | strm cr; tab; nextPutAll: 'self '; nextPutAll: each name; nextPut: $. . argNames size=0 ifTrue: [strm nextPutAll: selector] ifFalse: [keywords _ selector keywords. 1 to: argNames size do: [:i | strm nextPutAll: (keywords at: i); space; nextPutAll: (argNames at: i); space]]. strm nextPut: $.]. self compileUnchecked: strm contents!compilerClass "Return a compiler class appropriate for source methods of this class." ^Compiler!compileUnchecked: code "Compile the argument, code, and install the result in the receiver's method dictionary. Do not check for possible effect on inheritance, since that's what this is doing." | selector methodNode | methodNode _ self compilerClass new compile: code in: self notifying: nil ifFail: [^nil]. selector _ methodNode selector. self addSelectorUnchecked: selector withMethod: (methodNode generate: #(0 0 0)). ^selector!decompile: selector "Find the compiled code associated with the argument, selector, as a message selector in the receiver's method dictionary and decompile it. Answer the resulting source code as a string. Create an error if the selector is not in the receiver's method dictionary." ^self decompilerClass new decompile: selector in: self!decompilerClass "Return a decompiler class appropriate for compiled methods of this class." ^Decompiler!evaluatorClass "Return an evaluator class appropriate for evaluating expressions in the context of instances of this class." ^Compiler!parserClass "Return a parser class to use for parsing methods in this class." ^self compilerClass preferredParserClass!poolHas: varName ifTrue: assocBlock "Behaviors have no pools" ^false!recompile: selector ^ self recompile: selector from: self!recompile: selector from: oldClass "Recompile the method associated with selector in the receiver's method dictionary. Take care not to write out any new source code - just generate new bytes. oldClass may differ from self in order to decompile right (if sourceFiles == nil) when adding or removing fields of a class." | method trailer methodNode | method _ oldClass compiledMethodAt: selector. trailer _ (method size - 2 to: method size) collect: [:i | method at: i]. methodNode _ self compilerClass new compile: (oldClass sourceCodeAt: selector) in: self notifying: nil ifFail: []. methodNode == nil "Try again after proceed from SyntaxError" ifTrue: [^self recompile: selector]. selector == methodNode selector ifFalse: [self error: 'selector changed!!']. self addSelector: selector withMethod: (methodNode generate: trailer).!sourceCodeTemplate "Answer an expression to be edited and evaluated in order to define methods in this class." ^'message selector and argument names "comment stating purpose of message" | temporary variable names | statements'!subclassDefinerClass "Return an evaluator class appropriate for evaluating definitions of new subclasses of this class." ^Compiler! !!Behavior methodsFor: 'enumerating'!allAccessesTo: instVarName "Return a list of all methods in my hierarchy that refer to the named instance variable." | coll | coll _ OrderedCollection new. Cursor execute showWhile: [(self withAllSuperclasses reverse) , self allSubclasses do: [:class | (class whichSelectorsAccess: instVarName) do: [:sel | sel ~~ #DoIt ifTrue: [coll add: class name , ' ' , sel]]]]. ^coll "Collection allAccessesTo: 'contents'."!allCallsOn: aLiteral "Answer a SortedCollection of all the methods that call on aLiteral." | aSortedCollection special | aSortedCollection _ SortedCollection new. special _ Smalltalk hasSpecialSelector: aLiteral ifTrueSetByte: [:byte ]. (self withAllSuperclasses reverse) , self allSubclasses do: [:class | (class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [aSortedCollection add: class name , ' ' , sel]]. (class class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [aSortedCollection add: class class name , ' ' , sel]]. ]. ^aSortedCollection!allInstancesDo: aBlock "Evaluate the argument, aBlock, for each of the current instances of the receiver." | inst next | inst _ self someInstance. inst == nil ifFalse: [[next _ inst nextInstance. aBlock value: inst. next == nil] whileFalse: [inst _ next]]. nil class == self ifTrue: [aBlock value: nil]!allSubclassesDo: aBlock "Evaluate the argument, aBlock, for each of the receiver's subclasses." self subclasses do: [:cl | aBlock value: cl. cl allSubclassesDo: aBlock]!allSubInstancesDo: aBlock "Evaluate the argument, aBlock, for each of the current instances of the receiver's subclasses." self allSubclassesDo: [:sub | sub allInstancesDo: aBlock]!browseAllAccessesTo: instanceVariable "Create and schedule a Message Set browser for all the receiver's methods or any methods of a subclass that refer to the instance variable name. If the instance variable name is not defined for the receiver, the notification 'Nobody' occurs in the System Transcript." BrowserView openListBrowserOn: (self allAccessesTo: instanceVariable) label: instanceVariable initialSelection: instanceVariable!browseAllCallsOn: aSymbol "Create and schedule a message browser on each method that calls on aSymbol. For example, Number browseAllCallsOn: #/. " | label key | (aSymbol isMemberOf: Association) ifTrue: [key _ aSymbol key. label _ 'Users of ' , key] ifFalse: [key _ aSymbol. label _ 'Senders of ', key]. ^ BrowserView openListBrowserOn: (self allCallsOn: aSymbol) label: label, ' from ', self name initialSelection: key asSymbol keywords first!crossReference "Answer an array of arrays of size 2 whose first element is a message selector in the receiver's method dictionary and whose second element is a set of all message selectors in the method dictionary whose methods send a message with that selector. Subclasses are not included." ^self selectors asSortedCollection asArray collect: [:x | Array with: (String with: Character cr), x with: (self whichSelectorsReferTo: x)] "Point crossReference."!showVariableMenu: generatorBlock collect: valueBlock "Construct a menu of variable names supplied by the generatorBlock, with lines between classes in the superclass chain. Show the menu, returning the variable chosen by the user, or nil if no variable was chosen." | eachClass aStream lines count lastLine variables index | aStream _ WriteStream on: (String new: 200). lines _ OrderedCollection new. count _ 0. lastLine _ 0. variables _ OrderedCollection new. self withAllSuperclasses reverseDo: [:eachClass | count = lastLine ifFalse: [lines add: count. lastLine _ count]. (generatorBlock value: eachClass) do: [:var | aStream nextPutAll: ((valueBlock value: var) contractTo: 20); cr. variables addLast: var. count _ count + 1]]. variables isEmpty ifTrue: [^nil]. "Nothing to choose from" aStream skip: -1. index _ (PopUpMenu labels: aStream contents lines: lines) startUp. ^index = 0 ifTrue: [nil] ifFalse: [variables at: index]! !!Behavior methodsFor: 'fileIn/Out'!printMethodChunk: selector on: aFileStream moveSource: moveSource toFile: fileIndex "Print the source code for the method associated with the argument selector onto the fileStream. aFileStream, and, for backup, if the argument moveSource (a Boolean) is true, also set the file index within the method to be the argument fileIndex." | position | aFileStream cr; cr. moveSource ifTrue: [position _ aFileStream position]. aFileStream nextChunkPut: (self sourceMethodAt: selector) asString. moveSource ifTrue: [(self compiledMethodAt: selector) setSourcePosition: position inFile: fileIndex]! !!Behavior methodsFor: 'private'!accumulateInstVarNames: names traversedClasses: classSet "accumulate instance variable names in 'names'. Do this in depth-first, left-to-right order. This will give the ordering of instance variable names expected by the compiler and other parts of the system." self superclasses do: [:each | each accumulateInstVarNames: names traversedClasses: classSet]. (classSet includes: self) ifFalse: [names addAll: self instVarNames. classSet add: self]!checkMethodFor: selector "copy method from superclass if necessary. Answer true if no conflict detected" | descr unmoved copyOK local copied conflict | local _ methodDict includesKey: selector. copied _ (SelectorsOfCopiedMethods at: selector ifAbsent: [Array new]) includes: self. conflict _ (SelectorsOfConflictMethods at: selector ifAbsent: [Array new]) includes: self. local & copied not & conflict not ifTrue: [^true]. descr _ self superMethodDescriptionAt: selector. descr isMethodNotImplemented ifTrue: [self removeSelectorUnchecked: selector. ^true]. descr isConflictingMethods ifTrue: [self compileConflictCodeFor: selector. ^false]. conflict ifTrue: "Not conflicting any more, so remove if it had been." [self removeSelectorUnchecked: selector. self removeClass: self selector: selector in: SelectorsOfConflictMethods]. "If this method isnt on the dynamic chain, copy it." descr = (self dynamicMethodDescriptionAt: selector) ifFalse: [unmoved _ self unmovedVarsFrom: descr whichClass. copyOK _ true. "If method doesnt touch any vars which moved" descr method fieldsTouched do: [:field | copyOK _ copyOK & (unmoved at: field)]. copyOK ifTrue: "then can just install that same method" [self addSelectorUnchecked: descr selector withMethod: descr method] ifFalse: "otherwise have to recompile it here" [self compileUnchecked: descr sourceCode]. self insertClass: self selector: selector in: SelectorsOfCopiedMethods]. ^true!compileConflictCodeFor: selector | classes | classes _ SelectorsOfConflictMethods at: selector ifAbsent: [Array new]. (classes includes: self name) "This class already has conflict code for this selector" ifTrue: [^self]. self compile: (self conflictCodeFor: selector) classified: 'conflicting inherited methods' notifying: nil. self insertClass: self selector: selector in: SelectorsOfConflictMethods!compoundSelectorsMatching: simple ^ self selectors select: [:sel | sel isCompound and: [sel selectorPart = simple]]!conflictCodeFor: sel "return some code that indicates a conflicting definition" | code parser | code _ (self dynamicMethodDescriptionAt: sel) sourceCode. (parser _ self parserClass new) parseSelector: code. ^ (code copyFrom: 1 to: (parser endOfLastToken min: code size)) , (String with: Character cr) , ' ^self conflictingInheritanceError'!copyMethods "copy all methods from superclasses not on the dynamic lookup chain" | noConflicts | noConflicts _ true. self allSelectors do: [:selector | noConflicts _ noConflicts & (self checkMethodFor: selector)]. noConflicts ifFalse: [Transcript cr; show: self name , ' has conflicting inherited methods -- consult browser for their names']!defaultSelectorForMethod: aMethod "Given a method, invent an appropriate selector, that is, one that will parse with the correct number of arguments." | aStream | aStream _ WriteStream on: (String new: 16). aStream nextPutAll: 'unboundMethod'. 1 to: aMethod numArgs do: [:i | aStream nextPutAll: 'with:']. ^aStream contents asSymbol!flushCache "Tell the interpreter to remove the contents of its method lookup cache, if it has one. Essential. See Object documentation whatIsAPrimitive." <primitive: 89> self primitiveFailed!format: nInstVars variable: isVar words: isWords pointers: isPointers "Set the format for the receiver (a Class)." format _ nInstVars + (isVar ifTrue: [4096] ifFalse: [0]) + (isWords ifTrue: [8192] ifFalse: [0]) + (isPointers ifTrue: [-16384] ifFalse: [0])!insertClass: aClass selector: selector in: aDictionary | previous | previous _ aDictionary at: selector ifAbsent: [Array new]. (previous includes: aClass) ifFalse: [aDictionary at: selector put: (previous copyWith: aClass)]!printSubclassesOn: aStream callingSuperclass: whichSuper level: level "As part of the algorithm for printing a description of the receiver, print the subclass on the file stream, aStream, indenting level times." | subs supers | aStream crtab: level. aStream nextPutAll: self name. aStream space; print: self instVarNames. supers _ self superclasses. supers size>1 ifTrue: [aStream nextPutAll: ' [also a'. (supers copyWithout: whichSuper) do: [:s | aStream space; nextPutAll: s name; space; print: s allInstVarNames]. aStream nextPut: $] ]. subs _ self subclasses. self == Class ifTrue: [aStream crtab: level+1; nextPutAll: '... all the Metaclasses ...'. subs _ subs reject: [:sub | sub isMeta]]. "Print subclasses in alphabetical order" (subs asSortedCollection: [:x :y | x name < y name]) do: [:sub | sub printSubclassesOn: aStream callingSuperclass: self level: level + 1]!removeClass: aClass selector: selector in: aDictionary | list | list _ (aDictionary at: selector) copyWithout: aClass. list size = 0 ifTrue: [aDictionary removeKey: selector] ifFalse: [aDictionary at: selector put: list]!removeFromInheritanceTable: table "I have been deleted -- remove me from the given inheritance table" | keys list | "get keys first, since we may be deleting entries in the midst of the loop that follows" keys _ table keys. keys do: [:key | list _ (table at: key) copyWithout: self. list size = 0 ifTrue: [table removeKey: key] ifFalse: [table at: key put: list]]!removeFromInheritanceTables "I have been deleted. Remove me from multiple inheritance tables" self removeFromInheritanceTable: SelectorsOfConflictMethods. self removeFromInheritanceTable: SelectorsOfCopiedMethods. self removeFromInheritanceTable: SelectorsOfDirectedMethods!removeSelectorSimply: selector "Remove the message selector from the receiver's method dictionary. Internal access from compiler." methodDict removeKey: selector ifAbsent: [^self]. self flushCache!sourceTextAt: selector "Answer with the string of the source code for the message selector." | newSource method | method _ methodDict at: selector. Sensor leftShiftDown ifTrue: [newSource _ self decompilerClass new decompile: selector in: self method: method] ifFalse: [newSource _ method getSource. newSource == nil ifTrue: [newSource _ self decompilerClass new decompile: selector in: self method: method]]. ^newSource asText!unmovedVarsFrom: sup "Answer with an Array with true for fields with the same offset in this class as in super" | allInstVarNames supNames | allInstVarNames _ self allInstVarNames. supNames _ sup allInstVarNames. ^ ((1 to: sup instSize) collect: [:i | (supNames at: i) = (allInstVarNames at: i)])!updateInheritanceTable: table oldSelf: oldSelf "I have replaced an old behavior or class. Update the given multiple inheritance table" table do: [:array | 1 to: array size do: [:i | (array at: i)==oldSelf ifTrue: [array at: i put: self]]]!updateInheritanceTables: oldSelf "I have replaced an old behavior or class. Update the multiple inheritance tables" self updateInheritanceTable: SelectorsOfConflictMethods oldSelf: oldSelf. self updateInheritanceTable: SelectorsOfCopiedMethods oldSelf: oldSelf. self updateInheritanceTable: SelectorsOfDirectedMethods oldSelf: oldSelf! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Behavior class instanceVariableNames: ''!!Behavior class methodsFor: 'initialization'!init "Behavior init." SelectorsOfConflictMethods _ IdentityDictionary new. "selector -> Array of classes" SelectorsOfCopiedMethods _ IdentityDictionary new. "selector -> Array of classes" SelectorsOfDirectedMethods _ IdentityDictionary new "selector -> Array of classes"! ! Object subclass: #Benchmark instanceVariableNames: 'dummy verboseTranscript reporting reportStream fromList ' classVariableNames: 'Outputs StandardTests ' poolDictionaries: '' category: 'System-Support'!Benchmark comment:'Class Benchmark contains facilities for timing the performance of your system and reporting the results.There are built-in methods for timing certain activities that occur frequently in using Smalltalk-80. There are also facilities for timing the execution of most byte codes.It is intended that comparison of timing information between implementations and over time will allow implementors to discover where their systems could stand improvement and to gauge the value of intended performance enhancements.The main interface to these facilities is through sending the messsage Benchmark new test: aBlock labeled: aLabel repeated: howManyTimes.This will cause howManyTimes executions of aBlock and report the results, using aLabel for ease of identification.The results can be reported in several different ways. The default is to print a fairly verbose report in the Transcript. But the reporting mode can be altered by sending the Benchmark which is going to perform a given test the message setOutputParameters. This gives you the option of directing the report to a file or an internal stream and also of shortening the feedback in the Transcript. The system automatically invites you to respecify the output parameters (e.g. naming a new output report file) whenever you test more than one thing at a time, using the message testList: (as in testStandardTests below).Try an example. To time your system''s performance of simple addition, say Benchmark new test3plus4or to time pushing an instance variable onto the stack, say Benchmark new testLoadInstVar.If you had wished to print the results on a file or internal stream, you could have said Benchmark new setOutputParameters testLoadInstVar.If you look at the code for these methods (e.g. testLoadInstVar), you will notice that it does a few things that you didn''t want to time, such as sending the message ==, or popping things off the stack. This is to make the compiler happy or to keep the stack from overflowing. So you may want to subtract this stuff out. (Use systems of equations. Be clever!!)The message category "macro operations" contains methods for timing more involved activities such as compiling, decompiling, editing text, formatting text, etc.There is a message to class Benchmark which will invoke all the built-in benchmarks sequentially. Say Benchmark testStandardTests.There are also facilities for examining or automatically comparing the output files or streams generated by testing a bunch of benchmarks sequentially. See the "output" category. Be sure to read the comment to the streamsRatherThanFiles code.Have fun and share your results with a friend.'!!Benchmark methodsFor: 'load and popStore'!testLoadInstVar dummy _ 1. self test: [dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. dummy == dummy. nil] labeled: 'load an instance variable, 20 times' repeated: 10000 "Benchmark new testLoadInstVar"!testLoadLiteralIndirect self test: [Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. Point == Point. nil] labeled: 'load literal indirect (overflow refct), 20 times' repeated: 10000 "Benchmark new testLoadLiteralIndirect"!testLoadLiteralNRef self test: [3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. 3 == 3. nil] labeled: 'load nonRefcounted literal, 20 times' repeated: 10000 "Benchmark new testLoadLiteralNRef"!testLoadQuickConstant self test: [1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. 1 == 1. nil] labeled: 'load 1, 40 times; send ==, 20 times' repeated: 10000 "Benchmark new testLoadQuickConstant"!testLoadTempNRef | temp | temp _ 1. self test: [temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. nil] labeled: 'load 1 as a temp, 20 times' repeated: 10000 "Benchmark new testLoadTempNRef"!testLoadTempRef | temp | temp _ 0@0. self test: [temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. temp == temp. nil] labeled: 'load 0@0, 20 times' repeated: 10000 "Benchmark new testLoadTempRef"!testPopStoreInstVar self test: [dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. dummy _ 1. nil] labeled: 'store into an instance variable, 20 times' repeated: 10000 "Benchmark new testPopStoreInstVar"!testPopStoreTemp | temp | self test: [temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. temp _ 1. nil] labeled: 'store into a temp, 20 times' repeated: 10000 "Benchmark new testPopStoreTemp"! !!Benchmark methodsFor: 'arithmetic'!test16bitArith | twentyK | twentyK _ 20000. self test: [twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. twentyK+twentyK. nil] labeled: 'add 20000 + 20000, 10 times' repeated: 1000 "Benchmark new test16bitArith"!test3div4 self test: [3//4. 3//4. 3//4. 3//4. 3//4. 3//4. 3//4. 3//4. 3//4. 3//4. nil] labeled: 'divide 3 by 4, 10 times' repeated: 1000 "Benchmark new test3div4"!test3lessThan4 self test: [3<4. 3<4. 3<4. 3<4. 3<4. 3<4. 3<4. 3<4. 3<4. 3<4. nil] labeled: 'test 3 < 4, 10 times' repeated: 10000 "Benchmark new test3lessThan4"!test3plus4 self test: [3+4. 3+4. 3+4. 3+4. 3+4. 3+4. 3+4. 3+4. 3+4. 3+4. nil] labeled: 'add 3 + 4, 10 times' repeated: 10000 "Benchmark new test3plus4"!test3times4 self test: [3*4. 3*4. 3*4. 3*4. 3*4. 3*4. 3*4. 3*4. 3*4. 3*4. nil] labeled: 'multiply 3 * 4, 10 times' repeated: 10000 "Benchmark new test3times4"!testLargeIntArith | eightyK | eightyK _ 80000. self test: [eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. eightyK+eightyK. nil] labeled: 'add 80000 + 80000, 10 times' repeated: 100 "Benchmark new testLargeIntArith"! !!Benchmark methodsFor: 'control'!testActivationReturn self test: [self recur: 14] labeled: 'activate and return, 32K times' repeated: 1 "Benchmark new testActivationReturn"!testShortBranch self test: [false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. false ifTrue: [1] ifFalse: [2]. nil] labeled: 'short branch on false, 10 times' repeated: 10000 "Benchmark new testShortBranch"!testWhileLoop | temp | self test: [temp _ 10000. [temp > 0] whileTrue: [temp _ temp - 1]. nil] labeled: 'simple whileLoop, 10000 times through' repeated: 10 "Benchmark new testWhileLoop"! !!Benchmark methodsFor: 'arrays and strings'!testArrayAt | array index | array _ #(1 2 3 4 5 6). index _ 4. self test: [array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. array at: index. nil] labeled: 'send #at: 20 times (to an array)' repeated: 1000 "Benchmark new testArrayAt"!testArrayAtPut | array index element | array _ #(1 2 3 4 5 6). index _ 4. element _ 17. self test: [array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. array at: index put: element. nil] labeled: 'send #at:put: 20 times (to an array)' repeated: 1000 "Benchmark new testArrayAtPut"!testSize | string | string _ 'abcde'. self test: [string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. string size. nil] labeled: 'send #size 20 times (to a string)' repeated: 1000 "Benchmark new testSize"!testStringAt | string index | string _ 'abcdefg'. index _ 4. self test: [string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. string at: index. nil] labeled: 'send #at: 20 times (to a string)' repeated: 1000 "Benchmark new testStringAt"!testStringAtPut | string index char | string _ 'abcdefg'. index _ 4. char _ $q. self test: [string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. string at: index put: char. nil] labeled: 'send #at:put: 20 times (to a string)' repeated: 1000 "Benchmark new testStringAtPut"! !!Benchmark methodsFor: 'primitive byte codes'!testBlockCopy | tC | tC _ thisContext. self test: [tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. tC blockCopy: 0. nil] labeled: 'execute blockCopy: 0, 20 times' repeated: 1000 "Benchmark new testBlockCopy"!testClass | pt | pt _ 0@0. self test: [pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. pt class. nil] labeled: 'send #class 20 times (to a point)' repeated: 1000 "Benchmark new testClass"!testCreation self test: [Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. Point new. nil] labeled: 'create 20 uninitialized points' repeated: 1000 "Benchmark new testCreation"!testEQ | temp | temp _ 1. self test: [temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp == temp. nil] labeled: 'send ==, 20 times' repeated: 10000 "Benchmark new testEQ"!testLoadThisContext self test: [thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. thisContext == thisContext. nil] labeled: 'load thisContext, 20 times' repeated: 10000 "Benchmark new testLoadThisContext"!testPointCreation self test: [3@4. 3@4. 3@4. 3@4. 3@4. 3@4. 3@4. 3@4. 3@4. 3@4. nil] labeled: 'create 3@4, 10 times' repeated: 1000 "Benchmark new testPointCreation"!testPointX | pt | pt _ 0@0. self test: [pt x. pt x. pt x. pt x. pt x. pt x. pt x. pt x. pt x. pt x. nil] labeled: 'execute aPoint x, 10 times' repeated: 10000 "Benchmark new testPointX"!testStreamNext | strm | strm _ ReadStream on: 'abcdefghijklmnopqrstuvwxyz'. self test: [strm position: 0. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. strm next. nil] labeled: 'execute ReadStream next, 20 times' repeated: 1000 "Benchmark new testStreamNext"!testStreamNextPut | strm ch | strm _ ReadWriteStream on: 'abcdefghijklmnopqrstuvwxyz'. ch _ $q. self test: [strm position: 0. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. strm nextPut: ch. nil] labeled: 'execute ReadWriteStream nextPut:, 20 times' repeated: 1000 "Benchmark new testStreamNextPut"!testValue | block | block _ [3+4]. self test: [block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. block value. nil] labeled: 'evaluate the block: (3+4), 20 times' repeated: 1000 "Benchmark new testValue"! !!Benchmark methodsFor: 'primitive methods'!testAsFloat self test: [1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. 1 asFloat. nil] labeled: 'convert 1 to floating point, 20 times' repeated: 100 "Benchmark new testAsFloat"!testBasicAt | coll index | coll _ Set new: 16. index _ 5. self test: [coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. coll basicAt: index. nil] labeled: 'send #basicAt: 20 times (to a set)' repeated: 1000 "Benchmark new testBasicAt"!testBasicAtPut | coll index element | coll _ Set new: 16. index _ 5. element _ 17. self test: [coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. coll basicAt: index put: element. nil] labeled: 'send #basicAtPut: 20 times (to a set)' repeated: 1000 "Benchmark new testBasicAtPut"!testBitBLT | bLTer | bLTer _ self sampleBitBLT. self test: [bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. bLTer copyBits. nil] labeled: 'call bitBLT 10 times' repeated: 10 "Benchmark new testBitBLT"!testFloatingPointAddition | a b | a _ 3.1. b _ 4.1. self test: [a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. a+b. nil] labeled: 'add 3.1 plus 4.1, 20 times' repeated: 100 "Benchmark new testFloatingPointAddition"!testPerform self test: [3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. 3 perform: #+ with: 4. nil] labeled: '3 perform: #+ with: 4, 20 times' repeated: 1000 "Benchmark new testPerform"!testStringReplace | source sink size | source _ self longishString copy. sink _ source copy. size _ sink size. self test: [sink replaceFrom: 1 to: size with: source startingAt: 1. nil] labeled: 'replace characters in a string' repeated: 100 "Benchmark new testStringReplace"!testTextScanning | clipRect para range scanner stops | clipRect _ Display boundingBox. para _ Paragraph withText: 'Hi there, folks' asText. range _ 1 to: para numberOfLines. scanner _ DisplayScanner new. scanner displayLines: range in: para clippedBy: clipRect. stops _ scanner instVarAt: 17. self test: [scanner destX: 0. scanner scanCharactersFrom: 1 to: 16 in: 'Hi there, folks!!' rightX: 400 stopConditions: stops displaying: true] labeled: 'scan characters (primitive text display)' repeated: 100 "Benchmark new testTextScanning"! !!Benchmark methodsFor: 'macro operations'!testAllCallsOn self test: [Smalltalk allCallsOn: #printStringRadix:] labeled: 'find all calls on #printStringRadix:' repeated: 1 "Benchmark new testAllCallsOn"!testAllImplementors self test: [Smalltalk allImplementorsOf: #next] labeled: 'find all implementors of #next' repeated: 1 "Benchmark new testAllImplementors"!testClassOrganizer | class | class _ Benchmark. self test: [class organization changeFromString: class organization printString] labeled: 'read and write class organization' repeated: 1 "Benchmark new testClassOrganizer"!testCompiler self test: [Benchmark compile:'dummy: aBlock repeated: nTimes | i emptyBlock emptyTime blockTime | nTimes > 1000 ifTrue: [^self time: aBlock repeatedK: nTimes // 1000]. emptyBlock _ []. emptyTime _ Time millisecondsToRun: [i _ 0. [(i _ i + 1) <= nTimes] whileTrue: [emptyBlock value]]. blockTime _ Time millisecondsToRun: [i _ 0. [(i _ i + 1) <= nTimes] whileTrue: [aBlock value]]. ^blockTime - emptyTime' notifying: nil trailer: #(0 0 0)] labeled: 'compile dummy method' repeated: 5. Benchmark removeSelector: #dummy:repeated: "Benchmark new testCompiler"!testDecompiler | class | class _ InputSensor. self test: [class selectors do: [:sel | (Decompiler new decompile: sel in: class method: (class compiledMethodAt: sel)) decompileString]] labeled: 'decompile class InputSensor' repeated: 1 "Benchmark new testDecompiler"!testInspect | window | self test: [window _ InspectorView buildScheduledView: (Inspector inspect: Compiler new). window release] labeled: 'create an inspector view' repeated: 10 "Benchmark new testInspect"!testKeyboardLookAhead | aStringHolderView insert inputter editor | aStringHolderView _ self favoriteStringHolderView. editor _ aStringHolderView controller. editor selectAt: 5. inputter _ editor sensor class classPool at: #CurrentInputState. Sensor flushKeyboard. self test: ['Now!! ' do: [:char | inputter keyAt: char asciiValue put: 1]. editor readKeyboard] labeled: 'text keyboard response using lookahead buffer' repeated: 3. aStringHolderView release "Benchmark new testKeyboardLookAhead"!testKeyboardSingle | aStringHolderView insert inputter editor | aStringHolderView _ self favoriteStringHolderView. editor _ aStringHolderView controller. editor selectAt: 5. inputter _ editor sensor class classPool at: #CurrentInputState. Sensor flushKeyboard. self test: ['Now!! ' do: [:char | inputter keyAt: char asciiValue put: 1. editor readKeyboard]] labeled: 'text keyboard response for single keystroke' repeated: 3. aStringHolderView release "Benchmark new testKeyboardSingle"!testPrintDefinition | class | class _ Compiler. self test: [class definition] labeled: 'print a class definition' repeated: 20 "Benchmark new testPrintDefinition"!testPrintHierarchy | class | class _ InstructionStream. self test: [class printHierarchy] labeled: 'print a class hierarchy' repeated: 10 "Benchmark new testPrintHierarchy"!testTextDisplay | para | para _ Paragraph withText: self textForDisplay. para displayAt: 200@200. self test: [para displayAt: 200@200] labeled: 'display text' repeated: 10 "Benchmark new testTextDisplay"!testTextEditing | aStringHolderView editor selectPoint | aStringHolderView _ self favoriteStringHolderView. editor _ aStringHolderView controller. selectPoint _ 0. self test: [editor selectAt: (selectPoint _ selectPoint + 5). editor replaceSelectionWith: 'Now!! ' asText] labeled: 'text replacement and redisplay' repeated: 20. aStringHolderView release "Benchmark new testTextEditing"!testTextFormatting | aString aView contents | aString _ self stringForDisplay. aView _ StringHolderView container: StringHolder new. aView window: Display boundingBox viewport: (100@100 extent: 200@200). self test: [aView editString: (aString asText makeSelectorBoldIn: Benchmark) asParagraph] labeled: 'format a bunch of text' repeated: 5. aView release "Benchmark new testTextFormatting"! !!Benchmark methodsFor: 'testing'!test: aBlock labeled: label repeated: nTimes "This is the main message to a Benchmark. aBlock is repeated nTimes, and the results are reported." | time | time _ self time: aBlock repeated: nTimes. self report: label timedAt: time repeated: nTimes!testList: selectorList "This message allows you to test a series of benchmarks and record all the results on a file or stream." fromList _ true. self setOutputParameters. selectorList do: [:selector | self perform: selector. verboseTranscript ifTrue: [Transcript show: 'press any mouse button to continue'. Sensor waitButton. Transcript clear; refresh]]. reporting ifTrue: [self closeOutput: reportStream]. fromList _ false. "Benchmark new testList: #(testLoadInstVar testLoadLiteralIndirect testLoadLiteralNRef testLoadQuickConstant testLoadTempNRef)"!testList: selectorList toFile: aFileStream "This message allows you to test a series of benchmarks and record all the results on a file or stream." fromList _ true. self fileOutputParameters: aFileStream. selectorList do: [:selector | self perform: selector. verboseTranscript ifTrue: [Transcript show: 'press any mouse button to continue'. Sensor waitButton. Transcript clear; refresh]]. reporting ifTrue: [self closeOutput: reportStream]. fromList _ false. "Benchmark new testList: #(testLoadInstVar testLoadLiteralIndirect testLoadLiteralNRef testLoadQuickConstant testLoadTempNRef) toFile: (FileStream fileNamed: 'Smalltalk.timing')"!time: aBlock repeated10K: tenKTimes | i emptyBlock emptyTime blockTime | tenKTimes > 10000 ifTrue: [^self error: 'one hundred million repetitions is my limit']. emptyBlock _ []. emptyTime _ Time millisecondsToRun: [1 to: tenKTimes do: [:j | i _ 0. [(i _ i + 1) <= 10000] whileTrue: [emptyBlock value]]]. blockTime _ Time millisecondsToRun: [1 to: tenKTimes do: [:j | i _ 0. [(i _ i + 1) <= 10000] whileTrue: [aBlock value]]]. ^blockTime - emptyTime!time: aBlock repeated: nTimes "Answer how many milliseconds it takes to repeat aBlock nTimes, corrected for the time to repeat an empty block." | i emptyBlock emptyTime blockTime iBox | nTimes > 10000 ifTrue: [^self time: aBlock repeated10K: nTimes // 10000]. emptyBlock _ []. emptyTime _ Time millisecondsToRun: [i _ 0. [(i _ i + 1) <= nTimes] whileTrue: [emptyBlock value]]. blockTime _ Time millisecondsToRun: [i _ 0. [(i _ i + 1) <= nTimes] whileTrue: [aBlock value]]. ^blockTime - emptyTime! !!Benchmark methodsFor: 'output'!clearOutputs "This allows you to get rid of your old accumulated output streams." Outputs _ nil "Benchmark new clearOutputs"!closeOutput: aStream self streamsRatherThanFiles ifTrue: [aStream reset] ifFalse: [aStream close]!compareOldTimes: oldName toNewTimes: newName outputTo: outName "Compare two sets of benchmark ouput reports." | oldDict newDict labels compareStream oldTime newTime | oldDict _ Dictionary new. newDict _ Dictionary new. labels _ OrderedCollection new. self readOutput: (self outputNamed: oldName) intoDict: oldDict andCollection: nil. self readOutput: (self outputNamed: newName) intoDict: newDict andCollection: labels. compareStream _ self makeOutputNamed: outName. labels do: [:label | (oldDict includesKey: label) ifTrue: [compareStream nextPutAll: label; cr; tab; nextPutAll: 'old time: ', (oldTime _ oldDict at: label) printString; tab; nextPutAll: 'new time: ', (newTime _ newDict at: label) printString; tab; nextPutAll: 'percent change: ', (newTime - oldTime * 100.0 / oldTime) printString; cr; cr]]. self closeOutput: compareStream "Benchmark new compareOldTimes: 'test1.timing' toNewTimes: 'test2.timing' outputTo: 'compare1-2.timing'" "Benchmark new displayOutputNamed: 'compare1-2.timing'"!displayOutputNamed: name "Create a window on the display to view the contents of the named output. Does not allow editing of the output file or stream." | output contents | output _ self outputNamed: name. contents _ self streamsRatherThanFiles ifTrue: [output contents] ifFalse: [output contentsOfEntireFile]. StringHolderView open: (StringHolder new contents: contents) label: name!makeOutputNamed: name "Create a new output file or stream of the given name." self streamsRatherThanFiles ifTrue: [Outputs == nil ifTrue: [Outputs _ Dictionary new]. Outputs at: name put: (ReadWriteStream on: (String new: 1000))]. ^self outputNamed: name!outputNamed: name "Answer with the output file or stream of the given name." self streamsRatherThanFiles ifTrue: [^Outputs at: name] ifFalse: [^Disk file: name]!readOutput: aStream intoDict: aDict andCollection: aColl "Parse the output file or stream, aStream, putting labels and times in aDict. If aColl is non-nil (but rather an ordered collection), also add the labels to it in order." | leftBracket rightBracket tab space label value | leftBracket _ $[. rightBracket _ $]. tab _ $ . space _ $ . aStream upTo: leftBracket. [aStream atEnd] whileFalse: [label _ aStream upTo: rightBracket. aColl notNil ifTrue: [aColl add: label]. aStream next: 2; upTo: tab. value _ Number readFrom: (ReadStream on: (aStream upTo: space)). aDict at: label put: value. aStream upTo: leftBracket]. self closeOutput: aStream!report: label timedAt: time repeated: numberOfTimes "Do all the reporting, both in the Transcript and on the output file or stream." | reportString | reportString _ self reportStringFor: label timedAt: time repeated: numberOfTimes. verboseTranscript ifTrue: [Transcript show: reportString] ifFalse: [Transcript show: '[', label, ']']. reporting ifTrue: [reportStream nextPutAll: reportString. fromList ifFalse: [self closeOutput: reportStream]]!reportStringFor: label timedAt: time repeated: numberOfTimes "Generate the parsible string to represent the measurement of a benchmark." | nTimes unitTime seconds aStream| aStream _ WriteStream on: (String new: 200). nTimes _ numberOfTimes <= 1000 ifTrue: [numberOfTimes] ifFalse: [numberOfTimes // 1000 * 1000]. seconds _ time asFloat / 1000. aStream cr; nextPutAll: 'Testing: [' , label , ']'; cr. aStream tab; print: nTimes; nextPutAll: ' repetition(s) in'; cr; tab; print: seconds; nextPutAll: ' seconds'; cr. nTimes ~= 1 ifTrue: [unitTime _ (time * 1000) asFloat / nTimes. aStream tab; print: unitTime; nextPutAll: ' microseconds per repetition'; cr]. ^aStream contents!streamsRatherThanFiles "Should the named outputs be (internal Smalltalk-80) streams rather than disk files? They should if there is no file system. Feel free to change this method if you have a file system but want streams anyway." ^Disk == nil! !!Benchmark methodsFor: 'instance initialization'!defaultOutputParameters reporting _ false. verboseTranscript _ true. fromList _ false!fileOutputParameters: aFileStream reporting _ true. reportStream _ aFileStream. verboseTranscript _ false!setOutputParameters BinaryChoice message: 'Would you like the transcript to just show labels, rather than full reports?' displayAt: Sensor mousePoint centered: true ifTrue: [verboseTranscript _ false] ifFalse: [verboseTranscript _ true]. BinaryChoice message: 'Should the full reports to be output (saved on a file or stream)?' displayAt: Sensor mousePoint centered: true ifTrue: [reporting _ true] ifFalse: [reporting _ false]. reporting ifTrue: [FillInTheBlank request: 'Please supply desired output name' displayAt: Sensor mousePoint centered: true action: [:answer | reportStream _ self makeOutputNamed: answer] initialAnswer: '.timing']! !!Benchmark methodsFor: 'private'!favoriteStringHolderView | aStringHolderView message | message _ self longishString. aStringHolderView _ StringHolderView container: (StringHolder new contents: message). aStringHolderView window: (0@0 extent: 300@200). aStringHolderView translateBy: 100@250. aStringHolderView display. ^aStringHolderView!longishString ^ 'Now is the time for all good people to come to the aid of the cause of world peace. It is just fine, even desirable, to love your country, if that means wanting it to play a beneficial role in the course of world events and be the best possible example of a good society. But if it means wanting dominion over the rest of the world, it is not love but defensiveness or self-glorification, and will lead only to oblivion.'!recur: exp "Invokes a recursion involving ((2 raisedTo: exp+1) - 1) activations and returns." exp = 0 ifTrue: [^self]. self recur: exp - 1. ^self recur: exp - 1!sampleBitBLT ^BitBlt destForm: Display sourceForm: nil halftoneForm: Form black combinationRule: Form reverse destOrigin: 0@0 sourceOrigin: 0@0 extent: 400@400 clipRect: Display boundingBox!stringForDisplay ^'testTextDisplay | clipRect para range scanner | clipRect _ Display boundingBox. para _ Paragraph withText: self textForDisplay. range _ 1 to: para numberOfLines. scanner _ DisplayScanner new. self test: [scanner displayLines: range in: para clippedBy: clipRect] labeled: ''displaying text'' repeated: 10 "Benchmark new testTextDisplay"'!textForDisplay ^self stringForDisplay asText! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Benchmark class instanceVariableNames: ''!!Benchmark class methodsFor: 'standard tests'!setStandardTests "These are all the built-in benchmarks. Feel free to change if you add more or think some of these are useless. To just execute a few, use testList: directly." StandardTests _ #(testLoadInstVar testLoadTempNRef testLoadTempRef testLoadQuickConstant testLoadLiteralNRef testLoadLiteralIndirect testPopStoreInstVar testPopStoreTemp test3plus4 test3lessThan4 test3times4 test3div4 test16bitArith testLargeIntArith testActivationReturn testShortBranch testWhileLoop testArrayAt testArrayAtPut testStringAt testStringAtPut testSize testPointCreation testStreamNext testStreamNextPut testEQ testClass testBlockCopy testValue testCreation testPointX testLoadThisContext testBasicAt testBasicAtPut testPerform testStringReplace testAsFloat testFloatingPointAddition testBitBLT testTextScanning testClassOrganizer testPrintDefinition testPrintHierarchy testAllCallsOn testAllImplementors testInspect testCompiler testDecompiler testKeyboardLookAhead testKeyboardSingle testTextDisplay testTextFormatting testTextEditing )!testStandardTests "This message allows you to test the default series of benchmarks and record all the results according to how you answer the interactive prompts." self setStandardTests. self new testList: StandardTests "Benchmark testStandardTests"!testStandardToFile: aFileStream "This message allows you to test the default series of benchmarks and record all the results on the specified file or stream." self setStandardTests. self new testList: StandardTests toFile: aFileStream "Benchmark testStandardToFile: (FileStream fileNamed: 'Smalltalk.timing')"! !!Benchmark class methodsFor: 'instance creation'!new ^super new defaultOutputParameters "Benchmark new inspect"! ! Object subclass: #BinaryChoice instanceVariableNames: 'trueAction falseAction actionTaken ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!BinaryChoice comment:'I represent a true/false (yes/no) choice. My instances have two possible actions they can take, depending on which choice is made.Instance variables trueAction <BlockContext> sequence of expression to do if positive choice is made falseAction <BlockContext> sequence of expression to do if negative choice is made actionTaken <Boolean> was the action, true or false, already taken '!!BinaryChoice methodsFor: 'initialize-release'!falseAction: aBlock "The argument, aBlock, will be evaluated if the receiver is sent the message selectFalse." falseAction _ aBlock!initialize "Initialize the receiver so that it indicates no action has yet been taken." actionTaken _ false!trueAction: aBlock "The argument, aBlock, will be evaluated if the receiver is sent the message selectTrue." trueAction _ aBlock! !!BinaryChoice methodsFor: 'menu messages'!selectFalse "Take the action, if one, associated with selecting no or false." actionTaken _ true. falseAction notNil ifTrue: [falseAction value]!selectTrue "Take the action, if one, associated with selecting yes or true." actionTaken _ true. trueAction notNil ifTrue: [trueAction value]! !!BinaryChoice methodsFor: 'accessing'!actionTaken "Answer whether the receiver has carried out its actions yet." ^actionTaken!active "Answer whether the receiver is an active system view." ^false! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BinaryChoice class instanceVariableNames: ''!!BinaryChoice class methodsFor: 'instance creation'!message: messageString "Answer an instance of me whose question is messageString. If the user answer is yes, then return true. If the user answer is no, return false. Display the view of the instance at the cursor location." | answer | self message: messageString displayAt: Sensor cursorPoint centered: true ifTrue: [answer _ true] ifFalse: [answer _ false]. ^answer!message: messageString displayAt: aPoint centered: centered ifTrue: trueAlternative ifFalse: falseAlternative "Answer an instance of me whose question is messageString. If the user answer is yes, then evaluate trueAlternative. If the user answer is no, evaluate falseAlternative. If centered, a Boolean, is false, display the view of the instance at aPoint; otherwise display it with its center at aPoint." | newChoice | newChoice _ self new initialize. newChoice trueAction: trueAlternative. newChoice falseAction: falseAlternative. BinaryChoiceView openOn: newChoice message: messageString displayAt: aPoint centered: centered!message: messageString displayAt: originPoint ifFalse: falseAlternative "Answer an instance of me whose question is messageString. If the user answer is yes, then do nothing. If the user answer is no, evaluate falseAlternative. Display the view of the instance at originPoint." ^self message: messageString displayAt: originPoint centered: false ifTrue: nil ifFalse: falseAlternative!message: messageString displayAt: originPoint ifTrue: trueAlternative "Answer an instance of me whose question is messageString. If the user answer is yes, then evaluate trueAlternative. If the user answer is no, do nothing. Display the view of the instance at originPoint." ^self message: messageString displayAt: originPoint centered: false ifTrue: trueAlternative ifFalse: nil!message: messageString displayAt: originPoint ifTrue: trueAlternative ifFalse: falseAlternative "Answer an instance of me whose question is messageString. If the user answer is yes, then evaluate trueAlternative. If the user answer is no, evaluate falseAlternative. Display the view of the instance at originPoint." ^self message: messageString displayAt: originPoint centered: false ifTrue: trueAlternative ifFalse: falseAlternative! !!BinaryChoice class methodsFor: 'examples'!example BinaryChoice message: 'Are you happy?' displayAt: Sensor waitButton centered: true ifTrue: [Transcript cr; show: 'happy'] ifFalse: [Transcript cr; show: 'not happy'] "BinaryChoice example."! ! Controller subclass: #BinaryChoiceController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!BinaryChoiceController comment:'My instances assume that their model can carry out some action only once--that is, make a selection only once. Control is given up if the model responds true to the message actionTaken.'!!BinaryChoiceController methodsFor: 'control defaults'!isControlActive model actionTaken ifTrue: [^false]. [super isControlActive] whileFalse: [view flash]. ^true! !!BinaryChoiceController methodsFor: 'basic control sequence'!startUp Cursor normal showWhile: [super startUp]! !!BinaryChoiceController methodsFor: 'cursor'!centerCursorInView "Position sensor's mousePoint (which is assumed to be connected to the cursor) to the center of its view's inset display box (see Sensor|mousePoint: and View|insetDisplayBox)." | lowestSubView subViews | subViews_ view subViews. subViews isEmpty ifFalse: [lowestSubView _ subViews at: 1. subViews do: [:subView | (subView insetDisplayBox top > lowestSubView insetDisplayBox top) ifTrue: [lowestSubView _ subView]]. ^lowestSubView controller centerCursorInView]. ^super centerCursorInView! ! View subclass: #BinaryChoiceView instanceVariableNames: '' classVariableNames: 'ThumbsDown ThumbsUp ' poolDictionaries: '' category: 'Interface-Menus'!BinaryChoiceView comment:'I am a view of a BinaryChoice. I display a question and two switches, yes and no, indicating choices the user can make.'!!BinaryChoiceView methodsFor: 'controller access'!defaultControllerClass ^BinaryChoiceController! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BinaryChoiceView class instanceVariableNames: ''!!BinaryChoiceView class methodsFor: 'class initialization'!initialize ThumbsUp _ Cursor extent: 16@16 fromArray: #(16 104 72 120 136 136 3980 4227 8192 16128 8192 16128 8192 7943 2056 4080 ) offset: -15@0. ThumbsDown _ Cursor extent: 16@16 fromArray: #(4080 2056 7943 8192 16128 8192 16128 8192 4227 3980 136 136 120 72 104 16 ) offset: 0@0 "BinaryChoiceView initialize"! !!BinaryChoiceView class methodsFor: 'instance creation'!openOn: aBinaryChoice message: messageString displayAt: originPoint centered: centered "Answer an instance of me that displays aBinaryChoice asking the question messageString. If the argument centered, a Boolean, is false, display the instance with top left corner at originPoint; otherwise, display it with its center at originPoint. If necessary, translate so the view is completely on the screen. Do not schedule, rather take control immediately and insist that the user respond." | topView messageView switchView savedArea | messageView _ DisplayTextView new model: messageString asDisplayText. messageView insideColor: Form white. messageView controller: NoController new. messageView centered. switchView _ self buildSwitchesFor: aBinaryChoice width: messageView window width. topView _ self new model: aBinaryChoice. topView addSubView: messageView. topView addSubView: switchView below: messageView. topView align: (centered ifTrue: [switchView viewport center] ifFalse: [topView viewport topLeft]) with: originPoint. topView borderWidth: 2. topView translateBy: (topView displayBox amountToTranslateWithin: Display boundingBox). topView insideColor: Form white. savedArea _ Form fromDisplay: topView displayBox. topView display. topView controller startUp. topView release. savedArea displayOn: Display at: topView viewport topLeft! !!BinaryChoiceView class methodsFor: 'private'!buildSwitchesFor: aBinaryChoice width: anInteger |switchView yesSwitchView noSwitchView| switchView _ View new model: aBinaryChoice. switchView controller: BinaryChoiceController new. yesSwitchView _ SwitchView new model: aBinaryChoice. yesSwitchView borderWidthLeft: 0 right: 2 top: 0 bottom: 0. yesSwitchView selector: #active. yesSwitchView controller selector: #selectTrue. yesSwitchView controller cursor: ThumbsUp. yesSwitchView label: 'yes' asParagraph. yesSwitchView window: (0@0 extent: anInteger//2 @ yesSwitchView window height). noSwitchView _ SwitchView new model: aBinaryChoice. noSwitchView selector: #active. noSwitchView controller selector: #selectFalse. noSwitchView controller cursor: ThumbsDown. noSwitchView label: 'no' asParagraph. noSwitchView window: (0@0 extent: anInteger//2 @ noSwitchView window height). switchView addSubView: yesSwitchView. switchView addSubView: noSwitchView toRightOf: yesSwitchView. switchView borderWidthLeft: 0 right: 0 top: 2 bottom: 0. ^switchView! !BinaryChoiceView initialize! Object subclass: #BitBlt instanceVariableNames: 'destForm sourceForm halftoneForm combinationRule destX destY width height sourceX sourceY clipX clipY clipWidth clipHeight ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Support'!BitBlt comment: 'The BitBlt operation copies bits from one rectangle within a Form (source) to another (dest). The result is stored according to a combination rule which specifies one of the sixteen possibilities for how white and black should be combined.If halftoneForm is not nil, it is a halftone screen which masks (is ANDed with) the source during the operation. Halftones are 16x16 bit Forms which are repeated indefinitely as needed by the BitBlt operation. with the two forms and a halftoneForm.If sourceForm is nil, the halftone is taken by itself to be the source, as for filling with a constant pattern.The clipping parameters specify a rectangle in the destination outside of which BitBlt will not make any changes'!!BitBlt methodsFor: 'accessing'!clipHeight: anInteger "Set the clipHeight instance variable in BitBlt." clipHeight _ anInteger!clipRect "Answer the clipX, clipY clipWidth and clipHeight instance variables in BitBlt." ^clipX @ clipY extent: clipWidth @ clipHeight!clipRect: aRectangle "Set the clipX, clipY clipWidth andclipHeight instance variables in BitBlt. This is a shorthand way to set four of the parameters to BitBlt." clipX _ aRectangle left. clipY _ aRectangle top. clipWidth _ aRectangle width. clipHeight _ aRectangle height!clipWidth: anInteger "Set the clipWidth instance variable in BitBlt." clipWidth _ anInteger!clipX: anInteger "Set the clipX instance variable in BitBlt." clipX _ anInteger!clipY: anInteger "Set the clipY instance variable in BitBlt." clipY _ anInteger!combinationRule: anInteger "Set the combinationRule instance variable in BitBlt. anInteger is in the range 0-16." combinationRule _ anInteger!destForm: aForm "Set the destinationForm instance variable in BitBlt." destForm _ aForm!destOrigin: aPoint "Set the destination coordinates to be those of aPoint." destX _ aPoint x. destY _ aPoint y!destRect: aRectangle "Set the destination coordinates to be those of aRectangle top left and the width and height of the receiver to be the width and height of aRectangle." destX _ aRectangle left. destY _ aRectangle top. width _ aRectangle width. height _ aRectangle height!destX: anInteger "Set the destX instance variable in BitBlt." destX _ anInteger!destY: anInteger "Set the destY instance variable in BitBlt." destY _ anInteger!height: anInteger "Set the height instance variable in BitBlt ." height _ anInteger!mask: aForm "Set the halftoneForm instance variable in BitBlt." halftoneForm _ aForm!sourceForm: aForm "Set the sourceForm instance variable in BitBlt." sourceForm _ aForm!sourceOrigin: aPoint "Set the source form coordinats to be those of aPoint." sourceX _ aPoint x. sourceY _ aPoint y!sourceRect: aRectangle "Set the sourceX, sourceY width and height instance variables in BitBlt. This is a shorthand way to set four of the parameters to BitBlt." sourceX _ aRectangle left. sourceY _ aRectangle top. width _ aRectangle width. height _ aRectangle height!sourceX: anInteger "Set the sourceX instance variable in BitBlt." sourceX _ anInteger!sourceY: anInteger "Set the sourceY instance variable in BitBlt." sourceY _ anInteger!width: anInteger "Set the width instance variable in BitBlt." width _ anInteger! !!BitBlt methodsFor: 'copying'!copyBits "Perform the movement of bits from one From to another described by the instance variables of the receiver. Fail if any instance variables are not of the right type (Integer or Form) or if combinationRule is not between 0 and 15 inclusive. Set the variables and try again (BitBlt|copyBitsAgain). Essential. See Object documentation whatIsAPrimitive." <primitive: 96> combinationRule = Form paint ifTrue: [^self paintBits] ifFalse: [destX _ destX truncated. destY _ destY truncated. width _ width truncated. height _ height truncated. sourceX _ sourceX truncated. sourceY _ sourceY truncated. clipX _ clipX truncated. clipY _ clipY truncated. clipWidth _ clipWidth truncated. clipHeight _ clipHeight truncated. ^self copyBitsAgain]! !!BitBlt methodsFor: 'line drawing'!drawFrom: startPoint to: stopPoint | offset point1 point2 | "Always draw down, or at least left-to-right" ((startPoint y = stopPoint y and: [startPoint x < stopPoint x]) or: [startPoint y < stopPoint y]) ifTrue: [point1 _ startPoint. point2 _ stopPoint] ifFalse: [point1 _ stopPoint. point2 _ startPoint]. width _ sourceForm width. height _ sourceForm height. offset _ sourceForm offset. destX _ (point1 x + offset x) rounded. destY _ (point1 y + offset y) rounded. self drawLoopX: (point2 x - point1 x) rounded Y: (point2 y - point1 y) rounded!drawLoopX: xDelta Y: yDelta "This is the Bresenham plotting algorithm (IBM Systems Journal Vol 4 No. 1, 1965). It chooses a principal direction, and maintains a potential, P. When P's sign changes, it is time to move in the minor direction as well. Optional. See Object documentation whatIsAPrimitive." | dx dy px py P i | <primitive: 104> dx _ xDelta sign. dy _ yDelta sign. px _ yDelta abs. py _ xDelta abs. self copyBits. py > px ifTrue: ["more horizontal" P _ py // 2. i _ 0. [(i _ i + 1) <= py] whileTrue: [destX _ destX + dx. (P _ P - px) < 0 ifTrue: [destY _ destY + dy. P _ P + py]. self copyBits]] ifFalse: ["more vertical" P _ px // 2. i _ 0. [(i _ i + 1) <= px] whileTrue: [destY _ destY + dy. (P _ P - py) < 0 ifTrue: [destX _ destX + dx. P _ P + px]. self copyBits]]! !!BitBlt methodsFor: 'private'!copyBitsAgain <primitive: 96> "don't fail the primitive if no intersection with clipping rectangle (possible LargeIntegers)." (self clipRect intersects: (destX@destY extent: width@height)) ifTrue: [self primitiveFailed]!paintBits "Perform the paint operation, which may require two calls to BitBlt." | oldMask | (halftoneForm == nil or: [halftoneForm == Form black]) ifFalse: "optimization" [oldMask _ halftoneForm. combinationRule _ Form erase. halftoneForm _ nil. self copyBits. "first erase hole in dest" halftoneForm _ oldMask]. halftoneForm == Form white ifFalse: "optimization" [combinationRule _ Form under. self copyBits]. combinationRule _ Form paint. "restore rule" "(Form dotOfSize: 32) displayOn: Display at: Sensor cursorPoint clippingBox: Display boundingBox rule: Form paint mask: Form lightGray"!setDestForm: df sourceForm: sf halftoneForm: hf combinationRule: cr destOrigin: destOrigin sourceOrigin: sourceOrigin extent: extent clipRect: clipRect | aPoint | destForm _ df. sourceForm _ sf. halftoneForm _ hf. combinationRule _ cr. destX _ destOrigin x. destY _ destOrigin y. sourceX _ sourceOrigin x. sourceY _ sourceOrigin y. width _ extent x. height _ extent y. aPoint _ clipRect origin. clipX _ aPoint x. clipY _ aPoint y. aPoint _ clipRect corner. clipWidth _ aPoint x - clipX. clipHeight _ aPoint y - clipY! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BitBlt class instanceVariableNames: ''!!BitBlt class methodsFor: 'examples'!exampleOne "This tests BitBlt by displaying the result of all sixteen combination rules that BitBlt is capable of using. (Please see the Byte magazine article by D. Ingalls for the meaning of the combination rules and the complete documentation for BitBlt in SmallTalk-80.)" | path | path _ Path new. 0 to: 3 do: [:i | 0 to: 3 do: [:j | path add: j * 100 @ (i * 100)]]. Display white. path _ path translateBy: 100 @ 100. 1 to: 16 do: [:index | BitBlt exampleAt: (path at: index) rule: index - 1 mask: Form gray] "BitBlt exampleOne."!exampleTwo "This is to test painting with a gray tone. It also tests that the seaming with gray patterns is correct in the microcode. Lets you paint for awhile and then automatically stops." | f pt aBitBlt | "create a small black Form source as a brush." f _ Form new extent: 20 @ 20. f black. "create a BitBlt which will OR gray into the display" aBitBlt _ BitBlt destForm: Display sourceForm: f halftoneForm: Form gray combinationRule: Form under destOrigin: Sensor cursorPoint sourceOrigin: 0 @ 0 extent: f extent clipRect: Display computeBoundingBox. "paint the gray Form on the screen for a while" 1 to: 5000 do: [:i | aBitBlt destOrigin: Sensor cursorPoint. aBitBlt copyBits] "BitBlt exampleTwo."! !!BitBlt class methodsFor: 'private'!exampleAt: originPoint rule: rule mask: mask "This builds a source and destination form and copies the source to the destination using the specifed rule and mask. It is called from the method named exampleOne." | s d border aBitBlt | border_Form new extent: 32@32. border black. border fill: (1@1 extent: 30@30) mask: Form white. s_Form new extent: 32@32. s white. s fill: (7@7 corner: 25@25) mask: Form black. d_Form new extent: 32@32. d white. d fill: (0@0 corner: 32@16) mask: Form black. s displayOn: Display at: originPoint. border displayOn: Display at: originPoint rule: Form under. d displayOn: Display at: originPoint + (s width @0). border displayOn: Display at: originPoint + (s width @0) rule: Form under. d displayOn: Display at: originPoint + (s extent // (2 @ 1)). aBitBlt _ BitBlt destForm: Display sourceForm: s halftoneForm: mask combinationRule: rule destOrigin: originPoint + (s extent // (2 @ 1)) sourceOrigin: 0 @ 0 extent: s extent clipRect: Display computeBoundingBox. aBitBlt copyBits. border displayOn: Display at: originPoint + (s extent // (2 @ 1)) rule: Form under. "BitBlt exampleAt: 100@100 rule: 3 mask: Form gray."! !!BitBlt class methodsFor: 'instance creation'!destForm: df sourceForm: sf halftoneForm: hf combinationRule: cr destOrigin: destOrigin sourceOrigin: sourceOrigin extent: extent clipRect: clipRect "Answer an instance of me with values set according to the arguments. " ^self new setDestForm: df sourceForm: sf halftoneForm: hf combinationRule: cr destOrigin: destOrigin sourceOrigin: sourceOrigin extent: extent clipRect: clipRect!toReverse: aRectangle "Return an instance which will reverse a particular rectangle in the destination (which must be supplied later). This is currently used only for the Ethernet 'lights'." ^self destForm: nil sourceForm: nil halftoneForm: nil combinationRule: Form reverse destOrigin: aRectangle origin sourceOrigin: 0 @ 0 extent: aRectangle extent clipRect: aRectangle! ! MouseMenuController subclass: #BitEditor instanceVariableNames: 'scale squareForm color ' classVariableNames: 'ColorButtons YellowButtonMenu YellowButtonMessages ' poolDictionaries: '' category: 'Graphics-Editors'!BitEditor comment:'A bit-magnifying tool for editing small Forms directly on the display screen. Continue in blowup mode until the user depresses any key on the keyboard.'!!BitEditor methodsFor: 'initialize-release'!initialize super initialize. self initializeYellowButtonMenu!release super release. squareForm release. squareForm _ nil! !!BitEditor methodsFor: 'view access'!view: aView super view: aView. scale _ aView transformation scale. scale _ scale x rounded @ scale y rounded. squareForm _ Form new extent: scale. squareForm black! !!BitEditor methodsFor: 'basic control sequence'!controlInitialize super controlInitialize. Cursor crossHair show!controlTerminate Cursor normal show! !!BitEditor methodsFor: 'control defaults'!controlActivity | absoluteScreenPoint formPoint displayPoint | super controlActivity. [sensor redButtonPressed] whileTrue: [absoluteScreenPoint _ sensor cursorPoint. formPoint _ (view inverseDisplayTransform: absoluteScreenPoint - (scale//2)) rounded. displayPoint _ view displayTransform: formPoint. squareForm displayOn: Display at: displayPoint clippingBox: view insetDisplayBox rule: Form over mask: (Form perform: color). view changeValueAt: formPoint put: (#(white black gray) indexOf: color)-1].!isControlActive ^super isControlActive & sensor blueButtonPressed not & sensor keyboardPressed not! !!BitEditor methodsFor: 'menu messages'!accept "The edited information should now be accepted by the view." view accept!cancel "The edited informatin should be forgotten by the view." view cancel!setColor: aSymbol color _ aSymbol! !!BitEditor methodsFor: 'private'!initializeYellowButtonMenu self yellowButtonMenu: YellowButtonMenu yellowButtonMessages: YellowButtonMessages! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BitEditor class instanceVariableNames: ''!!BitEditor class methodsFor: 'class initialization'!initialize "The Bit Editor is the only controller to override the use of the blue button with a different pop-up menu. Initialize this menu." YellowButtonMenu _ PopUpMenu labels:'acceptcancel'. YellowButtonMessages _ #(accept cancel ) "BitEditor initialize."! !!BitEditor class methodsFor: 'instance creation'!openOnForm: aForm | scaleFactor | scaleFactor _ 8 @ 8. ^ self openOnForm: aForm at: (self locateMagnifiedView: aForm scale: scaleFactor) topLeft scale: scaleFactor!openOnForm: aForm at: magnifiedLocation ^ self openOnForm: aForm at: magnifiedLocation scale: 8 @ 8!openOnForm: aForm at: magnifiedLocation scale: scaleFactor "Create and schedule a BitEditor on the form aForm. Show the small and magnified view of aForm." | aScheduledView | aScheduledView _ self bitEdit: aForm at: magnifiedLocation scale: scaleFactor remoteView: nil. aScheduledView controller openDisplayAt: aScheduledView displayBox topLeft + (aScheduledView displayBox extent / 2)!openScreenViewOnForm: aForm at: formLocation magnifiedAt: magnifiedLocation scale: scaleFactor "Create and schedule a BitEditor on the form aForm. Show the magnified view of aForm in a scheduled window." | smallFormView bitEditor savedForm | smallFormView _ FormView new model: aForm. smallFormView align: smallFormView viewport topLeft with: formLocation. bitEditor _ self bitEdit: aForm at: magnifiedLocation scale: scaleFactor remoteView: smallFormView. savedForm _ Form fromDisplay: bitEditor displayBox. bitEditor controller blueButtonMenu: nil blueButtonMessages: nil. bitEditor controller startUp. savedForm displayOn: Display at: bitEditor displayBox topLeft. bitEditor release. smallFormView release! !!BitEditor class methodsFor: 'examples'!magnifyOnScreen "Bit editing of an area of the display screen. User designates a rectangular area that is magnified by 8 to allow individual screens dots to be modified. red button is used to set a bit to black and yellow button is used to set a bit to white. Editor is not scheduled in a view. Original screen location is updated immediately. This is the same as FormEditor magnify." | smallRect smallForm scaleFactor tempRect | scaleFactor _ 8 @ 8. smallRect _ Rectangle fromUser. smallRect isNil ifTrue: [^self]. smallForm _ Form fromDisplay: smallRect. tempRect _ self locateMagnifiedView: smallForm scale: scaleFactor. "show magnified form size until mouse is depressed" BitEditor openScreenViewOnForm: smallForm at: smallRect topLeft magnifiedAt: tempRect topLeft scale: scaleFactor "BitEditor magnifyOnScreen."!magnifyWithSmall "Bit editing of an area of the Form. User designates a rectangular area that is magnified by 8 to allow individual screens dots to be modified. red button is used to set a bit to black and yellow button is used to set a bit to white. Editor is scheduled in a view, showing the magnified view only." | smallRect smallForm | smallRect _ Rectangle fromUser. smallRect isNil ifTrue: [^self]. smallForm _ Form fromDisplay: smallRect. BitEditor openOnForm: smallForm "BitEditor magnifyWithSmall."! !!BitEditor class methodsFor: 'private'!bitEdit: aForm at: magnifiedFormLocation scale: scaleFactor remoteView: remoteView "Creates a BitEditor on aForm. That is, aForm is a small image that will change as a result of the BitEditor changing a second and magnified view of me. magnifiedFormLocation is where the magnified form is to be located on the screen. scaleFactor is the amount of magnification. This method implements a scheduled view containing both a small and magnified view of aForm. Upon accept, aForm is updated." | aFormView scaledFormView bitEditor topView extent menuView lowerRightExtent | scaledFormView _ FormHolderView new model: aForm. scaledFormView scaleBy: scaleFactor. bitEditor _ self new. bitEditor setColor: #black. scaledFormView controller: bitEditor. topView _ StandardSystemView new. remoteView == nil ifTrue: [topView label: 'Bit Editor']. topView borderWidth: 2. topView insideColor: Form white. topView addSubView: scaledFormView. remoteView == nil ifTrue: "If no remote view, then provide a local view of the form" [aFormView _ FormView new model: scaledFormView workingForm. aFormView controller: NoController new. (aForm isMemberOf: OpaqueForm) ifTrue: [scaledFormView insideColor: Form gray. aFormView insideColor: Form white]. aForm height < 50 ifTrue: [aFormView borderWidthLeft: 0 right: 2 top: 2 bottom: 2] ifFalse: [aFormView borderWidthLeft: 0 right: 2 top: 2 bottom: 0]. topView addSubView: aFormView below: scaledFormView] ifFalse: "Otherwise, the remote one should view the same form" [remoteView model: scaledFormView workingForm]. lowerRightExtent _ remoteView == nil ifTrue: [(scaledFormView viewport width - aFormView viewport width) @ (aFormView viewport height max: 50)] ifFalse: [scaledFormView viewport width @ 50]. menuView _ self buildColorMenu: lowerRightExtent colorCount: ((aForm isMemberOf: OpaqueForm) ifTrue: [3] ifFalse: [2]). menuView model: bitEditor. menuView borderWidthLeft: 0 right: 0 top: 2 bottom: 0. topView addSubView: menuView align: menuView viewport topRight with: scaledFormView viewport bottomRight. extent _ scaledFormView viewport extent + (0 @ lowerRightExtent y) + (4 @ 4). "+4 for borders" topView minimumSize: extent. topView maximumSize: extent. topView translateBy: magnifiedFormLocation. ^topView!buildColorMenu: extent colorCount: nColors "BitEditor magnifyWithSmall." | menuView index form aSwitchView connector button formExtent highlightForm color leftOffset | connector _ Object new. menuView _ FormMenuView new. menuView window: (0@0 corner: extent). formExtent _ 30@30 min: extent//(nColors*2+1@2). "compute this better" leftOffset _ extent x-(nColors*2-1*formExtent x)//2. highlightForm _ Form extent: formExtent. highlightForm borderWidth: 4 mask: Form black. 1 to: nColors do: [:index | color _ (nColors=2 ifTrue: [#(white black)] ifFalse: [#(white gray black)]) at: index. form _ Form extent: formExtent. form fill: form boundingBox mask: (Form perform: color). form borderWidth: 5 mask: Form black. color = #black ifTrue: [form borderWidth: 5 mask: Form white]. form borderWidth: 4 mask: Form white. button _ color = #black ifTrue: [OneOnSwitch newOn] ifFalse: [OneOnSwitch newOff]. button onAction: [menuView model setColor: color]. button connection: connector. aSwitchView _ SwitchView new model: button. aSwitchView key: ((nColors=3 ifTrue: ['xvn'] ifFalse: ['xn']) at: index). aSwitchView label: form. aSwitchView window: (0@0 extent: form extent). aSwitchView translateBy: (index-1*2*form width+leftOffset) @ (form height//2). aSwitchView insideColor: Form white. aSwitchView highlightForm: highlightForm. aSwitchView borderWidth: 1. aSwitchView controller selector: #turnOn. menuView addSubView: aSwitchView]. ^menuView!locateMagnifiedView: aForm scale: scaleFactor "Answers with a rectangle at the location where the scaled view of the form aForm should be displayed." | tempExtent tempRect | tempExtent _ aForm extent * scaleFactor + (0@50). tempRect _ (Sensor cursorPoint" grid: scaleFactor") extent: tempExtent. "show magnified form size until mouse is depressed" [Sensor redButtonPressed] whileFalse: [Display reverse: tempRect. Display reverse: tempRect. tempRect _ (Sensor cursorPoint grid: scaleFactor) extent: tempExtent]. ^tempRect! !BitEditor initialize! ContextPart variableSubclass: #BlockContext instanceVariableNames: 'nargs startpc home ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'!BlockContext comment:'My instances function similarly to instances of MethodContext, but they hold the dynamic state for execution of a block in Smalltalk. They access all temporary variables and the method sender via their home pointer, so that those values are effectively shared. Their indexable part is used to store their independent value stack during execution.My instance must hold onto its home in order to work. This can cause circularities if the home is also pointing (via a temp, perhaps) to the instance. In the rare event that this happens (as in SortedCollection sortBlock:) the message fixTemps will replace home with a copy of home, thus defeating the sharing of temps but, nonetheless, eliminating the circularity.Instance Variables: *indexed* nargs <Integer> number of block arguments startpc <Integer> home <Context>'!!BlockContext methodsFor: 'initialize-release'!home: aContextPart startpc: position nargs: anInteger "This is the initialization message. The receiver has been initialized with the correct size only." home _ aContextPart. startpc _ position. nargs _ anInteger. pc _ position. stackp _ 0! !!BlockContext methodsFor: 'accessing'!fixTemps "Fix the values of the temporary variables used in the block that are ordinarily shared with the method in which the block is defined." home _ home copy. home swapSender: nil!hasMethodReturn "answer true if there is an ^ in the code of this block" | method scanner end | method _ self method. "Determine end of block from long jump preceding it" end _ (method at: startpc-2)\\16-4*256 + (method at: startpc-1) + startpc - 1. scanner _ InstructionStream new method: method pc: startpc. scanner scanFor: [:byte | (byte between: 120 and: 124) or: [scanner pc > end]]. ^ scanner pc <= end!home "Answer the context in which the receiver was defined." ^home!method "Answer the compiled method in which the receiver was defined." ^home method!receiver ^home receiver! !!BlockContext methodsFor: 'temporaries'!tempAt: index ^home at: index!tempAt: index put: value ^home at: index put: value! !!BlockContext methodsFor: 'evaluating'!value "Evaluate the block represented by the receiver. Fail if the block expects any arguments or if the block is already being executed. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 81> ^self valueWithArguments: #()!value: arg "Evaluate the block represented by the receiver. Fail if the block expects other than one argument or if the block is already being executed. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 81> ^self valueWithArguments: (Array with: arg)!value: arg1 value: arg2 "Evaluate the block represented by the receiver. Fail if the block expects other than two arguments or if the block is already being executed. Optional. See Object documentation whatIsAPrimitive." <primitive: 81> ^self valueWithArguments: (Array with: arg1 with: arg2)!value: arg1 value: arg2 value: arg3 "Evaluate the block represented by the receiver. Fail if the block expects other than three arguments or if the block is already being executed. Optional. See Object documentation whatIsAPrimitive." <primitive: 81> ^self valueWithArguments: (Array with: arg1 with: arg2 with: arg3)!valueWithArguments: anArray "Evaluate the block represented by the receiver. The argument is an Array whose elements are the arguments for the block. Fail if the length of the Array is not the same as the the number of arguments that the block was expecting. Fail if the block is already being executed. Essential. See Object documentation whatIsAPrimitive." <primitive: 82> nargs = anArray size ifTrue: [self valueError] ifFalse: [self error: 'The block needs more or fewer arguments defined']! !!BlockContext methodsFor: 'controlling'!whileFalse "Evaluate the receiver once and then repeatedly as long as the value returned by the evaluation is false." ^[self value] whileFalse: []!whileFalse: aBlock "Evaluate the argument, aBlock, as long as the value of the receiver is false. Ordinarily compiled in-line. But could also be done in Smalltalk as follows" ^self value ifFalse: [aBlock value. self whileFalse: aBlock]!whileTrue "Evaluate the receiver once and then repeatedly as long as the value returned by the evaluation is true." ^[self value] whileTrue: []!whileTrue: aBlock "Evaluate the argument, aBlock, as long as the value of the receiver is true. Ordinarily compiled in-line. But could also be done in Smalltalk as follows" ^self value ifTrue: [aBlock value. self whileTrue: aBlock]! !!BlockContext methodsFor: 'scheduling'!fork "Create and schedule a process running the code in the receiver." self newProcess resume!forkAt: priority "Create and schedule a process running the code in the receiver. The priority of the process is the argument, priority." | forkedProcess | forkedProcess _ self newProcess. forkedProcess priority: priority. forkedProcess resume!newProcess "Answer a new process running the code in the receiver. The process is not scheduled." ^Process forContext: [self value. Processor terminateActive] priority: Processor activePriority!newProcessWith: anArray "Answer a new process running the code in the receiver. The receiver's block arguments are bound to the contents of the argument, anArray. The process is not scheduled." ^Process forContext: [self valueWithArguments: anArray. Processor terminateActive] priority: Processor activePriority! !!BlockContext methodsFor: 'instruction decoding'!blockReturnTop "Simulate the interpreter's action when a ReturnTopOfStack bytecode is encountered in the receiver." | save dest | save _ home. "Needed because return code will nil it" dest _ self return: self pop to: self sender. home _ save. sender _ nil. ^dest!pushArgs: args from: sendr "Simulates action of the value primitive." args size ~= nargs ifTrue: [^self error: 'incorrect number of args']. stackp _ 0. args do: [:arg | self push: arg]. sender _ sendr. pc _ startpc! !!BlockContext methodsFor: 'printing'!printOn: aStream home == nil ifTrue: [^aStream nextPutAll: 'a BlockContext with home=nil']. aStream nextPutAll: '[] in '. super printOn: aStream! !!BlockContext methodsFor: 'private'!valueError self error: 'Incompatible number of args, or already active'! ! ParseNode subclass: #BlockNode instanceVariableNames: 'arguments statements returns nArgsNode size remoteCopyNode sourceRange endPC ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!BlockNode comment: 'I represent a bracketed block with 0 or more arguments and 1 or more statements. If I am initialized with no statements, I create one. I have a flag to tell whether my last statement returns a value from the enclosing method. My last three fields remember data needed for code generation.I can emit for value in the usual way, in which case I create a literal method (actually a context remotely copied) to be evaluated by sending it value: at run time. Or I can emit code to be evaluated in line; this only happens at the top level of a method and in conditionals and while-loops, none of which have arguments.'!!BlockNode methodsFor: 'initialize-release'!arguments: argNodes statements: statementsCollection returns: returnBool from: encoder sourceEnd: sourceEnd "compile" sourceRange _ sourceEnd to: sourceEnd. arguments _ argNodes. statements _ statementsCollection size > 0 ifTrue: [statementsCollection] ifFalse: [argNodes size > 0 ifTrue: [statementsCollection copyWith: arguments last] ifFalse: [Array with: NodeNil]]. returns _ returnBool!default "[] argument of missing kwyword in ifTrue: or ifFalse:" statements _ Array with: NodeNil. arguments _ Array new: 0. returns _ false!statements: statementsCollection returns: returnBool "decompile" | returnLast | returnLast _ returnBool. returns _ false. statements _ (statementsCollection size > 1 and: [(statementsCollection at: statementsCollection size - 1) isReturningIf]) ifTrue: [returnLast _ false. statementsCollection copyFrom: 1 to: statementsCollection size - 1] ifFalse: [statementsCollection size = 0 ifTrue: [Array with: NodeNil] ifFalse: [statementsCollection]]. arguments _ Array new: 0. returnLast ifTrue: [self returnLast]! !!BlockNode methodsFor: 'accessing'!arguments: argNodes "decompile" arguments _ argNodes!numberOfArguments ^arguments size!returnLast self returns ifFalse: [returns _ true. statements at: statements size put: statements last asReturnNode]!returnSelfIfNoOther self returns ifFalse: [statements last == NodeSelf ifFalse: [statements add: NodeSelf]. self returnLast]! !!BlockNode methodsFor: 'testing'!canBeSpecialArgument "can I be an argument of (e.g.) ifTrue:?" ^arguments size = 0!isComplex ^statements size > 1!isJust: node returns ifTrue: [^false]. ^statements size = 1 and: [statements first == node]!isQuick ^statements size = 1 and: [statements first isVariableReference]!returns ^returns or: [statements last isReturningIf]! !!BlockNode methodsFor: 'code generation'!code ^statements first code!emitExceptLast: stack on: aStream 1 to: statements size - 1 do: [:i | (statements at: i) emitForEffect: stack on: aStream]!emitForEvaluatedEffect: stack on: aStream self returns ifTrue: [self emitForEvaluatedValue: stack on: aStream. stack pop: 1] ifFalse: [self emitExceptLast: stack on: aStream. statements last emitForEffect: stack on: aStream]!emitForEvaluatedValue: stack on: aStream self emitExceptLast: stack on: aStream. statements last emitForValue: stack on: aStream!emitForValue: stack on: aStream | arg blockStack | aStream nextPut: LdThisContext. stack push: 1. nArgsNode emitForValue: stack on: aStream. remoteCopyNode emit: stack args: 1 on: aStream. "jmp-around must be 2 bytes" self emitLongJump: size on: aStream. "Block gets its own stack in blockContext" blockStack _ ParseStack new init. blockStack push: arguments size. arguments reverseDo: [:arg | arg emitStorePop: blockStack on: aStream]. self emitForEvaluatedValue: blockStack on: aStream. endPC _ aStream position+1. self returns ifFalse: [aStream nextPut: EndRemote]. blockStack pop: 1. stack max: blockStack size!pc ^ endPC!sizeExceptLast: encoder | totalSize | totalSize _ 0. 1 to: statements size - 1 do: [:i | totalSize _ totalSize + ((statements at: i) sizeForEffect: encoder)]. ^totalSize!sizeForEvaluatedEffect: encoder self returns ifTrue: [^self sizeForEvaluatedValue: encoder]. ^(self sizeExceptLast: encoder) + (statements last sizeForEffect: encoder)!sizeForEvaluatedValue: encoder ^(self sizeExceptLast: encoder) + (statements last sizeForValue: encoder)!sizeForValue: encoder nArgsNode _ encoder encodeLiteral: arguments size. remoteCopyNode _ encoder encodeSelector: #blockCopy:. size _ self sizeForEvaluatedValue: encoder. self returns ifFalse: [size _ size+1. "end-block" encoder noteSourceRange: sourceRange forNode: self]. arguments do: [:arg | size _ size + (arg sizeForStorePop: encoder)]. ^1 + (nArgsNode sizeForValue: encoder) + (remoteCopyNode size: encoder) + 2 + size! !!BlockNode methodsFor: 'printing'!printArgumentsOn: aStream indent: level arguments size = 0 ifFalse: [arguments do: [:arg | aStream nextPut: $:. aStream nextPutAll: arg key. aStream space]. aStream nextPutAll: '| '. "If >0 args and >1 statement, put all statements on separate lines" statements size > 1 ifTrue: [aStream crtab: level]]!printOn: aStream indent: level statements size <= 1 ifFalse: [aStream crtab: level]. aStream nextPut: $[. self printArgumentsOn: aStream indent: level. self printStatementsOn: aStream indent: level. aStream nextPut: $]!printStatementsOn: aStream indent: level | len shown thisStatement | comment == nil ifFalse: [self printCommentOn: aStream indent: level. aStream crtab: level]. len _ shown _ statements size. (level = 1 and: [statements last isReturnSelf]) ifTrue: [shown _ 1 max: shown - 1] ifFalse: [(len = 1 and: [((statements at: 1) == NodeNil) & (arguments size = 0)]) ifTrue: [shown _ shown - 1]]. 1 to: shown do: [:i | thisStatement _ statements at: i. thisStatement == NodeSelf ifFalse: [thisStatement printOn: aStream indent: level. i < shown ifTrue: [aStream nextPut: $.; crtab: level]. thisStatement comment size > 0 ifTrue: [i = shown ifTrue: [aStream crtab: level]. thisStatement printCommentOn: aStream indent: level. i < shown ifTrue: [aStream crtab: level]]]]! ! Object subclass: #Boolean instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Objects'!Boolean comment: 'I implement behavior common to true and false.'!!Boolean methodsFor: 'logical operations'!& aBoolean "Evaluating conjunction -- Evaluate the argument. Then answer true if both the receiver and the argument are true." self subclassResponsibility!eqv: aBoolean "Answer true if the receiver is equivalent to aBoolean." ^self == aBoolean!not "Negation-- answer true if the receiver is false, answer false if the receiver is true." self subclassResponsibility!xor: aBoolean "Exclusive OR -- answer true if the receiver is not equivalent to aBoolean." ^(self == aBoolean) not!| aBoolean "Evaluating disjunction (OR) -- Evaluate the argument. Then answer true if either the receiver or the argument is true." self subclassResponsibility! !!Boolean methodsFor: 'controlling'!and: alternativeBlock "Nonevaluating conjunction -- if the receiver is true, answer the value of the argument, alternativeBlock; otherwise answer false without evaluating the argument." self subclassResponsibility!ifFalse: alternativeBlock "If the receiver is true (i.e., the condition is true), then the value is the true alternative, which is nil. Otherwise answer the result of evaluating the argument, alternativeBlock. Create an error if the receiver is nonBoolean. Execution does not actually reach here because the expression is compiled in-line." self subclassResponsibility!ifFalse: falseAlternativeBlock ifTrue: trueAlternativeBlock "Same as ifTrue:ifFalse:" self subclassResponsibility!ifTrue: alternativeBlock "If the receiver is false (i.e., the condition is false), then the value is the false alternative, which is nil. Otherwise answer the result of evaluating the argument, alternativeBlock. Create an error if the receiver is nonBoolean. Execution does not actually reach here because the expression is compiled in-line." self subclassResponsibility!ifTrue: trueAlternativeBlock ifFalse: falseAlternativeBlock "If the receiver is true (i.e., the condition is true), then answer the value of the argument trueAlternativeBlock. If the receiver is false, answer the result of evaluating the argument falseAlternativeBlock. If the receiver is a nonBoolean then create an error message. Execution does not actually reach here because the expression is compiled in-line." self subclassResponsibility!or: alternativeBlock "Nonevaluating disjunction -- if the receiver is false, answer the value of the argument, alternativeBlock; otherwise answer true without evaluating the argument." self subclassResponsibility! !!Boolean methodsFor: 'copying'!deepCopy "Receiver has two concrete subclasses, True and False. Only one instance of each should be made, so return self."!shallowCopy "Receiver has two concrete subclasses, True and False. Only one instance of each should be made, so return self."! !!Boolean methodsFor: 'printing'!storeOn: aStream self printOn: aStream! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Boolean class instanceVariableNames: ''!!Boolean class methodsFor: 'instance creation'!new self error: 'You may not create any more Booleans - this is two-valued logic'! ! SwitchView subclass: #BooleanView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!BooleanView comment:'BooleanView is a "pluggable" view of a boolean value. The notion of pluggable views is anexperiment in user interface design. The idea is to provide a view which can be pluggedonto any object, rather than having to define a new subclass specific to every kind ofobject which needs to be viewed.The chief mechanism is a set of selectors, which can be thought of as an adaptor toconvert the generic textView operations (such as interrogateModel) into model-specificoperations (such as metaclassSelected).See the creation messages in my class for an explication of the various parameters.Browse senders of the creation messages in my class for examples in the system.'!!BooleanView methodsFor: 'updating'!interrogateModel ^ (model perform: selector) = arguments first!update: aspect aspect == selector ifTrue: [super update: aspect]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BooleanView class instanceVariableNames: ''!!BooleanView class methodsFor: 'instance creation'!on: model aspect: aspect label: label change: changeSel value: onValue "Create a 'pluggable' (see class comment) switchView viewing anObject. aspect is sent to read the current boolean value in the model. It is also used as the changed: parameter for this view. changeSel is sent to inform anObject of new boolean value for the model." | view args | view _ self new. view model: model. view selector: aspect; arguments: (args _ Array with: onValue). view controller selector: changeSel; arguments: args. view label: label asParagraph. ^view! ! Object subclass: #Browser instanceVariableNames: 'organization category className meta protocol selector textMode ' classVariableNames: 'CategoryMenu ClassMenu MessageMenu MethodMoveCategory MethodMoveProtocol ProtocolMenu TextMenu ' poolDictionaries: '' category: 'Interface-Browser'!Browser comment:'A browser represents a hierarchical query path which identifies a method to be examined.organization - a SystemOrganizercategory - a selection from all categories in the organization.className - a selection from all classes in the category.meta - false for viewing normal methods, true for class methods.protocol - a selection from all protocols in the class.selector - a selection from all messages in the protocol.textMode - symbol indicating the nature of the currently viewed text.'!!Browser methodsFor: 'initialization'!on: anOrganizer organization _ anOrganizer. meta _ false!onClass: aClass organization _ SystemOrganization. className _ aClass isMeta ifTrue: [aClass soleInstance name] ifFalse: [aClass name]. meta _ aClass isMeta! !!Browser methodsFor: 'category list'!category ^ category!category: selection category _ selection. selection isNil ifTrue: [self textMode: nil]. self newClassList: className!categoryList ^ organization categories!categoryMenu "Browser flushMenus" category == nil ifTrue: [^ ActionMenu labels: 'add category\update\edit all' withCRs lines: #(1) selectors: #(addCategory updateCategories editCategories )]. CategoryMenu == nil ifTrue: [CategoryMenu _ ActionMenu labels: 'file out\print out\spawn\add category\rename\remove\update\edit all' withCRs lines: #(3 6) selectors: #(fileOutCategory printOutCategory spawnCategory addCategory renameCategory removeCategory updateCategories editCategories)]. ^ CategoryMenu!newCategoryList: initialSelection category _ initialSelection. self changed: #category! !!Browser methodsFor: 'category functions'!addCategory | aString newCategory | self changeRequest ifFalse: [^self]. aString _ self prompt: 'Enter new category name' initially: 'category name'. aString isEmpty ifTrue: [^ self]. newCategory _ aString asSymbol. organization addCategory: newCategory before: category. Smalltalk changes reorganizeSystem. self newCategoryList: newCategory!editCategories self changeRequest ifFalse: [^self]. self textMode: #categories!fileOutCategory organization fileOutCategory: category!printOutCategory organization printOutCategory: category!removeCategory | classes | self changeRequest ifFalse: [^self]. classes _ organization superclassOrder: category. classes isEmpty ifFalse: [(self confirm: 'Are you certain that you want toremove all classes in this category?') ifFalse: [^self]. classes reverseDo: [:cls | cls removeFromSystem]]. organization removeCategory: category. Smalltalk changes reorganizeSystem. self newCategoryList: nil!renameCategory | aString newCategory | self changeRequest ifFalse: [^self]. aString _ self prompt: 'Enter new category name' initially: category. aString isEmpty ifTrue: [^ self]. newCategory _ aString asSymbol. (organization renameCategory: category to: newCategory) ifTrue: [Smalltalk changes reorganizeSystem. self newCategoryList: newCategory]!spawnCategory BrowserView openCategoryBrowserOn: self copy!updateCategories self changeRequest ifFalse: [^self]. self newCategoryList: category! !!Browser methodsFor: 'class list'!classList category == nil ifTrue: [^ nil]. category = '**Hierarchy**' ifTrue: [^ (self selectedClass withAllSuperclasses reverse , self selectedClass allSubclasses) collect: [:cls | cls name]]. ^ organization listAtCategoryNamed: category!classMenu "Browser flushMenus" className == nil ifTrue: [^nil]. ClassMenu == nil ifTrue: [ClassMenu _ ActionMenu labels: 'file out\print out\spawn\spawn hierarchyhierarchy\definition\comment\protocolsinst var refs\class var refs\class refsrename\remove' withCRs lines: #(4 8 11) selectors: #(fileOutClass printOutClass spawnClass spawnHierarchy showHierarchy editClass editComment editProtocolsbrowseFieldReferences browseClassVariables browseClassReferences renameClass removeClass)]. ^ ClassMenu!className ^ className!className: selection className _ selection. self newProtocolList: protocol. selection isNil & category notNil ifTrue: [self textMode: #classDefinition] ifFalse: [self classMode ifTrue: [self changed: #text]]!newClassList: initialSelection className _ initialSelection. self changed: #className!selectedClass className == nil ifTrue: [^ nil]. meta ifTrue: [^ (Smalltalk at: className) class] ifFalse: [^ Smalltalk at: className]! !!Browser methodsFor: 'class functions'!acceptClass: aText from: aController | oldClass class | oldClass _ className == nil ifTrue: [Object] ifFalse: [self selectedClass]. class _ oldClass subclassDefinerClass evaluate: aText string notifying: aController logged: true. (class isKindOf: Behavior) ifTrue: [self newClassList: class name. ^true] ifFalse: [^false]!browseClassReferences Smalltalk browseAllCallsOn: (Smalltalk associationAt: className)!browseClassVariables "Show a menu of all class variables of the currently selected class and its superclasses. Browse all methods which refer to the variable selected." | association | association _ self selectedClass showVariableMenu: [:class | class classPool associations asSortedCollection] collect: [:association | association key]. association notNil ifTrue: [BrowserView openListBrowserOn: (self selectedClass allCallsOn: association) label: 'Users of ' , association key initialSelection: association key]!browseFieldReferences "Show a menu of all instance variables of the currently selected class and its superclasses. Browse all methods which refer to the variable selected." | name | name _ self selectedClass showVariableMenu: [:class | class instVarNames] collect: [:name | name]. name notNil ifTrue: [BrowserView openListBrowserOn: (self selectedClass allAccessesTo: name) label: name initialSelection: name]!browseHierarchy "I am a copy; put me in the right state to browse a hierarchy" category _ '**Hierarchy**'. self meta: false!classMode ^#(classDefinition hierarchy comment protocols) includes: textMode!editClass self changeRequest ifFalse: [^self]. self textMode: #classDefinition. self newProtocolList: nil!editComment self changeRequest ifFalse: [^self]. self textMode: #comment. self newProtocolList: nil!editProtocols self changeRequest ifFalse: [^self]. self textMode: #protocols. self newProtocolList: nil!fileOutClass self nonMetaClass fileOut!nonMetaClass ^ meta ifTrue: [self selectedClass soleInstance] ifFalse: [self selectedClass]!printOutClass self nonMetaClass printOut!promptClass self newClassList: nil. self textMode: #classDefinition!removeClass | class | self changeRequest ifFalse: [^self]. class _ self nonMetaClass. (self confirm: 'Are you certain that youwant to remove the class ', class name, '?') ifTrue: [class subclasses size > 0 ifTrue: [self notify: class name , ' has subclasses']. class removeFromSystem. self newClassList: nil]!renameClass | aString newName cleanString | self changeRequest ifFalse: [^self]. aString _ self prompt: 'Enter new ClassName' initially: self selectedClass name. aString isEmpty ifTrue: [^self]. cleanString _ aString select: [:char | char isAlphaNumeric]. cleanString = aString ifFalse: [aString _ cleanString. (self confirm: 'Invalid characters in class name. Should I use ', aString, '?') ifFalse: [^self]]. aString first isUppercase ifFalse: [aString at: 1 put: (aString at: 1) asUppercase. (self confirm: 'Class names must be capitalized. Should I use ', aString, '?') ifFalse: [^self]]. newName _ aString asSymbol. aString = self selectedClass name ifFalse: [self selectedClass rename: newName. self newClassList: newName. Transcript cr; show: 'Searching for references to this class...'. self browseClassReferences]!showHierarchy self changeRequest ifFalse: [^self]. self textMode: #hierarchy. self newProtocolList: nil!spawnClass BrowserView openClassBrowserOn: self copy!spawnHierarchy BrowserView openCategoryBrowserOn: self copy browseHierarchy! !!Browser methodsFor: 'class/inst switch'!meta ^ meta!meta: aBoolean self changeRequest ifFalse: [^ self changed: #meta]. meta _ aBoolean. self changed: #meta. self newProtocolList: protocol. self classMode ifTrue: [self changed: #text]! !!Browser methodsFor: 'protocol list'!newProtocolList: initialSelection protocol _ initialSelection. self changed: #protocol!protocol ^ protocol!protocol: selection protocol _ selection. self classMode ifTrue: [^ self newSelectorList: nil]. selection isNil & className notNil ifTrue: [self textMode: #classDefinition]. self newSelectorList: selector!protocolList className == nil ifTrue: [^ nil]. ^ self selectedClass organization categories!protocolMenu "Browser flushMenus" protocol == nil ifTrue: [^ ActionMenu labels: 'add protocol' selectors: #(addProtocol)]. ProtocolMenu == nil ifTrue: [ProtocolMenu _ ActionMenu labels: 'file out\print out\spawn\add protocol\rename\remove' withCRs lines: #(3) selectors: #(fileOutProtocol printOutProtocol spawnProtocol addProtocol renameProtocol removeProtocol)]. ^ ProtocolMenu! !!Browser methodsFor: 'protocol functions'!addProtocol | aString newProtocol | self changeRequest ifFalse: [^self]. aString _ self prompt: 'Enter new protocol name' initially: 'protocol name'. aString isEmpty ifTrue: [^ self]. newProtocol _ aString asSymbol. self selectedClass organization addCategory: newProtocol before: protocol. self logProtocolChange: self selectedClass name, ' organization addCategory: ', newProtocol storeString, ' before: ', protocol storeString. self selectedClass reorganize. self newProtocolList: newProtocol!fileOutProtocol self selectedClass fileOutCategory: protocol!printOutProtocol self selectedClass printOutCategory: protocol!removeProtocol | selectors | self changeRequest ifFalse: [^self]. selectors _ self selectedClass organization listAtCategoryNamed: protocol. selectors isEmpty ifFalse: [(self confirm: 'Are you certain that you want toremove all methods in this protocol?') ifFalse: [^self]. selectors do: [:sel | self selectedClass removeSelector: sel]]. self selectedClass organization removeCategory: protocol. self logProtocolChange: self selectedClass name, ' organization removeCategory: ', protocol storeString. self selectedClass reorganize. self newProtocolList: nil!renameProtocol | aString newProtocol | self changeRequest ifFalse: [^self]. aString _ self prompt: 'Enter new protocol name' initially: protocol. aString isEmpty ifTrue: [^ self]. newProtocol _ aString asSymbol. (self selectedClass organization renameCategory: protocol to: newProtocol) ifTrue: [self logProtocolChange: self selectedClass name, ' organization renameCategory: ', protocol storeString, ' to: ', newProtocol storeString.self selectedClass reorganize. self newProtocolList: newProtocol]!spawnProtocol BrowserView openProtocolBrowserOn: self copy! !!Browser methodsFor: 'selector list'!newSelectorList: initialSelection selector _ initialSelection. self changed: #selector!selector ^ selector!selector: selection selector _ selection. (selection == nil and: [protocol == nil]) ifTrue: [^ self]. self textMode: #methodDefinition!selectorList protocol == nil ifTrue: [^ nil]. ^ self selectedClass organization listAtCategoryNamed: protocol!selectorMenu "Browser flushMenus" selector == nil ifTrue: [^ nil]. MessageMenu == nil ifTrue: [MessageMenu _ ActionMenu labels: 'file out\print out\spawn\senders\implementors\messages\move\remove' withCRs lines: #(3 6) selectors: #(fileOutMessage printOutMessage spawnMethod browseSenders browseImplementors browseMessages moveMethod removeMethod)]. ^ MessageMenu! !!Browser methodsFor: 'selector functions'!acceptMethod: aText from: aController | newSelector | newSelector _ self selectedClass compile: aText classified: protocol notifying: aController. newSelector == nil ifTrue: [^false]. newSelector == selector ifFalse: [self newSelectorList: newSelector]. ^true!browseImplementors Smalltalk browseAllImplementorsOf: selector!browseMessages Smalltalk showMenuThenBrowse: (self selectedClass compiledMethodAt: selector) messages asSortedCollection!browseSenders Smalltalk browseAllCallsOn: selector!fileOutMessage self selectedClass fileOutMessage: selector!moveMethod | newProtocol classPart destClass protStart moved destClassName | self changeRequest ifFalse: [^self]. newProtocol _ self prompt: 'Type destination protocol(Class>protocol will copy)' initially: MethodMoveProtocol. newProtocol isEmpty ifTrue: [^self]. MethodMoveProtocol _ newProtocol. moved _ false. (newProtocol includes: $>) ifTrue: ["copy to another class" classPart _ newProtocol copyUpTo: $>. destClassName _ classPart copyUpTo: Character space. destClass _ Smalltalk at: destClassName asSymbol ifAbsent: [nil]. (destClass isKindOf: ClassDescription) ifFalse: [(Display flash: Display boundingBox). ^nil]. classPart size = destClassName size ifFalse: [(classPart size-destClassName size = 6 and: [(classPart copyFrom: classPart size - 5 to: classPart size) = ' class']) ifTrue: [destClass _ destClass class] ifFalse: [(Display flash: Display boundingBox). ^nil]]. protStart _ classPart size + 2. [(newProtocol at: protStart) = $ ] whileTrue: [protStart _ protStart + 1]. newProtocol _ (newProtocol copyFrom: protStart to: newProtocol size) asSymbol. destClass == self selectedClass ifFalse: [moved _ true. destClass compile: self text classified: newProtocol notifying: nil]] ifFalse: ["move within this class" destClass _ self selectedClass. newProtocol _ newProtocol asSymbol]. moved ifFalse: [(destClass organization categories includes: newProtocol) ifFalse: [destClass organization addCategory: newProtocol. self newProtocolList: protocol]. destClass organization classify: selector under: newProtocol. self logProtocolChange: destClass name , ' organization classify: ' , selector storeString , ' under: ' , newProtocol storeString. destClass reorganize]. self newSelectorList: selector!printOutMessage self selectedClass printOutMessage: selector!removeMethod (self changeRequest and: [self confirm: 'Are you certain that youwant to remove this method?']) ifTrue: [self selectedClass removeSelector: selector. self newSelectorList: nil. ^ true]. ^ false!spawnEdits: aText from: aController | newController | newController _ aController copy. "Copy gets the changes" aController cancel; controlTerminate. "Cancel changes in spawning browser" selector == nil "spawn full browser if not in a specific method" ifTrue: [BrowserView openOn: self copy withController: newController] ifFalse: [BrowserView openMethodBrowserOn: self copy withController: newController]!spawnMethod BrowserView openMethodBrowserOn: self copy! !!Browser methodsFor: 'text'!prompt: promptString initially: initialString | aString | FillInTheBlank request: promptString , 'then accept or CR' displayAt: Sensor cursorPoint centered: false action: [:aString] initialAnswer: initialString. ^ aString!text | text | textMode == #classDefinition ifTrue: [className == nil ifTrue: [^ (Class template: category) asText] ifFalse: [^ self selectedClass definition asText]]. textMode == #methodDefinition ifTrue: [selector == nil ifTrue: [^ self selectedClass sourceCodeTemplate asText] ifFalse: [^ (self selectedClass sourceCodeAt: selector) asText makeSelectorBoldIn: self selectedClass]]. textMode == #category ifTrue: [^ 'category to add' asText]. textMode == #categories ifTrue: [^ organization printString asText]. textMode == #protocol ifTrue: [^ 'protocol to add' asText]. textMode == #protocols ifTrue: [^ self selectedClass organization printString asText]. textMode == #comment ifTrue: [text _ self selectedClass comment asText. text isEmpty ifFalse: [^ text]. ^ 'This class has no comment' asText]. textMode == #hierarchy ifTrue: [^ self selectedClass printHierarchy asText]. ^ Text new!textMenu "Browser flushMenus" TextMenu == nil ifTrue: [TextMenu _ ActionMenu labels: 'again\undo\copy\cut\paste\do it\print it\accept\cancel\format\spawn\explain' withCRs lines: #(2 5 7 9) selectors: #(again undo copySelection cut paste doIt printIt accept cancel format spawnEdits:from: explain)]. ^ TextMenu!textMode: aSymbol textMode _ aSymbol. self changed: #text! !!Browser methodsFor: 'doIt/accept/explain'!acceptText: aText from: aController textMode == #classDefinition ifTrue: [^ self acceptClass: aText from: aController]. textMode == #methodDefinition ifTrue: [^ self acceptMethod: aText from: aController]. textMode == #categories ifTrue: [organization changeFromString: aText string. self newCategoryList: category. ^true]. textMode == #protocols ifTrue: [self selectedClass organization changeFromString: aText string. self selectedClass reorganize. self selectedClass logOrganizationChange. self textMode: #protocol; newProtocolList: nil. ^ true]. textMode == #comment ifTrue: [self selectedClass comment: aText string. self textMode: #comment; newProtocolList: nil. ^ true]. textMode == #hierarchy ifTrue: [aController flash]. ^ false!doItContext ^ nil!doItReceiver ^ nil!doItValue: ignored!explainSpecial: string "Answer with a string explaining the code pane selection if it is displaying one of the special edit functions." | classes whole lits reply | (textMode == #classDefinition) ifTrue: ["Selector parts in class definition" string last == $: ifFalse: [^nil]. lits _ Array with: #subclass:instanceVariableNames:classVariableNames:poolDictionaries:category:. (whole _ lits detect: [:each | (each keywords detect: [:frag | frag = string] ifNone: []) ~~ nil] ifNone: []) ~~ nil ifTrue: [reply _ '"' , string , ' is one part of the message selector ' , whole , '.'] ifFalse: [^nil]. classes _ Smalltalk allClassesImplementing: whole. classes _ 'these classes ' , classes printString. ^reply , ' It is defined in ' , classes , '."Smalltalk browseAllImplementorsOf: #' , whole]. textMode == #hierarchy ifTrue: ["Instance variables in subclasses" classes _ self selectedClass allSubclasses. classes _ classes detect: [:each | (each instVarNames detect: [:name | name = string] ifNone: []) ~~ nil] ifNone: [^nil]. classes _ classes printString. ^'"is an instance variable in class ' , classes , '."' , classes , ' browseAllAccessesTo: ''' , string , '''.']. ^nil! !!Browser methodsFor: 'change management'!logProtocolChange: aString "Add aString, which is an executable account of the last protocol change (rename, remove, selector move) to the changes file." | file | SourceFiles == nil ifFalse: [file _ SourceFiles at: 2. file setToEnd; readWriteShorten. file cr; nextChunkPut: aString. file cr; readOnly].! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Browser class instanceVariableNames: ''!!Browser class methodsFor: 'instance creation'!newOnClass: aClass BrowserView openClassBrowserOn: (self new onClass: aClass)! !!Browser class methodsFor: 'class initialization'!flushMenus "Browser flushMenus." "Causes all menus to be newly created (so changes appear)" MethodMoveProtocol _ 'protocol name'. CategoryMenu _ nil. ClassMenu _ nil. MessageMenu _ nil. ProtocolMenu _ nil. TextMenu _ nil! ! StandardSystemView subclass: #BrowserView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Browser'!BrowserView comment:'I am a StandardSystemView that provides initialization methods (messages to myself) to create and schedule the various system browsers: System Browser, System Category Browser, Class Browser, Message Category Browser, Message Browser.'!!BrowserView methodsFor: 'subview creation'!addCategoryView: area on: aBrowser readOnly: RO self addSubView: (SelectionInListView on: aBrowser printItems: false oneItem: RO aspect: #category change: #category: list: #categoryList menu: #categoryMenu initialSelection: #category) in: area borderWidth: 1!addClassView: area on: aBrowser readOnly: RO self addSubView: (SelectionInListView on: aBrowser printItems: false oneItem: RO aspect: #className change: #className: list: #classList menu: #classMenu initialSelection: #className) in: area borderWidth: 1!addMetaView: area on: aBrowser readOnly: ingored | mid | mid _ (area left + area right) * 0.5. self addSubView: (BooleanView on: aBrowser aspect: #meta label: 'instance' asText change: #meta: value: false) in: (area copy right: mid) borderWidth: 1. self addSubView: (BooleanView on: aBrowser aspect: #meta label: 'class' asText change: #meta: value: true) in: (area copy left: mid) borderWidth: 1!addMethodView: area on: aBrowser readOnly: RO self addSubView: (SelectionInListView on: aBrowser printItems: false oneItem: RO aspect: #methodName change: #methodName: list: #methodList menu: #methodMenu initialSelection: #methodName) in: area borderWidth: 1!addProtocolView: area on: aBrowser readOnly: RO self addSubView: (SelectionInListView on: aBrowser printItems: false oneItem: RO aspect: #protocol change: #protocol: list: #protocolList menu: #protocolMenu initialSelection: #protocol) in: area borderWidth: 1!addSelectorView: area on: aBrowser readOnly: RO self addSubView: (SelectionInListView on: aBrowser printItems: false oneItem: RO aspect: #selector change: #selector: list: #selectorList menu: #selectorMenu initialSelection: #selector) in: area borderWidth: 1!addTextView: area on: aBrowser initialSelection: sel self addSubView: (CodeView on: aBrowser aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: sel) in: area borderWidth: 1! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!BrowserView class instanceVariableNames: ''!!BrowserView class methodsFor: 'instance creation'!openCategoryBrowserOn: aBrowser | topView | (topView _ self model: aBrowser label: 'Category Browser' minimumSize: 400@250) addCategoryView: (0@0 extent: 0.3@0.06) on: aBrowser readOnly: true; addClassView: (0@0.06 extent: 0.3@0.28) on: aBrowser readOnly: false; addMetaView: (0@0.34 extent: 0.3@0.06) on: aBrowser readOnly: false; addProtocolView: (0.3@0 extent: 0.3@0.4) on: aBrowser readOnly: false; addSelectorView: (0.6@0 extent: 0.4@0.4) on: aBrowser readOnly: false; addTextView: (0@0.4 extent: 1.0@0.6) on: aBrowser initialSelection: nil. topView controller open!openClassBrowserOn: aBrowser | topView | (topView _ self model: aBrowser label: 'Class Browser' minimumSize: 400@250) addClassView: (0@0 extent: 0.5@0.1) on: aBrowser readOnly: true; addMetaView: (0.5@0 extent: 0.5@0.1) on: aBrowser readOnly: false; addProtocolView: (0@0.1 extent: 0.5@0.3) on: aBrowser readOnly: false; addSelectorView: (0.5@0.1 extent: 0.5@0.3) on: aBrowser readOnly: false; addTextView: (0@0.4 extent: 1.0@0.6) on: aBrowser initialSelection: nil. topView controller open!openListBrowserOn: aCollection label: labelString self openListBrowserOn: aCollection label: labelString initialSelection: nil!openListBrowserOn: aCollection label: labelString initialSelection: sel "Create and schedule a Method List browser for the methods in aCollection. If the collection is empty, print -Nobody- in the System Transcript." | topView aBrowser label | aCollection isEmpty ifTrue: [^ Transcript cr; show: 'Nobody']. aBrowser _ MethodListBrowser new on: aCollection. label _ (labelString isKindOf: LookupKey) ifTrue: [labelString key] ifFalse: [labelString asString]. topView _ self model: aBrowser label: label minimumSize: 300@100. topView addMethodView: (0@0 extent: 1.0@0.25) on: aBrowser readOnly: false; addTextView: (0@0.25 extent: 1@0.75) on: aBrowser initialSelection: sel. topView controller open!openMethodBrowserOn: aBrowser | topView | (topView _ self model: aBrowser label: 'Method Browser on ' , aBrowser selectedClass name minimumSize: 250@120) addSelectorView: (0@0 extent: 1@0.15) on: aBrowser readOnly: true; addTextView: (0@0.15 extent: 1@0.85) on: aBrowser initialSelection: nil. topView controller open!openMethodBrowserOn: aBrowser withController: aController "aController may contain changes that haven't already been accepted" | topView textView | topView _ self model: aBrowser label: 'Method Browser on ' , aBrowser selectedClass name minimumSize: 250@120. topView addSelectorView: (0@0 extent: 1@0.15) on: aBrowser readOnly: true. textView _ CodeView on: aBrowser aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil. textView controller: aController. topView addSubView: textView in: (0@0.15 extent: 1@0.85) borderWidth: 1. topView controller open!openOn: anOrganizer "BrowserView openOn: SystemOrganization." | topView aBrowser topY bottomY metaY | aBrowser _ Browser new on: anOrganizer. topY _ 0.35. "change this to re-proportion system browser" bottomY _ 1 - topY. metaY _ 0.05. "change this to re-proportion system browser" (topView _ self model: aBrowser label: 'System Browser' minimumSize: 400@250) addCategoryView: (0@0 extent: 0.25@topY) on: aBrowser readOnly: false; addClassView: (0.25@0 extent: 0.25@(topY - metaY)) on: aBrowser readOnly: false; addMetaView: (0.25@(topY - metaY) extent: 0.25@metaY) on: aBrowser readOnly: false; addProtocolView: (0.5@0 extent: 0.25@topY) on: aBrowser readOnly: false; addSelectorView: (0.75@0 extent: 0.25@topY) on: aBrowser readOnly: false; addTextView: (0@topY extent: 1.0@bottomY) on: aBrowser initialSelection: nil. topView controller open!openOn: aBrowser withController: aController "aController may contain changes that haven't already been accepted" | topView textView | (topView _ self model: aBrowser label: 'System Browser' minimumSize: 400@250) addCategoryView: (0@0 extent: 0.25@0.4) on: aBrowser readOnly: false; addClassView: (0.25@0 extent: 0.25@0.34) on: aBrowser readOnly: false; addMetaView: (0.25@0.34 extent: 0.25@0.06) on: aBrowser readOnly: false; addProtocolView: (0.5@0 extent: 0.25@0.4) on: aBrowser readOnly: false; addSelectorView: (0.75@0 extent: 0.25@0.4) on: aBrowser readOnly: false. textView _ CodeView on: aBrowser aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil. textView controller: aController. topView addSubView: textView in: (0@0.4 extent: 1@0.6) borderWidth: 1. topView controller open!openProtocolBrowserOn: aBrowser | topView | (topView _ self model: aBrowser label: 'Protocol Browser on ' , aBrowser selectedClass name minimumSize: 400@200) addProtocolView: (0@0 extent: 1@0.1) on: aBrowser readOnly: true; addSelectorView: (0@0.1 extent: 1@0.3) on: aBrowser readOnly: false; addTextView: (0@0.4 extent: 1.0@0.6) on: aBrowser initialSelection: nil. topView controller open! ! Switch subclass: #Button instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!Button comment:'I am a Switch that turns off automatically after being turned on, that is, I act like a push-button switch.'!!Button methodsFor: 'state'!turnOff "Sets the state of the receiver to 'off'. The off action of the receiver is not executed." on _ false!turnOn "The receiver remains in the 'off' state'." self doAction: onAction. self doAction: offAction! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Button class instanceVariableNames: ''!!Button class methodsFor: 'instance creation'!newOn self error: 'Buttons cannot be created in the on state'. ^nil! ! ArrayedCollection variableByteSubclass: #ByteArray instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed'!ByteArray comment:'My elements can only be integers between 0 and 255. The access messages at: and at:put: are handled primitively in class Object'!!ByteArray methodsFor: 'accessing'!doubleWordAt: i "Answer the value of the double word (4 bytes) starting at byte index i." | b0 b1 b2 w | "Primarily for reading socket #s in Pup headers" b0 _ self at: i. b1 _ self at: i+1. b2 _ self at: i+2. w _ self at: i+3. "Following sequence minimizes LargeInteger arithmetic for small results." b2=0 ifFalse: [w _ (b2 bitShift: 8) + w]. b1=0 ifFalse: [w _ (b1 bitShift: 16) + w]. b0=0 ifFalse: [w _ (b0 bitShift: 24) + w]. ^w!doubleWordAt: i put: value "Set the value of the double word (4 bytes) starting at byte index i." | w | "Primarily for setting socket #s in Pup headers" w _ value truncated. self at: i put: (w digitAt: 4). self at: i + 1 put: (w digitAt: 3). self at: i + 2 put: (w digitAt: 2). self at: i + 3 put: (w digitAt: 1)!replaceFrom: start to: stop with: replacement startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the collection, replacement. Answer the receiver." (replacement isKindOf: ByteArray) ifTrue: [self primReplaceFrom: start to: stop with: replacement startingAt: repStart] ifFalse: [super replaceFrom: start to: stop with: replacement startingAt: repStart]!replaceFrom: start to: stop withString: aString startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the string, aString. Answer the receiver." | index repOff | <primitive: 105> repOff _ repStart - start. index _ start - 1. [(index _ index + 1) <= stop] whileTrue: [self at: index put: (aString at: repOff + index) asInteger]!wordAt: i "Answer the value of the word (2 bytes) starting at index i." | j | j _ i + i. ^((self at: j - 1) bitShift: 8) + (self at: j)!wordAt: i put: v "Set the value of the word (2 bytes) starting at index i." | j | j _ i + i. self at: j - 1 put: ((v bitShift: -8) bitAnd: 8r377). self at: j put: (v bitAnd: 8r377)! !!ByteArray methodsFor: 'converting'!asString ^(String new: self size) replaceFrom: 1 to: self size withByteArray: self startingAt: 1!packBits: fieldSize into: byteArray "Pack the low order fieldSize bits of the receiver's bytes into the bytes of byteArray." ^self packBits: fieldSize startBit: 8-fieldSize into: byteArray!packBits: fieldSize startBit: fieldStart into: byteArray "Pack fieldSize bits of the receiver's bytes into the bytes of byteArray. fieldSize must be 1, 2, 4, or 8. fieldStart is the bit offset of the field within the byte (8-fieldSize for low order bits). The receiver's size must be a multiple of 16/fieldSize. byteArray's size must be even. Answers the packed array." | unpackedForm packedForm sourceX destX bitBlt fieldsPerWord ht | fieldsPerWord _ 16//fieldSize. ht _ self size//fieldsPerWord. unpackedForm _ Form new extent: fieldsPerWord*8@ht offset: 0@0 bits: self. packedForm _ Form new extent: 16@ht offset: 0@0 bits: byteArray. bitBlt _ BitBlt destForm: packedForm sourceForm: unpackedForm halftoneForm: nil combinationRule: Form over destOrigin: 0@0 sourceOrigin: 0@0 extent: fieldSize@ht clipRect: (0@0 corner: 16@ht). sourceX _ fieldStart. destX _ 0. fieldsPerWord timesRepeat: [bitBlt sourceX: sourceX; destX: destX; copyBits. sourceX _ sourceX + 8. destX _ destX + fieldSize]. ^byteArray!unpackBits: fieldSize into: byteArray "Unpack the packed bit fields of the receiver's bytes into the low order fieldSize bits of byteArray twice as large. fieldSize must be 1, 2, 4, or 8. The receiver's size must be even. byteArray's size must be a multiple of 16/fieldSize. Answers the unpacked array." | unpackedForm packedForm sourceX destX bitBlt fieldsPerWord ht | fieldsPerWord _ 16//fieldSize. ht _ self size//2. unpackedForm _ Form new extent: fieldsPerWord*8@ht offset: 0@0 bits: byteArray. packedForm _ Form new extent: 16@ht offset: 0@0 bits: self. bitBlt _ BitBlt destForm: unpackedForm sourceForm: packedForm halftoneForm: nil combinationRule: Form over destOrigin: 0@0 sourceOrigin: 0@0 extent: fieldSize@ht clipRect: unpackedForm boundingBox. sourceX _ 0. destX _ 8-fieldSize. fieldsPerWord timesRepeat: [bitBlt sourceX: sourceX; destX: destX; copyBits. sourceX _ sourceX + fieldSize. destX _ destX + 8]. ^byteArray! !!ByteArray methodsFor: 'private'!defaultElement ^0!primReplaceFrom: start to: stop with: replacement startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the collection, replacement. Answer the receiver. No range checks are performed - this may be primitively implemented." <primitive: 105> super replaceFrom: start to: stop with: replacement startingAt: repStart! ! ParseNode subclass: #CascadeNode instanceVariableNames: 'receiver messages ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!CascadeNode comment: 'The first message has the common receiver, the rest have receiver == nil, which signifies cascading.'!!CascadeNode methodsFor: 'initialize-release'!receiver: receivingObject messages: msgs "user show: 'abc'; tab; show: 'abc'; cr" receiver _ receivingObject. messages _ msgs! !!CascadeNode methodsFor: 'code generation'!emitForValue: stack on: aStream receiver emitForValue: stack on: aStream. 1 to: messages size - 1 do: [:i | aStream nextPut: Dup. stack push: 1. (messages at: i) emitForValue: stack on: aStream. aStream nextPut: Pop. stack pop: 1]. messages last emitForValue: stack on: aStream!sizeForValue: encoder | size | size _ (receiver sizeForValue: encoder) + (messages size - 1 * 2). messages do: [:aMessage | size _ size + (aMessage sizeForValue: encoder)]. ^size! !!CascadeNode methodsFor: 'printing'!printOn: aStream indent: level receiver printOn: aStream indent: level precedence: 0. 1 to: messages size do: [:i | (messages at: i) printOn: aStream indent: level. i < messages size ifTrue: [aStream nextPut: $;]]! ! Object subclass: #Change instanceVariableNames: 'file position ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!Change comment:'I represent a single change of some kind. I have many subclasses for specific kinds of changes. The text which represents me is a chunk of a file starting at a particular position.Since so many kinds of changes are related to classes, categories, and methods, there are dummy accessing methods for these parameters in class Change.Instance variables: file <FileStream> position <Integer>'!!Change methodsFor: 'initialize'!file: aFileStream position: anInteger file _ aFileStream. position _ anInteger! !!Change methodsFor: 'accessing'!category ^''!className ^''!classObject "Return the class in the present system referenced by my className" ^nil!defaultName: initialString "The default name is the first few characters of the text." | text cr | text _ WriteStream on: (String new: 50). text nextPutAll: initialString. cr _ Character cr. self text do: [:char | (char = cr or: [text position >= 40]) ifTrue: [text nextPutAll: ' ...'. ^text contents]. text nextPut: char]. ^text contents!name "Return the name which should appear in the list view." self subclassResponsibility!parameters "Return the parameters used for the 'same as' test" self subclassResponsibility!selector ^''!text file position: position. ^file nextChunk!text: aString | tempStream | tempStream _ ReadWriteStream on: (String new: aString size + 20). tempStream nextChunkPut: aString. tempStream position: 0. "Needed to set readLimit = writePosition" file _ ReadStream on: tempStream contents. position _ 0!values "Return the value to be used for the 'same as' filter" ^Array with: self class with: self parameters! !!Change methodsFor: 'file accessing'!file ^file!fileName (file isKindOf: FileStream) ifTrue: [^file name] ifFalse: [^'some local stream']! !!Change methodsFor: 'checking'!checkWith: aConflictChecker "This is a default, most subclasses do something more intelligent." aConflictChecker addDoIt: self! !!Change methodsFor: 'fileIn/Out'!fileIn ^Compiler evaluate: self text logged: true!fileOutOn: aStream "Default, subclasses may do something different" aStream nextChunkPut: self text; cr; cr!fileOutOn: aStream previous: previousChange next: nextChange "Default, subclasses may be able to encode runs more compactly" self fileOutOn: aStream! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Change class instanceVariableNames: ''!!Change class methodsFor: 'instance creation'!file: f position: p ^super new file: f position: p! ! StringHolderController subclass: #ChangeController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Changes'!ChangeController comment:'I am the text view controller for a change browser.'!!ChangeController methodsFor: 'menu messages'!accept model isUnlocked ifTrue: [^view flash]. self controlTerminate. "Submit the new contents to the model for validation before accepting." (model contents: paragraph string notifying: self) ifTrue: [super accept]. self controlInitialize! ! StringHolder subclass: #ChangeList instanceVariableNames: 'listName changes selectionIndex list filter removed filterList filterKey changeDict doItDict checkSystem fieldList ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Changes'!ChangeList comment:'I know how to scan a changes file and produce Change objects from it. I also function as a model for a ListView.Instance variables: listName <String> "label for browser, the set of files that I have read" changes <OrderedCollection of: Change> "my underlying collection of changes" selectionIndex <Integer> "currently selected change, or 0 if none" currentChange <String> "text of current selection" list <OrderedCollection of: Change> "filtered collection of changes" filter <BlockContext> "filter predicate" removed <Set> "removed changes" filterList <Array of: Symbol> "individual filters, or nil" filterKey <Change> "the change supplying the key value(s) for the filter(s)" changeDict <Dictionary from: Symbol to: (OrderedCollection of: Change)> "cross-index for conflict detection" doItDict <Dictionary from: String to: (OrderedCollection of: Change)> "cross-index for conflict detection" fieldList <Array of: Symbol> "individual field options, or nil" '!!ChangeList methodsFor: 'initialize-release'!addChanges: changedMessages ChangeScanner new scanChangedMessages: changedMessages do: [:change | changes add: change]. self updateList!addChangeSet: aChangeSet self addChanges: aChangeSet changedMessageList!initialize super initialize. listName _ ''. changes _ OrderedCollection new. list _ OrderedCollection new. selectionIndex _ 0. filter _ [:change | true]. removed _ Set new. filterList _ #(). fieldList _ #()!recoverFile: aFileStream "Recover all the changes from a .changes file since the last snapshot" | position | position _ self findLast: '''----SNAPSHOT----''!!' in: aFileStream. position isNil ifTrue: [position _ 0]. aFileStream position: position. self scanFile: aFileStream!release "break BlockContext cycles" filter _ nil. filterList _ #()!scanFile: aFileStream ChangeScanner new scanFile: aFileStream do: [:change | changes add: change]. listName size = 0 ifTrue: [listName _ aFileStream name] ifFalse: [listName _ listName, ' ..']. self updateList!scheduleMessageBrowser | change | selectionIndex > 0 ifTrue: [change _ list at: selectionIndex. (change isKindOf: MethodDefinitionChange) ifTrue: [^BrowserView openListBrowserOn: (Array with: change name) label: 'current definition']]. ^nil! !!ChangeList methodsFor: 'accessing'!contents: newText notifying: requestor | oldChange newChange | selectionIndex = 0 ifTrue: [^false]. oldChange _ list at: selectionIndex. newChange _ oldChange accept: newText notifying: requestor. newChange isNil ifTrue: [^false]. list at: selectionIndex put: newChange. changes at: (changes indexOf: oldChange) put: newChange. self contents: newText. self changed: #list!filterCopy ^self class new listName: '(', self listName, ')' changes: list removed: (list select: [:c | removed includes: c])!hasRemoved: index ^index > 0 and: [index <= list size and: [removed includes: (list at: index)]]!list | name | ^list collect: [:c | name _ nil. fieldList do: [:f | f == nil ifFalse: [f _ c perform: f. f == nil ifFalse: [name == nil ifTrue: [name _ WriteStream on: (String new: 50)]. name nextPut: $(; nextPutAll: f; nextPutAll: ') ']]]. name == nil ifTrue: [c name] ifFalse: [name nextPutAll: c name. name contents]]!listName listName size = 0 ifTrue: [^'Changes'] ifFalse: [^listName]!listSize ^list size! !!ChangeList methodsFor: 'selecting'!contents: aString "ignore"!deselect selectionIndex _ 0. contents _ ''!listIndex ^selectionIndex!selection selectionIndex > 0 ifTrue: [^(list at: selectionIndex) text]!toggleListIndex: anInteger selectionIndex = anInteger ifTrue: [self deselect] ifFalse: [selectionIndex _ anInteger. contents _ self selection]. self changed: #listIndex! !!ChangeList methodsFor: 'filter'!hasFilter: index ^index <= filterList size and: [(filterList at: index) notNil]!switchFilter: index perform: aSymbol index > filterList size ifTrue: [filterList _ filterList , (Array new: index - filterList size)]. (filterList at: index) isNil ifTrue: [selectionIndex > 0 ifTrue: [filterKey _ list at: selectionIndex. filterList at: index put: aSymbol]] ifFalse: [filterList at: index put: nil]. self updateList! !!ChangeList methodsFor: 'showing'!showingField: index ^index <= fieldList size and: [(fieldList at: index) notNil]!switchField: index perform: aSymbol index > fieldList size ifTrue: [fieldList _ fieldList , (Array new: index - fieldList size)]. (fieldList at: index) isNil ifTrue: [fieldList at: index put: aSymbol] ifFalse: [fieldList at: index put: nil]. self updateSelection: selectionIndex! !!ChangeList methodsFor: 'removing'!forget changes _ changes select: [:c | (removed includes: c) not]. removed _ Set new. self updateList!removeAll removed addAll: list!removeCurrent selectionIndex > 0 ifTrue: [removed add: (list at: selectionIndex)]!restoreAll list do: [:change | removed remove: change ifAbsent: []]!restoreCurrent selectionIndex > 0 ifTrue: [removed remove: (list at: selectionIndex) ifAbsent: []]! !!ChangeList methodsFor: 'checking'!checkWith: aConflictChecker list do: [:change | (removed includes: change) ifFalse: [change checkWith: aConflictChecker]]!checkWithSystem: aBoolean changeDict _ Dictionary new. doItDict _ Dictionary new. checkSystem _ aBoolean. list do: [:change | (removed includes: change) ifFalse: [change checkWith: self]]! !!ChangeList methodsFor: 'checking-Change'!addDoIt: aChange | fileName | fileName _ aChange fileName. (doItDict at: fileName ifAbsent: [doItDict at: fileName put: OrderedCollection new]) add: aChange!changesAt: changeName ^changeDict at: changeName ifAbsent: [#()]!changesAt: changeName add: aChange (changeDict at: changeName ifAbsent: [changeDict at: changeName put: OrderedCollection new]) add: aChange!checkSystem ^checkSystem!equalWithoutComments: text1 and: text2 | stream1 stream2 t | stream1 _ ReadStream on: text1. stream2 _ ReadStream on: text2. [(t _ self nextNonComment: stream1) = (self nextNonComment: stream2)] whileTrue: [t == nil ifTrue: [^true]]. ^false! !!ChangeList methodsFor: 'checking-reporting'!reportConflictsByClassWithExtension: extension "report conflicts among the changes" self reportChangesOn: nil extension: extension. ^self finishReportOn: (Disk file: 'DoIts', extension)!reportConflictsOn: aStream "report conflicts among the changes" self reportChangesOn: aStream extension: nil. ^self finishReportOn: aStream! !!ChangeList methodsFor: 'checking-private'!finishReportOn: aStream "report conflicts among the changes" | cr previous terminator | cr _ Character cr. terminator _ $!!. doItDict associationsDo: [:aDoIt | aStream cr; nextChunkPut: '"*** DoIts in ', aDoIt key, ' ***"'; cr; cr. aDoIt value do: [:doit | self tabText: doit text on: aStream] ]. aStream isEmpty ifTrue: [Transcript show: '*** no conflicts ***'. aStream nextChunkPut: '"*** no conflicts ***"'; cr]. ^aStream close!nextNonComment: sourceStream "Return the next item from the sourceStream (assumed not atEnd), carefully ignoring comments and separators." | char sepr | sepr _ false. [true] whileTrue: [sourceStream atEnd ifTrue: [^nil]. char _ sourceStream peek. char = $$ ifTrue: [sourceStream next. ^sourceStream next]. "catch chars/strings" char = $' ifTrue: [^String readFrom: sourceStream]. char = $" ifTrue: [sourceStream next; skipTo: $". sepr _ true] ifFalse: [char isSeparator ifTrue: [sourceStream skipSeparators. sepr _ true] ifFalse: [sepr ifTrue: [^Character space]. sourceStream next. ^char]]]!reportChangesOn: reportStream extension: extension "report conflicts among the changes" | aStream contendors oldText | aStream _ reportStream. changeDict keys asSortedCollection do: [:change | contendors _ changeDict at: change. contendors size > 1 ifTrue: [extension == nil ifFalse: [aStream _ Disk file: ((change copyUpTo: $ ) copyWithout: $ ), extension. aStream setToEnd]. aStream cr; nextChunkPut: '"*** conflict: ', change, ' ***"'; cr. oldText _ '...'. contendors do: [:contendor | oldText _ self writeContendor: contendor on: aStream oldText: oldText]. extension == nil ifFalse: [aStream close]] ].!tabText: text on: aStream "report conflicts among the changes" | cr previous terminator | cr _ Character cr. terminator _ $!!. previous _ cr. text do: [:char | char = cr ifFalse: [previous = cr ifTrue: [aStream tab]]. aStream nextPut: (previous _ char). char = terminator ifTrue: [aStream nextPut: char]]. aStream nextPut: terminator; cr!writeContendor: source on: aStream oldText: oldText "write out the change" | text method endComment code | aStream cr; nextChunkPut: '"File: ', source fileName, '"'; cr. text _ source text. (source isKindOf: MethodDefinitionChange) ifFalse: [self tabText: text on: aStream. ^oldText]. method _ ReadStream on: text. method skipSeparators; skipTo: Character cr; skipSeparators. "skip header" (method peekFor: $") ifTrue: [method skipTo: $"; skipSeparators]. endComment _ method position. code _ method nextChunk. (self equalWithoutComments: code and: oldText) ifTrue: [method reset. aStream cr; nextPutAll: (method next: endComment); nextPutAll: '[SAME CODE AS ABOVE]'; cr] ifFalse: [aStream cr; nextChunkPut: text; cr]. ^code! !!ChangeList methodsFor: 'lock access'!isUnlocked ^true!lock "ignore"!unlock "ignore"! !!ChangeList methodsFor: 'fileIn/Out'!doThis selectionIndex > 0 ifTrue: [(list at: selectionIndex) fileIn]!doThis: listIndex (list at: listIndex) fileIn!fileOutOn: aFile | previous current | list do: [:next | (removed includes: next) ifFalse: [current == nil ifFalse: [current fileOutOn: aFile previous: previous next: next]. previous _ current. current _ next]]. current == nil ifFalse: [current fileOutOn: aFile previous: previous next: nil]! !!ChangeList methodsFor: 'private'!addFilter: aSymbol | value oldFilter | value _ filterKey perform: aSymbol. filter isNil ifTrue: [filter _ [:change | (change perform: aSymbol) = value]] ifFalse: [oldFilter _ filter. filter _ [:change | (oldFilter value: change) and: [(change perform: aSymbol) = value]]]!findLast: aString in: aStream "Return the position in the stream of the end of the last occurrence of aString (presumably a snapshot message)" | firstChar endPosition position count index lastEnd | firstChar _ aString first. aStream setToEnd. position _ aStream position. [endPosition _ position. lastEnd == nil and: [(position _ endPosition - 5000 max: 0) < endPosition]] whileTrue: [aStream position: position. count _ endPosition - position. [count > 0] whileTrue: [count _ count - 1. aStream next = firstChar ifTrue: [index _ 2. [index <= aString size and: [(aString at: index) = aStream next]] whileTrue: [index _ index + 1]. index > aString size ifTrue: [lastEnd _ aStream position] ifFalse: [aStream position: endPosition - count]]]]. ^lastEnd!listName: aString changes: aChangeCollection removed: aSet listName _ aString. changes addAll: aChangeCollection. list addAll: aChangeCollection. removed addAll: aSet!updateList | oldChange newIndex | selectionIndex > 0 ifTrue: [oldChange _ list at: selectionIndex]. filter _ nil. filterList do: [:aSymbol | aSymbol notNil ifTrue: [self addFilter: aSymbol]]. filter isNil ifTrue: [filter _ [:change | true]]. list _ changes select: [:change | filter value: change]. newIndex _ oldChange == nil ifTrue: [0] ifFalse: [list indexOf: oldChange]. self updateSelection: newIndex!updateSelection: newIndex self deselect. self changed: #list. newIndex > 0 ifTrue: [self toggleListIndex: newIndex]! ! LockedListController subclass: #ChangeListController instanceVariableNames: '' classVariableNames: 'ChangeListYellowButtonMenu ChangeListYellowButtonMessages ' poolDictionaries: '' category: 'Interface-Changes'!ChangeListController comment:'I am the controller for ChangeListView, handling the list menu.'!!ChangeListController methodsFor: 'initialize-release'!initialize super initialize. self initializeYellowButtonMenu! !!ChangeListController methodsFor: 'menu messages'!browse "Create and schedule a list browser containing only the displayed items." self controlTerminate. model scheduleMessageBrowser. self controlInitialize!check self controlTerminate. self checkWithSystem: false. self controlInitialize!checkWithSystem self controlTerminate. self checkWithSystem: true. self controlInitialize!checkWithSystem: aBoolean self getFile: #file: withPrompt: 'type name of file on which to write confilicts' do: [:aFile | Cursor execute showWhile: [model checkWithSystem: aBoolean]. Cursor write showWhile: [model reportConflictsOn: aFile]. aFile shorten; close]!copyView "Create and schedule a list browser containing only the displayed items. Accessed by choosing the menu command clone." self controlTerminate. ChangeListView openOn: model filterCopy!doAll self controlTerminate. self doFrom: 1. self controlInitialize!doFrom: firstIndex "Reset selection each time through the loop, so that if an error occurs, the selection is left at the item which caused it." firstIndex to: model listSize do: [:index | (model hasRemoved: index) ifFalse: [model toggleListIndex: index. model doThis: index]]!doThis self controlTerminate. model doThis. self controlInitialize!fileIn self controlTerminate. self getFile: #oldFile: withPrompt: 'type name of file for reading' do: [:aFile | aFile readOnly. model scanFile: aFile. aFile close]. self controlInitialize!fileOut self controlTerminate. self getFile: #file: withPrompt: 'type name of file for writing' do: [:aFile | model fileOutOn: aFile. aFile shorten; close]. self controlInitialize!forget self controlTerminate. Cursor execute showWhile: [model forget]. self controlInitialize!getChanges self controlTerminate. model addChangeSet: Smalltalk changes. self controlInitialize!recover self controlTerminate. model recoverFile: (SourceFiles at: 2). self changeLabel. self controlInitialize!removeAll self controlTerminate. view deselect. model removeAll. view displaySelectionBox. self controlInitialize!removeItem view deselect. model removeCurrent. view displaySelectionBox!restoreAll view deselect. model restoreAll. view displaySelectionBox!restoreItem view deselect. model restoreCurrent. view displaySelectionBox! !!ChangeListController methodsFor: 'scrolling'!scrollView: anInteger | viewList maximumAmount minimumAmount amount | viewList _ view list. maximumAmount _ viewList clippingRectangle top - viewList compositionRectangle top max: 0. minimumAmount _ viewList clippingRectangle bottom - viewList compositionRectangle bottom min: 0. amount _ (anInteger min: maximumAmount) max: minimumAmount. amount ~= 0 ifTrue: [view deselect. viewList scrollBy: amount negated. view displaySelectionBox]! !!ChangeListController methodsFor: 'private'!changeLabel | superView | "This method accesses the label with a terrible kludge. It would be better if the label were a view of its own, but there would still be problems." superView _ view superView. Display gray: superView labelDisplayBox. superView label: model listName. superView displayView!changeModelSelection: anInteger model toggleListIndex: anInteger!getFile: aSymbol withPrompt: promptString do: actionBlock "find out the file name" | fixedBlock fileName directory end | fixedBlock _ actionBlock fixTemps. FillInTheBlank request: promptString displayAt: Sensor cursorPoint centered: true action: [:fileName | fileName] initialAnswer: ''. fileName isEmpty ifFalse: [directory _ Disk. (directory isLegalFileName: fileName) ifTrue: [Cursor wait showWhile: [actionBlock value: (directory perform: aSymbol with: fileName)]] ifFalse: [Transcript cr; show: 'You specified an illegal file name.']]!initializeYellowButtonMenu self yellowButtonMenu: ChangeListYellowButtonMenu yellowButtonMessages: ChangeListYellowButtonMessages.! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ChangeListController class instanceVariableNames: ''!!ChangeListController class methodsFor: 'class initialization'!initialize "ChangeListController initialize" ChangeListYellowButtonMenu _ PopUpMenu labels:'file infile outrecover last changesdisplay system changesdo allremove allrestore allspawn allforgetdo itremove itrestore itspawn itcheck conflictscheck with system' lines: #( 4 8 9 13 ). ChangeListYellowButtonMessages _ #(fileIn fileOut recover getChanges doAll removeAll restoreAll copyView forget doThis removeItem restoreItem browse check checkWithSystem)! !ChangeListController initialize! ListView subclass: #ChangeListView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Changes'!ChangeListView comment:'I am a list view of various system changes.'!!ChangeListView methodsFor: 'initialize-release'!release model release. super release! !!ChangeListView methodsFor: 'model access'!model: aChangeList super model: aChangeList. self list: model list. selection _ model listIndex.! !!ChangeListView methodsFor: 'controller access'!defaultControllerClass ^ChangeListController! !!ChangeListView methodsFor: 'selecting'!deselect super deselect. self reverseRemoved!displaySelectionBox self reverseRemoved. super displaySelectionBox!reverseRemoved | box line | self selectionInterval do: [:index | (model hasRemoved: index) ifTrue: [box _ self selectionBox: index. line _ Rectangle origin: box leftCenter - (0@1) extent: box width @ 2. Display reverse: (line intersect: self clippingBox)]]!selectionBox: listIndex "Answer the rectangle in which a particular selection is displayed." ^(self insetDisplayBox left @ (list compositionRectangle top + (self selectionBoxOffset: listIndex)) extent: self insetDisplayBox width @ list lineGrid) insetBy: (Rectangle left: 1 right: 1 top: 1 bottom: 0)!selectionBoxOffset: listIndex "Answer an integer that determines the y position for the display box of a particular selection." ^(listIndex - 1 + self minimumSelection - 1) * list lineGrid!selectionIndex: yPosition "Answer the selection index corresponding to a particular Y coordinate." ^(yPosition - list compositionRectangle top) // list lineGrid - self minimumSelection + 2!selectionInterval "Answer the currently visible range of selection indices." ^((self selectionIndex: self insetDisplayBox top) max: 1) to: ((self selectionIndex: self insetDisplayBox bottom) min: model listSize)! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ChangeListView class instanceVariableNames: ''!!ChangeListView class methodsFor: 'instance creation'!open "Open a view for changes files. Starts as an empty template." self openOn: ChangeList new "ChangeListView open"!openOn: aChangeList "schedule a change browser" | topView aChangeListView aChangeView alignPoint | topView _ StandardSystemView new model: aChangeList. topView label: aChangeList listName. topView minimumSize: 180@180. aChangeListView _ self new. aChangeListView model: aChangeList. aChangeListView window: (0@0 extent: 180@120). aChangeListView insideColor: Form white. aChangeListView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. topView addSubView: aChangeListView. alignPoint _ self openSwitches: #( ('show file' showingField: (1) switchField:perform: (1 fileName) 90) ('show category' showingField: (2) switchField:perform: (2 category) 90) ) topView: topView at: aChangeListView viewport bottomLeft model: aChangeList. alignPoint _ self openSwitches: #( (file hasFilter: (1) switchFilter:perform: (1 file) 30) (type hasFilter: (2) switchFilter:perform: (2 class) 30) (class hasFilter: (3) switchFilter:perform: (3 className) 30) (category hasFilter: (4) switchFilter:perform: (4 category) 30) (selector hasFilter: (5) switchFilter:perform: (5 selector) 30) (same hasFilter: (6) switchFilter:perform: (6 values) 30) ) topView: topView at: alignPoint model: aChangeList. aChangeView _ StringHolderView new. aChangeView model: aChangeList. aChangeView controller: ChangeController new. aChangeView window: (0@0 extent: 180@240). aChangeView insideColor: Form white. aChangeView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView addSubView: aChangeView align: aChangeView viewport topLeft with: alignPoint. topView controller open.!recover "Open a view of the current changes file since the last snapshot." self openOn: (ChangeList new recoverFile: (SourceFiles at: 2)) "ChangeListView recover"! !!ChangeListView class methodsFor: 'examples'!example "recover is an example, access other change files through the menu commands of a ChangeListView, or choose a recovery file to replace the following expression form ChangeListView openOn: (ChangeList new recoverFile: (Disk file: 'filename')) "! !!ChangeListView class methodsFor: 'private'!openSwitches: parameters topView: topView at: initialPoint model: aChangeList "Define a related group of switches" | aSwitchView alignPoint leftBorder | alignPoint _ initialPoint. leftBorder _ 2. parameters do: [:args | [:label :viewSelector :viewArguments :controllerSelector :controllerArguments :width | aSwitchView _ SwitchView new. aSwitchView model: aChangeList. aSwitchView controller: LockedSwitchController new. aSwitchView borderWidthLeft: leftBorder right: 2 top: 2 bottom: 0. aSwitchView selector: viewSelector. aSwitchView arguments: viewArguments. aSwitchView controller selector: controllerSelector. aSwitchView controller arguments: controllerArguments. aSwitchView window: (0 @ 0 extent: width @ 25). aSwitchView label: label asParagraph. topView addSubView: aSwitchView align: aSwitchView viewport topLeft with: alignPoint. alignPoint _ aSwitchView viewport topRight. leftBorder _ 0. ] valueWithArguments: args]. ^initialPoint x @ aSwitchView viewport bottom! ! Scanner subclass: #ChangeScanner instanceVariableNames: 'file chunkString ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ChangeScanner comment:'I know how to parse a file into a collection of changes.'!!ChangeScanner methodsFor: 'initialize'!initChangeScanner chunkString _ String new: 200! !!ChangeScanner methodsFor: 'change set scanning'!scanChangedMessages: changedMessages do: aBlock | selector change className remoteSource class category | changedMessages do: [:aString | super scan: (ReadStream on: aString). (className _ self nextClass) notNil ifTrue: [(selector _ self nextSelector) notNil ifTrue: [change _ MethodDefinitionChange new className: className; selector: selector. (className includes: Character space) ifTrue: [class _ (Smalltalk at: (className copyUpTo: Character space) asSymbol) class] ifFalse: [class _ Smalltalk at: className asSymbol]. category _ class whichCategoryIncludesSelector: selector. category == nil ifTrue: [category _ 'As yet unclassified']. change category: category. change getSource. aBlock value: change]]]! !!ChangeScanner methodsFor: 'file scanning'!scanFile: aFile do: aBlock "Evaluate aBlock with each item on the file" | position | file _ aFile. [file skipSeparators. file atEnd] whileFalse: [file peek = $!! ifTrue: [file next. super scan: self nextChunkStream. self scanSpecialDo: aBlock] ifFalse: [position _ file position. self scanExpression: self nextChunkStream do: [:item | aBlock value: (item file: file position: position)]]]!scanMethodsClass: class category: category do: aBlock | position method selector | [file skipSeparators. position _ file position. (method _ self nextChunkStream) atEnd] whileFalse: [method _ method contents. selector _ Parser new parseSelector: method. selector notNil ifTrue: [aBlock value: ((MethodDefinitionChange file: file position: position) className: class; selector: selector; category: category)]]!scanSpecialDo: aBlock "Scan a chunk of file beginning with a !!. For now, the only thing I understand is method definitions." | class category | (class _ self nextClass) notNil ifTrue: [(tokenType == #keyword and: [token = 'methodsFor:']) ifTrue: [self scanToken. tokenType == #string ifTrue: [category _ token. self scanToken. tokenType == #doIt ifTrue: [^self scanMethodsClass: class category: category asSymbol do: aBlock]]]]. "I don't understand what's on the file. Scan for a blank chunk and hope for the best." [self nextChunkStream atEnd] whileFalse: []! !!ChangeScanner methodsFor: 'expression scanning'!scanClassDefinition: classType className: superName do: aBlock "Scan a presumed class definition. The classType is the first keyword of the class defining message (subclass:, variableSubclass:, etc.)" | newName parameters | (tokenType == #literal and: [token isKindOf: Symbol]) ifFalse: [^nil]. newName _ token. parameters _ #('instanceVariableNames:' 'classVariableNames:' 'poolDictionaries:' 'category:') collect: [:keyword | self scanToken. (tokenType == #keyword and: [token = keyword]) ifFalse: [^nil]. self scanToken. tokenType == #string ifFalse: [^nil]. token]. self scanToken. ^aBlock value: (ClassDefinitionChange new className: newName; superclassName: superName classType: classType otherParameters: parameters)!scanClassExpression: class do: aBlock "Scan an expression beginning with a class name. This might be a class definition, a class removal, a class comment change, a class initialization, a method removal, or a doIt." | firstToken selector newName | firstToken _ token. self scanToken. firstToken = 'removeSelector:' ifTrue: [(tokenType == #literal and: [token isKindOf: Symbol]) ifTrue: [selector _ token. self scanToken. ^aBlock value: (MethodOtherChange new className: class; selector: selector; type: #remove)]]. firstToken = 'rename:' ifTrue: [(tokenType == #literal and: [token isKindOf: Symbol]) ifTrue: [newName _ token. self scanToken. aBlock value: (ClassOtherChange new className: class; type: #rename). ^aBlock value: (ClassOtherChange new className: newName; type: 'rename to' asSymbol)]]. firstToken = 'comment:' ifTrue: [tokenType == #string ifTrue: [self scanToken. ^aBlock value: (ClassCommentChange new className: class)]]. (#('subclass:' 'variableSubclass:' 'variableByteSubclass:' 'variableWordSubclass:') includes: firstToken) ifTrue: [^self scanClassDefinition: firstToken className: class do: aBlock]. firstToken = 'initialize' ifTrue: [^aBlock value: (ClassOtherChange new className: class; type: #initialize)]. firstToken = 'removeFromSystem' ifTrue: [^aBlock value: (ClassOtherChange new className: class; type: #remove)]. firstToken = 'instanceVariableNames:' ifTrue: [tokenType == #string ifTrue: [self scanToken. ^aBlock value: (ClassOtherChange new className: class; type: 'inst vars for' asSymbol)]]. ^nil!scanExpression: aStream do: aBlock "Scan a chunk of file consisting of an expression. This might be a class definition, a class removal, a class comment change, a method removal, or a doIt." | class item | super scan: aStream. ((class _ self nextClass) notNil and: [tokenType == #keyword or: [tokenType == #word]]) ifTrue: [self scanClassExpression: class do: [:item | tokenType == #doIt ifTrue: [aBlock value: item]]]. item == nil ifTrue: [aBlock value: OtherChange new]! !!ChangeScanner methodsFor: 'private'!nextChunkStream "Return a read stream on the next chunk of the file." | chunkStream char terminator | terminator _ $!!. file skipSeparators. chunkStream _ ReadWriteStream on: chunkString. [file atEnd] whileFalse: [char _ file next. char == terminator ifTrue: [(file peekFor: terminator) ifTrue: ["doubled terminator" chunkStream nextPut: char] ifFalse: [chunkStream position: 0. ^chunkStream]] ifFalse: [chunkStream nextPut: char]]. chunkStream position: 0. "Sets read limit to current position" ^chunkStream!nextClass | class | tokenType == #word ifTrue: [class _ token. self scanToken. (tokenType == #word and: [token = 'class']) ifTrue: [class _ (class, ' ', token) asSymbol. self scanToken] ifFalse: [class _ class asSymbol]. ^class]. ^nil!nextSelector | selector | tokenType == #keyword ifTrue: [self scanLitWord]. (tokenType == #word or: [tokenType == #keyword or: [tokenType == #binary]]) ifTrue: [selector _ token. self scanToken]. ^selector! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ChangeScanner class instanceVariableNames: ''!!ChangeScanner class methodsFor: 'instance creation'!new ^super new initChangeScanner! ! Object subclass: #ChangeSet instanceVariableNames: 'classChanges methodChanges classRemoves reorganizeSystem specialDoIts ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ChangeSet comment:'I keep track of the changes made to a system, so I can make an incremental fileOut. I do not remember the order in which changes are made although this sometimes matters.Instance variables: classChanges <Dictionary> {class name -> <Set> {add, change, comment, rename, reorganize, ''oldName: xxx''}} methodChanges <Dictionary> {class name -> <IdentityDictionary> {selector -> add | change | remove}} classRemoves <Set> {class name} reorganizeSystem <Boolean> - indicates if SystemOrganization was changed. specialDoIts <OrderedCollection> of Smalltalk expressions.'!!ChangeSet methodsFor: 'initialize-release'!initialize "Reset the receiver to be empty." classChanges _ Dictionary new. methodChanges _ Dictionary new. classRemoves _ Set new. reorganizeSystem _ false. specialDoIts _ OrderedCollection new.! !!ChangeSet methodsFor: 'testing'!isEmpty "Answer whether the receiver contains any elements." ^(((methodChanges isEmpty and: [classChanges isEmpty]) and: [classRemoves isEmpty]) and: [reorganizeSystem not]) and: [specialDoIts isEmpty]! !!ChangeSet methodsFor: 'converting'!asSortedCollection "Answer a new instance of SortedCollection whose elements are Strings describing the changes represented by the receiver." | summary | summary _ SortedCollection new. classChanges associationsDo: [:clAssoc | clAssoc value do: [:changeType | summary add: clAssoc key, ' - ', changeType]]. methodChanges associationsDo: [:clAssoc | clAssoc value associationsDo: [:mAssoc | summary add: clAssoc key, ' ', mAssoc key, ' - ', mAssoc value]]. classRemoves do: [:name | summary add: name, ' - ', 'remove']. reorganizeSystem ifTrue: [summary add: 'Reorganize System']. specialDoIts isEmpty not ifTrue: [summary add: 'SpecialDoIts - (', specialDoIts size printString, ')']. ^summary! !!ChangeSet methodsFor: 'change management'!addClass: class "Include indication that a new class was created." classRemoves remove: class name ifAbsent: []. self atClass: class add: #add!addDoIt: smalltalkExpression "When filing out changes, append this string to the file." specialDoIts add: smalltalkExpression!changeClass: class "Include indication that a class definition has been changed." self atClass: class add: #change!changedClasses "Answer a collection of the changed or edited classes, not including removed classes." | classes | classes _ Set new. methodChanges keys do: [:className | classes add: (self classNamed: className)]. classChanges keys do: [:className | classes add: (self classNamed: className)]. ^classes!commentClass: class "Include indication that a class comment has been changed." self atClass: class add: #comment!removeClass: class "Include indication that a class has been forgotten." | name | (self isNew: class) ifTrue: [^self removeClassChanges: class]. "only remember old classes" (self atClass: class includes: #rename) "remember as old name" ifTrue: [name _ self oldNameFor: class] ifFalse: [name _ class name]. self removeClassChanges: class. classRemoves add: name!removeClassChanges: class "Remove all memory of changes associated with this class and its metaclass." classChanges removeKey: class name ifAbsent: []. methodChanges removeKey: class name ifAbsent: []. classChanges removeKey: class class name ifAbsent: []. methodChanges removeKey: class class name ifAbsent: []. classRemoves remove: class name ifAbsent: [].!renameClass: class as: newName "Include indication that a class has been renamed." | value | (self atClass: class includes: #rename) ifFalse: [self atClass: class add: 'oldName: ', class name. "only original name matters" self atClass: class add: #rename]. "copy changes using new name (metaclass too)" (Array with: classChanges with: methodChanges) do: [:changes | (value _ changes at: class name ifAbsent: [nil]) == nil ifFalse: [changes at: newName put: value. changes removeKey: class name]. (value _ changes at: class class name ifAbsent: [nil]) == nil ifFalse: [changes at: (newName, ' class') put: value. changes removeKey: class class name]]!reorganizeClass: class "Include indication that a class was reorganized." self atClass: class add: #reorganize!reorganizeSystem "Include indication that the system classes were reorganized." reorganizeSystem _ true! !!ChangeSet methodsFor: 'method changes'!addSelector: selector class: class "Include indication that a method has been added." self atSelector: selector class: class put: #add!changedMessageList "Answer an array that identifies the methods that have been changed. Each entry is a String containing the class name and method selector." | messageList | messageList _ SortedCollection new. methodChanges associationsDo: [:clAssoc | clAssoc value associationsDo: [:mAssoc | mAssoc value = #remove ifFalse: [messageList add: clAssoc key asString, ' ' , mAssoc key]]]. ^messageList asArray!changeSelector: selector class: class "Include indication that a method has been edited." (self atSelector: selector class: class) = #add ifFalse: [self atSelector: selector class: class put: #change] "Don't forget a method is new just because it's been changed"!removeSelector: selector class: class "Include indication that a method has been forgotten." (self atSelector: selector class: class) = #add ifTrue: [self removeSelectorChanges: selector class: class] "Forgot a new method, no-op" ifFalse: [self atSelector: selector class: class put: #remove]!removeSelectorChanges: selector class: class "Remove all memory of changes associated with the argument, selector, in this class." | dictionary | dictionary _ methodChanges at: class name ifAbsent: [^self]. dictionary removeKey: selector ifAbsent: []. dictionary isEmpty ifTrue: [methodChanges removeKey: class name]! !!ChangeSet methodsFor: 'fileIn/Out'!fileOutChangesFor: class on: stream "Write out all the changes the receiver knows about this class." | changes removes | "first file out class changes" self fileOutClassChanges: class on: stream. "next file out changed methods" removes _ OrderedCollection new. changes _ OrderedCollection new. (methodChanges at: class name ifAbsent: [^self]) associationsDo: [:mAssoc | mAssoc value = #remove ifTrue: [removes add: mAssoc key] ifFalse: [changes add: mAssoc key]]. changes isEmpty ifFalse: [class fileOutChangedMessages: changes on: stream. stream cr]. removes do: [:selector | stream nextChunkPut: class name, ' removeSelector: ', selector storeString; cr]. "reintialize metaclass if necessary" ((class isMemberOf: Metaclass) and: [changes includes: #initialize]) ifTrue: [stream nextChunkPut: class soleInstance name, ' initialize'; cr].!fileOutOn: stream "Write out all the changes the receiver knows about." self isEmpty ifTrue: [self notify: 'Warning: no changes to file out']. (ChangeSet superclassOrder: self changedClasses asOrderedCollection) do: [:class | self fileOutChangesFor: class on: stream]. classRemoves do: [:className | stream nextChunkPut: 'Smalltalk removeClassNamed: #', className; cr]. reorganizeSystem ifTrue: [stream cr; nextPut: $!!; nextChunkPut: 'SystemOrganization'; cr. stream nextChunkPut: SystemOrganization printString; cr; cr]. specialDoIts do: [:expression | stream nextChunkPut: expression; cr].! !!ChangeSet methodsFor: 'private'!atClass: class add: changeType (self isNew: class) ifFalse: "new classes don't matter" [(classChanges at: class name ifAbsent: [^classChanges at: class name put: (Set with: changeType)]) add: changeType]!atClass: class includes: changeType ^(classChanges at: class name ifAbsent: [^false]) includes: changeType!atSelector: selector class: class ^(methodChanges at: class name ifAbsent: [^#none]) at: selector ifAbsent: [#none]!atSelector: selector class: class put: changeType | name dict | (self isNew: class) ifTrue: [^self]. "Don't keep method changes for new classes" name _ class name. (methodChanges at: name ifAbsent: [dict _ IdentityDictionary new. methodChanges at: name put: dict. dict]) at: selector put: changeType!classNamed: className "className is either a class name or a class name followed by ' class'. Answer the class or metaclass it names." | meta name class | (className size > 6 and: [(className copyFrom: className size - 5 to: className size) = ' class']) ifTrue: [meta _ true. name _ className copyFrom: 1 to: className size - 6] ifFalse: [meta _ false. name _ className]. class _ Smalltalk at: name asSymbol. meta ifTrue: [^class class] ifFalse: [^class]!fileOutClassChanges: class on: stream "Write out class changes. i.e. new class, definition, comment, renaming." (self atClass: class includes: #add) ifTrue: [stream cr. class fileOutOn: stream. stream cr. ^self atClass: class add: #add "fileOut clears this!!"]. (self atClass: class includes: #rename) ifTrue: [stream nextChunkPut: (self oldNameFor: class), ' rename: #', class name; cr]. (self atClass: class includes: #change) ifTrue: [stream emphasis: 5; nextChunkPut: class definition; cr; emphasis: 1]. (self atClass: class includes: #comment) ifTrue: [class organization putCommentOnFile: stream numbered: nil moveSource: false. stream cr]. (self atClass: class includes: #reorganize) ifTrue: [class fileOutOrganizationOn: stream. stream cr]!isNew: class "Answer whether this class was added since the ChangeSet was cleared." class isMeta ifTrue: [^self atClass: class soleInstance includes: #add "check class"] ifFalse: [^self atClass: class includes: #add]!oldNameFor: class | name | name _ (classChanges at: class name) asOrderedCollection detect: [:x | 'oldName: *' match: x]. ^(Scanner new scanTokens: name) last! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ChangeSet class instanceVariableNames: ''!!ChangeSet class methodsFor: 'instance creation'!new ^super new initialize! !!ChangeSet class methodsFor: 'fileIn/Out'!superclassOrder: classes "Arrange the classes in the collection, classes, in superclass order so the classes can be properly filed in." | aa bb na nb | ^classes asSortedCollection: [:a :b | "find lengths (na, nb) of superclass chains (a, b)" aa _ a. na _ 1. bb _ b. nb _ 1. [(aa _ aa superclass) notNil] whileTrue: [na _ na + 1]. [(bb _ bb superclass) notNil] whileTrue: [nb _ nb + 1]. "follow longer chain to same depth as shorter" na - nb timesRepeat: [a _ a superclass]. nb - na timesRepeat: [b _ b superclass]. "trace back until the chains meet" [(aa _ a superclass) ~~ (bb _ b superclass)] whileTrue: [a _ aa. b _ bb]. a == b ifTrue: [na <= nb] "chains overlap--one is sub*-class of other" ifFalse: [a name <= b name] "alphabetize at the fork" ]! ! Magnitude subclass: #Character instanceVariableNames: 'value ' classVariableNames: 'CharacterTable ' poolDictionaries: '' category: 'Collections-Text'!Character comment: 'This class represents characters by storing their associated ASCII (extended to 256 codes) code. The instances of this class are created uniquely, so that all instances $R (for instance) are identical'!!Character methodsFor: 'comparing'!< aCharacter "Answer true if the receiver's value < aCharacter's value." ^self asciiValue < aCharacter asciiValue!= aCharacter "Answer true if the receiver and the argument are the same object (have the same object pointer) and false otherwise. Optional. See Object documentation whatIsAPrimitive." <primitive: 110> ^self == aCharacter!> aCharacter "Answer true if the receiver's value > aCharacter's value." ^self asciiValue > aCharacter asciiValue!hash ^value! !!Character methodsFor: 'accessing'!asciiValue "Answer the value of the receiver." ^value!digitValue "Answer 0-9 if the receiver is $0-$9, 10-35 if it is $A-$Z, and < 0 otherwise. This is used to parse literal numbers of radix 2-36." value <= $9 asciiValue ifTrue: [^value - $0 asciiValue]. value >= $A asciiValue ifTrue: [value <= $Z asciiValue ifTrue: [^value - $A asciiValue + 10]]. ^-1! !!Character methodsFor: 'testing'!isAlphaNumeric "Answer whether the receiver is a letter or a digit." ^self isLetter or: [self isDigit]!isDigit "Answer whether the receiver is a digit." ^self >= $0 and: [self <= $9]!isLetter "Answer whether the receiver is a letter." ^(8r141 <= value and: [value <= 8r172]) or: [8r101 <= value and: [value <= 8r132]]!isLowercase "Answer whether the receiver is a lowercase letter." ^self >= $a and: [self <= $z]!isSeparator "Answer whether the receiver is one of the separator characters--space, cr, tab, line feed, or form feed." value = 32 ifTrue: [^true]. "space" value = 13 ifTrue: [^true]. "cr" value = 9 ifTrue: [^true]. "tab" value = 10 ifTrue: [^true]. "line feed" value = 12 ifTrue: [^true]. "form feed" ^false!isUppercase "Answer whether the receiver is an uppercase letter." ^self >= $A and: [self <= $Z]!isVowel "Answer whether the receiver is one of the vowels, AEIOU, in upper or lower case." ^'AEIOU' includes: self asUppercase!tokenish "Answer whether the receiver is a valid token-character--letter, digit, or colon." ^self isLetter or: [self isDigit or: [self = $:]]! !!Character methodsFor: 'copying'!copy "Answer with me because Characters are unique."!deepCopy "Answer with me becuase Characters are unique."! !!Character methodsFor: 'printing'!isLiteral ^true!printOn: aStream aStream nextPut: $$. aStream nextPut: self!storeOn: aStream "Character literals are preceded by '$'." aStream nextPut: $$; nextPut: self! !!Character methodsFor: 'converting'!asCharacter "Answer the receiver itself." ^self!asInteger "Answer the value of the receiver." ^value!asLowercase "Answer a Character that is the lower case letter corresponding to the receiver. If the receiver is not an upper case letter, answer the receiver itself." 8r101 <= value ifTrue: [value <= 8r132 ifTrue: [^Character value: value+8r40]]!asSymbol ^Symbol internCharacter: self!asUppercase "Answer a Character that is the upper case letter corresponding to the receiver. If the receiver is not a lower case letter, answer the receiver itself." 8r141 <= value ifTrue: [value <= 8r172 ifTrue: [^Character value: value-8r40]]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Character class instanceVariableNames: ''!!Character class methodsFor: 'class initialization'!initialize "Create the table of unique Characters. This code is not shown so that the user can not destroy the system by trying to recreate the table."! !!Character class methodsFor: 'instance creation'!digitValue: x "Answer the Character whose digit value is x. For example, answer $9 for x=9, $0 for x=0, $A for x=10, $Z for x=35." | index | index _ x truncated. ^CharacterTable at: (index < 10 ifTrue: [48 + index] ifFalse: [55 + index]) + 1!new "Creating new characters is not allowed." self error: 'cannot create new characters'!value: anInteger "Answer the Character whose value is anInteger. Characters are unique; they are stored in the class variable CharacterTable." ^CharacterTable at: anInteger + 1! !!Character class methodsFor: 'accessing untypeable characters'!backspace "Answer the Character representing a backspace." ^self value: 8!cr "Answer the Character representing a carriage return." ^self value: 13!esc "Answer the Character representing an escape." ^self value: 160!newPage "Answer the Character representing a form feed." ^self value: 12!space "Answer the Character representing a space." ^self value: 32!tab "Answer the Character representing a tab." ^self value: 9! !!Character class methodsFor: 'constants'!characterTable "Answer the class variable in which unique Characters are stored." ^CharacterTable! !Character initialize! Rectangle subclass: #CharacterBlock instanceVariableNames: 'stringIndex character ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!CharacterBlock comment: 'CharacterBlocks contain information about displayed characters. They are used to return the results of methods Paragraph characterBlockAtPoint: aPoint and Paragraph characterBlockForIndex: stringIndex.Any recomposition or movement of a Paragraph can make the information obsolete.'!!CharacterBlock methodsFor: 'comparing'!< aCharacterBlock "Answer whether the string index of the receiver precedes that of aCharacterBlock." ^stringIndex < aCharacterBlock stringIndex!<= aCharacterBlock "Answer whether the string index of the receiver does not come after that of aCharacterBlock." ^(self > aCharacterBlock) not!= aCharacterBlock self species = aCharacterBlock species ifTrue: [^stringIndex = aCharacterBlock stringIndex] ifFalse: [^false]!> aCharacterBlock "Answer whether the string index of the receiver comes after that of aCharacterBlock." ^aCharacterBlock < self!>= aCharacterBlock "Answer whether the string index of the receiver does not precede that of aCharacterBlock." ^(self < aCharacterBlock) not! !!CharacterBlock methodsFor: 'copying'!copy ^self deepCopy! !!CharacterBlock methodsFor: 'accessing'!character "Answer the character in the receiver." ^character!stringIndex "Answer the position of the receiver in the string it indexes." ^stringIndex! !!CharacterBlock methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'a CharacterBlock with index '. stringIndex printOn: aStream. aStream nextPutAll: ' and character '. character printOn: aStream. aStream nextPutAll: ' and rectangle '. super printOn: aStream! !!CharacterBlock methodsFor: 'private'!newStringIndex: anInteger Character: aCharacter BoundingRectangle: aRectangle stringIndex _ anInteger. character _ aCharacter. super origin: aRectangle topLeft. super corner: aRectangle corner!newStringIndex: anInteger Character: aCharacter TopLeft: originPoint Extent: extentPoint stringIndex _ anInteger. character _ aCharacter. super origin: originPoint. super extent: extentPoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!CharacterBlock class instanceVariableNames: ''!!CharacterBlock class methodsFor: 'instance creation'!stringIndex: anInteger character: aCharacter boundingRectangle: aRectangle "Answer an instance of me with values set to the arguments." ^self new newStringIndex: anInteger Character: aCharacter BoundingRectangle: aRectangle!stringIndex: anInteger character: aCharacter topLeft: originPoint extent: extentPoint "Answer an instance of me with values set to the arguments." ^self new newStringIndex: anInteger Character: aCharacter TopLeft: originPoint Extent: extentPoint! ! CharacterScanner subclass: #CharacterBlockScanner instanceVariableNames: 'characterPoint characterIndex lastCharacter lastCharacterExtent lastSpaceOrTabExtent nextLeftMargin ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!CharacterBlockScanner comment:'Instance Variables characterPoint<Point> Used in character location domain. The topLeft of the character to be returned in a CharacterBlock. characterIndex<Integer> Used in character location domain. The index in the stylizedString of the character to be returned in a CharacterBlock. lastCharacter<Character> Used in character location domain. The character to be returned in a CharacterBlock. lastCharacterExtent<Point> Used in character location domain. The extent of the character to be returned in a CharacterBlock. The height is usually the stringStyle*s lineGrid. lastSpaceOrTabExtent<Point> Used in character location domain. If the lastCharacter is a space or a tab, this will be its extent, an unexpected value when justification is turned on, and a variable value in the case of tab no matter what the alignment value is. nextLeftMargin<Integer> When, as in the case of cr, the left margin of the succeeding line is what is desired, this value, known to the paragraph is needed. Since the paragraph is not available to the stop conditions, this value is set when the line of the character is discovered and before access to the paragraph is lost.CharacterBlockScanners are used to scan text to compute the CharacterBlock for a character specified by its index in the text or its proximity to the cursor location'!!CharacterBlockScanner methodsFor: 'scanning'!characterBlockAtPoint: aPoint in: aParagraph "Answer a CharacterBlock for character in aParagraph at point aPoint. It is assumed that aPoint has been transformed into coordinates appropriate to the text's destinationForm rectangle and the compositionRectangle." super initializeFromParagraph: aParagraph clippedBy: aParagraph clippingRectangle. characterPoint _ aPoint. ^self buildCharacterBlockIn: aParagraph!characterBlockForIndex: targetIndex in: aParagraph "Answer a CharacterBlock for character in aParagraph at targetIndex. The coordinates in the CharacterBlock will be appropriate to the intersection of the destinationForm rectangle and the compositionRectangle." super initializeFromParagraph: aParagraph clippedBy: aParagraph clippingRectangle. characterIndex _ targetIndex. characterPoint _ aParagraph rightMarginForDisplay @ (aParagraph topAtLineIndex: (aParagraph lineIndexOfCharacterIndex: characterIndex)). ^self buildCharacterBlockIn: aParagraph!characterNotInFont "This does not handle character selection nicely, i.e., illegal characters are a little tricky to select. Since the end of a run or line is subverted here by actually having the scanner scan a different string in order to manage the illegal character, things are not in an absolutely correct state for the character location code. If this becomes too odious in use, logic will be added to accurately manage the situation." lastCharacterExtent _ (font widthOf: (font maxAscii + 1) asCharacter) @ textStyle lineGrid. ^super characterNotInFont! !!CharacterBlockScanner methodsFor: 'stop conditions'!cr "Answer an instance of CharacterBlock that specifies the current location of the mouse relative to a carriage return stop condition that has just been encountered. The ParagraphEditor convention is to denote selections by CharacterBlocks, sometimes including the carriage return (cursor is at the end) and sometimes not (cursor is in the middle of the text). " ((characterIndex ~= nil and: [characterIndex > text size]) or: [(line last = text size) and: [(destY + textStyle lineGrid) < characterPoint y]]) ifTrue: ["When off end of string, give data for next character" destY _ destY + textStyle lineGrid. lastCharacter _ nil. characterPoint _ Point x: ((text at: lastIndex) = CR ifTrue: [leftMargin] ifFalse: [nextLeftMargin]) y: destY. lastIndex _ lastIndex + 1. lastCharacterExtent x: 0. ^ true]. lastCharacter _ CR. characterPoint _ destX @ destY. lastCharacterExtent x: rightMargin - destX. ^true!crossedX "Text display has wrapping. The scanner just found a character past the x location of the cursor. We know that the cursor is pointing at a character or before one." | leadingTab currentX | ((characterPoint x <= (destX + ((lastCharacterExtent x) // 2))) or: [line last = lastIndex]) ifTrue: [lastCharacter _ (text at: lastIndex). ((lastCharacter = Space and: [textStyle alignment = Justified]) and: [destX + lastCharacterExtent x > rightMargin]) ifTrue: [characterPoint _ nextLeftMargin @ (destY + textStyle lineGrid). characterIndex notNil ifTrue: [lastIndex _ (characterIndex min: (line last + 1))] ifFalse: [lastIndex _ (lastIndex + 1) min: (line last + 1)]] ifFalse: [((lastCharacter = Tab) and: [line last = lastIndex]) ifTrue: [(characterPoint x <= (destX + ((lastCharacterExtent x) // 2))) ifFalse: [destX _ (destX + lastCharacterExtent x). characterPoint _ destX @ destY. ^ self endOfRun]]. characterPoint _ destX @ destY]. ^true]. "Pointing past middle of a character, return the next character." lastIndex _ lastIndex + 1. lastCharacter _ text at: lastIndex. currentX _ destX + lastCharacterExtent x. lastCharacterExtent x: (font widthOf: lastCharacter). characterPoint _ currentX @ destY. "Yukky if next character is space or tab." (lastCharacter = Space and: [textStyle alignment = Justified]) ifTrue: [lastCharacterExtent x: (lastCharacterExtent x + (line justifiedPadFor: (spaceCount + 1))). ^true]. lastCharacter = Tab ifTrue: ["See tabForDisplay for illumination on the following awfulness." leadingTab _ true. (line first to: lastIndex - 1) do: [:index | (text at: index) = Space ifTrue: [leadingTab _ false]]. (textStyle alignment ~= Justified or: [leadingTab]) ifTrue: [lastCharacterExtent x: (textStyle nextTabXFrom: currentX leftMargin: leftMargin rightMargin: rightMargin) - currentX] ifFalse: [lastCharacterExtent x: (((currentX + (textStyle tabWidth - (line justifiedTabDeltaFor: spaceCount))) - currentX) max: 0)]]. ^ true!endOfRun "Before arriving at the cursor location, the selection has encountered an end of run. Answer false if the selection continues, true otherwise. Set up indexes for building the appropriate CharacterBlock." | runLength lineStop | ((characterIndex ~~ nil and: [runStopIndex < characterIndex and: [runStopIndex < text size]]) or: [characterIndex == nil and: [lastIndex < line last]]) ifTrue: ["We're really at the end of a real run." runLength _ (text runLengthFor: (lastIndex _ lastIndex + 1)). characterIndex ~~ nil ifTrue: [lineStop _ characterIndex "scanning for index"] ifFalse: [lineStop _ line last "scanning for point"]. (runStopIndex _ lastIndex + (runLength - 1)) > lineStop ifTrue: [runStopIndex _ lineStop]. self setStopConditions. ^false]. lastCharacter _ text at: lastIndex. characterPoint _ destX @ destY. ((lastCharacter = Space and: [textStyle alignment = Justified]) or: [lastCharacter = Tab]) ifTrue: [lastCharacterExtent _ lastSpaceOrTabExtent]. characterIndex ~~ nil ifTrue: ["If scanning for an index and we've stopped on that index, then we back destX off by the width of the character stopped on (it will be pointing at the right side of the character) and return" runStopIndex = characterIndex ifTrue: [characterPoint x: destX - lastCharacterExtent x. ^true]. "Otherwise the requested index was greater than the length of the string. Return string size + 1 as index, indicate further that off the string by setting character to nil and the extent to 0." lastIndex _ lastIndex + 1. lastCharacter _ nil. lastCharacterExtent x: 0. ^true]. "Scanning for a point and either off the end of the line or off the end of the string." runStopIndex = text size ifTrue: ["off end of string" lastIndex _ lastIndex + 1. lastCharacter _ nil. lastCharacterExtent x: 0. ^true]. "just off end of line without crossing x" lastIndex _ lastIndex + 1. ^true!onePixelBackspace "Decrement destX by 1 pixel size." | characterWidth | characterWidth _ 1. lastCharacterExtent x: characterWidth. lastIndex _ lastIndex + 1. destX _ (destX - characterWidth) max: leftMargin. ^ false!onePixelSpace "Increment destX by 1 pixel size." | characterWidth | characterWidth _ 1. lastCharacterExtent x: characterWidth. (destX + characterWidth) >= characterPoint x ifTrue: [^self crossedX]. lastIndex _ lastIndex + 1. destX _ destX + characterWidth. ^ false!paddedSpace "When the line is justified, the spaces will not be the same as the font's space character. A padding of extra space must be considered in trying to find which character the cursor is pointing at. Answer true if the scanning has crossed the cursor, false otherwise." | pad | spaceCount _ spaceCount + 1. pad _ line justifiedPadFor: spaceCount. lastSpaceOrTabExtent _ lastCharacterExtent copy. lastSpaceOrTabExtent x: spaceWidth + pad. (destX + lastSpaceOrTabExtent x) >= characterPoint x ifTrue: [lastCharacterExtent _ lastSpaceOrTabExtent copy. ^self crossedX]. lastIndex _ lastIndex + 1. destX _ destX + lastSpaceOrTabExtent x. ^ false!setStopConditions "Set the font and the stop conditions for the current run." | fontIndex displayFont | font _ textStyle fontAt: (text emphasisAt: lastIndex). super setStopConditions. stopConditions at: Space asInteger + 1 put: (textStyle alignment = Justified ifTrue: [#paddedSpace] ifFalse: [nil])!tab "Handle leading and internal tabs in a justified line. Leading tabs are considered legal and should be reflected on the display gracefully. Internal tabs (when the line is justified) are considered at the very best a misguided use of the character, and are reflected on the display the best we can." | leadingTab currentX | currentX _ destX. leadingTab _ true. (line first to: lastIndex) do: [:index | (text at: index) = Space ifTrue: [leadingTab _ false]]. (textStyle alignment ~= Justified or: [leadingTab]) ifTrue: [currentX _ textStyle nextTabXFrom: currentX leftMargin: leftMargin rightMargin: rightMargin] ifFalse: [currentX _ currentX + (textStyle tabWidth - (line justifiedTabDeltaFor: spaceCount)) max: destX]. lastSpaceOrTabExtent _ lastCharacterExtent copy. lastSpaceOrTabExtent x: (currentX - destX max: 0). currentX >= characterPoint x ifTrue: [lastCharacterExtent _ lastSpaceOrTabExtent copy. ^self crossedX]. destX _ currentX. lastIndex _ lastIndex + 1. ^false! !!CharacterBlockScanner methodsFor: 'private'!buildCharacterBlockIn: aParagraph | lineIndex runLength lineStop characterBlock done stopCondition | "handle nullText" (aParagraph numberOfLines = 0 or: [text size = 0]) ifTrue: [leftMargin _ (aParagraph leftMarginForDisplayForLine: 1). ^CharacterBlock stringIndex: 1 "like being off end of string" character: nil topLeft: (leftMargin @ (aParagraph compositionRectangle) top) extent: (0 @ textStyle lineGrid)]. "find the line" lineIndex _ aParagraph lineIndexOfTop: characterPoint y. destY _ (aParagraph topAtLineIndex: lineIndex). line _ aParagraph lineAt: lineIndex. text _ aParagraph textAt: lineIndex. rightMargin _ aParagraph rightMarginForDisplay. (lineIndex = aParagraph numberOfLines and: [(destY + textStyle lineGrid) < characterPoint y]) ifTrue: ["if beyond lastLine, force search to last character" characterPoint x: rightMargin] ifFalse: [characterPoint y < (aParagraph compositionRectangle) top ifTrue: ["force search to first line" characterPoint _ (aParagraph compositionRectangle) topLeft]. characterPoint x > rightMargin ifTrue: [characterPoint x: rightMargin]]. destX _ leftMargin _ aParagraph leftMarginForDisplayForLine: lineIndex. nextLeftMargin_ aParagraph leftMarginForDisplayForLine: lineIndex+1. lastIndex _ line first. self setStopConditions. "also sets font" runLength _ (text runLengthFor: line first). characterIndex ~~ nil ifTrue: [lineStop _ characterIndex "scanning for index"] ifFalse: [lineStop _ line last]. (runStopIndex _ lastIndex + (runLength - 1)) > lineStop ifTrue: [runStopIndex _ lineStop]. lastCharacterExtent _ 0 @ textStyle lineGrid. spaceCount _ 0. done _ false. [done] whileFalse: [stopCondition _ self scanCharactersFrom: lastIndex to: runStopIndex in: text string rightX: characterPoint x stopConditions: stopConditions displaying: false. "see setStopConditions for stopping conditions for character block operations." lastCharacterExtent x: (font widthOf: (text at: lastIndex)). (self perform: stopCondition) ifTrue: [^CharacterBlock stringIndex: lastIndex character: lastCharacter topLeft: characterPoint extent: lastCharacterExtent]]! ! BitBlt subclass: #CharacterScanner instanceVariableNames: 'lastIndex xTable stopConditions text textStyle leftMargin rightMargin font line runStopIndex spaceCount spaceWidth outputMedium ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!CharacterScanner comment:'My instances hold the state associated with scanning text.Instance Variables lastIndex<Integer> String index of last character scanned. xTable<Array> Array left x-coordinates of character glyphs (cached from font). stopConditions<Array> Array of selectors to perform when scanning various characters. ---- text<Text> The text being scanned. textStyle<TextStyle> The style (font set, etc.) being used with this text. leftMargin, rightMargin<Integers> Screen coordinates delimiting the text. font <StrikeFont> The font currently in use. line <TextLineInterval> Giving the current range in text. runStopIndex<Integer> Where the current run ends in text. spaceCount<Integer> How many spaces have been scanned in this line. spaceWidth<Integer> How wide spaces should be in this line. outputMedium<Symbol> Either #Display, #PressPrinter or #DisplayPrinterWidths as of 1/20/80. Needed by CompositionScanner for determining the nature of the font to be used for character widths. For the DisplayScanner there are several places where distinguishing between displaying and printing is required.The first three variables are required (in addition to inherited BitBlt state) by the primitive scanning operation.'!!CharacterScanner methodsFor: 'scanning'!characterNotInFont "All fonts have an illegal character to be used when a character is not within the font's legal range. When characters out of ranged are encountered in scanning text, then this special character indicates the appropriate behavior. The character is usually treated as a unary message understood by a subclass of CharacterScanner." | illegalAsciiString saveIndex stopCondition | saveIndex _ lastIndex. illegalAsciiString _ String with: (font maxAscii + 1) asCharacter. (self isMemberOf: CompositionScanner) not ifTrue: [ stopCondition _ self scanCharactersFrom: 1 to: 1 in: illegalAsciiString rightX: rightMargin stopConditions: stopConditions displaying: self doesDisplaying] ifFalse: [ stopCondition _ self scanCharactersFrom: 1 to: 1 in: illegalAsciiString rightX: rightMargin stopConditions: stopConditions displaying: self doesDisplaying]. lastIndex _ saveIndex + 1. stopCondition ~= (stopConditions at: EndOfRun) ifTrue: [^self perform: stopCondition] ifFalse: [lastIndex = runStopIndex ifTrue: [^self perform: (stopConditions at: EndOfRun)]. ^false]!scanCharactersFrom: startIndex to: stopIndex in: sourceString rightX: rightX stopConditions: stops displaying: display "This is the inner loop of text display -- but consider scanCharactersFrom: to:rightX: which would get the string, stopConditions and displaying from the instance. March through source String from startIndex to stopIndex. If any character is flagged with a non-nil entry in stops, then return the corresponding value. Determine width of each character from xTable. If dextX would exceed rightX, then return stops at: 258. If displaying is true, then display the character. Advance destX by the width of the character. If stopIndex has been reached, then return stops at: 257. Fail under the same conditions that the Smalltalk code below would cause an error. Optional. See Object documentation whatIsAPrimitive. " | ascii nextDestX | <primitive: 103> lastIndex _ startIndex. [lastIndex <= stopIndex] whileTrue: [ascii _ (sourceString at: lastIndex) asciiValue. (stopConditions at: ascii + 1) ~~ nil ifTrue: [^stops at: ascii + 1]. sourceX _ xTable at: ascii + 1. nextDestX _ destX + (width _ (xTable at: ascii + 2) - sourceX). nextDestX > rightX ifTrue: [^stops at: CrossedX]. display ifTrue: [self copyBits]. destX _ nextDestX. lastIndex _ lastIndex + 1]. lastIndex _ stopIndex. ^stops at: EndOfRun! !!CharacterScanner methodsFor: 'stop conditions'!setStopConditions "Set default stop conditions for the font." spaceWidth _ font widthOf: Space. sourceForm _ font glyphs. xTable _ font xTable. height _ font height. stopConditions _ font stopConditions. stopConditions at: Space asInteger + 1 put: #space. stopConditions at: Tab asInteger + 1 put: #tab. stopConditions at: CR asInteger + 1 put: #cr. stopConditions at: EndOfRun put: #endOfRun. stopConditions at: CrossedX put: #crossedX. stopConditions at: Ctrls asInteger + 1 put: #onePixelSpace. stopConditions at: CtrlS asInteger + 1 put: #onePixelBackspace. stopConditions at: Ctrlz asInteger + 1 put: #characterNotInFont.! !!CharacterScanner methodsFor: 'private'!doesDisplaying ^false!initializeFromParagraph: aParagraph clippedBy: clippingRectangle text _ aParagraph text. textStyle _ aParagraph textStyle. destForm _ aParagraph destinationForm. outputMedium _ aParagraph outputMedium. halftoneForm _ aParagraph mask. self combinationRule: aParagraph rule. self clipRect: clippingRectangle. sourceY _ 0.! ! Object subclass: #Checker instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Releasing'!Checker comment:'I contain a collection of checks to run for system consistency.'!"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Checker class instanceVariableNames: ''!Checker class comment:'I am a class used for running static checks over the system.'!!Checker class methodsFor: 'printing checks'!printAllMessagesOn: aFileStream "Smalltalks printAllMessagesOn: (Disk file: 'smalltalk.allMessages')." | class selectorStream | selectorStream _ WriteStream on: (String new: 100). SystemOrganization categories do: [:sysCat | Transcript show: sysCat; cr. "form feed between categories of classes" aFileStream nextPut: 12 asCharacter; cr; nextPutAll: sysCat. (SystemOrganization listAtCategoryNamed: sysCat) do: [:className | class _ self at: className. aFileStream crtab: 1; nextPutAll: className. class organization categories do: [:classCat | aFileStream crtab: 2; nextPutAll: classCat; crtab: 3. selectorStream reset. (class organization listAtCategoryNamed: classCat) do: [:selector | (selectorStream position + selector size) > 70 ifTrue: [aFileStream nextPutAll: selectorStream contents. aFileStream crtab: 4. selectorStream reset]. selectorStream space; nextPutAll: selector. aFileStream nextPutAll: selectorStream contents.]]. aFileStream crtab: 1; nextPutAll: class class name. class class organization categories do: [:classCat | aFileStream crtab: 2; nextPutAll: classCat; crtab: 3. selectorStream reset. (class class organization listAtCategoryNamed: classCat) do: [:selector | (selectorStream position + selector size) > 70 ifTrue: [aFileStream nextPutAll: selectorStream contents. aFileStream crtab: 4. selectorStream reset]. selectorStream space; nextPutAll: selector. aFileStream nextPutAll: selectorStream contents.]]. ] ]. aFileStream close.!printCategoryNamesOn: aFileStream "Print the names of all the categories, alphabetically, in the file aFileStream." self allCategoryNames do: [:catName | aFileStream nextPutAll: catName; cr]. aFileStream close "Smalltalk printCategoryNamesOn: (Disk file: 'Smalltalk.categories')."!printInstanceCounts "Smalltalk printInstanceCounts. (Disk file: 'Instance.counts') edit." | file | file _ Disk file: 'Instance.counts'. Smalltalk timeStamp: file. Smalltalk instanceCountsAndSpaceDo: [:class :count :nwords | file cr; nextPutAll: class name. (25 - class name size) timesRepeat: [file space]. file print: count; tab; print: nwords]. file close!printInstanceVariablesNotReferencedOn: aFileStream "Print a list of classes and instance variables defined in, but not used in that class Smalltalk printInstanceVariablesNotReferencedOn: (Disk file: 'smalltalk.unrefedIvars') " self instanceVariablesNotReferenced do: [:ivar | aFileStream nextPutAll: ivar; cr]. aFileStream close!printMessageUsage "Smalltalk printMessageUsage." | dict file set | dict _ IdentityDictionary new: 1024. Cursor execute showWhile: [CompiledMethod allInstancesDo: [:meth | set _ meth messages. set do: [:sel | dict at: sel put: (dict at: sel ifAbsent: [0]) + 1] ] ]. Cursor write showWhile: [file _ Disk file: 'message.counts'. dict associationsDo: [:assn | assn value > 10 ifTrue: [file cr; nextPutAll: assn key; tab; nextPutAll: assn value printString]]. file close]!printMultipleCategoryMessageNamesOn: aFileStream "Print the names of all the messages defined in more than one category." | aCollection | aCollection _ self multipleCategoryMessageNames asSortedCollection. aCollection do: [:selector | aFileStream cr; nextPutAll: selector. Smalltalk allBehaviorsDo: [:class | (class includesSelector: selector) ifTrue: [ aFileStream crtab: 1; nextPutAll: class name. aFileStream nextPutAll: '>'. aFileStream nextPutAll: (class whichCategoryIncludesSelector: selector)]]]. aFileStream close "Checker printMultipleCategoryMessageNamesOn: (Disk file: 'Smalltalk.multcats')."!printOnlyReturnSelvesOn: aFileStream "Print a list of messages that are only ^self (unimplemented). Smalltalk printOnlyReturnSelvesOn: (Disk file: 'smalltalk.unimplementeds') " self onlyReturnSelves do: [:aString | aFileStream nextPutAll: aString; cr]. aFileStream close!printReceivedButNotSentOn: aFileStream "Print a list of messages implemented but not sent anywhere (could be sent by performs). Smalltalk printReceivedButNotSentOn: (Disk file: 'smalltalk.receivedButNotSent')" self allUnSentMessages do: [:aString | aFileStream nextPutAll: aString; cr]. aFileStream close!printSentButNotReceivedOn: aFileStream "Print a list of messages sent but not implemented anywhere. Smalltalk printSentButNotReceivedOn: (Disk file: 'smalltalk.sentButNotReceived') " self allUnimplementedCalls do: [:aString | aFileStream nextPutAll: aString; cr]. aFileStream close!printSingleClassCategoryNamesOn: aFileStream "Print the names of all the categories defined in only one class. Smalltalk printSingleClassCategoryNamesOn: (Disk file: 'Smalltalk.singles'). " self singleClassCategoryNames do: [:catName | aFileStream nextPutAll: catName; cr]. aFileStream close!printUnaryCategoryNamesOn: aFileStream "Print the names of all the categories with only one message. Smalltalk printUnaryCategoryNamesOn: (Disk file: 'Smalltalk.unaries')." self unaryCategoryNames do: [:catName | aFileStream nextPutAll: catName; cr]. aFileStream close!printUnresponsivesOn: aFileStream "Print a list of unimplemented subclassResponsibilities. Smalltalk printUnresponsivesOn: (Disk file: 'smalltalk.subclassUnimps')" self unResponsives do: [:aString | aFileStream nextPutAll: aString; cr]. aFileStream close! !!Checker class methodsFor: 'static checks'!allCategoryNames "Answer a SortedCollection of the names of all the categories (sorted alphabetically)." | aSet | aSet _ Set new: 1000. Smalltalk allBehaviorsDo: [:class | class organization categories do: [:catName | aSet add: catName]]. ^aSet asSortedCollection!allUnimplementedCalls "Answer an Array of each message that is sent by an expression in a method but is not implemented by any object in the system." | aStream secondStream all | all _ self allImplementedMessages. aStream _ WriteStream on: (Array new: 50). Cursor execute showWhile: [self allBehaviorsDo: [:cl | cl selectors do: [:sel | secondStream _ WriteStream on: (String new: 5). (cl compiledMethodAt: sel) messages do: [:m | (all includes: m) ifFalse: [secondStream nextPutAll: m; space]]. secondStream position = 0 ifFalse: [aStream nextPut: cl name , ' ' , sel , ' calls: ', secondStream contents]]]]. ^aStream contents!allUnSentMessages "Answer an Array of each message that is implemented by some object in the system but is not sent by any." | all anArray | all _ self allImplementedMessages. anArray _ Array new: 0. Cursor execute showWhile: [self allBehaviorsDo: [:cl | cl selectors do: [:sel | (cl compiledMethodAt: sel) literals do: [:m | all remove: m ifAbsent: []]]]. 1 to: self specialSelectorSize do: [:index | all remove: (self specialSelectorAt: index) ifAbsent: []]. Transcript show: all size printString. all do: [:sel | anArray _ anArray , (self allImplementorsOf: sel)]]. ^anArray!browseAllNonAsciiMessages "Bring up a Message Set Window with methods containing bad characters" | char cr ff tab aStream badCharacter | cr _ Character cr asciiValue. ff _ Character newPage asciiValue. tab _ Character tab asciiValue. Smalltalk browseAllSelect: [:method | badCharacter _ false. aStream _ ReadStream on: method getSource. [aStream atEnd or: [badCharacter]] whileFalse: [char _ aStream next asciiValue. (char > 127 or: [char < 32 and: [char ~= cr & (char ~= ff) & (char ~= tab)]]) ifTrue: [Transcript show: '*'. badCharacter _ true]]. badCharacter] "Smalltalk browseAllNonAsciiMessages."!categoriesSelect: aBlock "Smalltalk categoriesSelect: [:catName | catName first = $A]" | aDictionary aStream | aDictionary _ IdentityDictionary new: 512. aStream _ WriteStream on: (Array new: 500). Smalltalk allBehaviorsDo: [:class | class organization categories do: [:catName | (aBlock value: catName) ifTrue: [aStream nextPut: class name, ' >> ',catName]]]. ^aStream contents asSortedCollection!checkOrganizations "Check for organization/messagedict inconsistencies. Print the result in the System Transcript. Smalltalk checkOrganizations. Smalltalk allClassesDo: [:cl | cl removeSelector: #DoIt; removeSelector: #DoItIn:]. " | className class cat sel set | Smalltalk classNames do: [:className | (Array with: (Smalltalk at: className) with: (Smalltalk at: className) class) do: [:class | set _ Set new. class organization categories do: [:cat | (class organization listAtCategoryNamed: cat) do: [:sel | (set includes: sel) ifTrue: [Transcript show: class name , ' multiple: ' , sel; cr]. set add: sel]]. class selectors do: [:sel | (set includes: sel) ifTrue: [set remove: sel] ifFalse: [Transcript show: class name , ' missing: ' , sel; cr]]. set do: [:sel | Transcript show: class name , ' spurious: ' , sel; cr]]]. Transcript show: 'Done checking.'; cr!findAllNonAsciiSources "Collect chunks from the source files containing bad characters" | char cr ff tab aStream badCharacter aFileStream aChunk badStream| cr _ Character cr asciiValue. ff _ Character newPage asciiValue. tab _ Character tab asciiValue. badStream _ WriteStream on: (Array new: 10). Cursor execute show. 1 to: 2 do: [:i | aFileStream _ (SourceFiles at: i) copy. aFileStream reset. [aFileStream atEnd] whileFalse: [aChunk _ aFileStream nextChunk. aStream _ ReadStream on: aChunk. badCharacter _ false. [aStream atEnd or: [badCharacter]] whileFalse: [char _ aStream next asciiValue. (char > 127 or: [char < 32 and: [char ~= cr & (char ~= ff) & (char ~= tab)]]) ifTrue: [Transcript show: '*'. badCharacter _ true]]. badCharacter ifTrue: [badStream nextPut: aChunk]]. aFileStream close]. Cursor normal show. ^badStream contents "Smalltalk findAllNonAsciiSources inspect."!findSharedPoolVariables "Smalltalk findSharedPoolVariables." | aSet duplicates | duplicates _ OrderedCollection new. Smalltalk allClassesDo: [:class | class subclasses isEmpty ifTrue: [aSet _ Set new. class allSharedPools do: [:pool | pool keys do: [:key | (aSet includes: key) ifTrue: [duplicates add: (Association key: key value: class)]. aSet add: key]]]]. ^duplicates!instanceCountsAndSpaceDo: aBlock "Evaluate aBlock value: class value: instanceCount value: totalSpace for every class in the system." | nwords isBytes n | Smalltalk allClassesDo: [:class | nwords _ 0. class isVariable ifTrue: [n _ 0. isBytes _ class isBytes. class allInstancesDo: [:inst | n _ n + 1. nwords _ nwords + (isBytes ifTrue: [inst basicSize + 1 // 2] ifFalse: [inst basicSize])]] ifFalse: [n _ class instanceCount]. nwords _ nwords + (class instSize + 2 * n). "+2 for header" aBlock value: class value: n value: nwords]!instanceVariablesNotReferenced "Return a list of classes and instance variables defined in, but not used in that class Smalltalk instanceVariablesNotReferenced" | aStream | aStream _ WriteStream on: (Array new: 50). Smalltalk allBehaviorsDo: [:class | class instVarNames do: [:instVarName | (class whichSelectorsAccess: instVarName) size = 0 ifTrue: [aStream nextPut: class name, ' ', instVarName]]]. ^aStream contents!multipleCategoryMessageNames "Return the names of all the messages defined in more then one category, along with the category names." | aDictionary class catName selector | aDictionary _ IdentityDictionary new: 1024. Smalltalk allBehaviorsDo: [:class | class organization categories do: [:catName | (class organization listAtCategoryNamed: catName) do: [:selector | (aDictionary includesKey: selector) ifTrue: [(aDictionary at: selector) add: catName] ifFalse: [aDictionary at: selector put: (Set with: catName)]]]]. ^aDictionary keys select: [:selector | (aDictionary at: selector) size > 1]!obsoleteAssociations "Return a collection of all associations containing obsolete classes. Smalltalk obsoleteAssociations " | class | ^Association allInstances select: [:assoc | class _ assoc value class. class isMeta and: [class isObsolete]]!obsoleteClasses "Return a collection of all obsolete classes. Smalltalk obsoleteClasses " ^(Metaclass allInstances select: [:metaclass | metaclass isObsolete]) collect: [:metaclass | metaclass someInstance]!obsoleteClassReferences "Answer a collection of all the methods that reference obsolete classes." | methods | methods _ SortedCollection new. self obsoleteAssociations do: [:assoc | methods addAll: (self allCallsOn: assoc)]. ^methods "BrowserView openListBrowserOn: Smalltalk obsoleteClassReferences label: 'References to Obsolete Classes' "!obsoleteInstanceCounts "Compute the number of instances of each obsolete class. Smalltalk obsoleteInstanceCounts " | obsolete count | obsolete _ Dictionary new. self obsoleteClasses do: [:class | count _ class instanceCount. count > 0 ifTrue: [obsolete at: class put: count]]. ^obsolete!onlyReturnSelves "Return message names for messages that are ^self only (i.e. no implementation) Smalltalk onlyReturnSelves." | aStream | aStream _ WriteStream on: (Array new: 50). Smalltalk allBehaviorsDo: [:class | class selectors do: [:selector | (class compiledMethodAt: selector) isReturnSelf ifTrue: [aStream nextPut: class name, ' ', selector]]]. ^aStream contents!rehashBadSets "Checker rehashBadSets" | badSets checkSet | badSets _ Set new. checkSet _ [:set | (set isKindOf: Dictionary) ifTrue: [set keysDo: [:x | (set includesKey: x) ifFalse: [badSets add: set]]] ifFalse: [set do: [:x | (set includes: x) ifFalse: [badSets add: set]]]]. Set allInstances do: checkSet. Set allSubInstancesDo: checkSet. badSets do: [:bad | bad rehash]. Transcript cr; print: badSets size; show: ' bad sets/dictionaries rehashed'. ^badSets!removeEmptyCategories "Remove all empty class and method categories. Smalltalk removeEmptyCategories " SystemOrganization removeEmptyCategories. ClassOrganizer allInstancesDo: [:organizer | organizer removeEmptyCategories].!singleClassCategoryNames "Return the names of all the categories defined in only one class, alphabetic Smalltalk singleClassCategoryNames." | aDictionary aStream | aDictionary _ IdentityDictionary new: 512. Smalltalk allBehaviorsDo: [:class | class organization categories do: [:catName | (aDictionary includesKey: catName) ifTrue: [(aDictionary at: catName) = nil ifFalse: [aDictionary at: catName put: nil]] ifFalse: [aDictionary at: catName put: class name]]]. aStream _ WriteStream on: (Array new: 500). aDictionary associationsDo: [:assn | assn value == nil ifFalse: [aStream nextPut: assn value, ' >> ',assn key]]. ^aStream contents asSortedCollection!unaryCategoryNames "Return the names of all the categories with only one message in them" | aSet | aSet _ Set new: 1000. Smalltalk allBehaviorsDo: [:class | class organization categories do: [:catName | (class organization listAtCategoryNamed: catName) size = 1 ifTrue: [aSet add: class name, ' >> ', catName]]]. ^aSet asSortedCollection!unResponsives "Smalltalk unResponsives" | aStream aCollection satisfiedSet workingSet aSubclass special | aStream _ WriteStream on: (Array new: 50). special _ self hasSpecialSelector: #subclassResponsibility ifTrueSetByte: [:byte ]. Smalltalk allBehaviorsDo: [:class | aCollection _ class whichSelectorsReferTo: #subclassResponsibility special: special byte: byte. aCollection size > 0 ifTrue: [aCollection do: [:selector | workingSet _ class subclasses asOrderedCollection. satisfiedSet _ Set new. [workingSet isEmpty] whileFalse: [aSubclass _ workingSet removeFirst. (aSubclass includesSelector: selector) ifFalse: [satisfiedSet add: aSubclass. workingSet addAll: aSubclass subclasses]]. satisfiedSet do: [:subclass | aStream nextPut: class name, ' ', selector, ' ', subclass name]]]]. ^aStream contents!whichClassesHaveCategory: categoryName "Return the names of all the classes with the category. Smalltalk whichClassesHaveCategory: 'accessing'." | aStream | aStream _ WriteStream on: (Array new: 500). Smalltalk allBehaviorsDo: [:class | (class organization categories includes: categoryName asSymbol) ifTrue: [aStream nextPut: class name]]. ^aStream contents asSortedCollection!whichClassesIncludeCategory: categoryName "Answer an Array of each class that includes the name, categoryName, as one of its message categories." | aStream cat | aStream _ WriteStream on: (Array new: 10). cat _ categoryName asSymbol. self allClassesDo: [:class | (class organization categories includes: cat) ifTrue: [aStream nextPut: class]. (class class organization categories includes: cat) ifTrue: [aStream nextPut: class class]]. ^aStream contents "Smalltalk whichClassesIncludeCategory: #comparison."! !!Checker class methodsFor: 'browsing'!browseAllUnimplementedCalls "Create and schedule a message browser on each method that includes a message that is not implemented in any object in the system. Smalltalk browseAllUnimplementedCalls " BrowserView openListBrowserOn: self allUnimplementedCalls label: 'Unimplemented calls'! ! Arc subclass: #Circle instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!Circle comment: 'A full circle is made from four arcs.'!!Circle methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm 1 to: 4 do: [:i | super quadrant: i. super displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm]!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm 1 to: 4 do: [:i | super quadrant: i. super displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm]! !!Circle methodsFor: 'display box access'!computeBoundingBox ^center - radius + form offset extent: form extent + (radius * 2) asPoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Circle class instanceVariableNames: ''!!Circle class methodsFor: 'examples'!exampleOne "Click any button somewhere on the screen. The point will be the center of the circcle of radius 150." | aCircle aForm | aForm _ Form new extent: 1@30. aForm black. aCircle _ Circle new. aCircle form: aForm. aCircle radius: 150. aCircle center: Sensor waitButton. aCircle displayOn: Display "Circle exampleOne."!exampleTwo "Designate a rectangular area that should be used as the brush for displaying the circle. Click any button at a point on the screen which will be the center location for the circle. The curve will be displayed with a long black form." | aCircle aForm | aForm _ Form fromUser. aCircle _ Circle new. aCircle form: aForm. aCircle radius: 150. aCircle center: Sensor waitButton. aCircle displayOn: Display at: 0 @ 0 rule: Form reverse "Circle exampleTwo."! ! ClassDescription subclass: #Class instanceVariableNames: 'name classPool sharedPools ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Classes'!Class comment:'My instances describe the representation and behavior of objects. I add more comprehensive programming support facilities to the basic attributes of Behavior and the descriptive facilities of ClassDescription. An example is accessing shared (pool) variables.Instance Variables: name <Symbol> name of class for printing and global reference classPool <Dictionary> of variables common to all instances sharedPools <Array> of Dictionaries access to other shared variables'!!Class methodsFor: 'initialize-release'!declare: varString "Declare class variables common to all instances. Answer whether recompilation is advisable." | newVars conflicts assoc class | newVars _ (Scanner new scanFieldNames: varString) collect: [:x | x asSymbol]. newVars do: [:var | var first isLowercase ifTrue: [self error: var, ' class variable name should be capitalized; proceed to include anyway.']]. conflicts _ false. classPool == nil ifFalse: [(classPool keys reject: [:x | newVars includes: x]) do: [:var | self removeClassVarName: var]]. (newVars reject: [:var | self classPool includesKey: var]) do: [:var | "adding" "check if new vars defined elsewhere" (self scopeHas: var ifTrue: [:ignored | ignored]) ifTrue: [self error: var , ' is defined elsewhere'. conflicts _ true]]. newVars size > 0 ifTrue: [classPool _ self classPool. "in case it was nil" newVars do: [:var | classPool declare: var from: Undeclared]]. ^conflicts!obsolete "Change the receiver to an obsolete class by changing its name to have the prefix -AnObsolete-, and nilling the fields of any instances." self isPointers ifTrue: [self allInstancesDo: [:instance | instance nilFields]]. "nil fields of instances" ('AnObsolete*' match: name) ifFalse: [name _ 'AnObsolete' , name]. classPool _ Dictionary new. self class obsolete. super obsolete!removeFromSystem "Forget the receiver, and all of its subclasses, from the Smalltalk global dictionary. Any existing instances will refer to an obsolete version of the receiver." Smalltalk removeClassNamed: self name. "remove from system dictionary"!sharing: poolString "Set up sharedPools. Answer whether recompilation is advisable." | oldPools poolName pool | oldPools _ self sharedPools. sharedPools _ Set new. (Scanner new scanFieldNames: poolString) do: [:poolName | sharedPools add: (Smalltalk at: poolName asSymbol)]. sharedPools isEmpty ifTrue: [sharedPools _ nil]. oldPools detect: [:pool | (self sharedPools includes: pool) not] ifNone: [^false]. ^true "A pool got deleted - who knows if there are still references?"!superclass: sup methodDict: md format: ft name: nm organization: org instVarNames: nilOrArray classPool: pool sharedPools: poolSet "Answer an instance of me, a new class, using the arguments of the message as the needed information." superclass _ sup. methodDict _ md. format _ ft. name _ nm. organization _ org. instanceVariables _ nilOrArray. classPool _ pool. sharedPools _ poolSet!validateFrom: oldClass in: environ instanceVariableNames: invalidFields methods: invalidMethods "Recompile the receiver and redefine its subclasses if necessary." super validateFrom: oldClass in: environ instanceVariableNames: invalidFields methods: invalidMethods. self ~~ oldClass ifTrue: [environ at: name put: self. self updateInheritanceTables: oldClass. oldClass obsolete]! !!Class methodsFor: 'accessing'!classPool "Answer the dictionary of class variables." classPool == nil ifTrue: [^Dictionary new] ifFalse: [^classPool]!name "Answer the name of the receiver." name == nil ifTrue: [^super name] ifFalse: [^name]! !!Class methodsFor: 'accessing class hierarchy'!hasMultipleSuperclasses ^self class instHasMultipleSuperclasses!isObsolete "Answer whether the receiver is an obsolete class." ^self class isObsolete "ask the metaclass"! !!Class methodsFor: 'testing method dictionary'!hasMethods "Answer a Boolean as to whether any methods are defined for the receiver (includes whether there are methods defined in the receiver's metaclass)." ^super hasMethods or: [self class hasMethods]! !!Class methodsFor: 'copying'!copy | newClass | newClass _ self class copy new superclass: superclass methodDict: methodDict copy format: format name: name organization: organization copy instVarNames: instanceVariables copy classPool: classPool copy sharedPools: sharedPools. Class instSize to: self class instSize do: [:offset | newClass instVarAt: offset put: (self instVarAt: offset)]. ^newClass!copyForValidation "Make a copy of the receiver (a class) but do not install the created class as a new class in the system. This is used for creating a new version of the receiver in which the installation is deferred until all changes are successfully completed." ^self class copy new superclass: superclass methodDict: methodDict copy format: format name: name organization: organization instVarNames: instanceVariables copy classPool: classPool sharedPools: sharedPools! !!Class methodsFor: 'class name'!rename: aString "The new name of the receiver is the argument, aString." | newName | newName _ aString asSymbol. (Smalltalk includesKey: newName) ifTrue: [^self error: newName , ' already exists']. Smalltalk renameClass: self as: newName. name _ newName. self comment: self comment. self class comment: self class comment! !!Class methodsFor: 'instance variables'!addInstVarName: aString "Add the argument, aString, as one of the receiver's instance variables." superclass class name: self name inEnvironment: Smalltalk subclassOf: superclass instanceVariableNames: self instanceVariablesString , aString variable: self isVariable words: self isWords pointers: self isPointers classVariableNames: self classVariablesString poolDictionaries: self sharedPoolsString category: self category comment: nil changed: false!removeInstVarName: aString "Remove the argument, aString, as one of the receiver's instance variables." | newInstVarString | (self instVarNames includes: aString) ifFalse: [self error: aString , ' is not one of my instance variables']. newInstVarString _ ''. (self instVarNames copyWithout: aString) do: [:varName | newInstVarString _ newInstVarString , ' ' , varName]. superclass class name: self name inEnvironment: Smalltalk subclassOf: superclass instanceVariableNames: newInstVarString variable: self isVariable words: self isWords pointers: self isPointers classVariableNames: self classVariablesString poolDictionaries: self sharedPoolsString category: self category comment: nil changed: false! !!Class methodsFor: 'class variables'!addClassVarName: aString "Add the argument, aString, as a class variable of the receiver." aString first isLowercase ifTrue: [^self error: aString, ' class variable name should be capitalized; proceed to include anyway.']. self withAllSubclasses do: [:subclass | subclass poolHas: aString asSymbol ifTrue: [:ignored | ^self error: aString , ' is already used as a variable name in ' , subclass name]]. classPool _ self classPool. "might be nil" classPool add: (Association key: aString asSymbol value: nil)!allClassVarNames "Answer a Set of the names of the receiver's class variables, including those defined in the superclasses of the receiver." | aSet | superclass == nil ifTrue: [^self classVarNames] "This is the keys so it is a new Set." ifFalse: [aSet _ superclass allClassVarNames. aSet addAll: self classVarNames. ^aSet]!classVarNames "Answer a Set of the names of the class variables defined in the receiver." ^self classPool keys!initialize "Typically used for the initialization of class variables and metaclass instance variables. Does nothing, but may be overridden in Metaclasses." ^self!removeClassVarName: aString "Remove the class variable whose name is the argument, aString, from the names defined in the receiver, a class." | anAssoc aSymbol | aSymbol _ aString asSymbol. (classPool includesKey: aSymbol) ifFalse: [^self error: aString, ' is not a class variable']. anAssoc _ classPool associationAt: aSymbol. self withAllSubclasses do: [:subclass | (Array with: subclass with: subclass class) do: [:classOrMeta | (classOrMeta whichSelectorsReferTo: (classPool associationAt: aSymbol)) isEmpty ifFalse: [^self error: aString , ' is still used in code of class ' , classOrMeta name]]]. classPool removeKey: aSymbol! !!Class methodsFor: 'pool variables'!addSharedPool: aDictionary "Add the argument, aDictionary, as one of the receiver's pool dictionaries. Create an error if the dictionary is already one of the pools." (self sharedPools includes: aDictionary) ifTrue: [^self error: 'The dictionary is already in my pool']. sharedPools == nil ifTrue: [sharedPools _ Set with: aDictionary] ifFalse: [sharedPools add: aDictionary]!allSharedPools "Answer a Set of the pools the receiver shares, including those defined in the superclasses of the receiver." | aSet | superclass == nil ifTrue: [^self sharedPools copy] ifFalse: [aSet _ superclass allSharedPools. aSet addAll: self sharedPools. ^aSet]!removeSharedPool: aDictionary "Remove the pool dictionary, aDictionary, as one of the receiver's pool dictionaries. Create an error if the dictionary is not one of the pools." | satisfiedSet workingSet aSubclass| (self sharedPools includes: aDictionary) ifFalse: [^self error: 'the dictionary is not in my pool']. "first see if it is declared in a superclass in which case we can remove it." (self allSuperclasses select: [:class | class sharedPools includes: aDictionary]) isEmpty ifFalse: [sharedPools remove: aDictionary. sharedPools isEmpty ifTrue: [sharedPools _ nil]. ^self]. "second get all the subclasses that reference aDictionary through me rather than a superclass that is one of my subclasses." workingSet _ self subclasses asOrderedCollection. satisfiedSet _ Set new. [workingSet isEmpty] whileFalse: [aSubclass _ workingSet removeFirst. (aSubclass sharedPools includes: aDictionary) ifFalse: [satisfiedSet add: aSubclass. workingSet addAll: aSubclass subclasses]]. "for each of these, see if they refer to any of the variables in aDictionary because if they do, we can not remove the dictionary." satisfiedSet add: self. satisfiedSet do: [:aSubclass | aDictionary associationsDo: [:aGlobal | (aSubclass whichSelectorsReferTo: aGlobal) isEmpty ifFalse: [^self error: aGlobal key , ' is still used in code of class ' , aSubclass name]]]. sharedPools remove: aDictionary. sharedPools isEmpty ifTrue: [sharedPools _ nil]!sharedPools "Answer a Set of the pool dictionaries declared in the receiver." sharedPools == nil ifTrue: [^Set new] ifFalse: [^sharedPools]! !!Class methodsFor: 'compiling'!compileAllFrom: otherClass super compileAllFrom: otherClass. self class compileAllFrom: otherClass class!poolHas: varName ifTrue: assocBlock "Look up the first argument in the context of the receiver. If it is there, pass the association to assocBlock, and answer true, else answer false." | assoc pool | assoc _ self classPool associationAt: varName ifAbsent: []. assoc == nil ifFalse: [assocBlock value: assoc. ^true]. self sharedPools do: [:pool | assoc _ pool associationAt: varName ifAbsent: []. assoc == nil ifFalse: [assocBlock value: assoc. ^true]]. ^ false! !!Class methodsFor: 'subclass creation'!subclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat "This is the standard initialization message for creating a new class as a subclass of an existing class (the receiver)." self isVariable ifTrue: [self isPointers ifTrue: [^self variableSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat]. self isBytes ifTrue: [^self variableByteSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat]. ^self variableWordSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat]. ^self class name: t inEnvironment: Smalltalk subclassOf: self instanceVariableNames: f variable: false words: true pointers: true classVariableNames: d poolDictionaries: s category: cat comment: nil changed: false!subclass: t otherSupers: others instanceVariableNames: f classVariableNames: d category: cat "This is the standard initialization message for creating a new class as a subclass of an existing class (the receiver)." self isVariable ifTrue: [self isPointers ifTrue: [^self variableSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: '' category: cat]. self isBytes ifTrue: [^self variableByteSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: '' category: cat]. ^self variableWordSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: '' category: cat]. ^self class name: t inEnvironment: Smalltalk subclassOf: self and: others instanceVariableNames: f variable: false words: true pointers: true classVariableNames: d poolDictionaries: '' category: cat comment: nil changed: false!variableByteSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat "This is the standard initialization message for creating a new class as a subclass of an existing class (the receiver) in which the subclass is to have indexable byte-sized nonpointer variables." self instSize > 0 ifTrue: [^self error: 'cannot make a byte subclass of a class with named fields']. (self isVariable and: [self isWords]) ifTrue: [^self error: 'cannot make a byte subclass of a class with word fields']. (self isVariable and: [self isPointers]) ifTrue: [^self error: 'cannot make a byte subclass of a class with pointer fields']. ^self class name: t inEnvironment: Smalltalk subclassOf: self instanceVariableNames: f variable: true words: false pointers: false classVariableNames: d poolDictionaries: s category: cat comment: nil changed: false!variableSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat "This is the standard initialization message for creating a new class as a subclass of an existing class (the receiver) in which the subclass is to have indexable pointer variables." self isBits ifTrue: [^self error: 'cannot make a pointer subclass of a class with non-pointer fields']. ^self class name: t inEnvironment: Smalltalk subclassOf: self instanceVariableNames: f variable: true words: true pointers: true classVariableNames: d poolDictionaries: s category: cat comment: nil changed: false!variableWordSubclass: t instanceVariableNames: f classVariableNames: d poolDictionaries: s category: cat "This is the standard initialization message for creating a new class as a subclass of an existing class (the receiver) in which the subclass is to have indexable word-sized nonpointer variables." self instSize > 0 ifTrue: [^self error: 'cannot make a word subclass of a class with named fields']. self isBytes ifTrue: [^self error: 'cannot make a word subclass of a class with byte fields']. (self isVariable and: [self isPointers]) ifTrue: [^self error: 'cannot make a word subclass of a class with pointer fields']. ^self class name: t inEnvironment: Smalltalk subclassOf: self instanceVariableNames: f variable: true words: true pointers: false classVariableNames: d poolDictionaries: s category: cat comment: nil changed: false! !!Class methodsFor: 'fileIn/Out'!fileOut "Create a file whose name is the name of the receiver with -.st- as the extension, and file a description of the receiver onto it" | fileStream | Transcript refresh; cr; cr; show: 'Filing out class:'. fileStream _ Disk file: self name , '.st'. fileStream timeStamp. self fileOutOn: fileStream moveSource: false toFile: 0. fileStream shorten; close. self removeFromChanges.!fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex "File a description of the receiver on aFileStream. If the boolean argument, moveSource, is true, then set the trailing bytes to the position of aFileStream and to fileIndex in order to indicate where to find the source code." Transcript cr; show: name. super fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex. self class nonTrivial ifTrue: [aFileStream cr; nextPutAll: '"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!!'; cr; cr. self class fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex].!printOut "Create a readable version of my definition, and send to a printer. Defaults to fileOut." self fileOut!removeFromChanges "References to the receiver, a class, and its metaclass should no longer be included in the system ChangeSet." Smalltalk changes removeClassChanges: self! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Class class instanceVariableNames: ''!!Class class methodsFor: 'instance creation'!getSuperclasses: superNames | supers | "find the superclasses corresponding to the superclass names" supers _ (Scanner new scanTokens: superNames) collect: [:each | Smalltalk at: each]. "check that each is a kind of Behavior" supers do: [:each | (each isKindOf: Behavior) ifFalse: [self error: 'superclass must be a class-describing object']]. ^supers!named: newClassName superclasses: newSuperNames instanceVariableNames: myInstVarNames classVariableNames: classVarNames category: cat | newClass supers firstSuper otherSupers fork | "find the superclasses corresponding to the superclass names" supers _ self getSuperclasses: newSuperNames. supers size=1 ifTrue: [^supers first "if there's only one superclass, just use old code" subclass: newClassName instanceVariableNames: myInstVarNames classVariableNames: classVarNames poolDictionaries: '' category: cat]. newClass _ supers first subclass: newClassName otherSupers: (supers copyFrom: 2 to: supers size) instanceVariableNames: myInstVarNames classVariableNames: classVarNames category: cat. ^newClass!template: category "Answer an expression that can be edited and evaluated in order to define a new class." ^'NameOfSuperclass subclass: #NameOfClass instanceVariableNames: ''instVarName1 instVarName2'' classVariableNames: ''ClassVarName1 ClassVarName2'' poolDictionaries: '''' category: ''' , category , ''''! ! Object subclass: #ClassCategoryReader instanceVariableNames: 'class category ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Support'!ClassCategoryReader comment: 'Instance Variables: class <ClassDescription> the class being read in category <String> the category for methods being read inI am created during fileIn in response to "class methodsFor: cat" message. I subsequently scan consecutive "chunks" from the fileIn stream and ask class to compile them in this category. I continue in this way until an empty chunk is found.'!!ClassCategoryReader methodsFor: 'fileIn/Out'!scanFrom: aStream "Files in methods from the stream, aStream. Prints the name and category of the methods in the transcript view." | string | [string _ aStream nextChunk. string size > 0] "done when double terminators" whileTrue: [class compile: string classified: category]. Transcript show: class name , '<' , category , ''! !!ClassCategoryReader methodsFor: 'private'!setClass: aClass category: aCategory class _ aClass. category _ aCategory! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ClassCategoryReader class instanceVariableNames: ''!!ClassCategoryReader class methodsFor: 'instance creation'!class: aClass category: aCategory "Answer a new instance of ClassCategoryReader for the category, aCategory, of the class, aClass." ^self new setClass: aClass category: aCategory! ! ClassRelatedChange subclass: #ClassChange instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ClassChange comment:'I am a change to some part of a class definition (actual definition, comment, name, ...) as opposed to a change to a method within a class.'! ClassOtherChange subclass: #ClassCommentChange instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ClassCommentChange comment:'I am a change to some part of a class comment.'!!ClassCommentChange methodsFor: 'accessing'!text ^file == nil ifTrue: [className, ' comment:', (Smalltalk at: className) comment printString] ifFalse: [super text]! !!ClassCommentChange methodsFor: 'checking'!checkWith: aChecker aChecker changesAt: className, '<', type, '>' add: self! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ClassCommentChange class instanceVariableNames: ''!!ClassCommentChange class methodsFor: 'instance creation'!new ^super new type: #comment! ! ClassChange subclass: #ClassDefinitionChange instanceVariableNames: 'superclassName classType otherParameters ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ClassDefinitionChange comment:'I am a change to some part of a class definition.'!!ClassDefinitionChange methodsFor: 'accessing'!name ^' define ', className!superclassName: aSymbol classType: aSelector otherParameters: anArray superclassName _ aSymbol. classType _ aSelector. otherParameters _ anArray!text ^file == nil ifTrue: [(Smalltalk at: className) definition] ifFalse: [super text]! !!ClassDefinitionChange methodsFor: 'checking'!checkWith: aChecker | class | aChecker changesAt: className add: self. aChecker checkSystem ifTrue: [class _ Smalltalk at: className ifAbsent: [^self]. self text = class definition ifFalse: [aChecker changesAt: className add: (self class new className: className)]]! ! Behavior subclass: #ClassDescription instanceVariableNames: 'instanceVariables organization ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Classes'!ClassDescription comment:'Instance Variables: instanceVariables <Array> names of instance fields organization <ClassOrganizer> provides organization of message protocolClassDescription adds a number of facilities to basic Behavior: - named instance variables - category organization for methods - the notion of a name of this class (implemented as subclass responsibility) - the maintenance of the Changes set, and logging changes on a file - most of the mechanism for fileOutClassDescription is an abstract class: its facilities are intended for inheritance by the two subclasses, Class and Metaclass.'!!ClassDescription methodsFor: 'initialize-release'!obsolete "Make the receiver obsolete." organization _ nil. super obsolete!subclassOf: newSuper oldClass: oldClass instanceVariableNames: newInstVarString variable: v words: w pointers: p ifBad: badBlock "Basic initialization message for creating classes using the information provided as arguments. Answer whether old instances will be invalidated." | old new usedNames invalid oldSuperMeta newInstVarArray | old _ self allInstVarNames. usedNames _ #(self super thisContext true false nil ) asSet. newInstVarArray _ Scanner new scanFieldNames: newInstVarString. (invalid _ superclass ~~ newSuper) ifTrue: ["superclass changed" oldSuperMeta _ superclass class. superclass removeSubclass: self. superclass _ newSuper. superclass addSubclass: self. self class superclass == oldSuperMeta ifTrue: ["Only false when self is a metaclass" self class superclass: newSuper class]]. instanceVariables _ nil. "To give us all super names" new _ self allInstVarNames , newInstVarArray. new do: [:fieldName | (usedNames includes: fieldName) ifTrue: [self error: fieldName , ' is reserved (maybe in a superclass)'. ^badBlock value]. usedNames add: fieldName]. instanceVariables _ newInstVarArray size = 0 ifTrue: [nil] ifFalse: [newInstVarArray]. invalid _ invalid | (new ~= old). "field names changed" old _ format. self format: new size variable: v words: w pointers: p. invalid _ invalid | (format ~= old). "format changed" ^invalid!updateInstancesFrom: oldClass "Recreate any existing instances of the argument, oldClass, as instances of the receiver, which is a newly changed class. Permute variables as necessary." | oldInstVarNames map variable old new instSize offset fieldName | oldClass someInstance == nil ifTrue: [^self]. "no instances to convert" oldInstVarNames _ oldClass allInstVarNames. map _ self allInstVarNames collect: [:instVarName | oldInstVarNames indexOf: instVarName]. variable _ self isVariable. instSize _ self instSize. oldClass allInstances do: [:old | "note allInstsDo would get confused by becoming" variable ifTrue: [new _ self basicNew: old basicSize] ifFalse: [new _ self basicNew]. 1 to: instSize do: [:offset | (map at: offset) > 0 ifTrue: [new instVarAt: offset put: (old instVarAt: (map at: offset))]]. variable ifTrue: [1 to: old basicSize do: [:offset | new basicAt: offset put: (old basicAt: offset)]]. old become: new]!validateFrom: oldClass in: environ instanceVariableNames: invalidFields methods: invalidMethods "Recompile the receiver, a class, and redefine its subclasses if necessary." | sub newSub | invalidFields & invalidMethods ifFalse: [^self]. invalidMethods & self hasMethods ifTrue: [Transcript show: 'recompiling ' , self name , '...'. self compileAllFrom: oldClass. Transcript show: ' done'; cr]. self ~~ oldClass ifTrue: [self updateInstancesFrom: oldClass]. oldClass subclasses do: [:sub | newSub _ sub copyForValidation. newSub subclassOf: self oldClass: sub instanceVariableNames: sub instVarNames variable: sub isVariable words: sub isBytes not pointers: sub isBits not ifBad: [self error: 'terrible problem in recompiling subclasses!!']. newSub validateFrom: sub in: environ instanceVariableNames: invalidFields methods: invalidMethods]! !!ClassDescription methodsFor: 'accessing'!comment "Answer the receiver's comment." | aString | aString _ self organization classComment. aString size = 0 ifTrue: [^'']. "get string only of classComment, undoubling quotes" ^ String readFromString: aString!comment: aString "Set the receiver's comment to be the argument, aString." | aStream | aString size = 0 ifTrue: [self organization classComment: aString] ifFalse: ["double internal quotes of the comment string" aStream _ WriteStream on: (String new: aString size). aStream nextPutAll: self name , ' comment:'; cr. aString storeOn: aStream. self organization classComment: aStream contents. Smalltalk changes commentClass: self]!commentTemplate "Answer an expression to edit and evaluate in order to produce the receiver's comment." | aString | aString _ self organization classComment. aString size = 0 ifTrue: [^self name , ' comment:''This class has not yet been commented. A proper comment should include the purpose of the class and the type and purpose of each instance variable.'''] ifFalse: [^aString]!name "Answer a String that is the name of the receiver." self subclassResponsibility! !!ClassDescription methodsFor: 'copying'!copy: sel from: class "Install the method associated with the first arugment, sel, a message selector, found in the method dictionary of the second argument, class, as one of the receiver's methods. Classify the message under -as yet not classified-" self copy: sel from: class classified: nil!copy: sel from: class classified: cat "Install the method associated with the first arugment, sel, a message selector, found in the method dictionary of the second argument, class, as one of the receiver's methods. Classify the message under the third argument, cat." | code category | "Useful when modifying an existing class" code _ class sourceMethodAt: sel. code == nil ifFalse: [cat == nil ifTrue: [category _ class organization categoryOfElement: sel] ifFalse: [category _ cat]. (methodDict includesKey: sel) ifTrue: [code asString = (self sourceMethodAt: sel) asString ifFalse: [self error: self name , ' ' , sel , ' will be redefined if you proceed.']]. self compile: code classified: category]!copyAll: selArray from: class "Install all the methods found in the method dictionary of the second argument, class, as the receiver's methods. Classify the messages under -as yet not classified-" self copyAll: selArray from: class classified: nil!copyAll: selArray from: class classified: cat "Install all the methods found in the method dictionary of the second argument, class, as the receiver's methods. Classify the messages under the third argument, cat." selArray do: [:s | self copy: s from: class classified: cat]!copyAllCategoriesFrom: aClass "Specify that the categories of messages for the receiver include all of those found in the class, aClass. Install each of the messages found in these categories into the method dictionary of the receiver, classified under the appropriate categories." aClass organization categories do: [:cat | self copyCategory: cat from: aClass]!copyCategory: cat from: class "Specify that one of the categories of messages for the receiver is cat, as found in the class, aClass. Copy each message found in this category." self copyCategory: cat from: class classified: cat!copyCategory: cat from: aClass classified: newCat "Specify that one of the categories of messages for the receiver is the third argument, newCat. Copy each message found in the category cat in class aClass into this new category." self copyAll: (aClass organization listAtCategoryNamed: cat) from: aClass classified: newCat! !!ClassDescription methodsFor: 'testing'!isMeta ^ false! !!ClassDescription methodsFor: 'printing'!classVariablesString "Answer a string of my class variable names separated by spaces, in alphabetical order." | aStream | aStream _ WriteStream on: (String new: 100). self classPool keys asSortedCollection do: [:key | aStream nextPutAll: key; space]. ^ aStream contents!definition "Answer a string that defines the receiver." | aStream | aStream _ WriteStream on: (String new: 300). self hasMultipleSuperclasses ifTrue: [aStream nextPutAll: 'Class named: '. self name storeOn: aStream. aStream cr; tab; nextPutAll: 'superclasses: '. aStream store: self superclassesString. aStream cr; tab; nextPutAll: 'instanceVariableNames: '. aStream store: self instanceVariablesString. aStream cr; tab; nextPutAll: 'classVariableNames: '. aStream store: self classVariablesString] ifFalse: [aStream nextPutAll: (superclass == nil ifTrue: ['nil'] ifFalse: [superclass name]). aStream nextPutAll: self kindOfSubclass. self name storeOn: aStream. aStream cr; tab; nextPutAll: 'instanceVariableNames: '. aStream store: self instanceVariablesString. aStream cr; tab; nextPutAll: 'classVariableNames: '. aStream store: self classVariablesString. aStream cr; tab; nextPutAll: 'poolDictionaries: '. aStream store: self sharedPoolsString]. aStream cr; tab; nextPutAll: 'category: '. (SystemOrganization categoryOfElement: self name) asString storeOn: aStream. ^aStream contents!instanceVariablesString "Answer a string of my instance variable names separated by spaces." | aStream names | aStream _ WriteStream on: (String new: 100). names _ self instVarNames. 1 to: names size do: [:i | aStream nextPutAll: (names at: i); space]. ^ aStream contents!printOn: aStream aStream nextPutAll: self name!sharedPoolsString "Answer a string of my class variable names separated by spaces." | aStream | aStream _ WriteStream on: (String new: 100). self sharedPools do: [:x | aStream nextPutAll: (Smalltalk keyAtValue: x); space]. ^ aStream contents!storeOn: aStream "Clases and Metaclasses have global names." aStream nextPutAll: self name!superclassesString "Answer a string of my superclass names separated by spaces." | aStream names | aStream _ WriteStream on: (String new: 100). self superclasses do: [:each | aStream nextPutAll: each name; space]. ^ aStream contents! !!ClassDescription methodsFor: 'instance variables'!addInstVarName: aString "Add the argument, aString, as one of the receiver's instance variables." self subclassResponsibility!instVarNames "Answer an Array of the names of instance variables defined in the receiver." instanceVariables == nil ifTrue: [^#()] ifFalse: [^instanceVariables]!removeInstVarName: aString "Remove the argument, aString, as one of the receiver's instance variables." self subclassResponsibility! !!ClassDescription methodsFor: 'method dictionary'!removeCategory: aString "Remove each of the messages categorized under aString in the method dictionary of the receiver. Then remove the category aString." (self organization listAtCategoryNamed: aString asSymbol) do: [:sel | self removeSelector: sel]. self organization removeEmptyCategories!removeSelector: aSymbol "Remove the message whose selector is aSymbol from the method dictionary of the receiver, if it is there. Answer nil otherwise." (methodDict includesKey: aSymbol) ifFalse: [^nil]. super removeSelector: aSymbol. self organization removeElement: aSymbol. Smalltalk changes removeSelector: aSymbol class: self. Smalltalk logChange: self name , ' removeSelector: #' , aSymbol! !!ClassDescription methodsFor: 'organization'!category "Answer the system organization category for the receiver." ^SystemOrganization categoryOfElement: self name!category: cat "Categorize the receiver under the system category, cat, removing it from any previous categorization." (cat isKindOf: String) ifTrue: [SystemOrganization classify: self name under: cat asSymbol] ifFalse: [self errorCategoryName]!logOrganizationChange "Record that the receiver is being reorganized on the changes file." | file | SourceFiles == nil ifFalse: [file _ SourceFiles at: 2. file setToEnd; readWriteShorten. file cr; nextChunkPut: self name, ' organization changeFromString: ', self organization printString storeString. file cr; readOnly]!organization "Answer the instance of ClassOrganizer that represents the organization of the messages of the receiver." organization==nil ifTrue: [organization _ ClassOrganizer new]. ^organization!reorganize "Record that the receiver is being reorganized and answer the receiver's organization." Smalltalk changes reorganizeClass: self. ^self organization!whichCategoryIncludesSelector: aSelector "Answer the category of the argument, aSelector, in the organization of the receiver, or answer nil if the receiver does not inlcude this selector." (self includesSelector: aSelector) ifTrue: [^organization categoryOfElement: aSelector] ifFalse: [^nil]! !!ClassDescription methodsFor: 'compiling'!compile: code classified: heading "Compile the argument, code, as source code in the context of the receiver and install the result in the receiver's method dictionary under the classification indicated by the second argument, heading. nil is to be notified if an error occurs. The argument code is either a string or an object that converts to a string or a PositionableStream on an object that converts to a string." ^self compile: code classified: heading notifying: nil!compile: code classified: heading notifying: requestor "Compile the argument, code, as source code in the context of the receiver and install the result in the receiver's method dictionary under the classification indicated by the second argument, heading The third argument, requestor, is to be notified if an error occurs. The argument code is either a string or an object that converts to a string or a PositionableStream on an object that converts to a string." | selector | selector _ self compile: code notifying: requestor trailer: #(0 0 0 ) ifFail: [^nil]. (methodDict at: selector) putSource: code asString class: self category: heading inFile: 2. self organization classify: selector under: heading. ^selector!compile: code notifying: requestor trailer: bytes ifFail: failBlock "Intercept this message in order to remember system changes." | methodNode selector | Cursor execute showWhile: [methodNode _ self compilerClass new compile: code in: self notifying: requestor ifFail: failBlock. selector _ methodNode selector. (methodDict includesKey: selector) ifTrue: [Smalltalk changes changeSelector: selector class: self] ifFalse: [Smalltalk changes addSelector: selector class: self]. self addSelector: selector withMethod: (methodNode generate: bytes)]. ^selector! !!ClassDescription methodsFor: 'fileIn/Out'!fileOutCategory: aString "Create a file whose name is the name of the receiver with -.st- as the extension, and file a description of the receiver's category aString onto it" | fileName fileStream | fileName _ Disk checkName: self name , '-' , aString , '.st' fixErrors: true. fileStream _ Disk file: fileName. fileStream timeStamp. self fileOutCategory: aString on: fileStream moveSource: false toFile: 0. fileStream shorten; close!fileOutCategory: aString on: aFileStream moveSource: moveSource toFile: fileIndex "File a description of the receiver's category, aString, onto aFileStream. If the boolean argument, moveSource, is true, then set the trailing bytes to the position of aFileStream and to fileIndex in order to indicate where to find the source code." self printCategoryChunk: aString on: aFileStream. (self organization listAtCategoryNamed: aString) do: [:sel | self printMethodChunk: sel on: aFileStream moveSource: moveSource toFile: fileIndex]. aFileStream nextChunkPut: ' '!fileOutChangedMessages: aSet on: aFileStream "File a description of the messages of the receiver that have been changed (i.e., are entered into the system ChangeSet) onto aFileStream." self fileOutChangedMessages: aSet on: aFileStream moveSource: false toFile: 0!fileOutChangedMessages: aSet on: aFileStream moveSource: moveSource toFile: fileIndex "File a description of the messages of the receiver that have been changed (i.e., are entered into the system ChangeSet) onto aFileStream. If the boolean argument, moveSource, is true, then set the trailing bytes to the position of aFileStream and to fileIndex in order to indicate where to find the source code." | org sels | (org _ self organization) categories do: [:cat | sels _ (org listAtCategoryNamed: cat) select: [:sel | aSet includes: sel]. sels size > 0 ifTrue: [Transcript cr; show: self name , '>' , cat. self printCategoryChunk: cat on: aFileStream. sels do: [:sel | self printMethodChunk: sel on: aFileStream moveSource: moveSource toFile: fileIndex]. aFileStream nextChunkPut: ' ']]!fileOutMessage: aString "Create a fileName which is the name of the receiver with -.st as the extension, and file a description of the receiver's message aString onto it" self fileOutMessage: aString fileName: (Disk checkName: self name , '-' , aString , '.st' fixErrors: true)!fileOutMessage: aString fileName: fileName "Create a local file named fileName and file a description of the receiver's message aString onto it" | fileStream | fileStream _ Disk file: fileName. fileStream timeStamp. self fileOutMessage: aString on: fileStream moveSource: false toFile: 0. fileStream close!fileOutMessage: aString on: aFileStream moveSource: moveSource toFile: fileIndex "File a description of the receiver's message, aString, onto aFileStream. If the boolean argument, moveSource, is true, then set the trailing bytes to the position of aFileStream and to fileIndex in order to indicate where to find the source code." | cat | cat _ self organization categoryOfElement: aString. cat == nil ifTrue: [^self error: 'no such message']. self printCategoryChunk: cat on: aFileStream. self printMethodChunk: aString on: aFileStream moveSource: moveSource toFile: fileIndex. aFileStream nextChunkPut: ' '!fileOutOn: aFileStream "File a description of the receiver on aFileStream." self fileOutOn: aFileStream moveSource: false toFile: 0!fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex "file me out on aFileStream" aFileStream emphasis: 5. "Meant to be 12 point bold font." aFileStream nextChunkPut: self definition. self organization putCommentOnFile: aFileStream numbered: fileIndex moveSource: moveSource. aFileStream cr. self organization categories do: [:heading | self fileOutCategory: heading on: aFileStream moveSource: moveSource toFile: fileIndex]!fileOutOrganizationOn: aFileStream "File a description of the receiver's organization onto aFileStream." aFileStream emphasis: 3. aFileStream cr; nextPut: $!!. aFileStream nextChunkPut: self name, ' reorganize'; cr. aFileStream nextChunkPut: self organization printString; cr. aFileStream emphasis: 1!kindOfSubclass "Answer a string that describes what kind of subclass the receiver is, i.e., variable, variable byte, variable word, or not variable." self isVariable ifTrue: [self isBits ifTrue: [self isBytes ifTrue: [^' variableByteSubclass: '] ifFalse: [^' variableWordSubclass: ']] ifFalse: [^' variableSubclass: ']] ifFalse: [^' subclass: ']!methodsFor: aString "Answer a ClassCategoryReader for accessing the messages in the method dictionary category, aString, of the receiver." ^ClassCategoryReader class: self category: aString asSymbol "False methodsFor: 'logical operations' inspect"!moveChangesTo: newFile "Used in the process of condensing changes, this message requests that the source code of all methods of the receiver that have been changed should be moved to newFile." | changes | self organization moveChangedCommentToFile: newFile numbered: 2. changes _ methodDict keys select: [:sel | (methodDict at: sel) fileIndex > 1]. self fileOutChangedMessages: changes on: newFile moveSource: true toFile: 2!printCategoryChunk: aString on: aFileStream "print category definition on aFileStream" aFileStream cr; cr; nextPut: $!!. aFileStream nextChunkPut: self name , ' methodsFor: ' , '''' , aString , ''''!printMethodChunk: aSelector on: aFileStream moveSource: moveSource toFile: fileIndex "Print the source code for the method associated with the argument selector onto the fileStream. aFileStream, and, for backup, if the argument moveSource (a Boolean) is true, also set the file index within the method to be the argument fileIndex. " | position | aFileStream cr. Cursor write showWhile: [moveSource ifTrue: [position _ aFileStream position. aFileStream nextChunkPut: (self sourceCodeAt: aSelector). (self compiledMethodAt: aSelector) setSourcePosition: position inFile: fileIndex] ifFalse: [aFileStream cr; nextChunkPut: (self sourceCodeAt: aSelector)]]!printOutCategory: aString "Create a readable version of the message category aString, and send to a printer. Defaults to fileOut." self fileOutCategory: aString!printOutMessage: aString "Create a readable version of the message with selector aString, and send to a printer. Defaults to fileOut." self fileOutMessage: aString! !!ClassDescription methodsFor: 'private'!errorCategoryName self error: 'Category name must be a String'! ! Object subclass: #ClassOrganizer instanceVariableNames: 'globalComment categoryArray categoryStops elementArray ' classVariableNames: 'Default ' poolDictionaries: '' category: 'Kernel-Support'!ClassOrganizer comment: 'Instance variables: globalComment <RemoteString> comment for the class as a whole categoryArray <Array of: String> category names categoryStops <Array of: Integer> see below elementArray <Array of: Symbol> message selectorsClassOrganizers contain the categorization information for classes. A ClassOrganizer consists of an Array of category names (categoryArray), each of which refers to an Array of elements (elementArray). This association is made through an Array of stop indices (categoryStops), each of which is the index in elementArray of the last element (if any) of the corresponding category. For example: categories _ Array with: #firstCat with: secondCat with: thirdCat stops _ Array with: 1 with: 4 with: 4 elements _ Array with: #a with: #b with: #c with: #d means that category firstCat has ony #a, secondCat has #b, #c, and #d, and thirdCat has no elements. This means that stops at: stops size must be the same as elements size.'!!ClassOrganizer methodsFor: 'accessing'!changeFromString: aString "Parse the string and make this be the receiver's structure. Categories or elements not found are not affected. New elements are ignored." | scanner oldElements newElements newCategories newStops currentStop anArray | scanner _ Scanner new scanTokens: aString. "If nothing was scanned and I had no elements before, then default me" (scanner size = 0 and: [elementArray size = 0]) ifTrue: [^self setDefaultList]. oldElements _ elementArray asSet. newCategories _ Array new: scanner size. newStops _ Array new: scanner size. currentStop _ 0. newElements _ WriteStream on: (Array new: 16). 1 to: scanner size do: [:i | anArray _ scanner at: i. newCategories at: i put: anArray first asSymbol. (anArray copyFrom: 2 to: anArray size) asSortedCollection do: [:elem | (oldElements remove: elem ifAbsent: [nil]) notNil ifTrue: [newElements nextPut: elem. currentStop _ currentStop+1]]. newStops at: i put: currentStop]. "Ignore extra elements but don't lose any existing elements!!" oldElements _ oldElements collect: [:elem | Array with: (self categoryOfElement: elem) with: elem]. newElements _ newElements contents. categoryArray _ newCategories. categoryStops _ newStops. elementArray _ newElements. oldElements do: [:pair | self classify: pair last under: pair first].! !!ClassOrganizer methodsFor: 'categories'!addCategory: heading "Add a new category named heading." ^ self addCategory: heading before: nil!addCategory: heading before: nextHeading | nextIndex elements | "Add a new category named heading. If nextHeading is specified (not nil) and can be found, then INSERT before that entry. Otherwise ADD it at the end. If heading already exists, then MOVE it where it would have gone otherwise." (categoryArray indexOf: heading) > 0 ifTrue: "already there - maybe move" ["slow but sure; remove all, then insert all" elements _ self listAtCategoryNamed: heading. "Save elements" elements do: [:elt | self removeElement: elt]. self removeCategory: heading. "Remove old entry" self addCategory: heading before: nextHeading. "Now insert anew" self classifyAll: elements under: heading. "And restore elements" ^self]. nextIndex _ categoryArray indexOf: nextHeading ifAbsent: [categoryArray size+1]. categoryArray _ categoryArray "insert before nextIndex" copyReplaceFrom: nextIndex to: nextIndex-1 with: (Array with: heading). categoryStops _ categoryStops copyReplaceFrom: nextIndex to: nextIndex-1 with: (Array with: (nextIndex=1 ifTrue: [0] ifFalse: [categoryStops at: nextIndex-1])).!categories "Answer an array of categories (names)." (categoryArray size = 1 and: [categoryArray first = Default & (elementArray size = 0)]) ifTrue: [^Array new]. ^categoryArray!categories: anArray "Reorder my categories to be in the order of anArray. If the resulting organization does not include all elements, then give an error." | newCategories newStops newElements catName list runningTotal | newCategories _ Array new: anArray size. newStops _ Array new: anArray size. newElements _ Array new: 0. runningTotal _ 0. 1 to: anArray size do: [:i | catName _ (anArray at: i) asSymbol. list _ self listAtCategoryNamed: catName. newElements _ newElements, list. newCategories at: i put: catName. newStops at: i put: (runningTotal _ runningTotal + list size)]. elementArray do: [:element | "check to be sure all elements are included" (newElements includes: element) ifFalse: [^self error: 'New categories must match old ones']]. "Everything is good, now update my three arrays." categoryArray _ newCategories. categoryStops _ newStops. elementArray _ newElements!categoryOfElement: element "Answer the category associated with the argument, element." | index | index _ self numberOfCategoryOfElement: element. index = 0 ifTrue: [^nil] ifFalse: [^categoryArray at: index]!removeCategory: cat "Remove the category named, cat. Create an error if the category has any elements in it." | index lastStop | index _ categoryArray indexOf: cat ifAbsent: [^self]. lastStop _ index = 1 ifTrue: [0] ifFalse: [categoryStops at: index - 1]. (categoryStops at: index) - lastStop > 0 ifTrue: [^self error: 'cannot remove non-empty category']. categoryArray _ (categoryArray copyFrom: 1 to: index - 1) , (categoryArray copyFrom: index + 1 to: categoryArray size). categoryStops _ (categoryStops copyFrom: 1 to: index - 1) , (categoryStops copyFrom: index + 1 to: categoryStops size). categoryArray size = 0 ifTrue: [categoryArray _ Array with: Default. categoryStops _ Array with: 0]!removeEmptyCategories "Remove empty categories." | categoryIndex currentStop keptCategories keptStops | keptCategories _ WriteStream on: (Array new: 16). keptStops _ WriteStream on: (Array new: 16). currentStop _ categoryIndex _ 0. [(categoryIndex _ categoryIndex + 1) <= categoryArray size] whileTrue: [(categoryStops at: categoryIndex) > currentStop ifTrue: [keptCategories nextPut: (categoryArray at: categoryIndex). keptStops nextPut: (currentStop _ categoryStops at: categoryIndex)]]. categoryArray _ keptCategories contents. categoryStops _ keptStops contents. categoryArray size = 0 ifTrue: [categoryArray _ Array with: Default. categoryStops _ Array with: 0] "ClassOrganizer allInstancesDo: [:co | co removeEmptyCategories]."!renameCategory: oldName to: newName "Answer the array of elements associated with the name, categoryName." | i symbol | i _ categoryArray indexOf: oldName ifAbsent: [^ false]. symbol _ newName asSymbol. categoryArray indexOf: symbol ifAbsent: [categoryArray at: i put: symbol. ^ true]. ^ false "newName was already there"! !!ClassOrganizer methodsFor: 'elements'!classify: element under: heading "Store the argument, element, in the category named heading." | catName catIndex elemIndex realHeading | realHeading _ heading asSymbol. (catName _ self categoryOfElement: element) ~~ nil ifTrue: "Element already there" [realHeading = Default ifTrue: [^self]. "Default causes no change" realHeading = catName ifTrue: [^self]. "heading didnt change" self removeElement: element]. "remove from old heading if did change" (categoryArray indexOf: realHeading) = 0 ifTrue: [self addCategory: realHeading]. "add realHeading if not there already" catIndex _ categoryArray indexOf: realHeading. elemIndex _ catIndex > 1 ifTrue: [categoryStops at: catIndex - 1] ifFalse: [0]. [(elemIndex _ elemIndex + 1) <= (categoryStops at: catIndex) and: [element >= (elementArray at: elemIndex)]] whileTrue. "elemIndex is now the index for inserting the element. Do the insertion before it." elementArray _ (elementArray copyFrom: 1 to: elemIndex - 1) , (Array with: element) , (elementArray copyFrom: elemIndex to: elementArray size). "insertion" "add one to stops for this and later categories" catIndex to: categoryArray size do: [:i | categoryStops at: i put: (categoryStops at: i) + 1]. "remove empty default category if any" categoryArray indexOf: Default ifAbsent: [^self]. (self listAtCategoryNamed: Default) size = 0 ifTrue: [self removeCategory: Default].!classifyAll: aCollection under: heading aCollection do: [:element | self classify: element under: heading]!includesElement: element ^ (self categoryOfElement: element) ~~ nil!listAtCategoryNamed: categoryName "Answer the array of elements associated with the name, categoryName." | i | i _ categoryArray indexOf: categoryName ifAbsent: [^Array new]. ^self listAtCategoryNumber: i!removeElement: element "Remove the selector, element, from all categories." | categoryIndex elementIndex nextStop newElements | categoryIndex _ 1. elementIndex _ 0. nextStop _ 0. "nextStop keeps track of the stops in the new element array" newElements _ WriteStream on: (Array new: elementArray size). [(elementIndex _ elementIndex + 1) <= elementArray size] whileTrue: [[elementIndex > (categoryStops at: categoryIndex)] whileTrue: [categoryStops at: categoryIndex put: nextStop. categoryIndex _ categoryIndex + 1]. element = (elementArray at: elementIndex) ifFalse: [nextStop _ nextStop + 1. newElements nextPut: (elementArray at: elementIndex)]]. [categoryIndex <= categoryStops size] whileTrue: [categoryStops at: categoryIndex put: nextStop. categoryIndex _ categoryIndex + 1]. elementArray _ newElements contents! !!ClassOrganizer methodsFor: 'comment'!classComment "Answer the comment associated with the object that refers to the receiver." globalComment == nil ifTrue: [^'']. ^globalComment string!classComment: aString "Store the comment, aString, associated with the object that refers to the receiver." aString size = 0 ifTrue: [globalComment _ nil] ifFalse: [globalComment _ RemoteString newString: aString onFileNumber: 2]!hasNoComment "Answer whether the class classified by the receiver has a comment." ^globalComment == nil!moveChangedCommentToFile: aFileStream numbered: sourceIndex "This is part of source code compression. Move the comment about the class classified by the receiver from the file referenced by sourceIndex and to the stream, aFileStream." (globalComment ~~ nil and: [globalComment sourceFileNumber > 1]) ifTrue: [aFileStream cr; cr. globalComment _ RemoteString newString: globalComment string onFileNumber: sourceIndex toFile: aFileStream]!putCommentOnFile: aFileStream numbered: sourceIndex moveSource: moveSource "Store the comment about the class onto file, aFileStream." | newRemoteString saveEmphasis | saveEmphasis _ aFileStream emphasis. aFileStream emphasis: 3. "meant to be 10 point italic font" globalComment ~~ nil ifTrue: [aFileStream cr. newRemoteString _ RemoteString newString: globalComment string onFileNumber: sourceIndex toFile: aFileStream. moveSource ifTrue: [globalComment _ newRemoteString]]. aFileStream emphasis: saveEmphasis.! !!ClassOrganizer methodsFor: 'printing'!printOn: aStream | elementIndex lastStop | elementIndex _ 1. lastStop _ 1. 1 to: categoryArray size do: [:i | aStream nextPut: $(. (categoryArray at: i) asString printOn: aStream. [elementIndex <= (categoryStops at: i)] whileTrue: [aStream space. (elementArray at: elementIndex) printOn: aStream. elementIndex _ elementIndex + 1]. aStream nextPut: $). aStream cr]! !!ClassOrganizer methodsFor: 'fileIn/Out'!scanFrom: aStream "Reads in the organization from the next chunk on aStream. Categories or elements not found in the definition are not affected. New elements are ignored." self changeFromString: aStream nextChunk! !!ClassOrganizer methodsFor: 'private'!listAtCategoryNumber: index "Answer the array of elements stored at the position index." | firstIndex lastIndex | firstIndex _ index = 1 ifTrue: [1] ifFalse: [(categoryStops at: index - 1) + 1]. lastIndex _ categoryStops at: index. ^ elementArray copyFrom: firstIndex to: lastIndex!numberOfCategoryOfElement: element "Answer the index of the category with which the argument, element, is associated." | categoryIndex elementIndex | categoryIndex _ 1. elementIndex _ 0. [(elementIndex _ elementIndex + 1) <= elementArray size] whileTrue: ["point to correct category" [elementIndex > (categoryStops at: categoryIndex)] whileTrue: [categoryIndex _ categoryIndex + 1]. "see if this is element" element = (elementArray at: elementIndex) ifTrue: [^categoryIndex]]. ^0!setDefaultList self classComment: ''. categoryArray _ categoryStops _ elementArray _ Array new!setDefaultList: aSortedCollection self classComment: ''. categoryArray _ Array with: Default. categoryStops _ Array with: aSortedCollection size. elementArray _ aSortedCollection asArray! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ClassOrganizer class instanceVariableNames: ''!!ClassOrganizer class methodsFor: 'class initialization'!defaultProtocol ^Default!initialize Default _ 'As yet unclassified' asSymbol "ClassOrganizer initialize"! !!ClassOrganizer class methodsFor: 'instance creation'!new "Answer a new instance of ClassOrganizer with no initial elements." ^super new setDefaultList! !ClassOrganizer initialize! ClassChange subclass: #ClassOtherChange instanceVariableNames: 'type ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ClassOtherChange comment:'I represent a change to a class, other than a class definition. Possible types are: comment, initialize, inst vars for, rename, rename to'!!ClassOtherChange methodsFor: 'accessing'!name ^' ', type, ' ', className!type ^type!type: aSymbol type _ aSymbol! !!ClassOtherChange methodsFor: 'checking'!checkWith: aChecker aChecker changesAt: className add: self. type == 'inst vars for' asSymbol ifFalse: [aChecker addDoIt: self]! ! Change subclass: #ClassRelatedChange instanceVariableNames: 'className ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!ClassRelatedChange comment:'I am a change related in some way to a particular class.'!!ClassRelatedChange methodsFor: 'accessing'!className ^className!className: aSymbol className _ aSymbol asSymbol!classObject | class | ^Smalltalk at: className ifAbsent: [(className size > 6 and: [(className copyFrom: className size - 5 to: className size) = ' class']) ifTrue: [class _ Smalltalk at: (className copyFrom: 1 to: className size - 6) asSymbol ifAbsent: [^nil]. (class isKindOf: Class) ifTrue: [class class] ifFalse: [nil]] ifFalse: [nil]]!getSource "Set me up to point to the version of this change which is currently installed in the system." self subclassResponsibility!parameters ^className! ! TextController subclass: #CodeController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!CodeController comment:'This controller adds some capability appropriate only to viewing Smalltalk code,such as ''explain'' and ''format''.'!!CodeController methodsFor: 'menu messages'!doIt "Evaluate the current text selection as an expression" | result selectionStart oldTextSize selection | self controlTerminate. selectionStart _ startBlock stringIndex. oldTextSize _ self text size. selection _ self selection. result _ model doItReceiver class evaluatorClass new evaluate: self selectionAsStream in: model doItContext to: model doItReceiver notifying: self ifFail: [self controlInitialize. ^#failedDoit]. self selection asString = selection asString ifFalse: [self selectFrom: selectionStart "Reselect doIt range after compiler interaction" to: selectionStart + selection size - 1 + (self text size - oldTextSize)]. Smalltalk logChange: self selection string. model doItValue: result. self controlInitialize. ^result!explain "Try to shed some light on what kind of entity the current selection is. The selection must be a single token or construct. Insert the answer after the selection. Call private routines whose names begin with 'explain'. They return a String if they recognise the selection, else nil." | reply | reply _ (Explainer new class: model selectedClass selector: model selector instance: model doItReceiver context: model doItContext methodText: model text) explain: self selection string for: model. reply size = 0 ifTrue: [reply _ '"Sorry, I can''t explain that. Please select a single token, construct, or special character.' , (model isUnlocked ifTrue: ['"'] ifFalse: [' Also, please cancel or accept."']).]. self insertAndSelect: reply at: stopBlock stringIndex!format "Reformat the contents of the receiver's view, formatted, if the view is unlocked." | selectedClass aCompiler newText | Sensor leftShiftDown ifTrue: [^self miniFormat]. self textHasChanged ifTrue: [view flash. ^self]. selectedClass _ model selectedClass. self controlTerminate. Cursor execute showWhile: [aCompiler _ selectedClass compilerClass new. self selectFrom: 1 to: paragraph text size. self deselect. newText _ aCompiler format: model text in: selectedClass notifying: self. newText == nil ifFalse: [self replaceSelectionWith: (newText asText makeSelectorBoldIn: selectedClass). self selectAt: 1]]. self controlInitialize!localMenuItem: selector ^ (#(doIt printIt format explain) includes: selector) or: [super localMenuItem: selector]!miniFormat "Replace selection with selection un-wrapped." | inStream outStream char | inStream _ ReadStream on: (self selection copyWithout: Character tab). outStream _ WriteStream on: (String new: self selection size). [inStream atEnd] whileFalse: [char _ inStream next. char isSeparator ifTrue: [outStream space. [inStream atEnd not and: [inStream peek isSeparator]] whileTrue: [inStream next]] ifFalse: [outStream nextPut: char]]. self deselect. self replaceSelectionWith: outStream contents asText. self select!printIt "Evaluate the current selection as an expression. If successful, insert and select the printString of the result of evaluation after the current selection." | result | result _ self doIt. result ~~ #failedDoit ifTrue: [self insertAndSelect: result printString at: stopBlock stringIndex]! ! TextView subclass: #CodeView instanceVariableNames: 'initialSelection ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!CodeView comment:'I am a TextView that assumes the text is code. I include support for initial selection of a part of the text.'!!CodeView methodsFor: 'initialize-release'!initialSelection: sel initialSelection _ sel!newText: aText super newText: aText. initialSelection==nil ifFalse: [self controller findAndSelect: initialSelection]! !!CodeView methodsFor: 'controller access'!defaultControllerClass ^ CodeController! !!CodeView methodsFor: 'updating'!update: aSymbol | range | aSymbol == #pc ifTrue: [range _ model pcRange. self controller selectAndScrollFrom: range first to: range last]. super update: aSymbol! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!CodeView class instanceVariableNames: ''!!CodeView class methodsFor: 'instance creation'!on: anObject aspect: m1 change: m3 menu: m4 initialSelection: sel "Create an instance viewing anObject. See super method in TextView for full explanation. initialSelection (if not nil) is a string which will be searched for, and then highlighted if found, whenever the viewed text changes." ^ (super on: anObject aspect: m1 change: m3 menu: m4) initialSelection: sel! ! Object subclass: #Collection instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Abstract'!Collection comment: 'I am the abstract class of all collection classes.'!!Collection methodsFor: 'accessing'!size "Answer how many elements the receiver contains." | tally | tally _ 0. self do: [:each | tally _ tally + 1]. ^tally! !!Collection methodsFor: 'testing'!includes: anObject "Answer whether anObject is one of the receiver's elements." self do: [:each | anObject = each ifTrue: [^true]]. ^false!isEmpty "Answer whether the receiver contains any elements." ^self size = 0!occurrencesOf: anObject "Answer how many of the receiver's elements are equal to anObject." | tally | tally _ 0. self do: [:each | anObject = each ifTrue: [tally _ tally + 1]]. ^tally! !!Collection methodsFor: 'adding'!add: newObject "Include newObject as one of the receiver's elements. Answer newObject. This message should not be sent to instances of subclasses of ArrayedCollection." self subclassResponsibility!addAll: aCollection "Include all the elements of aCollection as the receiver's elements. Answer aCollection." aCollection do: [:each | self add: each]. ^aCollection! !!Collection methodsFor: 'removing'!remove: oldObject "Remove oldObject as one of the receiver's elements. Answer oldObject unless no element is equal to oldObject, in which case, create an error message." ^self remove: oldObject ifAbsent: [self errorNotFound]!remove: oldObject ifAbsent: anExceptionBlock "Remove oldObject as one of the receiver's elements. If several of the elements are equal to oldObject, only one is removed. If no element is equal to oldObject, answer the result of evaluating anExceptionBlock. Otherwise, answer the argument, oldObject. SequenceableCollections can not respond to this message." self subclassResponsibility!removeAll: aCollection "Remove each element of aCollection from the receiver. If successful for each, answer aCollection." aCollection do: [:each | self remove: each]. ^aCollection! !!Collection methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect the resulting values into a collection that is like the receiver. Answer the new collection. " | newCollection | newCollection _ self species new. self do: [:each | newCollection add: (aBlock value: each)]. ^newCollection!detect: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Answer the first element for which aBlock evaluates to true." ^self detect: aBlock ifNone: [self errorNotFound]!detect: aBlock ifNone: exceptionBlock "Evaluate aBlock with each of the receiver's elements as the argument. Answer the first element for which aBlock evaluates to true." self do: [:each | (aBlock value: each) ifTrue: [^each]]. ^exceptionBlock value!do: aBlock "Evaluate aBlock with each of the receiver's elements as the argument." self subclassResponsibility!inject: thisValue into: binaryBlock "Accumulate a running value associated with evaluating the argument, binaryBlock, with the current value and the receiver as block arguments. The initial value is the value of the argument, thisValue. For instance, to sum a collection, use: collection inject: 0 into: [:subTotal :next | subTotal + next]." | nextValue | nextValue _ thisValue. self do: [:each | nextValue _ binaryBlock value: nextValue value: each]. ^nextValue!reject: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect into a new collection like the receiver, only those elements for which aBlock evaluates to false. Answer the new collection." ^self select: [:element | (aBlock value: element) == false]!select: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect into a new collection like the receiver, only those elements for which aBlock evaluates to true. Answer the new collection." | newCollection | newCollection _ self species new. self do: [:each | (aBlock value: each) ifTrue: [newCollection add: each]]. ^newCollection! !!Collection methodsFor: 'printing'!printOn: aStream | tooMany | tooMany _ aStream position + self maxPrint. aStream nextPutAll: self class name, ' ('. self do: [:element | aStream position > tooMany ifTrue: [aStream nextPutAll: '...etc...)'. ^self]. element printOn: aStream. aStream space]. aStream nextPut: $)!storeOn: aStream | noneYet | aStream nextPutAll: '(('. aStream nextPutAll: self class name. aStream nextPutAll: ' new)'. noneYet _ true. self do: [:each | noneYet ifTrue: [noneYet _ false] ifFalse: [aStream nextPut: $;]. aStream nextPutAll: ' add: '. aStream store: each]. noneYet ifFalse: [aStream nextPutAll: '; yourself']. aStream nextPut: $)! !!Collection methodsFor: 'converting'!asBag "Answer a new instance of Bag whose elements are the elements of the receiver." | aBag | aBag _ Bag new. self do: [:each | aBag add: each]. ^aBag!asOrderedCollection "Answer a new instance of OrderedCollection whose elements are the elements of the receiver. The order in which elements are added depends on the order in which the receiver enumerates its elements. In the case of unordered collections, the ordering is not necessarily the same for multiple requests for the conversion." | anOrderedCollection | anOrderedCollection _ OrderedCollection new: self size. self do: [:each | anOrderedCollection addLast: each]. ^anOrderedCollection!asSet "Answer a new instance of Set whose elements are the unique elements of the receiver." | aSet | aSet _ Set new: self size. self do: [:each | aSet add: each]. ^aSet!asSortedCollection "Answer a new instance of SortedCollection whose elements are the elements of the receiver. The sort order is the default less than or equal ordering." | aSortedCollection | aSortedCollection _ SortedCollection new: self size. aSortedCollection addAll: self. ^aSortedCollection!asSortedCollection: aBlock "Answer a new instance of SortedCollection whose elements are the elements of the receiver. The sort order is defined by the argument, aBlock." | aSortedCollection | aSortedCollection _ SortedCollection new: self size. aSortedCollection sortBlock: aBlock. aSortedCollection addAll: self. ^aSortedCollection! !!Collection methodsFor: 'private'!emptyCheck self isEmpty ifTrue: [self errorEmptyCollection]!errorEmptyCollection self error: 'this collection is empty'!errorNoMatch self error: 'collection sizes do not match'!errorNotFound self error: 'Object is not in the collection.'!errorNotKeyed self error: self class name, 's do not respond to keyed accessing messages.'!growSize "Answer an amount by which the receiver should grow to make room for more elements (in response to the message 'grow')." self basicSize >= self maxSize ifTrue: [self error: 'unable to grow this collection']. ^(self basicSize max: 2) min: self maxSize - self basicSize!maxPrint "Answer the maximum number of characters to print with printOn:." ^5000!maxSize "Answer the largest basicSize which is valid for the receiver's class." ^65486 "for VM3 interpreter DoradoST80Aug19"! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Collection class instanceVariableNames: ''!!Collection class methodsFor: 'instance creation'!with: anObject "Answer a new instance of me containing anObject." | newCollection | newCollection _ self new. newCollection add: anObject. ^newCollection!with: firstObject with: secondObject "Answer a new instance of me containing the two arguments as elements." | newCollection | newCollection _ self new. newCollection add: firstObject. newCollection add: secondObject. ^newCollection!with: firstObject with: secondObject with: thirdObject "Answer with a new instance of me containing the three arguments as elements." | newCollection | newCollection _ self new. newCollection add: firstObject. newCollection add: secondObject. newCollection add: thirdObject. ^newCollection!with: firstObject with: secondObject with: thirdObject with: fourthObject "Answer a new instance of me, containing the four arguments as the elements." | newCollection | newCollection _ self new. newCollection add: firstObject. newCollection add: secondObject. newCollection add: thirdObject. newCollection add: fourthObject. ^newCollection! ! ByteArray variableByteSubclass: #CompiledMethod instanceVariableNames: '' classVariableNames: 'BytesForHeader BytesPerLiteral LargeFrame SmallFrame SpecialConstants TempNameCache ' poolDictionaries: '' category: 'Kernel-Methods'!CompiledMethod comment:'I represent a method suitable for interpretation by the virtual machine. My instances have pointer fields, including a header and some literals, followed by non-pointer fields comprising the byte encoded instructions for the method. The header encodes the number of arguments, the number of literals, and the amount of temporary space needed (for context allocation).An extra three bytes are added after the executable code. These contain an external file address to the source code for the method.Instance Variables: *byte indexed*'!!CompiledMethod methodsFor: 'initialize-release'!needsStack: newStackSize encoder: encoder "If newStackSize does not fit in the receiver, then the receiver becomes a method with large stack." | newMethod newNumLits extraBytes largeBit | (self numTemps + newStackSize + 1) <= SmallFrame ifTrue: ["no problem" ^ self]. (self numTemps + newStackSize + 1) > LargeFrame ifTrue: [^self error: 'Stack (including temps) is too deep']. newMethod _ CompiledMethod newBytes: self endPC - self initialPC + 1 flags: self flags nTemps: self numTemps nStack: newStackSize nLits: self numLiterals. 1 to: self numLiterals do: [:index | newMethod literalAt: index put: (self literalAt: index)]. extraBytes _ 0. self initialPC to: self size do: [:index | newMethod at: index+extraBytes put: (self at: index)]. self become: newMethod! !!CompiledMethod methodsFor: 'accessing'!endPC "Answer the index of the last bytecode." (self last between: 120 and: 124) ifTrue: [^self size]. ^self size - 3!flags "Answer the 3-bit number that indicates the number of arguments the receiver takes and whether it is associated with a primitive." ^(self header bitShift: -12) bitAnd: 7!frameSize "Answer the size of temporary frame needed to run the receiver." self needsLargeFrame ifTrue: [^ LargeFrame] ifFalse: [^ SmallFrame]!initialPC "Answer the program counter for the receiver's first bytecode." ^self numLiterals * BytesPerLiteral + BytesForHeader + 1!numArgs "Answer the number of arguments the receiver takes." | flags | (flags _ self flags) <= 4 ifTrue: [^flags]. flags < 7 ifTrue: [^0]. ^((self literalAt: self numLiterals - 1) bitShift: -8) bitAnd: 31!numLiterals "Answer the number of literals used by the receiver." self isQuick ifTrue: [^0]. ^self header bitAnd: 63!numStack "Answer the size of the available stack." self isQuick ifTrue: [^0] "The method was simply a return of self or instance variable." ifFalse: [^self frameSize - self numTemps - self numArgs]!numTemps "Answer the number of temporary variables used by the receiver." self isQuick ifTrue: [^0] ifFalse: [^self numTempsField]!numTempsField "Answer the 5-bit number that indicates the number of temporary variables the receiver uses." ^self header // 128 bitAnd: 31!primitive "Answer the primitive index associated with the receiver. Zero indicates that there is either no primitive or just a quick primitive." self flags < 7 ifTrue: [^0] ifFalse: [^(self literalAt: self numLiterals - 1) bitAnd: 255 ]!returnField "Answer the index of the instance variable returned by a quick return method." self flags ~= 6 ifTrue: [self error: 'only meaningful for quick-return'] ifFalse: [^self numTempsField]! !!CompiledMethod methodsFor: 'testing'!isQuick "Answer whether the receiver is a quick return (of self or of an instance variable)." ^self flags between: 5 and: 6!isReturnField "Answer whether the receiver is a quick return of an instance variable." ^self flags = 6!isReturnSelf "Answer whether the receiver is a quick return of self." ^self flags = 5!needsLargeFrame ^self header allMask: 64! !!CompiledMethod methodsFor: 'printing'!printOn: aStream "Overrides method inherited from the byte arrayed collection" aStream nextPutAll: 'a CompiledMethod'!storeOn: aStream | noneYet index | aStream nextPutAll: '(('. aStream nextPutAll: self class name. aStream nextPutAll: ' newMethod: '. aStream store: self size - self initialPC + 1. aStream nextPutAll: ' header: '. aStream store: self header. aStream nextPut: $). noneYet _ self storeElementsFrom: self initialPC to: self endPC on: aStream. 1 to: self numLiterals do: [:index | noneYet ifTrue: [noneYet _ false] ifFalse: [aStream nextPut: $;]. aStream nextPutAll: ' literalAt: '. aStream store: index. aStream nextPutAll: ' put: '. aStream store: (self literalAt: index)]. noneYet ifFalse: [aStream nextPutAll: '; yourself']. aStream nextPut: $)!symbolic "Answer a String that contains a list of all the byte codes in a method with a short description of each." | aStream | self isQuick ifTrue: [self isReturnSelf ifTrue: [^'Quick return self']. ^'Quick return field ' , self returnField printString , ' (0-based)']. aStream _ WriteStream on: (String new: 1000). self primitive > 0 ifTrue: [aStream nextPutAll: '<primitive: '. aStream print: self primitive. aStream nextPut: $>. aStream cr]. (InstructionPrinter on: self) printInstructionsOn: aStream. ^aStream contents!who "Answer an Array of the class in which the receiver is defined and the selector to which it corresponds." Smalltalk allBehaviorsDo: [:class | class selectors do: [:sel | (class compiledMethodAt: sel) == self ifTrue: [^Array with: class with: sel]]]! !!CompiledMethod methodsFor: 'literals'!header "Answer the word containing the information about the form of the receiver and the form of the context needed to run the receiver." ^self objectAt: 1!literalAt: index "Answer the literal indexed by the argument." ^self objectAt: index + 1!literalAt: index put: value "Replace the literal indexed by the first argument with the second argument." ^self objectAt: index + 1 put: value!literals "Answer with an array of the literals referenced by the receiver." | literals numberLiterals index | literals _ Array new: (numberLiterals _ self numLiterals). index _ 0. [(index _ index + 1) <= numberLiterals] whileTrue: [literals at: index put: (self objectAt: index + 1)]. ^literals!objectAt: index "Answer with the method header (if index=1) or a literal (if index >1) from the receiver. Essential. See Object documentation whatIsAPrimitive." <primitive: 68> self primitiveFailed!objectAt: index put: value "Store the value argument into a literal in the receiver. An index of 2 corresponds to the first literal. Fails if the index is less than 2 or greater than the number of literals. Answer the value as the result. Normally only the compiler sends this message, because only the compiler stores values in CompiledMethods. Essential. See Object documentation whatIsAPrimitive." <primitive: 69> self primitiveFailed!refersToLiteral: literal "Answer whether the receiver references the argument, literal. The last literal, if used for super, will not cause a true answer" | flags header numLiteralsPlus1 index | "numLiteralsPlus1 _ self numLiterals + 1. -- expanded for speed" header _ self objectAt: 1. flags _ (header bitShift: -12) bitAnd: 7. (flags = 6 or: [flags = 5]) ifTrue: [^ false]. numLiteralsPlus1 _ (header bitAnd: 63) + 1. index _ 1. [(index _ index + 1) <= numLiteralsPlus1] whileTrue: [literal == (self objectAt: index) ifTrue: [index < numLiteralsPlus1 ifTrue: [^ true]. "slow check for last literal which might just be super" ^ (literal isMemberOf: Association) not or: [(self readsRef: literal) or: [self writesRef: literal]]]]. ^ false! !!CompiledMethod methodsFor: 'scanning'!fieldsTouched "Answer a Set of fields touched by this method." | scanner aSet | self isReturnField ifTrue: [^ Set with: self returnField + 1]. self isReturnSelf ifTrue: [^ Set new]. aSet _ Set new. scanner _ InstructionStream on: self. scanner scanFor: [:x | scanner addFieldIndexTo: aSet. false "keep scanning"]. ^aSet!messages "Answer a Set of all the message selectors sent by this method." | scanner aSet | aSet _ Set new. scanner _ InstructionStream on: self. scanner scanFor: [:x | scanner addSelectorTo: aSet. false "keep scanning"]. ^aSet!readsField: varIndex "Answer whether the receiver loads the instance variable indexed by the argument." self isReturnField ifTrue: [^self returnField + 1 = varIndex]. varIndex <= 16 ifTrue: [^self scanFor: varIndex - 1]. ^self scanLongLoad: varIndex - 1!readsRef: literalAssociation "Answer whether the receiver loads the argument." | lit | lit _ self literals indexOf: literalAssociation ifAbsent: [^false]. lit <= 32 ifTrue: [^self scanFor: 64 + lit - 1]. ^self scanLongLoad: 192 + lit - 1!scanFor: byte "Answer whether the receiver contains the argument as a bytecode." | instr | ^(InstructionStream on: self) scanFor: [:instr | instr = byte]!scanLongLoad: extension "Answer whether the receiver contains a long load whose extension is the argument." | scanner | scanner _ InstructionStream on: self. ^scanner scanFor: [:instr | instr = 128 and: [scanner followingByte = extension]]!scanLongStore: extension "Answer whether the receiver contains a long store whose extension is the argument." | scanner | scanner _ InstructionStream on: self. ^scanner scanFor: [:instr | (instr between: 129 and: 130) and: [scanner followingByte = extension]]!writesField: field "Answer whether the receiver stores into the instance variable indexed by the argument." self isQuick ifTrue: [^false]. (field <= 8 and: [self scanFor: 96 + field - 1]) ifTrue: [^true] ifFalse: [^self scanLongStore: field - 1]!writesRef: ref "Answer whether the receiver stores the argument." | lit | lit _ self literals indexOf: ref ifAbsent: [^false]. ^self scanLongStore: 192 + lit - 1! !!CompiledMethod methodsFor: 'source code management'!cacheTempNames: names TempNameCache _ Association key: self value: names!fileIndex "Answer 1 if the source code of the receiver is on the *.sources file and 2 if it is on the *.changes file." (self last between: 120 and: 124) ifTrue: [self error: 'Somehow a method does not have a file index.']. ^self last // 64 + 1!getSource "Answer the source code for the receiver. Answer nil if there are no source files specified in the global SourceFiles." | end highByte position source | SourceFiles == nil ifTrue: [^nil]. Cursor read showWhile: [end _ self size. highByte _ self at: end. position _ highByte bitAnd: 63. position _ position * 256 + (self at: end - 1). position _ position * 256 + (self at: end - 2). position = 0 ifTrue: [source _ nil] ifFalse: [source _ (RemoteString newFileNumber: (highByte bitShift: -6) + 1 position: position) string]]. ^source!putSource: sourceStr class: class category: catName inFile: fileIndex "Print an expression that is a message to the argument, class, asking the class to accept the source code, sourceStr, as a method in category, catName. This is part of the format for writing descriptions of methods on files. If no sources are specified, i.e., SourceFile is nil, then do nothing. If the fileIndex is 1, print on *.sources; if it is 2, print on *.changes." | file remoteString | SourceFiles == nil ifTrue: [^self]. file _ SourceFiles at: fileIndex. file setToEnd; readWriteShorten. class printCategoryChunk: catName on: file. file cr. remoteString _ RemoteString newString: sourceStr onFileNumber: fileIndex toFile: file. file nextChunkPut: ' '; readOnly. self setSourcePosition: remoteString position inFile: fileIndex!putSource: sourceStr inFile: fileIndex "Store the source code for the receiver on an external file. If no sources are specified, i.e., SourceFile is nil, then do nothing. If the fileIndex is 1, print on *.sources; if it is 2, print on *.changes." | file remoteString | SourceFiles == nil ifTrue: [^self]. file _ SourceFiles at: fileIndex. file setToEnd; readWriteShorten. file cr; nextPut: $!!; nextChunkPut: 'Behavior method'; cr. remoteString _ RemoteString newString: sourceStr onFileNumber: fileIndex toFile: file. file nextChunkPut: ' '; readOnly. self setSourcePosition: remoteString position inFile: fileIndex!setSourcePosition: position inFile: fileIndex "Store the location of the source code for the receiver in the receiver. The location consists of which source file (*.sources or *.changes) and the position in that file." | index hiByte middleByte lowByte | "set last three bytes to be position in file (1-4)" fileIndex > 4 ifTrue: [^self error: 'invalid file number']. index _ self size - 2. middleByte _ position bitShift: -8. hiByte _ middleByte bitShift: -8. middleByte _ middleByte bitAnd: 255. lowByte _ position bitAnd: 255. hiByte > 62 ifTrue: [Transcript show: 'Source file is getting full!!!!'; cr]. self at: index + 2 put: fileIndex - 1 * 64 + hiByte. self at: index + 1 put: middleByte. self at: index put: lowByte!setTempNamesIfCached: aBlock TempNameCache == nil ifTrue: [^self]. TempNameCache key == self ifTrue: [aBlock value: TempNameCache value]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!CompiledMethod class instanceVariableNames: ''!!CompiledMethod class methodsFor: 'class initialization'!initialize "Initialize class variables specifying the size of the temporary frame needed to run instances of me, and the size of my instances' header and literals (which may be system-dependent.)" SmallFrame _ 12. "Context range for temps+stack" LargeFrame _ 32. BytesForHeader _ (self newMethod: 0 header: 0) size. "Just a header, no literals" BytesPerLiteral _ (self newMethod: 0 header: 1) size - BytesForHeader. "1 literal" "CompiledMethod initialize."! !!CompiledMethod class methodsFor: 'instance creation'!newBytes: numberOfBytes flags: flags nTemps: numberTemps nStack: stackSpace nLits: numberLiterals "Answer an instance of me. The header is specified by the message arguments. The remaining parts are not as yet determined." | flagBits | flags >= 4 ifTrue: [flagBits _ flags - 8] ifFalse: [flagBits _ flags]. "ensure 15-bit integer result" ^self newMethod: numberOfBytes + 3 "+3 to store source location" header: flagBits * 4096 + (numberTemps * 128) + (numberTemps + stackSpace > SmallFrame ifTrue: [64] ifFalse: [0]) + numberLiterals!newMethod: numberOfBytes header: headerWord "Answer an instance of me. The number of literals (and other information) is specified the headerWord. The first argument specifies the number of fields for bytecodes in the method. Fail if either argument is not a SmallInteger, or if numberOfBytes is negative. Once the header of a method is set by this primitive, it cannot be changed in any way. Essential. See Object documentation whatIsAPrimitive. " <primitive: 79> ^self primitiveFailed!toReturnField: field "Answer an instance of me that is a quick return of the instance variable indexed by the argument, field." ^self newBytes: 0 flags: 6 nTemps: field nStack: 0 nLits: 0!toReturnSelf "Answer an instance of me that is a quick return of the instance (^self)." ^self newBytes: 0 flags: 5 nTemps: 0 nStack: 0 nLits: 0! !CompiledMethod initialize! Object subclass: #Compiler instanceVariableNames: 'sourceStream requestor class context ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!Compiler comment:'The compiler accepts Smalltalk source code from sourceStream, and compiles it in the context of a given class. The debugger supplies a context as well, so that temporary variables are accessible. If there is an error, the requestor (usually a CodeController) is sent the message notify:at:in:. If not, then the result of compilation is a parse tree (made up of subinstances of ParseNode) whose root is a MethodNode. The parse tree can then generate code in a CompiledMethod (for compile or evaluate), or prettyPrint the code (for format), or produce a map from object code back to source code (used by debugger pc selection). See also Parser, Encoder, ParseNode.'!!Compiler methodsFor: 'error handling'!editor ^ requestor!notify: aString at: position Cursor normal show. requestor == nil ifTrue: [^SyntaxError errorInClass: class withCode: (sourceStream contents copyReplaceFrom: position to: position - 1 with: aString) errorString: aString] ifFalse: [^ requestor insertAndSelect: aString at: (position max: 1)]! !!Compiler methodsFor: 'public access'!compile: textOrStream in: aClass notifying: aRequestor ifFail: failBlock "Answer with a parse tree whose root is a MethodNode. This can then be told to generate code as is done in the calls from Behavior" self from: textOrStream class: aClass context: nil notifying: aRequestor. ^self translate: sourceStream noPattern: false ifFail: failBlock!evaluate: textOrStream in: aContext to: receiver notifying: aRequestor ifFail: failBlock "Compiles the sourceStream into a parse tree, then generates code into a method. This method is then installed in the receiver's class so that it can be invoked. In other words, if receiver is not nil, then the text can refer to instance variables of that receiver (the Inspector uses this). If aContext is not nil, the text can refer to temporaries in that context (the Debugger uses this). If aRequestor is not nil, then it will receive a notify:at: message before the attempt to evaluate is aborted. Finally, the compiled method is invoked from here as DoIt or (in the case of evaluation in aContext) DoItIn:. The method is subsequently removed from the class, but this will not get done if the invocation causes an error which is terminated. Such garbage can be removed by executing: Smalltalk allBehaviorsDo: [:cl | cl removeSelector: #DoIt; removeSelector: #DoItIn:]." | methodNode method value | Cursor execute show. class _ (aContext == nil ifTrue: [receiver] ifFalse: [aContext receiver]) class. self from: textOrStream class: class context: aContext notifying: aRequestor. methodNode _ self translate: sourceStream noPattern: true ifFail: [^failBlock value]. method _ methodNode generate: #(0 0 0). context == nil ifTrue: [class addSelector: #DoIt withMethod: method. value _ receiver DoIt. class removeSelectorSimply: #DoIt. Cursor normal show. ^value] ifFalse: [class addSelector: #DoItIn: withMethod: method. value _ receiver DoItIn: context. class removeSelectorSimply: #DoItIn:. Cursor normal show. ^value]!format: textOrStream in: aClass notifying: aRequestor "Compile a parse tree from the incoming text, and then print the parse tree to yield the answer, a string containing the original code in standard format." | aNode | self from: textOrStream class: aClass context: nil notifying: aRequestor. aNode _ self format: sourceStream noPattern: false ifFail: [^nil]. ^aNode decompileString!parse: textOrStream in: aClass notifying: req "Compile the incoming text and answer with the resulting parse tree." self from: textOrStream class: aClass context: nil notifying: req. ^self translate: sourceStream noPattern: false ifFail: []! !!Compiler methodsFor: 'private'!format: aStream noPattern: noPattern ifFail: failBlock | tree | tree _ class parserClass new parse: aStream class: class noPattern: noPattern context: context notifying: self ifFail: [^failBlock value]. ^tree!from: textOrStream class: aClass context: aContext notifying: req (textOrStream isKindOf: PositionableStream) ifTrue: [sourceStream _ textOrStream] ifFalse: [sourceStream _ ReadStream on: textOrStream asString]. class _ aClass. context _ aContext. requestor _ req!translate: aStream noPattern: noPattern ifFail: failBlock | tree | tree _ class parserClass new parse: aStream class: class noPattern: noPattern context: context notifying: self ifFail: [^failBlock value]. ^tree! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Compiler class instanceVariableNames: ''!!Compiler class methodsFor: 'evaluating'!evaluate: textOrString ^self evaluate: textOrString for: nil logged: false!evaluate: textOrString for: anObject logged: logFlag ^ self evaluate: textOrString for: anObject notifying: nil logged: logFlag!evaluate: textOrString for: anObject notifying: aController logged: logFlag "Compile and execute the supplied text (see message to instance for details). If both were successful then, if logFlag is true, log (write) the text onto the changes file so that it can be replayed if necessary." | val | val _ self new evaluate: textOrString in: nil to: anObject notifying: aController ifFail: [^nil]. logFlag ifTrue: [Smalltalk logChange: textOrString]. ^val!evaluate: textOrString logged: logFlag ^self evaluate: textOrString for: nil logged: logFlag!evaluate: textOrString notifying: aController logged: logFlag ^self evaluate: textOrString for: nil notifying: aController logged: logFlag! !!Compiler class methodsFor: 'accessing'!preferredParserClass "Return a parser class which is appropriate for parsing methods compilable by this compiler class. Should be overwritten by subclasses." ^Parser! ! CharacterScanner subclass: #CompositionScanner instanceVariableNames: 'spaceX spaceIndex ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!CompositionScanner comment:'My instances hold the state of CharacterScanner in addition to the following required only for composition.Instance Variables spaceX<Integer> Left edge of last space scanned. When line overflows this value is substracted from the rightMargin to determine how much padding is available for justification, centering, etc. spaceIndex<Integer> Character index of last space scanned in line. Installed as stop in the TextLineInterval for the line being composed. CompositionScanners are used to measure text and determine where line breaks and space padding should occur.'!!CompositionScanner methodsFor: 'initialize-release'!in: aParagraph "Initialize the paragraph to be scanned as the argument, aParagraph. Set the composition frame for the paragraph." super initializeFromParagraph: aParagraph clippedBy: aParagraph clippingRectangle! !!CompositionScanner methodsFor: 'accessing'!rightX "Meaningful only when a line has just been composed -- refers to the line most recently composed. This is a subtrefuge to allow for easy resizing of a composition rectangle to the width of the maximum line. Useful only when there is only one line in the form or when each line is terminated by a carriage return. Handy for sizing menus and lists." ^spaceX! !!CompositionScanner methodsFor: 'scanning'!composeLine: lineIndex fromCharacterIndex: startIndex inParagraph: aParagraph "Answer an instance of TextLineInterval that represents the next line in the paragraph." | runLength done stopCondition | lastIndex _ startIndex. "scanning sets last index" self setStopConditions. "also sets font" spaceX _ destX _ leftMargin _ (aParagraph leftMarginForCompositionForLine: lineIndex). rightMargin _ aParagraph rightMarginForComposition. leftMargin >= rightMargin ifTrue: [self error: 'No room between margins to compose']. runLength _ text runLengthFor: startIndex. runStopIndex _ (lastIndex _ startIndex) + (runLength - 1). line _ TextLineInterval start: lastIndex stop: 0 internalSpaces: 0 paddingWidth: 0. spaceCount _ 0. done _ false. [done] whileFalse: [stopCondition _ self scanCharactersFrom: lastIndex to: runStopIndex in: text string rightX: rightMargin stopConditions: stopConditions displaying: false. "See setStopConditions for stopping conditions for composing." (self perform: stopCondition) ifTrue: [^line]]! !!CompositionScanner methodsFor: 'stop conditions'!cr "Answer true. Sets up values for the text line interval currently being composed." line stop: lastIndex. spaceX _ destX. line paddingWidth: rightMargin - destX. ^true!crossedX "There is a word that has fallen across the right edge of the composition rectangle. This signals the need for wrapping which is done to the last space that was encountered, as recorded by the space stop condition." line stop: spaceIndex. spaceCount > 1 ifTrue: ["The common case. First back off the space at which we wrap." spaceCount _ spaceCount - 1. spaceIndex _ spaceIndex - 1. ["Check to see if any spaces preceding the one at which we wrap. Double space after a period, most likely." (spaceCount > 1 and: [(text at: spaceIndex) = Space])] whileTrue: [spaceCount _ spaceCount - 1. spaceIndex _ spaceIndex - 1. "Account for backing over a run which might change width of space." font _ self resetFont. spaceX _ spaceX - (font widthOf: Space)]. line paddingWidth: rightMargin - spaceX. line internalSpaces: spaceCount] ifFalse: [spaceCount = 1 ifTrue: ["wrap at space, but no internal spaces" line internalSpaces: 0. line paddingWidth: rightMargin - spaceX] ifFalse: ["Neither internal nor trailing spaces, almost never happen, she says confidently." lastIndex _ lastIndex - 1. [destX <= rightMargin] whileFalse: [destX _ destX - (font widthOf: (text at: lastIndex)). "bug --doesn't account for backing over run and changing actual width of characters. Also doesn't account for backing over a tab. Happens only when no spaces in line, presumably rare." lastIndex _ lastIndex - 1]. spaceX _ destX. line paddingWidth: rightMargin - destX. lastIndex < line first ifTrue: [line stop: line first] ifFalse: [line stop: lastIndex]]]. ^true!endOfRun "Answer true if scanning has reached the end of the paragraph. Otherwise set stop conditions (mostly install potential new font) and answer false." | runLength | lastIndex = text size ifTrue: [line stop: lastIndex. spaceX _ destX. line paddingWidth: rightMargin - destX. ^true] ifFalse: [runLength _ (text runLengthFor: (lastIndex _ lastIndex + 1)). runStopIndex _ lastIndex + (runLength - 1). self setStopConditions. ^false]!onePixelBackspace "Decrement destX by 1. " destX _ (destX - 1) max: leftMargin. lastIndex _ lastIndex + 1. ^false!onePixelSpace "Increment destX by 1. " destX _ destX+1. lastIndex _ lastIndex + 1. destX > rightMargin ifTrue: [^self crossedX]. ^false!setStopConditions "Set the font and the stop conditions for the current run." font _ textStyle fontAt: (text emphasisAt: lastIndex). super setStopConditions.!space "Record left x and character index of the space character just encounted. Used for wrap-around. Answer whether the character has crossed the right edge of the composition rectangle of the paragraph." spaceX _ destX. destX _ spaceX + spaceWidth. lastIndex _ (spaceIndex _ lastIndex) + 1. spaceCount _ spaceCount + 1. destX > rightMargin ifTrue: [^self crossedX]. ^false!tab "Advance destination x according to tab settings in the paragraph's textStyle. Answer whether the character has crossed the right edge of the composition rectangle of the paragraph. Scale allows use of same code for display and printing composition" destX _ textStyle nextTabXFrom: destX leftMargin: leftMargin rightMargin: rightMargin. destX > rightMargin ifTrue: [^self crossedX]. lastIndex _ lastIndex + 1. ^false! !!CompositionScanner methodsFor: 'private'!resetFont "Mainly to allow the stop condition crossedX to be shared by display and printer media." ^ textStyle fontAt: (text emphasisAt: spaceIndex)! ! Inspector subclass: #ContextInspector instanceVariableNames: 'tempNames ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Inspector'!ContextInspector comment:'I represent a query path into the internal representation of a ContextPart. Typically this is a context at a point in the query path of a Debugger. As a StringHolder, the string I represent is the value of the currently selected variable of the observed temporary variable of the context.Instance Variables: contextCode <String> the method whose activation is being inspected tempNames <Array> of Strings, each the name of a temporary variable.'!!ContextInspector methodsFor: 'field list'!fieldIndex ^ tempNames indexOf: field!fieldList object == nil ifTrue: [^nil]. ^(tempNames _ object tempNames)!fieldMenu field == nil ifTrue: [^ nil]. ^ActionMenu labels: 'inspect' selectors: #(inspectField)!fieldValue field = 'self' ifTrue: [^ object receiver]. ^ object tempAt: self fieldIndex! !!ContextInspector methodsFor: 'doIt/accept'!acceptText: aText from: aController | val | (field == nil) | (field = 'self') ifTrue: [^ false]. val _ self evaluateText: aText string from: aController ifFail: [^ false]. object tempAt: self fieldIndex put: val. self changed: #text. ^ true!doItContext ^object!doItReceiver ^object receiver! !!ContextInspector methodsFor: 'initialization'!inspect: anObject object _ anObject. self changed: #field! ! InstructionStream subclass: #ContextPart instanceVariableNames: 'stackp ' classVariableNames: 'TryPrimitiveMethods ' poolDictionaries: '' category: 'Kernel-Methods'!ContextPart comment: 'Instance Variables: stackp <Integer> indicating the offset of the top of my temporary value stackTo the instruction parsing ability of InstructionStream I add the actual semantics for execution. The execution state is stored in my subclasses indexable fields, which store temporary variables and a stack of values used in evaluating expressions. The actual semantics of execution can be found in my category "simulator", which exactly parallels the operation of the Smalltalk machine itself.'!!ContextPart methodsFor: 'accessing'!home "Answer the context in which the receiver was defined." self subclassResponsibility!method self subclassResponsibility!receiver "Answer the receiver of the message that created this context." self subclassResponsibility!sourceCode "Answer the source form of the receiver's method." | mclass selector method | method _ self method. selector _ self receiver class selectorAtMethod: method setClass: [:mclass]. ^ mclass sourceCodeForMethod: method at: selector! !!ContextPart methodsFor: 'temporaries'!tempAt: index "Answer the value of the temporary variable whose index is the argument, index." self subclassResponsibility!tempAt: index put: value "Store the argument, value, as the temporary variable whose index is the argument, index." self subclassResponsibility!tempNames "Answer an OrderedCollection of the names of the receiver's temporary variables, which are strings." | names | self method setTempNamesIfCached: [:names | ^names]. names _ (self mclass compilerClass new parse: self sourceCode in: self mclass notifying: nil) tempNames. self method cacheTempNames: names. ^names! !!ContextPart methodsFor: 'instruction decoding'!doDup "Simulates the action of a 'duplicate top of stack' bytecode." self push: self top!doPop "Simulates the action of a 'remove top of stack' bytecode." self pop!jump: distance "Simulates the action of a 'unconditional jump' bytecode whose offset is the argument, distance." pc _ pc + distance!jump: distance if: condition "Simulates the action of a 'conditional jump' bytecode whose offset is the argument, distance, and whose condition is the argument, condition." (self pop eqv: condition) ifTrue: [self jump: distance]!methodReturnConstant: value "Simulates the action of a 'return constant' bytecode whose value is the argument, value. This corresponds to a source expression like '^0'." ^self return: value to: self home sender!methodReturnReceiver "Simulates the action of a 'return receiver' bytecode. This corresponds to the source expression '^self'." ^self return: self receiver to: self home sender!methodReturnTop "Simulates the action of a 'return top of stack' bytecode. This corresponds to source expressions like '^something'." ^self return: self pop to: self home sender!popIntoLiteralVariable: value "Simulates the action of bytecode that removes the top of the stack and stores it into a literal variable of my method." value value: self pop!popIntoReceiverVariable: offset "Simulates the action of bytecode that removes the top of the stack and stores it into an instance variable of my receiver." self receiver instVarAt: offset + 1 put: self pop!popIntoTemporaryVariable: offset "Simulates the action of bytecode that removes the top of the stack and stores it into one of my temporary variables." self home at: offset + 1 put: self pop!pushActiveContext "Simulates the action of bytecode that pushes the the active context on the top of its own stack." self push: self!pushConstant: value "Simulates the action of bytecode that pushes the constant, value, on the top of the stack." self push: value!pushLiteralVariable: value "Simulates the action of bytecode that pushes the contents of the literal variable whose index is the argument, index, on the top of the stack." self push: value value!pushReceiver "Simulates the action of bytecode that pushes the the active context's receiver on the top of the stack." self push: self receiver!pushReceiverVariable: offset "Simulates the action of bytecode that pushes the contents of the receiver's instance variable whose index is the argument, index, on the top of the stack." self push: (self receiver instVarAt: offset + 1)!pushTemporaryVariable: offset "Simulates the action of bytecode that pushes the contents of the temporary variable whose index is the argument, index, on the top of the stack." self push: (self home at: offset + 1)!send: selector super: superFlag numArgs: numArgs "Simulates the action of bytecodes that send a message with selector, selector. The argument, superFlag, tells whether the receiver of the message was specified with 'super' in the source method. The arguments of the message are found in the top numArgs locations on the stack and the receiver just below them." | receiver arguments | arguments _ OrderedCollection new. numArgs timesRepeat: [arguments addFirst: self pop]. receiver _ self pop. (selector == #halt or: [selector == #halt:]) ifTrue: [self error: 'Cant simulate halt. Proceed to bypass it.'. self push: nil. ^self]. ^self send: selector to: receiver with: arguments super: superFlag!storeIntoLiteralVariable: value "Simulates the action of bytecode that stores the top of the stack into a literal variable of my method." value value: self top!storeIntoReceiverVariable: offset "Simulates the action of bytecode that stores the top of the stack into an instance variable of my receiver." self receiver instVarAt: offset + 1 put: self top!storeIntoTemporaryVariable: offset "Simulates the action of bytecode that stores the top of the stack into one of my temporary variables." self home at: offset + 1 put: self top! !!ContextPart methodsFor: 'debugger access'!depthBelow: aContext "Answer how many calls between this and aContext." | this depth | this _ self. depth _ 0. [this == aContext or: [this == nil]] whileFalse: [this _ this sender. depth _ depth + 1]. ^depth!hasSender: context "Answer true if the receiver is strictly above context on the stack." | s | self == context ifTrue: [^false]. s _ sender. [s == nil] whileFalse: [s == context ifTrue: [^true]. s _ s sender]. ^false!mclass "Answer the class in which the receiver's method was found." | mclass | self receiver class selectorAtMethod: self method setClass: [:mclass]. ^mclass!pc "Answer the index of the next bytecode to be executed." ^pc!release "Remove information from the receiver and all of the contexts on its sender chain in order to break circularities." self releaseTo: nil!releaseTo: caller "Remove information from the receiver and the contexts on its sender chain up to caller in order to break circularities." | c s | c _ self. [c == nil or: [c == caller]] whileFalse: [s _ c sender. c singleRelease. c _ s]!selector "Answer the selector of the method that created the receiver." ^self receiver class selectorAtMethod: self method setClass: [:ignored]!sender "Answer the context that sent the message that created the receiver." ^sender!shortStack "Answer a string showing the top five contexts on my sender chain." | shortStackStream | shortStackStream _ WriteStream on: (String new: 400). (self stackOfSize: 5) do: [:item | shortStackStream print: item; cr]. ^shortStackStream contents!singleRelease "Remove information from the receiver in order to break circularities." stackp == nil ifFalse: [1 to: stackp do: [:i | self at: i put: nil]]. sender _ nil!stack "Answer an array of the contexts on the receiver's sender chain." ^self stackOfSize: 9999!stackOfSize: limit "Answer an array of the top 'limit' contexts on the receiver's sender chain." | a stack | stack _ OrderedCollection new: 100. stack addLast: (a _ self). [(a _ a sender) ~~ nil and: [stack size < limit]] whileTrue: [stack addLast: a]. ^ stack!swapSender: coroutine "Replace the receiver's sender with coroutine and answer the receiver's previous sender. For use in coroutining." | oldSender | oldSender _ sender. sender _ coroutine. ^oldSender! !!ContextPart methodsFor: 'controlling'!activateMethod: newMethod withArgs: args receiver: rcvr class: class "Answer a new context initialized with the arguments." ^MethodContext sender: self receiver: rcvr method: newMethod arguments: args!blockCopy: numArgs "Distinguish a block of code from its enclosing method by creating a new BlockContext for that block. The compiler inserts into all methods that contain blocks the bytecodes to send the message blockCopy:. Do not use blockCopy: in code that you write!! Only the compiler can decide to send the message blockCopy:. Fail if numArgs is not a SmallInteger. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 80> ^(BlockContext new: self size) home: self home startpc: pc + 2 nargs: numArgs!pop "Answer the top of the receiver's stack and remove the top of the stack." | val | val _ self at: stackp. self at: stackp put: nil. stackp _ stackp - 1. ^val!push: val "Push val on the receiver's stack." self at: (stackp _ stackp + 1) put: val!return: value to: sendr "Simulate the return of value to sendr." self releaseTo: sendr. ^sendr push: value!send: selector to: rcvr with: args super: superFlag "Simulates the action of sending a message with selector, selector, and arguments, args, to receiver. The argument, superFlag, tells whether the receiver of the message was specified with 'super' in the source method." | class meth val | class _ superFlag ifTrue: [(self method literalAt: self method numLiterals) value superclass] ifFalse: [rcvr class]. [class == nil] whileFalse: [(class includesSelector: selector) ifTrue: [meth _ class compiledMethodAt: selector. val _ self tryPrimitiveFor: meth receiver: rcvr args: args. val == #primitiveFail ifFalse: [^val]. ^self activateMethod: meth withArgs: args receiver: rcvr class: class]. class _ class superclass]. self error: 'Simulated message ' , selector , ' not understood'!top "Answer the top of the receiver's stack." ^self at: stackp! !!ContextPart methodsFor: 'printing'!printOn: aStream | mclass selector class | selector _ (class _ self receiver class) selectorAtMethod: self method setClass: [:mclass]. selector == #? ifTrue: [aStream nextPut: $?; print: self method who. ^self]. aStream nextPutAll: class name. mclass == class ifFalse: [aStream nextPut: $(. aStream nextPutAll: mclass name. aStream nextPut: $)]. aStream nextPutAll: '>>'. aStream nextPutAll: selector! !!ContextPart methodsFor: 'system simulation'!completeCallee: aContext "Simulate the execution of bytecodes until a return to the receiver." | ctxt current | self class initPrimitives. ctxt _ aContext. [ctxt == current or: [ctxt hasSender: self]] whileTrue: [current _ ctxt. ctxt _ ctxt step]. self stepToSendOrReturn!runSimulated: aBlock contextAtEachStep: block2 "Simulate the execution of aBlock until it ends. aBlock MUST NOT contain an ^. Evaluate block2 with current context prior each instruction executed. Answer with the simulated value of aBlock." | current | aBlock hasMethodReturn ifTrue: [self error: 'simulation of blocks with ^ can run loose']. self class initPrimitives. current _ aBlock. current pushArgs: Array new from: self. [current == self] whileFalse: [block2 value: current. current _ current step]. ^self pop!step "Simulate the execution of the receiver's next bytecode. Answer the context that would be the active context after this bytecode." ^self interpretNextInstructionFor: self!stepToSendOrReturn "Simulate the execution of bytecodes until either sending a message or returning a value to the receiver (that is, until switching contexts)." [self willSend | self willReturn] whileFalse: [self step]! !!ContextPart methodsFor: 'private'!doPrimitive: primitiveIndex receiver: receiver args: arguments "Simulate a primitive method whose index is primitiveIndex. The simulated receiver and arguments are given as arguments to this message." | numberArguments primitiveMethod value | "If successful, push result and return resuming context, else ^#primitiveFail" (primitiveIndex = 80 and: [receiver isKindOf: ContextPart]) ifTrue: [^self push: ((BlockContext new: receiver size) home: receiver home startpc: pc + 2 nargs: arguments first)]. (primitiveIndex = 81 and: [receiver isMemberOf: BlockContext]) ifTrue: [^receiver pushArgs: arguments from: self]. primitiveIndex = 83 ifTrue: [^self send: arguments first to: receiver with: (arguments copyFrom: 2 to: arguments size) super: false]. numberArguments _ arguments size. numberArguments > 4 ifTrue: [^#primitiveFail]. "currently fails text primitive" primitiveMethod _ TryPrimitiveMethods at: numberArguments + 1. primitiveMethod literalAt: 2 put: ((primitiveMethod literalAt: 2) bitAnd: -256) + primitiveIndex. "slam num into primitive" "Instead of 100 such messages in Object" Class flushCache. "in case interp caches primitive #" numberArguments = 0 ifTrue: [value _ receiver tryPrimitive0]. numberArguments = 1 ifTrue: [value _ receiver tryPrimitive1: (arguments at: 1)]. numberArguments = 2 ifTrue: [value _ receiver tryPrimitive2: (arguments at: 1) with: (arguments at: 2)]. numberArguments = 3 ifTrue: [value _ receiver tryPrimitive3: (arguments at: 1) with: (arguments at: 2) with: (arguments at: 3)]. numberArguments = 4 ifTrue: [value _ receiver tryPrimitive4: (arguments at: 1) with: (arguments at: 2) with: (arguments at: 3) with: (arguments at: 4)]. numberArguments > 4 ifTrue: [self error: 'too many arguments to this primitive']. value == #primitiveFail ifTrue: [^value] ifFalse: [^self push: value]!tryPrimitiveFor: method receiver: receiver args: arguments "Simulate a primitive method, method for the receiver and arguments given as arguments to this message. Answer resuming the context if successful, else answer the symbol, #primitiveFail." | flag primIndex | (method objectAt: 1) > 0 ifTrue: [^#primitiveFail]. "fast check flags < 4" (flag _ method flags) < 5 ifTrue: [^#primitiveFail]. flag = 5 ifTrue: [^self push: receiver]. flag = 6 ifTrue: [^self push: (receiver instVarAt: method numTempsField + 1)]. flag = 7 ifTrue: [(primIndex _ method primitive) = 0 ifTrue: [^#primitiveFail]. ^self doPrimitive: primIndex receiver: receiver args: arguments]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ContextPart class instanceVariableNames: ''!!ContextPart class methodsFor: 'class initialization'!initPrimitives "The methods (from class Object) that are cached in tryPrimitiveMethods are used by the simulator to catch failures when simulating primitives" | method | TryPrimitiveMethods _ #(tryPrimitive0 tryPrimitive1: tryPrimitive2:with: tryPrimitive3:with:with: tryPrimitive4:with:with:with: ) collect: [:sel | method _ Object compiledMethodAt: sel. method numLiterals = 3 ifFalse: [self error: 'doPrimitive assumes 3']. method]! !!ContextPart class methodsFor: 'examples'!runSimulated: aBlock "The simulator is a group of methods in class ContextPart which do what the Smalltalk interpreter does. They execute Smalltalk bytecodes. By adding code to the simulator, you could take statistics on the running of Smalltalk methods. See also trace: callStatistics: and instructionStatistics: for sample uses" ^ thisContext sender runSimulated: aBlock contextAtEachStep: [:ignored] "ContextPart runSimulated: [Pen new defaultNib: 5; go: 100]"!tallyInstructions: aBlock "This method uses the simulator to count the number of occurrences of each of the Smalltalk instructions executed during evaluation of aBlock. Results appear in order of the byteCode set." | current tallies | tallies _ Bag new. thisContext sender runSimulated: aBlock contextAtEachStep: [:current | tallies add: current nextByte]. ^tallies sortedElements "ContextPart tallyInstructions: [3.14159 printString]."!tallyMethods: aBlock "This method uses the simulator to count the number of calls on each method invoked in evaluating aBlock. Results are given in order of decreasing counts." | prev current tallies | tallies _ Bag new. prev _ aBlock. thisContext sender runSimulated: aBlock contextAtEachStep: [:current | current == prev ifFalse: "call or return" [prev sender == nil ifFalse: "call only" [tallies add: current printString]. prev _ current]]. ^tallies sortedCounts "ContextPart tallyMethods: [3.14159 printString]."!trace: aBlock "This method uses the simulator to print calls and returned values in the Transcript" | prev current | prev _ aBlock. ^ thisContext sender runSimulated: aBlock contextAtEachStep: [:current | current == prev ifFalse: [prev sender == nil ifTrue: "returning" [Transcript space; nextPut: $^; print: current top]. Transcript cr; nextPutAll: (String new: (current depthBelow: aBlock) withAll: $ ); print: current receiver; space; nextPutAll: current selector; endEntry. prev _ current]] "ContextPart trace: [3 factorial]"! ! Object subclass: #Controller instanceVariableNames: 'model view sensor ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Framework'!Controller comment: 'A Controller coordinates a View, its model, and user actions'!!Controller methodsFor: 'initialize-release'!initialize "Initializes the state of the receiver. Subclasses should include 'super initialize' when redefining this message to insure proper initialization." sensor _ InputSensor default!release "Breaks the cycle between the receiver and its view. It is usually not necessary to send release provided the receiver's view has been properly released independently." super release. view ~= nil ifTrue: [view controller: nil. view _ nil]! !!Controller methodsFor: 'model access'!model "Answer the receiver's model which is the same as the model of the receiver's view." ^model!model: aModel "Controller|model: and Controller|view: are sent by View|controller: in order to coordinate the links between the model, view, and controller. In ordinary usage, the receiver is created and passed as the parameter to View|controller: so that the receiver's model and view links can be set up by the view." model _ aModel! !!Controller methodsFor: 'view access'!view "Answer the receiver's view." ^view!view: aView "Controller|view: and Controller|model: are sent by View|controller: in order to coordinate the links between the model, view, and controller. In ordinary usage, the receiver is created and passed as the parameter to View|controller: and the receiver's model and view links are set up automatically by the view." view _ aView! !!Controller methodsFor: 'sensor access'!sensor "Answer the receiver's sensor. Subclasses may use other objects that are not instances of Sensor or its subclasses if more general kinds of input/output functions are required." ^sensor!sensor: aSensor "Set the receiver's sensor to aSensor." sensor _ aSensor! !!Controller methodsFor: 'basic control sequence'!controlInitialize "Sent by Controller|startUp as part of the standard control sequence. It provides a place in the standard control sequence for initializing the receiver (taking into account the current state of its model and view). It should be redefined in subclasses to perform some specific action." ^self!controlLoop "Sent by Controller|startUp as part of the standard control sequence. Controller|controlLoop sends the message Controller|isControlActive to test for loop termination. As long as true is returned, the loop continues. When false is returned, the loop ends. Each time through the loop, the message Controller|controlActivity is sent." [self isControlActive] whileTrue: [Processor yield. self controlActivity]!controlTerminate "Provide a place in the standard control sequence for terminating the receiver (taking into account the current state of its model and view). It should be redefined in subclasses to perform some specific action." ^self!startUp "Give control to the receiver. The default control sequence is to initialize (see Controller|controlInitialize), to loop (see Controller|controlLoop), and then to terminate (see Controller|controlTerminate). After this sequence, control is returned to the sender of Control|startUp. The receiver's control sequence is used to coordinate the interaction of its view and model. In general, this consists of polling the sensor for user input, testing the input with respect to the current display of the view, and updating the model to reflect intended changes." self controlInitialize. self controlLoop. self controlTerminate! !!Controller methodsFor: 'control defaults'!controlActivity "Pass control to the next control level (that is, to the Controller of a subView of the receiver's view) if possible. It is sent by Controller|controlLoop each time through the main control loop. It should be redefined in a subclass if some other action is needed." self controlToNextLevel!controlToNextLevel "Pass control to the next control level, that is, to the Controller of a subView of the receiver's view if possible. The receiver finds the subView (if any) whose controller wants control and sends that controller the message startUp." | aView | aView _ view subViewWantingControl. aView ~~ nil ifTrue: [aView controller startUp]!isControlActive "Answer whether the receiver wants control. The default is to take control if the cursor is inside the view and the blue button is not pressed. Pressing blue button a default to explicitly give up control without moving the cursor. It is sent by Controller|controlLoop in order to determine when the receiver's control loop should terminate, and should be redefined in a subclass if some other condition for terminating the main control loop is needed." ^(view containsPoint: sensor cursorPoint) & sensor blueButtonPressed not!isControlWanted "Answer true if the cursor is inside the inset display box (see View|insetDisplayBox) of the receiver's view, and answer false, otherwise. It is sent by Controller|controlNextLevel in order to determine whether or not control should be passed to this receiver from the Controller of the superView of this receiver's view." ^self viewHasCursor! !!Controller methodsFor: 'cursor'!centerCursorInView "Position sensor's mousePoint (which is assumed to be connected to the cursor) to the center of its view's inset display box (see Sensor|mousePoint: and View|insetDisplayBox)." ^sensor cursorPoint: view insetDisplayBox center!viewHasCursor | temp | "Answer true if the cursor point of the receiver's sensor lies within the inset display box of the receiver's view (see View|insetDisplayBox), and answer false, otherwise. Controller|viewHasCursor is normally used in internal methods." ^view containsPoint: sensor cursorPoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Controller class instanceVariableNames: ''!!Controller class methodsFor: 'instance creation'!new ^super new initialize! ! Object subclass: #ControlManager instanceVariableNames: 'scheduledControllers activeController activeControllerProcess screenController ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Framework'!ControlManager comment:'I represent the top level control over scheduling which controller of a view on the screen the user is actively using. ScheduledControllers is the global reference to an instance of me, the one attached to the Project currently being used. Instance Variables: scheduledControllers <OrderedCollection> of Controllers, usually ScheduledControllers activeController <Controller> usually a ScheduledController activeControllerProcess <Process> screenController <ScreenController> also appears in ScheduledControllers '!!ControlManager methodsFor: 'initialize-release'!initialize "Initialize the receiver to refer to only the background controller." | screenView | screenController _ ScreenController new. screenView _ FormView new. screenView model: (InfiniteForm with: Form gray) controller: screenController. screenView window: Display boundingBox. scheduledControllers _ OrderedCollection with: screenController!release scheduledControllers == nil ifFalse: [scheduledControllers do: [:controller | (controller isKindOf: Controller) ifTrue: [controller view release] ifFalse: [controller release]]. scheduledControllers _ nil]! !!ControlManager methodsFor: 'accessing'!activeController "Answer the currently active controller." ^activeController!activeController: aController "Set aController to be the currently active controller. Give the user control in it." activeController _ aController. self promote: activeController. activeControllerProcess _ [activeController startUp. self searchForActiveController] newProcess. activeControllerProcess priority: Processor userSchedulingPriority. activeControllerProcess resume!activeController: aController andProcess: aProcess "Set aController to be the currently active controller and aProcess to be the the process that is handles controller scheduling activities in the system." self inActiveControllerProcess ifTrue: [aController~~nil ifTrue: [(scheduledControllers includes: aController) ifTrue: [self promote: aController] ifFalse: [self error: 'Old controller not scheduled']]. activeController controlTerminate. activeController _ aController. activeController == nil ifFalse: [activeController controlInitialize]. activeControllerProcess _ aProcess. activeControllerProcess resume] ifFalse: [self error: 'New active controller process must be set from old one']!activeControllerNoTerminate: aController andProcess: aProcess "Set aController to be the currently active controller and aProcess to be the the process that handles controller scheduling activities in the system. This message differs from activeController:andProcess: in that it does not send controlTerminate to the currently active controller." self inActiveControllerProcess ifTrue: [aController~~nil ifTrue: [(scheduledControllers includes: aController) ifTrue: [self promote: aController] ifFalse: [self error: 'Old controller not scheduled']]. activeController _ aController. activeController == nil ifFalse: [activeController controlInitialize]. activeControllerProcess _ aProcess. activeControllerProcess resume] ifFalse: [self error: 'New active controller process must be set from old one']!activeControllerProcess "Answer the process that is currently handling controller scheduling activities in the system." ^activeControllerProcess!scheduledControllers "Answer a copy of the ordered collection of scheduled controllers." ^scheduledControllers copy! !!ControlManager methodsFor: 'scheduling'!inActiveControllerProcess "Answer whether the active scheduling process is the actual active process in the system." ^activeControllerProcess == Processor activeProcess!interruptName: title "Create a Notifier on the active scheduling process whose label is title Make the Notifier the active controller." | newActiveController suspendingList | suspendingList _ activeControllerProcess suspendingList. suspendingList isNil ifTrue: [activeControllerProcess==Processor activeProcess ifTrue: [activeControllerProcess suspend]] ifFalse: [suspendingList remove: activeControllerProcess. activeControllerProcess offList]. newActiveController _ (NotifierView openInterrupt: title onProcess: activeControllerProcess) controller. activeController ~~ nil ifTrue: [activeController controlTerminate]. newActiveController centerCursorInView. self activeController: newActiveController!promote: aController "Make aController be the first scheduled controller in the ordered collection." scheduledControllers remove: aController. scheduledControllers addFirst: aController!pullBottomToTop "Make the last scheduled view which wants control be the first one. Used for implementing the message under to a scheduled controller." scheduledControllers reverseDo: [:controller | (controller isControlWanted and: [controller ~~ screenController]) ifTrue: [^scheduledControllers addFirst: (scheduledControllers remove: controller)]]!scheduleActive: aController "Make aController be scheduled as the active controller. Presumably the active scheduling process asked to schedule this controller and that a new process associated this controller takes control. So this is the last act of the active scheduling process." Cursor normal show. self scheduleActiveNoTerminate: aController. Processor terminateActive!scheduleActiveNoTerminate: aController "Make aController be the active controller. Presumably the process that requested the new active controller wants to keep control to do more activites before the new controller can take control. Therefore, do not terminate the currently active process." self schedulePassive: aController. self scheduled: aController from: Processor activeProcess!scheduleOnBottom: aController "Make aController be scheduled as a scheduled controller, but not the active one. Put it at the end of the ordered collection of controllers." scheduledControllers addLast: aController!schedulePassive: aController "Make aController be scheduled as a scheduled controller, but not the active one. Put it at the beginning of the ordered collection of controllers." scheduledControllers addFirst: aController!searchForActiveController "Find a scheduled controller that wants control and give control to it. If none wants control, then see if the System Menu has been requested." | aController | activeController _ nil. activeControllerProcess _ Processor activeProcess. [Processor yield. aController _ scheduledControllers detect: [:aController | aController isControlWanted and: [aController ~~ screenController]] ifNone: [screenController isControlWanted ifTrue: [screenController] ifFalse: [nil]]. aController isNil] whileTrue. self activeController: aController. Processor terminateActive!unschedule: aController "Remove the view, aController, from the collection of scheduled controllers." scheduledControllers remove: aController ifAbsent: []! !!ControlManager methodsFor: 'displaying'!restore "Clear the screen to gray and then redisplay all the scheduled views." self unschedule: screenController. self scheduleOnBottom: screenController. screenController view window: Display boundingBox. scheduledControllers reverseDo: [:aController | aController view display; deEmphasize]. Cursor normal show! !!ControlManager methodsFor: 'private'!deactivate activeController _ nil. activeControllerProcess _ nil!scheduled: aController from: aProcess activeControllerProcess==aProcess ifTrue: [activeController ~~ nil ifTrue: [activeController controlTerminate]. aController centerCursorInView. self activeController: aController] ifFalse: [aController view display]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ControlManager class instanceVariableNames: ''!!ControlManager class methodsFor: 'instance creation'!new ^super new initialize! !!ControlManager class methodsFor: 'exchange'!newScheduler: controlManager "When switching projects, the control scheduler has to be exchanged. The active one is the one associated with the current project." ScheduledControllers deactivate. Smalltalk at: #ScheduledControllers put: controlManager. ScheduledControllers restore. controlManager searchForActiveController! ! FillInTheBlankController subclass: #CRFillInTheBlankController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!CRFillInTheBlankController comment:'I am a FillInTheBlankController that causes termination on a carriage return.'!!CRFillInTheBlankController methodsFor: 'basic control sequence'!controlInitialize startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: stopBlock stringIndex. self initializeSelection. beginTypeInBlock _ nil!controlTerminate "self closeTypeIn ifTrue: [startBlock _ stopBlock copy]." "so leaving and entering window won't select last type-in" super controlTerminate! !!CRFillInTheBlankController methodsFor: 'sensor access'!readKeyboard "Copied from ParagraphEditor to gain access to carriage return termination--read a key that the user strikes on the keyboard." | typeAhead currentCharacter | self deselect. typeAhead _ WriteStream on: (String new: 128). beginTypeInBlock == nil ifTrue: [UndoSelection _ self selection. beginTypeInBlock _ startBlock copy]. [sensor keyboardPressed] whileTrue: [currentCharacter _ sensor keyboardPeek. currentCharacter = Character cr ifTrue: [^self cr: typeAhead]. (self perform: (Keyboard at: currentCharacter asciiValue + 1) with: typeAhead) ifTrue: [^self]]. self replaceSelectionWith: (Text string: typeAhead contents emphasis: emphasisHere). startBlock _ stopBlock copy. self selectAndScroll! !!CRFillInTheBlankController methodsFor: 'stop conditions'!cr: characterStream "The carriage return was typed by the user. This designates that the receiver should give up control." sensor keyboard. "gobble cr" characterStream isEmpty ifFalse: [self replaceSelectionWith: (Text string: characterStream contents emphasis: emphasisHere)]. self accept! ! Form subclass: #Cursor instanceVariableNames: '' classVariableNames: 'BlankCursor CornerCursor CrossHairCursor CurrentCursor DownCursor MarkerCursor NormalCursor OriginCursor ReadCursor SquareCursor UpCursor WaitCursor WriteCursor XeqCursor ' poolDictionaries: '' category: 'Graphics-Display Objects'!Cursor comment:'I am a 16 x 16 dot matrix suitable for use as the current cursor.'!!Cursor methodsFor: 'printing'!printOn: aStream self storeOn: aStream base: 2! !!Cursor methodsFor: 'displaying'!beCursor "Tell the interpreter to use the receiver as the current cursor image. Fail if the receiver does not match the size expected by the hardware. Essential. See Object documentation whatIsAPrimitive." <primitive: 101> self primitiveFailed!show "Make the current cursor shape be the receiver." Sensor currentCursor: self!showGridded: gridPoint "Make the current cursor shape be the receiver, forcing the location of cursor to the point nearest gridPoint." Sensor primCursorLocPut: ((Sensor cursorPoint grid: gridPoint) + self offset). Sensor currentCursor: self!showWhile: aBlock "While evaluating the argument, aBlock, make the receiver be the cursor shape." | oldcursor value | oldcursor _ Sensor currentCursor. self show. value _ aBlock value. oldcursor show. ^value! !!Cursor methodsFor: 'updating'!changed: aParameter self == CurrentCursor ifTrue: [self beCursor]. super changed: aParameter! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Cursor class instanceVariableNames: ''!!Cursor class methodsFor: 'class initialization'!initialize "Create all the standard cursors Cursor blank Cursor corner Cursor crossHair Cursor down Cursor execute Cursor marker Cursor normal Cursor origin Cursor read Cursor square Cursor up Cursor wait Cursor write" OriginCursor _ (Cursor extent: 16@16 fromArray: #( 2r1111111111111111 2r1111111111111111 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000) offset: -2@-2). CornerCursor _ (Cursor extent: 16@16 fromArray: #( 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r0000000000000011 2r1111111111111111 2r1111111111111111) offset: -14@-14). ReadCursor _ (Cursor extent: 16@16 fromArray: #( 2r0000110000000110 2r0001001000001001 2r0001001000001001 2r0010000000010000 2r0100000000100000 2r1111101111100000 2r1000010000100000 2r1000010000100000 2r1011010110100000 2r0111101111000000 2r0 2r0 2r0 2r0 2r0 2r0) offset: 0@0). WriteCursor _ (Cursor extent: 16@16 fromArray: #( 2r0000000000000110 2r0000000000001111 2r0000000000010110 2r0000000000100100 2r0000000001001000 2r0000000010010000 2r0000000100100000 2r0000001001000011 2r0000010010000010 2r0000100100000110 2r0001001000001000 2r0010010000001000 2r0111100001001000 2r0101000010111000 2r0110000110000000 2r1111111100000000) offset: 0@0). WaitCursor _ (Cursor extent: 16@16 fromArray: #( 2r1111111111111111 2r1000000000000001 2r0100000000000010 2r0010000000000100 2r0001110000111000 2r0000111101110000 2r0000011011100000 2r0000001111000000 2r0000001111000000 2r0000010110100000 2r0000100010010000 2r0001000110001000 2r0010001101000100 2r0100111111110010 2r1011111111111101 2r1111111111111111) offset: 0@0). BlankCursor _ Cursor new. XeqCursor _ (Cursor extent: 16@16 fromArray: #( 2r1000000000010000 2r1100000000010000 2r1110000000111000 2r1111000111111111 2r1111100011000110 2r1111110001000100 2r1111111001111100 2r1111000001101100 2r1101100011000110 2r1001100010000010 2r0000110000000000 2r0000110000000000 2r0000011000000000 2r0000011000000000 2r0000001100000000 2r0000001100000000) offset: 0@0). SquareCursor _ (Cursor extent: 16@16 fromArray: #( 2r0 2r0 2r0 2r0 2r0 2r0000001111000000 2r0000001111000000 2r0000001111000000 2r0000001111000000 2r0 2r0 2r0 2r0 2r0 2r0 2r0) offset: -8@-8). NormalCursor _ (Cursor extent: 16@16 fromArray: #( 2r1000000000000000 2r1100000000000000 2r1110000000000000 2r1111000000000000 2r1111100000000000 2r1111110000000000 2r1111111000000000 2r1111100000000000 2r1111100000000000 2r1001100000000000 2r0000110000000000 2r0000110000000000 2r0000011000000000 2r0000011000000000 2r0000001100000000 2r0000001100000000) offset: 0@0). CrossHairCursor _ (Cursor extent: 16@16 fromArray: #( 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r1111111111111110 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0000000100000000 2r0) offset: -7@-7). MarkerCursor _ Cursor extent: 16@16 fromArray: #( 2r0 2r0 2r0 2r0000001000000000 2r0000001110000000 2r0000001111100000 2r1111111111111000 2r1111111111111110 2r1111111111111000 2r0000001111100000 2r0000001110000000 2r0000001000000000 2r0 2r0 2r0 2r0) offset: -7@-7. UpCursor _ Cursor extent: 16@16 fromArray: #( 2r1000000000000000 2r1100000000000000 2r1110000000000000 2r1111000000000000 2r1111100000000000 2r1111110000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000 2r1100000000000000) offset: 0@-7. DownCursor _ Cursor extent: 16@16 fromArray: #( 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r0000110000000000 2r1111110000000000 2r0111110000000000 2r0011110000000000 2r0001110000000000 2r0000110000000000 2r0000010000000000) offset: -5@-7."Cursor initialize"! !!Cursor class methodsFor: 'instance creation'!extent: extentPoint fromArray: anArray offset: offsetPoint "Answer a new instance of me with width and height specified by extentPoint, offset by offsetPoint, and bits from anArray." extentPoint = (16 @ 16) ifTrue: [^super extent: extentPoint fromArray: anArray offset: offsetPoint] ifFalse: [self error: 'cursors must be 16@16']!new ^self extent: 16 @ 16 fromArray: Array new offset: 0 @ 0 "Cursor new bitEdit show."! !!Cursor class methodsFor: 'current cursor'!currentCursor "Answer the instance of Cursor that is the one currently displayed." ^CurrentCursor!currentCursor: aCursor "Make the instance of cursor, aCursor, be the current cursor. Display it. Create an error if the argument is not a Cursor." aCursor class == self ifTrue: [CurrentCursor _ aCursor. aCursor beCursor] ifFalse: [self error: 'The new cursor must be an instance of class Cursor']!cursorLink: boolean "Cause the cursor to track the pointing device location if the argument is true. Decouple the cursor from the pointing device if the argument is false. Essential. See Object documentation whatIsAPrimitive." <primitive: 92> ^self primitiveFailed! !!Cursor class methodsFor: 'constants'!blank "Answer the instance of me that is all white." ^BlankCursor!corner "Answer the instance of me that is the shape of the bottom right corner of a rectangle." ^CornerCursor!crossHair "Answer the instance of me that is the shape of a cross." ^CrossHairCursor!down "Answer the instance of me that is the shape of an arrow facing downward." ^DownCursor!execute "Answer the instance of me that is the shape of an arrow slanted left with a star next to it." ^XeqCursor!marker "Answer the instance of me that is displayed when thumb-scrolling." ^MarkerCursor!normal "Answer the instance of me that is the shape of an arrow slanted left." ^NormalCursor!origin "Answer the instance of me that is the shape of the top left corner of a rectangle." ^OriginCursor!read "Answer the instance of me that is the shape of eyeglasses." ^ReadCursor!square "Answer the instance of me that is the shape of a square." ^SquareCursor!up "Answer the instance of me that is the shape of an arrow facing upward." ^UpCursor!wait "Answer the instance of me that is the shape of an hourglass." ^WaitCursor!write "Answer the instance of me that is the shape of a pen writing." ^WriteCursor! !Cursor initialize! Path subclass: #Curve instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!Curve comment: 'A subclass of Path that is a conic section determined by three points p1,p2 and p3 that interpolates p1 and p3 and is tangent to p1,p2 and p3,p2 at p1 and p3 respectively.'!!Curve methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm | pa pb k s p1 p2 p3 line | line _ Line new. line form: self form. collectionOfPoints size < 3 ifTrue: [self error: 'Curve must have three points']. p1 _ self firstPoint. p2 _ self secondPoint. p3 _ self thirdPoint. s _ Path new. s add: p1. pa _ p2 - p1. pb _ p3 - p2. k _ 5 max: pa x abs + pa y abs + pb x abs + pb y abs // 20. "k is a guess as to how many line segments to use to approximate the curve." 1 to: k do: [:i | s add: pa * i // k + p1 * (k - i) + (pb * (i - 1) // k + p2 * (i - 1)) // (k - 1)]. s add: p3. 1 to: s size - 1 do: [:i | line beginPoint: (s at: i). line endPoint: (s at: i + 1). line displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm]!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm | transformedPath newCurve | transformedPath _ aTransformation applyTo: self. newCurve _ Curve new. newCurve firstPoint: transformedPath firstPoint. newCurve secondPoint: transformedPath secondPoint. newCurve thirdPoint: transformedPath thirdPoint. newCurve form: self form. newCurve displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRect rule: anInteger mask: aForm! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Curve class instanceVariableNames: ''!!Curve class methodsFor: 'instance creation'!new | newSelf | newSelf _ super new: 3. newSelf add: 0@0. newSelf add: 0@0. newSelf add: 0@0. ^newSelf! !!Curve class methodsFor: 'examples'!example "Designate three locations on the screen by clicking any button. The curve determined by the points will be displayed with a long black form." | aCurve aForm | aForm _ Form new extent: 1@30. "make a long thin Form for display " aForm black. "turn it black" aCurve _ Curve new. aCurve form: aForm. "set the form for display" "collect three Points and show them on the dispaly" aCurve firstPoint: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aCurve firstPoint. aCurve secondPoint: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aCurve secondPoint. aCurve thirdPoint: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aCurve thirdPoint. aCurve displayOn: Display "display the Curve" "Curve example."! ! Magnitude subclass: #Date instanceVariableNames: 'day year ' classVariableNames: 'DaysInMonth FirstDayOfMonth MonthNames SecondsInDay WeekDayNames ' poolDictionaries: '' category: 'Numeric-Magnitudes'!Date comment: 'Implements dates.'!!Date methodsFor: 'comparing'!< aDate "Answer whether aDate precedes the date of the receiver." year = aDate year ifTrue: [^day < aDate day] ifFalse: [^year < aDate year]!= aDate "Answer whether aDate is the same day as the receiver." self species = aDate species ifTrue: [^day = aDate day & (year = aDate year)] ifFalse: [^false]!hash "Hash is reimplemented because = is implemented." ^(year hash bitShift: 3) bitXor: day! !!Date methodsFor: 'accessing'!day "Answer the day of the year represented by the receiver." ^day!leap "Answer whether the receiver's year is a leap year." ^Date leapYear: year!monthIndex "Answer the index of the month in which the receiver falls." | leap firstDay | leap _ self leap. 12 to: 1 by: -1 do: [ :monthIndex | firstDay _ (FirstDayOfMonth at: monthIndex) + (monthIndex > 2 ifTrue: [leap] ifFalse: [0]). firstDay<= day ifTrue: [^monthIndex]]. self error: 'illegal month'!monthName "Answer the name of the month in which the receiver falls." ^MonthNames at: self monthIndex!weekday "Answer the name of the day of the week on which the receiver falls." ^WeekDayNames at: self weekdayIndex!year "Answer the year in which the receiver falls." ^year! !!Date methodsFor: 'arithmetic'!addDays: dayCount "Answer a new Date that is dayCount more days than the receiver." ^Date newDay: day + dayCount year: year!subtractDate: aDate "Answer the number of days between the receiver and aDate." year = aDate year ifTrue: [^day - aDate day] ifFalse: [^year - 1 // 4 - (aDate year // 4) + day + aDate daysLeftInYear + (year - 1 - aDate year * 365)]!subtractDays: dayCount "Answer a new Date that is dayCount days before the receiver." ^Date newDay: day - dayCount year: year! !!Date methodsFor: 'inquiries'!dayOfMonth "Answer which day of the month is represented by the receiver." ^day - (self firstDayOfMonthIndex: self monthIndex) + 1!daysInMonth "Answer the number of days in the month represented by the receiver." ^(DaysInMonth at: self monthIndex) + (self monthIndex = 2 ifTrue: [self leap] ifFalse: [0])!daysInYear "Answer the number of days in the year represented by the receiver." ^Date daysInYear: self year!daysLeftInYear "Answer the number of days in the year after the date of the receiver." ^self daysInYear - self day!firstDayOfMonth "Answer the index of the day of the year that is the first day of the receiver's month" ^self firstDayOfMonthIndex: self monthIndex!previous: dayName "Answer the previous date whose weekday name is dayName." ^self subtractDays: 7 + self weekdayIndex - (Date dayOfWeek: dayName) \\ 7! !!Date methodsFor: 'converting'!asSeconds "Answer the seconds between a time on1 January 1901 and the same time in the receiver's day." ^SecondsInDay * (self subtractDate: (Date newDay: 1 year: 1901))! !!Date methodsFor: 'printing'!printFormat: formatArray "Answer a string description of the receiver. The argument formatArray is the print format, where 1-3 positions to print day,month,year respectively 4 character separator 5 month format (1 month #, 2 first 3 chars, 3 entire name) 6 year format (1 year #, 2 year # \\ 100)" | aStream | aStream _ WriteStream on: (String new: 16). self printOn: aStream format: formatArray. ^aStream contents!printOn: aStream self printOn: aStream format: #(1 2 3 32 3 1 )!printOn: aStream format: formatArray "Print a description of the receiver on aStream. The argument formatArray is the print format, where 1-3 positions to print day,month,year respectively 4 character separator 5 month format (1 month #, 2 first 3 chars, 3 entire name) 6 year format (1 year #, 2 year # \\ 100)" | monthIndex element monthFormat | monthIndex _ self monthIndex. 1 to: 3 do: [:elementIndex | element _ formatArray at: elementIndex. element = 1 ifTrue: [day - self firstDayOfMonth + 1 printOn: aStream]. element = 2 ifTrue: [monthFormat _ formatArray at: 5. monthFormat = 1 ifTrue: [monthIndex printOn: aStream]. monthFormat = 2 ifTrue: [aStream nextPutAll: ((MonthNames at: monthIndex) copyFrom: 1 to: 3)]. monthFormat = 3 ifTrue: [aStream nextPutAll: (MonthNames at: monthIndex)]]. element = 3 ifTrue: [(formatArray at: 6) = 1 ifTrue: [year printOn: aStream] ifFalse: [(year \\ 100) printOn: aStream]]. elementIndex < 3 ifTrue: [(formatArray at: 4) ~= 0 ifTrue: [aStream nextPut: (formatArray at: 4) asCharacter]]]!storeOn: aStream aStream nextPutAll: '(', self class name, ' readFromString: '; print: self printString; nextPut: $)! !!Date methodsFor: 'private'!day: dayInteger year: yearInteger day _ dayInteger. year _ yearInteger!firstDayOfMonthIndex: monthIndex "Answer the day of the year (an Integer) that is the first day of my month" ^(FirstDayOfMonth at: monthIndex) + (monthIndex > 2 ifTrue: [self leap] ifFalse: [0])!weekdayIndex "Sunday=1, ... , Saturday=7" | yearIndex dayIndex | day < (self firstDayOfMonthIndex: 3) ifTrue: [yearIndex _ year - 1. dayIndex _ 307] ifFalse: [yearIndex _ year. dayIndex _ -58 - self leap]. ^dayIndex + day + yearIndex + (yearIndex // 4) + (yearIndex // 400) - (yearIndex // 100) \\ 7 + 1! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Date class instanceVariableNames: ''!!Date class methodsFor: 'class initialization'!initialize "Initialize class variables representing the names of the months and days and the number of seconds, days in each month, and first day of each month." MonthNames _ #(January February March April May June July August September October November December ). SecondsInDay _ 24 * 60 * 60. DaysInMonth _ #(31 28 31 30 31 30 31 31 30 31 30 31 ). FirstDayOfMonth _ #(1 32 60 91 121 152 182 213 244 274 305 335 ). WeekDayNames _ #(Monday Tuesday Wednesday Thursday Friday Saturday Sunday ) "Date initialize."! !!Date class methodsFor: 'instance creation'!fromDays: dayCount "Answer an instance of me that is dayCount days after Jan 1 1901." ^self newDay: 1 + (dayCount truncated rem: 1461) "There are 1461 days in a 4-year cycle. 2000 is a leap year, so no extra correction is necessary. " year: 1901 + ((dayCount truncated quo: 1461) * 4)!newDay: day month: monthName year: year "Answer an instance of me which is the day'th day of the month named monthName in the year'th year. The year may be specified as the actual number of years since the beginning of the Roman calendar or the number of years since the beginning of the century." | monthIndex daysInMonth firstDayOfMonth | year < 100 ifTrue: [^self newDay: day month: monthName year: 1900 + year]. monthIndex _ self indexOfMonth: monthName. monthIndex = 2 ifTrue: [daysInMonth _ (DaysInMonth at: monthIndex) + (self leapYear: year)] ifFalse: [daysInMonth _ DaysInMonth at: monthIndex]. monthIndex > 2 ifTrue: [firstDayOfMonth _ (FirstDayOfMonth at: monthIndex) + (self leapYear: year)] ifFalse: [firstDayOfMonth _ FirstDayOfMonth at: monthIndex]. (day < 1 or: [day > daysInMonth]) ifTrue: [self error: 'illegal day in month'] ifFalse: [^self new day: day - 1 + firstDayOfMonth year: year]!newDay: dayCount year: referenceYear "Answer with a Date which is dayCount days after the beginning of the year referenceYear." | day year daysInYear | day _ dayCount. year _ referenceYear. [day > (daysInYear _ self daysInYear: year)] whileTrue: [year _ year + 1. day _ day - daysInYear]. [day <= 0] whileTrue: [year _ year - 1. day _ day + (self daysInYear: year)]. ^self new day: day year: year!readFrom: aStream "Read a Date from the stream in any of the forms: <day> <monthName> <year> (5 April 1982; 5-APR-82) <monthName> <day> <year> (April 5, 1982) <monthNumber> <day> <year> (4/5/82)" | day month | aStream peek isDigit ifTrue: [day _ Integer readFrom: aStream]. [aStream peek isAlphaNumeric] whileFalse: [aStream skip: 1]. aStream peek isLetter ifTrue: "number/name... or name..." [month _ WriteStream on: (String new: 10). [aStream peek isLetter] whileTrue: [month nextPut: aStream next]. month _ month contents. day isNil ifTrue: "name/number..." [[aStream peek isAlphaNumeric] whileFalse: [aStream skip: 1]. day _ Integer readFrom: aStream]] ifFalse: "number/number..." [month _ Date nameOfMonth: day. day _ Integer readFrom: aStream]. [aStream peek isAlphaNumeric] whileFalse: [aStream skip: 1]. ^self newDay: day month: month year: (Integer readFrom: aStream) "Date readFrom: (ReadStream on: '5APR82')"!today "Answer with the Date representing the day and year right now." ^self dateAndTimeNow at: 1! !!Date class methodsFor: 'general inquiries'!dateAndTimeNow "Answer an array with first element Date today and second element Time now." ^Time dateAndTimeNow!dayOfWeek: dayName "Answer the index in a week, 1 - 7, of the day named dayName. Create an error if no such day exists." 1 to: 7 do: [:index | (WeekDayNames at: index) = dayName ifTrue: [^index \\ 7]]. self error: dayName asString , ' is not a day of the week'!daysInMonth: monthName forYear: yearInteger "Answer the number of days in the month named monthName in the year yearInteger." ^(self newDay: 1 month: monthName year: yearInteger) daysInMonth!daysInYear: yearInteger "Answer the number of days in the year, yearInteger." ^365 + (self leapYear: yearInteger)!indexOfMonth: monthName "Answer the index, 1 - 12, of the month monthName. Create an error if no such month exists." 1 to: 12 do: [ :index | (monthName , '*' match: (MonthNames at: index)) ifTrue: [^index]]. self error: monthName , ' is not a recognized month name'!leapYear: yearInteger "Answer 1 if the year yearInteger is a leap year; answer 0 if it is not." (yearInteger \\ 4 ~= 0 or: [yearInteger \\ 100 = 0 and: [yearInteger \\ 400 ~= 0]]) ifTrue: [^0] ifFalse: [^1]!nameOfDay: dayIndex "Answer a symbol representing the name of the day indexed by dayIndex, 1 - 7." ^WeekDayNames at: dayIndex!nameOfMonth: monthIndex "Answer a symbol representing the name of the month indexed by monthIndex, 1 - 12." ^MonthNames at: monthIndex! !Date initialize! Browser subclass: #Debugger instanceVariableNames: 'context receiverInspector contextInspector shortStack sourceMap sourceCode processHandle ' classVariableNames: 'ContextMenu HighlightPC ' poolDictionaries: '' category: 'Interface-Debugger'!Debugger comment:'The debugger allows browsing among the stack of contexts of a suspended process. In addition to viewing the source code at each level, the debugger supports inspection (and change) of temporary and instance variables in each context.Instance Variables: context <ContextPart> the currently viewed context receiverInspector <Inspector> on instance variables in the current context contextInspector <Inspector> on temporary variables in the current context shortStack <Boolean> true if only a short portion of the stack is being shown sourceMap <SortedCollection> of associations (pc -> range) tempNames <Array of: String>, cached names of the temporary variables processHandle <ProcessHandle> holding onto the observed process'!!Debugger methodsFor: 'initialize-release'!process: aProcess context: aContext interrupted: aBoolean sourceCode _ nil. shortStack _ true. processHandle _ ProcessHandle on: aProcess at: aContext interrupted: aBoolean!release processHandle terminate. context _ nil. receiverInspector _ nil. contextInspector _ nil. Smalltalk resetSpaceLimits. super release! !!Debugger methodsFor: 'accessing'!interruptedContext "Answer the suspended context of the interrupted process." ^processHandle topContext!selectedClass ^ context mclass! !!Debugger methodsFor: 'menu messages'!correct: aNotifierController "Attempt to correct the spelling of the not-understood message and resend." | oldSelector oldFirst oldArgs selectors guess score bestScore | processHandle topContext selector == #doesNotUnderstand: ifFalse: [^ aNotifierController view flash]. oldSelector _ (processHandle topContext tempAt: 1) selector. oldFirst _ oldSelector first. oldArgs _ oldSelector numArgs. selectors _ processHandle topContext receiver class allSelectors select: [:sel | sel first = oldFirst and: [sel numArgs = oldArgs]]. bestScore _ 0. selectors do: [:sel | (score _ sel spellAgainst: oldSelector) > bestScore ifTrue: [bestScore _ score. guess _ sel]]. (self confirm: 'retry with selector: ', guess) ifFalse: [^ aNotifierController view flash]. processHandle topContext tempAt: 1 put: (Message selector: guess arguments: (processHandle topContext tempAt: 1) arguments). ^ self proceed!fullStack "Expand the stack to include all contexts, rather than the first few." shortStack _ false. self changed: #context!proceed "Proceed from the interrupted state of the currently selected context. The argument is a controller on a view of the receiver. That view is closed." self checkContextSelection. (context ~= processHandle topContext) | (processHandle interrupted not) ifTrue: [context push: processHandle proceedValue]. self resumeProcess!restart "Proceed from the initial state of the currently selected context. The argument is a controller on a view of the receiver. That view is closed." self checkContextSelection. self revertBlock ifFalse: [^self]. context restart. self resumeProcess!spawn: aString "Create and schedule a message browser on the message, aString. Any edits already made are retained." context == nil ifFalse: [^BrowserView openMethodBrowserOn: (MethodListBrowser on: (Array with: self selectedClass name with: selector)) "editString: aString"]!spawnEdits: aText from: aController context == nil "cant spawn changes when deselected" ifFalse: [super spawnEdits: aText from: aController]! !!Debugger methodsFor: 'pc selection'!computeSourceMap "Compute the sourceMap for PC selection in the current code." | methodNode | methodNode _ self selectedClass compilerClass new parse: sourceCode in: self selectedClass notifying: nil. sourceMap _ methodNode sourceMap. context method cacheTempNames: methodNode tempNames!pcRange "Answer the indices in the source code for the method corresponding to the selected context's program counter value." | i methodNode pc end | (HighlightPC and: [context ~~ nil]) ifFalse: [^1 to: 0]. (sourceMap == nil or: [sourceMap size = 0]) ifTrue: [^1 to: 0]. pc_ context pc - ((context == processHandle topContext and: [processHandle interrupted]) ifTrue: [1] ifFalse: [2]). i _ sourceMap indexForInserting: (Association key: pc value: nil). i < 1 ifTrue: [^1 to: 0]. i > sourceMap size ifTrue: [end _ sourceMap inject: 0 into: [:prev :this | prev max: this value last]. ^ end+1 to: end]. ^(sourceMap at: i) value! !!Debugger methodsFor: 'inspectors'!contextInspector ^contextInspector!openInspectors "Further initialization when opening notify view to debug view" receiverInspector _ Inspector inspect: nil. contextInspector _ ContextInspector inspect: nil. self changed: #contextList!receiverInspector ^receiverInspector!updateInspectors receiverInspector update. contextInspector update! !!Debugger methodsFor: 'doIt/accept/explain'!acceptText: aText from: aController "Recompile the method of the selected context." | newSelector classOfMethod newMethod | context == nil ifTrue: [^ false]. self revertBlock ifFalse: [^ false]. classOfMethod _ context mclass. newSelector _ classOfMethod parserClass new parseSelector: aText. newSelector ~~ selector ifTrue: [self notify: 'selector must not change']. Cursor execute showWhile: [newSelector _ classOfMethod compile: aText classified: ClassOrganizer defaultProtocol notifying: aController]. newSelector == nil ifTrue: [^ false]. Cursor execute showWhile: ["**have to handle newMethod needing big stack!!" newMethod _ classOfMethod compiledMethodAt: newSelector. sourceCode _ aText string. newMethod isQuick ifTrue: "If compiled quick, we need a non-quick version to put in the context." [newMethod _ (classOfMethod compilerClass new parse: sourceCode in: classOfMethod notifying: nil) generateNoQuick]. newMethod frameSize > context size ifTrue: "This could be handled by allocating another bigger context, but you would have to inform processHandle of change in stack." [self notify: 'The new method requires more frame space than the old.You MUST not restart or proceed in this context.Other debugging, and restarting other methods is OK.You may proceed from this notification']. context restartWith: newMethod. self computeSourceMap. "Should get cached in CompiledMethod-class like tempNames" self resetContext: context]. ^ true!doItContext "Answer the context in which a text selection can be evaluated." ^ context!doItReceiver "Answer the receiver in which to evaluate code pane doIts." context == nil ifTrue: [^ nil]. ^ context receiver!doItValue: anObject "Set the value to be returned when the interrupted process proceeds." processHandle proceedValue: anObject! !!Debugger methodsFor: 'stack manipulation'!checkContextSelection context == nil ifTrue: [context _ processHandle topContext]!resetContext: aContext "Used when a new context becomes top-of-stack, for instance when the method of the selected context is re-compiled, or the simulator steps or returns to a new method." processHandle topContext: aContext. self changed: #context. context == aContext ifFalse: "old ctxt not in new stack" [self context: aContext. self changed: #context]!resumeProcess processHandle topContext: context. processHandle resumeProcess!revertBlock "If the selected context is a block, then revert to its home." (context isKindOf: MethodContext) ifFalse: [(self confirm:'I will have to revert to the method fromwhich this block originated. Is that OK?') ifTrue: [self context: context home. ^ true] ifFalse: [^ false]]. ^ true!send "The top context on the stack must be selected. This being so, either some message is about to be sent in that context, or that context is about to return. Send is only effective in the former case. It will cause the next message to be sent. The send is actually simulated, so that the debugger will regain control at the beginning of the method which is invokedi (unless it is a primitive). In this way, you can step your way deeper into a computation" self checkContextSelection. processHandle interrupted ifFalse: [processHandle topContext push: processHandle proceedValue]. processHandle interrupted: true. "simulation leaves same state as interrupting" context stepToSendOrReturn. (context ~~ processHandle topContext) | context willReturn ifFalse: [self resetContext: context step. context stepToSendOrReturn]!step "Some context is selected (force top if none). When this is so, either some message is about to be sent in that context, or that context is about to return. Step will cause the next message to be sent or the return to be executed. In either case, the debugger regains control so that you can step your way down through a method, and out to the caller when it returns. Note that the execution invoked by step is actually simulated, so it will run much slower than normal" | currentContext | self checkContextSelection. processHandle interrupted ifFalse: [processHandle topContext push: processHandle proceedValue]. processHandle interrupted: true. "simulation leaves same state as interrupting" context == processHandle topContext ifTrue: [currentContext _ context. currentContext stepToSendOrReturn. currentContext willReturn ifTrue: [currentContext _ currentContext step. currentContext stepToSendOrReturn. self resetContext: currentContext] ifFalse: [currentContext completeCallee: currentContext step. self changed: #pc. self updateInspectors]] ifFalse: ["Have to complete any stuff called from here" context completeCallee: processHandle topContext. self resetContext: context]! !!Debugger methodsFor: 'contextList'!context ^ context!context: aContext | oldContext class | oldContext _ context. context _ aContext. context == nil ifTrue: [contextInspector inspect: nil. receiverInspector inspect: nil. self changed: #text. ^ self]. class _ context receiver class. meta _ class isMeta. meta ifTrue: [className _ class soleInstance name] ifFalse: [className _ class name]. selector _ context selector. (oldContext == nil or: [oldContext method ~~ context method]) ifTrue: [sourceCode _ context sourceCode. self computeSourceMap. "will compute tempNames" self changed: #text]. receiverInspector inspect: context receiver. contextInspector inspect: context. self changed: #pc!contextList shortStack ifTrue: [^ processHandle topContext stackOfSize: 9] ifFalse: [^ processHandle topContext stack]!contextMenu "Debugger flushMenus" context == nil ifTrue: [^ ActionMenu labels: 'full stack\proceed' withCRs selectors: #(fullStack proceed)]. ContextMenu == nil ifTrue: [ContextMenu _ ActionMenu labels: 'full stack\proceed\restart\senders\implementors\messages\step\send' withCRs lines: #(3 6) selectors: #(fullStack proceed restart browseSenders browseImplementors browseMessages step send)]. ^ ContextMenu! !!Debugger methodsFor: 'text'!text context == nil ifTrue: [^ Text new]. ^ sourceCode asText makeSelectorBoldIn: self selectedClass! !!Debugger methodsFor: 'dependents access'!removeDependent: aDependent super removeDependent: aDependent. self dependents isEmpty ifTrue: [self release]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Debugger class instanceVariableNames: ''!!Debugger class methodsFor: 'instance creation'!context: aContext "Answer an instance of me that models the current state of the system. The active process has determined that a debugger should be set up (often by the user issuing the command debug)." | aDebugger | aDebugger _ self new. aDebugger process: Processor activeProcess context: aContext interrupted: false. ^aDebugger!interruptProcess: interruptedProcess "Answer an instance of me that models the current state of the system. The active process has decided to provide a debugger on an interrupted process. This message is called if the user types the ctrl c interrupt, or a low space notification occurs." | debugger | debugger _ self new. debugger process: interruptedProcess context: interruptedProcess suspendedContext interrupted: true. ^debugger!openFullViewOn: aDebugger label: aString "Answer an instance of me on the model, aDebugger. The label is aString. Do not terminate the current active process." | topView | aDebugger openInspectors. topView _ BrowserView model: aDebugger label: aString minimumSize: 300@230. topView addSubView: (SelectionInListView on: aDebugger printItems: true oneItem: false aspect: #context change: #context: list: #contextList menu: #contextMenu initialSelection: #context) in: (0@0 extent: 1@0.2) borderWidth: 1. topView addSubView: (CodeView on: aDebugger aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: (0@0.2 extent: 1@0.6) borderWidth: 1. InspectorView view: aDebugger receiverInspector in: (0@0.8 extent: 0.5@0.2) of: topView. InspectorView view: aDebugger contextInspector in: (0.5@0.8 extent: 0.5@0.2) of: topView. topView controller openNoTerminate. ^topView! !!Debugger class methodsFor: 'class initialization'!flushMenus "Debugger flushMenus." ContextMenu _ nil!initialize "Debugger initialize." HighlightPC _ true! !Debugger initialize! InstructionStream subclass: #Decompiler instanceVariableNames: 'constructor method instVars tempVars constTable stack statements lastPc exit lastJumpPc lastReturnPc limit hasValue ' classVariableNames: 'ArgumentFlag CascadeFlag ' poolDictionaries: '' category: 'System-Compiler'!Decompiler comment:'I translate CompiledMethods into source code.'!!Decompiler methodsFor: 'initialize-release'!initSymbols: aClass | nTemps | constructor method: method class: aClass literals: method literals. constTable _ constructor codeConstants. instVars _ Array new: aClass instSize. "parse the header" nTemps _ method numTemps. tempVars _ Array new: nTemps. 1 to: nTemps do: [:i | tempVars at: i put: (constructor codeTemp: i - 1)]! !!Decompiler methodsFor: 'control'!blockTo: end | exprs block | "Decompile a range of code as in statementsTo:, but return a block node" exprs _ self statementsTo: end. block _ constructor codeBlock: exprs returns: lastReturnPc = lastPc. lastReturnPc _ -1. "So as not to mislead outer calls" ^block!checkForBlock: receiver "We just saw a blockCopy: message. Check for a following block." | savePc jump args argPos block | receiver == constructor codeThisContext ifFalse: [^false]. savePc _ pc. (jump _ self interpretJump) notNil ifFalse: [pc _ savePc. ^nil]. "Definitely a block" jump _ jump + pc. argPos _ statements size. [self willStorePop] whileTrue: [stack addLast: ArgumentFlag. "Flag for doStore:" self interpretNextInstructionFor: self]. args _ Array new: statements size - argPos. 1 to: args size do: [:i | args at: i put: statements removeLast]. "Retrieve args" block _ self blockTo: jump. stack addLast: (constructor codeArguments: args block: block). ^true!statementsTo: end | blockPos stackPos t | "Decompile the method from pc up to end and return an array of expressions. If at run time this block will leave a value on the stack, set hasValue to true. If the block ends with a jump or return, set exit to the destination of the jump, or the end of the method; otherwise, set exit = end. Leave pc = end." blockPos _ statements size. stackPos _ stack size. [pc < end] whileTrue: [lastPc _ pc. limit _ end. "for performs" self interpretNextInstructionFor: self]. "If there is an additional item on the stack, it will be the value of this block." (hasValue _ stack size > stackPos) ifTrue: [statements addLast: stack removeLast]. lastJumpPc = lastPc ifFalse: [exit _ pc]. ^self popTo: blockPos! !!Decompiler methodsFor: 'instruction decoding'!blockReturnTop "No action needed"!doDup stack last == CascadeFlag ifFalse: ["Save position and mark cascade" stack addLast: statements size. stack addLast: CascadeFlag]. stack addLast: CascadeFlag!doPop statements addLast: stack removeLast!doStore: stackOrBlock "Only called internally, not from InstructionStream. StackOrBlock is stack for store, statements for storePop." | var expr | var _ stack removeLast. expr _ stack removeLast. stackOrBlock addLast: (expr == ArgumentFlag ifTrue: [var] ifFalse: [constructor codeAssignTo: var value: expr])!jump: dist exit _ pc + dist. lastJumpPc _ lastPc!jump: dist if: condition | savePc elseDist sign elsePc elseStart end cond ifExpr thenBlock elseBlock thenJump elseJump condHasValue n b | elsePc _ lastPc. elseStart _ pc + dist. end _ limit. "Check for bfp-jmp to invert condition. Don't be fooled by a loop with a null body." sign _ condition. savePc _ pc. ((elseDist _ self interpretJump) notNil and: [elseDist >= 0 and: [elseStart = pc]]) ifTrue: [sign _ sign not. elseStart _ pc + elseDist] ifFalse: [pc _ savePc]. ifExpr _ stack removeLast. thenBlock _ self blockTo: elseStart. condHasValue _ hasValue. "ensure jump is within block (in case thenExpr returns)" thenJump _ exit <= end ifTrue: [exit] ifFalse: [elseStart]. "if jump goes back, then it's a loop" thenJump < elseStart ifTrue: ["thenJump will jump to the beginning of the while expr. In the case of while's with a block in the condition, the while expr should include more than just the last expression: find all the statements needed by re-decompiling." pc _ thenJump. b _ self statementsTo: elsePc. "discard unwanted statements from block" b size - 1 timesRepeat: [statements removeLast]. statements addLast: (constructor codeMessage: (constructor codeBlock: b returns: false) selector: (constructor codeSelector: (sign ifTrue: [#whileFalse:] ifFalse: [#whileTrue:]) code: #macro) arguments: (Array with: thenBlock)). pc _ elseStart] ifFalse: [elseBlock _ self blockTo: thenJump. elseJump _ exit. "if elseJump is backwards, it is not part of the elseExpr" elseJump < elsePc ifTrue: [pc _ lastPc]. cond _ constructor codeMessage: ifExpr selector: (constructor codeSelector: #ifTrue:ifFalse: code: #macro) arguments: (sign ifTrue: [Array with: elseBlock with: thenBlock] ifFalse: [Array with: thenBlock with: elseBlock]). condHasValue ifTrue: [stack addLast: cond] ifFalse: [statements addLast: cond]]!methodReturnConstant: value self pushConstant: value; methodReturnTop!methodReturnReceiver self pushReceiver; methodReturnTop!methodReturnTop exit _ method size + 1. lastJumpPc _ lastReturnPc _ lastPc. statements addLast: stack removeLast!popIntoLiteralVariable: value self pushLiteralVariable: value; doStore: statements!popIntoReceiverVariable: offset self pushReceiverVariable: offset; doStore: statements!popIntoTemporaryVariable: offset self pushTemporaryVariable: offset; doStore: statements!pushActiveContext stack addLast: constructor codeThisContext!pushConstant: value | node | node _ value == true ifTrue: [constTable at: 2] ifFalse: [value == false ifTrue: [constTable at: 3] ifFalse: [value == nil ifTrue: [constTable at: 4] ifFalse: [constructor codeAnyLiteral: value]]]. stack addLast: node!pushLiteralVariable: assoc stack addLast: (constructor codeAnyLitInd: assoc)!pushReceiver stack addLast: (constTable at: 1)!pushReceiverVariable: offset | var | (var _ instVars at: offset + 1) == nil ifTrue: ["Not set up yet" instVars at: offset + 1 put: (var _ constructor codeInst: offset)]. stack addLast: var!pushTemporaryVariable: offset stack addLast: (tempVars at: offset + 1)!send: selector super: superFlag numArgs: numArgs | args rcvr selNode msgNode messages | args _ Array new: numArgs. (numArgs to: 1 by: -1) do: [:i | args at: i put: stack removeLast]. rcvr _ stack removeLast. superFlag ifTrue: [rcvr _ constructor codeSuper]. (selector == #blockCopy: and: [self checkForBlock: rcvr]) ifFalse: [selNode _ constructor codeAnySelector: selector. rcvr == CascadeFlag ifTrue: [msgNode _ constructor codeCascadedMessage: selNode arguments: args. stack last == CascadeFlag ifFalse: ["Last message of a cascade" statements addLast: msgNode. messages _ self popTo: stack removeLast. "Depth saved by first dup" msgNode _ constructor codeCascade: stack removeLast messages: messages]] ifFalse: [msgNode _ constructor codeMessage: rcvr selector: selNode arguments: args]. stack addLast: msgNode]!storeIntoLiteralVariable: assoc self pushLiteralVariable: assoc; doStore: stack!storeIntoReceiverVariable: offset self pushReceiverVariable: offset; doStore: stack!storeIntoTemporaryVariable: offset self pushTemporaryVariable: offset; doStore: stack! !!Decompiler methodsFor: 'public access'!decompile: aSelector in: aClass ^self decompile: aSelector in: aClass method: (aClass compiledMethodAt: aSelector)!decompile: aSelector in: aClass method: aMethod "answer with a parse tree (root is a MethodNode) for this method" ^self decompile: aSelector in: aClass method: aMethod using: DecompilerConstructor new! !!Decompiler methodsFor: 'private'!decompile: aSelector in: aClass method: aMethod using: aConstructor | block | constructor _ aConstructor. method _ aMethod. self initSymbols: aClass. "create symbol tables" method isQuick ifTrue: [block _ self quickMethod] ifFalse: [stack _ OrderedCollection new: method frameSize. statements _ OrderedCollection new: 20. super method: method pc: method initialPC. block _ self blockTo: method endPC + 1. stack isEmpty ifFalse: [self error: 'stack not empty']]. ^constructor codeMethod: aSelector block: block tempVars: tempVars primitive: method primitive class: aClass!popTo: oldPos | t | t _ Array new: statements size - oldPos. (t size to: 1 by: -1) do: [:i | t at: i put: statements removeLast]. ^t!quickMethod ^method isReturnSelf ifTrue: [constructor codeBlock: (Array with: (constTable at: 1 "self")) returns: true] ifFalse: [method isReturnField ifTrue: [constructor codeBlock: (Array with: (constructor codeInst: method returnField)) returns: true] ifFalse: [self error: 'improper short method']]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Decompiler class instanceVariableNames: ''!!Decompiler class methodsFor: 'class initialization'!initialize "Decompiler initialize" CascadeFlag _ 'cascade'. "A unique object" ArgumentFlag _ 'argument'. "Ditto"! !Decompiler initialize! ParseNode subclass: #DecompilerConstructor instanceVariableNames: 'method instVars nArgs literalValues tempVars ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!DecompilerConstructor comment:'I am used by the decompiler to construct parse tree nodes and other appropriate items corresponding to each unit identified by the decompiler. This factoring allows the decompiler, in principle, to use other constructors for other purposes. '!!DecompilerConstructor methodsFor: 'initialize-release'!method: aMethod class: aClass literals: literals method _ aMethod. instVars _ aClass allInstVarNames. nArgs _ method numArgs. literalValues _ literals! !!DecompilerConstructor methodsFor: 'constructor'!codeAnyLiteral: value ^LiteralNode new key: value index: 0 type: LdLitType!codeAnyLitInd: association ^VariableNode new name: association key key: association index: 0 type: LdLitIndType!codeAnySelector: selector ^SelectorNode new key: selector index: 0 type: SendType!codeArguments: args block: block ^block arguments: args!codeAssignTo: variable value: expression ^AssignmentNode new variable: variable value: expression!codeBlock: statements returns: returns ^BlockNode new statements: statements returns: returns!codeCascade: receiver messages: messages ^CascadeNode new receiver: receiver messages: messages!codeCascadedMessage: selector arguments: arguments ^self codeMessage: nil selector: selector arguments: arguments!codeConstants "Answer with an array of the objects representing self, true, false, nil, -1, 0, 1, 2" | i | ^(Array with: NodeSelf with: NodeTrue with: NodeFalse with: NodeNil) , ((-1 to: 2) collect: [:i | LiteralNode new key: i code: LdMinus1 + i + 1])!codeEmptyBlock ^BlockNode new default!codeInst: index ^VariableNode new name: (instVars at: index + 1) index: index type: LdInstType!codeMessage: receiver selector: selector arguments: arguments | symbol | symbol _ selector key. ^MessageNode new receiver: receiver selector: selector arguments: arguments precedence: (symbol isInfix ifTrue: [2] ifFalse: [symbol isKeyword ifTrue: [3] ifFalse: [1]])!codeMethod: selector block: block tempVars: vars primitive: primitive class: class | node precedence | node _ self codeSelector: selector code: nil. precedence _ selector isInfix ifTrue: [2] ifFalse: [selector isKeyword ifTrue: [3] ifFalse: [1]]. tempVars _ vars. ^MethodNode new selector: node arguments: (tempVars copyFrom: 1 to: nArgs) precedence: precedence temporaries: (tempVars copyFrom: nArgs + 1 to: tempVars size) block: block encoder: (Encoder new initScopeAndLiteralTables nTemps: tempVars size literals: literalValues class: class) primitive: primitive!codeSelector: sel code: code ^SelectorNode new key: sel code: code!codeSuper ^NodeSuper!codeTemp: index ^VariableNode new name: 't' , (index + 1) printString index: index type: LdTempType!codeThisContext ^NodeThisContext! ! Object subclass: #Delay instanceVariableNames: 'delayDuration resumptionTime delaySemaphore delayInProgress ' classVariableNames: 'AccessProtect ActiveDelay SuspendedDelays TimingSemaphore ' poolDictionaries: '' category: 'Kernel-Processes'!Delay comment:'I represent a realtime delay in the execution of a Process. See the howToUse message in the class messages.Instance Variables: delayDuration <Integer> number of milliseconds to delay process resumptionTime <Integer> value of millisecond clock at which to resume delaySemaphore <Semaphore> on which to delay process delayInProgress <Boolean> true if delaying now'!!Delay methodsFor: 'accessing'!resumptionTime "Answer the value of the system's millisecondClock at which the receiver's suspended Process will resume." ^resumptionTime! !!Delay methodsFor: 'process delay'!disable AccessProtect wait. delayInProgress ifTrue: [ActiveDelay == self ifTrue: [SuspendedDelays isEmpty ifTrue: [Processor signal: nil atTime: 0. ActiveDelay _ nil] ifFalse: [SuspendedDelays removeFirst activate]] ifFalse: [SuspendedDelays remove: self]. delaySemaphore terminateProcess. delayInProgress _ false]. AccessProtect signal!wait "Suspend the active process for an amount of time specified when the receiver was initialized." AccessProtect wait. self setResumption. ActiveDelay == nil ifTrue: [self activate] ifFalse: [resumptionTime < ActiveDelay resumptionTime ifTrue: [SuspendedDelays add: ActiveDelay. self activate] ifFalse: [SuspendedDelays add: self]]. AccessProtect signal. delaySemaphore wait! !!Delay methodsFor: 'private'!activate "For the moment, the receiver will be the next Delay to resume the reciever's suspended process." ActiveDelay _ self. TimingSemaphore initSignals. Processor signal: TimingSemaphore atTime: resumptionTime!delay: millisecondCount delayDuration _ millisecondCount. delayInProgress _ false. delaySemaphore _ Semaphore new!delayInProgress: aBoolean delayInProgress _ aBoolean!postSnapshot | pendingDelay | delayInProgress ifTrue: [resumptionTime == nil ifTrue: [self error: 'uninitialized Delay'] ifFalse: ["convert from milliseconds since Jan. 1 1901 to local millisecond clock" pendingDelay _ resumptionTime - (Time totalSeconds * 1000). pendingDelay _ pendingDelay max: 0. resumptionTime _ Time millisecondClockValue + pendingDelay]] "if false then this delay must be ready and waiting (on AccessProtect) to resume"!preSnapshot | pendingDelay | delayInProgress ifTrue: [resumptionTime == nil ifTrue: [self error: 'uninitialized Delay'] ifFalse: ["convert from local millisecond clock to milliseconds since Jan. 1 1901" pendingDelay _ resumptionTime - Time millisecondClockValue. resumptionTime _ Time totalSeconds * 1000 + pendingDelay]] ifFalse: [self error: 'This Delay is not waiting']!reactivate "Make sure the timer is armed to go off for this delay." delayInProgress ifTrue: [TimingSemaphore initSignals. Processor signal: TimingSemaphore atTime: resumptionTime] "if false then the timer has already fired for this delay and it is waiting (on AccessProtect) to resume"!resume "The receiver's delay duration has expired, the process the receiver suspended will resume now. " Processor signal: nil atTime: 0. delayInProgress _ false. delaySemaphore signal!resumption: millisecondCount delayDuration _ nil. resumptionTime _ millisecondCount. delayInProgress _ false. delaySemaphore _ Semaphore new!setResumption delayInProgress ifTrue: [self error: 'This Delay is already waiting'] ifFalse: [delayDuration == nil ifTrue: [resumptionTime == nil ifTrue: [self error: 'uninitialized Delay']] ifFalse: [resumptionTime _ Time millisecondClockValue + delayDuration]. delayInProgress _ true]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Delay class instanceVariableNames: ''!!Delay class methodsFor: 'class initialization'!initialize "Initialize class variables that keep track of active Delays." TimingSemaphore _ Semaphore new. AccessProtect _ Semaphore forMutualExclusion. SuspendedDelays _ SortedCollection sortBlock: [:oldDelay :addedDelay | oldDelay resumptionTime <= addedDelay resumptionTime]. ActiveDelay _ nil. self initializeTimingProcess "Delay initialize."!initializeTimingProcess [[true] whileTrue: [TimingSemaphore wait. ActiveDelay delayInProgress: false. AccessProtect wait. ActiveDelay resume. SuspendedDelays isEmpty ifTrue: [ActiveDelay _ nil] ifFalse: [SuspendedDelays removeFirst activate]. AccessProtect signal]] forkAt: Processor timingPriority! !!Delay class methodsFor: 'instance creation'!forMilliseconds: millisecondCount "Answer a new instance that will delay the active process for millisecondCount milliseconds when sent the message wait." ^self new delay: millisecondCount!forSeconds: secondCount "Answer a new instance that will delay the active process for secondCount seconds when sent the message wait." ^self new delay: (secondCount * 1000) rounded!untilMilliseconds: millisecondCount "Answer a new instance that will delay the active process until the system's millisecond clock value is millisecondCount when sent the message wait." ^self new resumption: millisecondCount! !!Delay class methodsFor: 'testing'!testAbsoluteDelayOf: delay for: testCount label: label | time | time _ Delay millisecondClockValue. [1 to: testCount do: [:index | (Delay untilMilliseconds: time + (index * delay)) wait. Transcript show: label. Transcript show: index printString. Transcript space]] forkAt: Processor userInterruptPriority "Transcript cr. Delay testAbsoluteDelayOf: 1000 for: 10 label: 'A'. Delay testAbsoluteDelayOf: 1500 for: 10 label: 'B'. "!testRelativeDelayOf: delay for: testCount label: label | myDelay | myDelay _ Delay forMilliseconds: delay. [1 to: testCount do: [:index | myDelay wait. Transcript show: label. Transcript show: index printString. Transcript space]] forkAt: Processor userInterruptPriority "Transcript cr. Delay testRelativeDelayOf: 1000 for: 10 label: 'A'. Delay testRelativeDelayOf: 1500 for: 10 label: 'B'. "! !!Delay class methodsFor: 'general inquiries'!millisecondClockValue "Answer the current value of the system's millisecond clock." ^Time millisecondClockValue! !!Delay class methodsFor: 'documentation'!howToUse "An instance of Delay will respond to the message #wait by suspending the active process for a certain amount of time. The time for resumption of the active process is specified when the Delay is created. The resumption time can be specified relative to the current time with the messages {Delay forMilliseconds: anInteger} and {Delay forSeconds: anInteger}. Delays created in this way can be sent the message #wait again after they have finished a previous delay. The resumption time can also be specified at an absolute time with respect to the system's millisecond clock with the message {Delay untilMillisecond: anInteger}. Delays created in this way cannot be sent the message #wait repeatedly. "! !!Delay class methodsFor: 'snapshots'!postSnapshot ActiveDelay~~nil ifTrue: [ActiveDelay postSnapshot. SuspendedDelays do: [ :delay | delay postSnapshot]. ActiveDelay reactivate]. AccessProtect signal!preSnapshot AccessProtect wait. ActiveDelay~~nil ifTrue: [ActiveDelay preSnapshot]. SuspendedDelays do: [ :delay | delay preSnapshot]! !Delay initialize! Set variableSubclass: #Dictionary instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Unordered'!Dictionary comment: 'I am a set of associations.'!!Dictionary methodsFor: 'accessing'!associationAt: key "Answer the association at key. If key is not found, create an error message." ^self associationAt: key ifAbsent: [self errorKeyNotFound]!associationAt: key ifAbsent: aBlock "Answer the association at key. If key is not found, answer the result of evaluating aBlock." | index | index _ self findKey: key ifAbsent: [^aBlock value]. ^self basicAt: index!associations "Answer an OrderedCollection containing the receiver's associations in an arbitrary order." | aCollection key | aCollection _ OrderedCollection new: self size. self associationsDo: [:key | aCollection add: key]. ^aCollection!at: key "Answer the value at key. If key is not found, create an error message." ^self at: key ifAbsent: [self errorKeyNotFound]!at: key ifAbsent: aBlock "Answer the value at key. If key is not found, answer the result of evaluating aBlock." | index | index _ self findKey: key ifAbsent: [^aBlock value]. ^(self basicAt: index) value!at: key put: anObject "Set the value at key to be anObject. If key is not found, create a new entry for key and set is value to anObject. Answer anObject." | index element | index _ self findKeyOrNil: key. element _ self basicAt: index. element == nil ifTrue: [self atNewIndex: index put: (Association key: key value: anObject)] ifFalse: [element value: anObject]. ^anObject!keyAtValue: value "Answer the key whose value equals the argument, value. If there is none, cause an error." ^self keyAtValue: value ifAbsent: [self errorValueNotFound]!keyAtValue: value ifAbsent: exceptionBlock "Answer the key whose value equals the argument, value. If there is none, answer the result of evaluating exceptionBlock." self associationsDo: [:association | value == association value ifTrue: [^association key]]. ^exceptionBlock value!keys "Answer a set containing the receiver's keys." | aSet key | aSet _ Set new: self size. self keysDo: [:key | aSet add: key]. ^aSet!values "Answer a Bag containing the receiver's values." | aBag | aBag _ Bag new. self do: [:value | aBag add: value]. ^aBag! !!Dictionary methodsFor: 'testing'!includes: anObject self do: [:each | anObject = each ifTrue: [^true]]. ^false!occurrencesOf: anObject "Answer how many of the receiver's elements are equal to anObject." | count | count _ 0. self do: [:each | anObject = each ifTrue: [count _ count + 1]]. ^count! !!Dictionary methodsFor: 'adding'!add: anAssociation | index element | index _ self findKeyOrNil: anAssociation key. element _ self basicAt: index. element == nil ifTrue: [self atNewIndex: index put: anAssociation] ifFalse: [element value: anAssociation value]. ^anAssociation!declare: key from: aDictionary "Add key to the receiver. If key already exists, do nothing. If aDictionary includes key, then remove it from aDictionary and use its association as the entry to the receiver." (self includesKey: key) ifTrue: [^self]. (aDictionary includesKey: key) ifTrue: [self add: (aDictionary associationAt: key). aDictionary removeKey: key] ifFalse: [self at: key put: nil]!grow | newSelf | newSelf _ self species new: self basicSize + self growSize. self associationsDo: [:each | newSelf noCheckAdd: each]. self become: newSelf! !!Dictionary methodsFor: 'removing'!remove: anObject self shouldNotImplement!remove: anObject ifAbsent: exceptionBlock self shouldNotImplement! !!Dictionary methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of my values as the argument. Collect the resulting values into a collection that is like me. Answer with the new collection." | newCollection | newCollection _ Bag new. self do: [:each | newCollection add: (aBlock value: each)]. ^newCollection!do: aBlock super do: [:assoc | aBlock value: assoc value]!select: aBlock "Evaluate aBlock with each of my values as the argument. Collect into a new dictionary, only those associations for which aBlock evaluates to true." | newCollection | newCollection _ self species new. self associationsDo: [:each | (aBlock value: each value) ifTrue: [newCollection add: each]]. ^newCollection! !!Dictionary methodsFor: 'converting'!asSortedCollection | aSortedCollection | aSortedCollection _ SortedCollection new: self size. self associationsDo: [:association | aSortedCollection add: association]. ^aSortedCollection! !!Dictionary methodsFor: 'printing'!printOn: aStream | tooMany | tooMany _ aStream position + self maxPrint. aStream nextPutAll: self class name, ' ('. self associationsDo: [:element | aStream position > tooMany ifTrue: [aStream nextPutAll: '...etc...)'. ^self]. element printOn: aStream. aStream space]. aStream nextPut: $)!storeOn: aStream | noneYet | aStream nextPutAll: '(('. aStream nextPutAll: self class name. aStream nextPutAll: ' new)'. noneYet _ true. self associationsDo: [:each | noneYet ifTrue: [noneYet _ false] ifFalse: [aStream nextPut: $;]. aStream nextPutAll: ' add: '. aStream store: each]. noneYet ifFalse: [aStream nextPutAll: '; yourself']. aStream nextPut: $)! !!Dictionary methodsFor: 'dictionary testing'!includesAssociation: anAssociation "Answer whether the receiver has an element (association between a key and a value) that is equal to the argument, anAssociation." ^super includes: anAssociation!includesKey: key "Answer whether the receiver has a key equal to the argument, key." | index | index _ self findKeyOrNil: key. ^(self basicAt: index) ~~ nil! !!Dictionary methodsFor: 'dictionary removing'!removeAssociation: anAssociation "Remove the key and value association, anAssociation, from the receiver. Answer anAssociation." ^self removeAssociation: anAssociation ifAbsent: [self errorNotFound]!removeAssociation: anAssociation ifAbsent: anExceptionBlock "Remove the key and value association, anAssociation, from the receiver. If not found, answer the result of evaluating anExceptionBlock, otherwise answer anAssociation." ^super remove: anAssociation ifAbsent: anExceptionBlock!removeKey: key "Remove key from the receiver. If key is not in the receiver, create an error message. Otherwise, answer the value associated with key." ^self removeKey: key ifAbsent: [self errorKeyNotFound]!removeKey: key ifAbsent: aBlock "Remove key from the receiver. If key is not in the receiver, answer the result of evaluating aBlock. Otherwise, answer the value associated with key." | index element | index _ self findKey: key ifAbsent: [^aBlock value]. element _ self basicAt: index. self basicAt: index put: nil. tally _ tally - 1. self fixCollisionsFrom: index. ^element! !!Dictionary methodsFor: 'dictionary enumerating'!associationsDo: aBlock "Evaluate aBlock for each of the receiver's key/value associations." super do: aBlock!keysDo: aBlock "Evaluate aBlock for each of the receiver's keys." self associationsDo: [:association | aBlock value: association key]! !!Dictionary methodsFor: 'user interface'!inspect "Create and schedule a DictionaryInspector in which the user can examine the receiver's variables." InspectorView open: (DictionaryInspector inspect: self)! !!Dictionary methodsFor: 'private'!errorKeyNotFound self error: 'key not found'!errorValueNotFound self error: 'value not found'!findKey: key ifAbsent: aBlock | index | index _ self findKeyOrNil: key. (self basicAt: index) == nil ifTrue: [^aBlock value]. ^index!findKeyOrNil: key | location length probe pass | length _ self basicSize. pass _ 1. location _ key hash \\ length + 1. [(probe _ self basicAt: location) == nil or: [probe key = key]] whileFalse: [(location _ location + 1) > length ifTrue: [location _ 1. pass _ pass + 1. pass > 2 ifTrue: [^self grow findKeyOrNil: key]]]. ^location!rehash "Smalltalk rehash." | newSelf | newSelf _ self species new: self basicSize. self associationsDo: [:each | newSelf noCheckAdd: each]. self become: newSelf! ! Inspector subclass: #DictionaryInspector instanceVariableNames: 'ok ' classVariableNames: 'DictListMenu ' poolDictionaries: '' category: 'Interface-Inspector'!DictionaryInspector comment:'Note that the "field" instance variable of DictionaryInspectors contains the actual current dictionary key object, not a field name string.'!!DictionaryInspector methodsFor: 'field list'!acceptText: aText from: aController | val | field == nil ifTrue: [^ false]. val _ self evaluateText: aText string from: aController ifFail: [^ false]. object at: field put: val. self changed: #text. ^ true!fieldList "Answer a collection of the keys of the inspected dictionary." | keys | keys _ object keys. keys detect: [:key | (key class == Symbol) not] ifNone: [^keys asSortedCollection]. "sort dictionaries with Symbol keys" ^keys asOrderedCollection!fieldMenu "DictionaryInspector flushMenus" field == nil ifTrue: [^ActionMenu labels: 'add field' withCRs selectors: #(addField)]. DictListMenu == nil ifTrue: [DictListMenu _ ActionMenu labels: 'inspect\references\add field\remove' withCRs lines: #(2) selectors: #(inspectField browseReferences addField removeField)]. ^DictListMenu!fieldValue ^object at: field!printItems "Answer whether the elements of the fieldList need to be converted to strings" ^true! !!DictionaryInspector methodsFor: 'menu commands'!addField | aString key | aString _ Browser new prompt: 'Enter key as a Smalltalk constant' initially: ''. aString isEmpty ifTrue: [^ self]. ok _ true. key _ Compiler evaluate: aString for: nil notifying: self logged: false. ok ifFalse: [^nil]. object add: (Association key: key value: nil). field _ key. self changed: #field!browseReferences Smalltalk browseAllCallsOn: (object associationAt: field)!removeField (self confirm: 'Confirm removal of ', field printString) ifFalse: [^self]. object removeKey: field. field _ nil. self changed: #field! !!DictionaryInspector methodsFor: 'compiler interface'!insertAndSelect: aString at: ignoredIndex ok _ false! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!DictionaryInspector class instanceVariableNames: ''!!DictionaryInspector class methodsFor: 'examples'!example "Create and schedule an Inspector in which the user can examine the receiver's variables." InspectorView open: (DictionaryInspector inspect: Smalltalk) "DictionaryInspector example."! !!DictionaryInspector class methodsFor: 'initialization'!flushMenus DictListMenu _ nil! ! WordArray variableWordSubclass: #DisplayBitmap instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Support'!DisplayBitmap comment: 'This subclass of Bitmap is used to indicate the particular bitmap which is being displayed, so that various implementations can treat it specially'! DisplayObject subclass: #DisplayMedium instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!DisplayMedium comment:'I am a display object which can both paint myself on a medium (displayOn: messages), and can act as a medium myself. My chief subclass is Form.'!!DisplayMedium methodsFor: 'coloring'!black "Set all bits in the receiver to black (ones)." self fill: self boundingBox mask: Form black!black: aRectangle "Set all bits in the receiver's area defined by aRectangle to black (ones)." self fill: aRectangle rule: Form over mask: Form black!darkGray "Set all bits in the receiver to darkGray." self fill: self boundingBox mask: Form darkGray!darkGray: aRectangle "Set all bits in the receiver's area defined by aRectangle to the darkGray mask." self fill: aRectangle rule: Form over mask: Form darkGray!fill: aRectangle "Fill aRectangle with the default background, Form gray." self fill: aRectangle rule: Form over mask: Form gray!fill: aRectangle mask: aForm "Replace a rectangular area of the receiver with the pattern described by aForm according to the rule over." self fill: aRectangle rule: Form over mask: aForm!fill: aRectangle rule: anInteger mask: aForm "Replace a rectangular area of the receiver with the pattern described by aForm according to the rule anInteger." self subclassResponsibility!gray "Set all bits in the receiver to gray." self fill: self boundingBox mask: Form gray!gray: aRectangle "Set all bits in the receiver's area defined by aRectangle to the gray mask." self fill: aRectangle rule: Form over mask: Form gray!lightGray "Set all bits in the receiver to lightGray." self fill: self boundingBox mask: Form lightGray!lightGray: aRectangle "Set all bits in the receiver's area defined by aRectangle to the lightGray mask." self fill: aRectangle rule: Form over mask: Form lightGray!reverse "Change all the bits in the receiver that are white to black, and the ones that are black to white." self fill: self boundingBox rule: Form reverse mask: Form black!reverse: aRectangle "Change all the bits in the receiver's area that intersects with aRectangle that are white to black, and the ones that are black to white." self fill: aRectangle rule: Form reverse mask: Form black!reverse: aRectangle mask: aMask "Change all the bits in the receiver's area that intersects with aRectangle according to the mask. Black does not necessarily turn to white, rather it changes with respect to the rule and the bit in a corresponding mask location. Bound to give a surprise." self fill: aRectangle rule: Form reverse mask: aMask!veryLightGray "Set all bits in the receiver to veryLightGray." self fill: self boundingBox mask: Form veryLightGray!veryLightGray: aRectangle "Set all bits in the receiver's area defined by aRectangle to the veryLightGray mask." self fill: aRectangle rule: Form over mask: Form veryLightGray!white "Set all bits in the form to white ( to zeros)." self fill: self boundingBox mask: Form white!white: aRectangle "Set all bits in the receiver's area defined by aRectangle to white (zeros)." self fill: aRectangle rule: Form over mask: Form white! !!DisplayMedium methodsFor: 'bordering'!border: aRectangle width: borderWidth "Paint a border whose rectangular area is defined by aRectangle. The width of the border of each side is borderWidth. Uses Form black for drawing the border." self border: aRectangle width: borderWidth mask: Form black!border: aRectangle width: borderWidth mask: aHalfTone "Paint a border whose rectangular area is defined by aRectangle. The width of the border of each side is borderWidth. Uses aHalfTone for drawing the border." self border: aRectangle widthRectangle: (Rectangle left: borderWidth right: borderWidth top: borderWidth bottom: borderWidth) mask: aHalfTone!border: aRectangle widthRectangle: insets mask: aHalfTone "Paint a border whose rectangular area is defined by aRectangle. The width of each edge of the border is determined by the four coordinates of insets. Uses aHalfTone for drawing the border." (aRectangle areasOutside: (aRectangle insetBy: insets)) do: [:edgeStrip | self fill: edgeStrip mask: aHalfTone]!border: aRectangle widthRectangle: insets mask: aHalfTone clippingBox: clipRect "Paint a border whose rectangular area is defined by aRectangle. The width of each edge of the border is determined by the four coordinates of insets. Uses aHalfTone for drawing the border." (aRectangle areasOutside: (aRectangle insetBy: insets)) do: [:edgeStrip | self fill: (edgeStrip intersect: clipRect) mask: aHalfTone]! !!DisplayMedium methodsFor: 'displaying'!copyBits: sourceRect from: sourceForm at: destOrigin clippingBox: clipRect rule: rule mask: aForm "Make up a BitBlt table and copy the bits." self subclassResponsibility!drawLine: sourceForm from: beginPoint to: endPoint clippingBox: clipRect rule: anInteger mask: aForm self subclassResponsibility! ! Object subclass: #DisplayObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!DisplayObject comment: 'The abstract protocol for most display primitives that are used by Views for presenting information on the screen.'!!DisplayObject methodsFor: 'accessing'!extent "Answer the point that represents the width and height of the receiver's bounding box." ^self boundingBox extent!height "Answer the number that represents the height of the receiver's bounding box." ^self boundingBox height!offset "Answer the amount by which the receiver should be offset when it is displayed or its position is tested." self subclassResponsibility!offset: aPoint "Set the amount by which the receiver's position is offset." ^self!relativeRectangle "Answer a Rectangle whose top left corner is the receiver's offset position and whose width and height are the same as the receiver." ^Rectangle origin: self offset extent: self extent!width "Answer the number that represents the width of the receiver's bounding box." ^self boundingBox width! !!DisplayObject methodsFor: 'truncation and round off'!rounded "Convert the offset of the receiver to integer coordinates." self offset: self offset rounded! !!DisplayObject methodsFor: 'transforming'!align: alignmentPoint with: relativePoint "Translate the receiver's offset such that alignmentPoint aligns with relativePoint." self offset: (self offset translateBy: relativePoint - alignmentPoint)!scaleBy: aPoint "Scale the receiver's offset by aPoint." self offset: (self offset scaleBy: aPoint)!translateBy: aPoint "Translate the receiver's offset." self offset: (self offset translateBy: aPoint)! !!DisplayObject methodsFor: 'display box access'!boundingBox "Answer the rectangular area that represents the boundaries of the receiver's space of information." ^self computeBoundingBox!computeBoundingBox "Answer the rectangular area that represents the boundaries of the receiver's area for displaying information. This is the primitive for computing the area if it is not already known." self subclassResponsibility! !!DisplayObject methodsFor: 'displaying-generic'!displayOn: aDisplayMedium "Simple default display in order to see the receiver in the upper left corner of screen." self displayOn: aDisplayMedium at: 0 @ 0!displayOn: aDisplayMedium at: aDisplayPoint "Display the receiver located at aDisplayPoint with default settings for rule and halftone." self displayOn: aDisplayMedium at: aDisplayPoint clippingBox: aDisplayMedium boundingBox rule: Form over mask: Form black!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle "Display the receiver located at aDisplayPoint with default settings for rule and halftone. Information to be displayed must be confined to the area that intersects with clipRectangle." self displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: Form over mask: Form black!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "This is the basic display primitive for graphic display objects. Display the receiver located at aDisplayPoint with rule, ruleInteger, and mask, aForm. Information to be displayed must be confined to the area that intersects with clipRectangle." self subclassResponsibility!displayOn: aDisplayMedium at: aDisplayPoint rule: ruleInteger "Display the receiver located at aPoint with default setting for the halftone and clippingBox." self displayOn: aDisplayMedium at: aDisplayPoint clippingBox: aDisplayMedium boundingBox rule: ruleInteger mask: Form black!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle "Display primitive for the receiver where a DisplayTransformation is provided as an argument. Alignment is defaulted to the receiver's rectangle. Information to be displayed must be confined to the area that intersects with clipRectangle." self displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: self relativeRectangle center with: self relativeRectangle center rule: Form over mask: Form black!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint "Display primitive where a DisplayTransformation is provided as an argument, rule is over and mask is Form black. Information to be displayed must be confined to the area that intersects with clipRectangle." self displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: Form over mask: Form black!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: ruleInteger mask: aForm "Display the receiver where a DisplayTransformation is provided as an argument, rule is ruleInteger and mask is aForm. Translate by relativePoint-alignmentPoint. Information to be displayed must be confined to the area that intersects with clipRectangle." | absolutePoint | absolutePoint _ displayTransformation applyTo: relativePoint. self displayOn: aDisplayMedium at: (absolutePoint - alignmentPoint) clippingBox: clipRectangle rule: ruleInteger mask: aForm!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle fixedPoint: aPoint "Display the receiver where a DisplayTransformation is provided as an argument, rule is over and mask is Form black. No translation. Information to be displayed must be confined to the area that intersects with clipRectangle." self displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: aPoint with: aPoint rule: Form over mask: Form black!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle rule: ruleInteger mask: aForm "Display the receiver where a DisplayTransformation is provided as an argument, rule is ruleInteger and mask is aForm. No translation. Information to be displayed must be confined to the area that intersects with clipRectangle." self displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: self relativeRectangle origin with: self relativeRectangle origin rule: ruleInteger mask: aForm! !!DisplayObject methodsFor: 'displaying-Display'!backgroundAt: location "Answer a Form containing the contents of the Display which will be altered if I am displayed at location. The Form remembers location in its offset" ^ (Form fromDisplay: (location extent: self extent)) offset: location!display self displayOn: Display!displayAt: aDisplayPoint "Display the receiver located at aDisplayPoint with default settings for the displayMedium, rule and halftone." self displayOn: Display at: aDisplayPoint clippingBox: Display boundingBox rule: Form over mask: Form black!follow: locationBlock while: durationBlock "This method moves an image around on the Display. It restores the background continuously without causing flashing. LocationBlock supplies each new location, and durationBlock supplies true to continue, and then false to stop. See (or run) OpaqueForm example." | location background | location _ locationBlock value. background _ self backgroundAt: location. self displayAt: location. [durationBlock value] whileTrue: [self moveTo: locationBlock value restoring: background]. background display!moveTo: newLoc restoring: background "Move an image to a new location on the Display, restoring the background without causing flashing. Background must be a Form containing the bits to be restored at the previous location (its offset), and this method will update its bits and offset appropriately" | location saveAll rect1 rect2 bothRects | "This method should be rewritten to use the offset in background directly" (location _ background offset) = newLoc ifTrue: [^background]. background offset: 0@0. rect1 _ location extent: self extent. rect2 _ newLoc extent: self extent. bothRects _ rect1 merge: rect2. (rect1 intersects: rect2) ifTrue: "When overlap, buffer background for both rectangles" [saveAll _ Form fromDisplay: bothRects. background displayOn: saveAll at: rect1 origin - bothRects origin. "now saveAll is clean background; get new bits for background" background copy: (0@0 extent: self extent) from: rect2 origin - bothRects origin in: saveAll rule: Form over. self displayOn: saveAll at: rect2 origin - bothRects origin. saveAll displayOn: Display at: bothRects origin] ifFalse: "If no overlap, do the simple thing (bothrects might be too big)" [background displayOn: Display at: location. background fromDisplay: rect2. self displayOn: Display at: newLoc]. ^ background offset: newLoc! ! CharacterScanner subclass: #DisplayScanner instanceVariableNames: 'lineY runX ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!DisplayScanner comment:'My instances hold the state of CharacterScanner in addition to the following required only for displaying or printing. They are used to scan text and display it on the screen or in a hidden form.Instance Variables lineY <Integer> Top of line currently being displayed or scanned. The textStyle lineGrid is added or subtracted to discover the top of the next line. May differ from destY when fonts of differing height fall on the same line. runX <Integer> Left of first character in the current run -- allows for creating underlining or similar emphasis.'!!DisplayScanner methodsFor: 'scanning'!displayLines: linesInterval in: aParagraph clippedBy: visibleRectangle "The central display routine. The call on the primitive (scanCharactersFrom:to:in:rightX:) will be interrupted according to the StopConditions array passed to the primitive at which time the code to handle the stopCondition is run and the call on the primitive continued until a stopCondition returns true which means the line has terminated." | runLength done lineGrid lineIndex stopCondition displaying| self initializeFromParagraph: aParagraph clippedBy: visibleRectangle. rightMargin _ aParagraph rightMarginForDisplay. lineGrid _ textStyle lineGrid. "assume outputMedium Display" lineY _ destY _ aParagraph topAtLineIndex: linesInterval first. displaying _ self doesDisplaying. linesInterval do: [:lineIndex | runX _ destX _ leftMargin _ aParagraph leftMarginForDisplayForLine: lineIndex. line _ aParagraph lineAt: lineIndex. text _ aParagraph textAt: lineIndex. lastIndex _ line first. self setStopConditions. "also sets the font" destY _ lineY + self fontAscentDelta. "fontAscent delta". runLength _ text runLengthFor: line first. (runStopIndex _ lastIndex + (runLength - 1)) > line last ifTrue: [runStopIndex _ line last]. spaceCount _ 0. done _ false. [done] whileFalse: [stopCondition _ self scanCharactersFrom: lastIndex to: runStopIndex in: text string rightX: rightMargin stopConditions: stopConditions displaying: displaying. "see setStopConditions for stopping conditions for displaying." done _ self perform: stopCondition]. "Y origin upper left -- increases as moving down page." lineY _ lineY + lineGrid]. ^lineIndex! !!DisplayScanner methodsFor: 'stop conditions'!cr "When a carriage return is encountered, simply increment the pointer into the paragraph." "When displaying line stopped in endOfRun, primitive hasn't incremented lastIndex when cr stop occurs, hence, " lastIndex_ lastIndex + 1. ^false!crossedX "This condition will sometimes be reached 'legally' during printing, when, for instance the space that caused the line to wrap actually extends over the right boundary. This character is allowed to print, even though it is technically outside or straddling the clippingRectangle since it is in the normal case not visible and is in any case appropriately clipped by the scanner." self checkEmphasis. ^true!endOfRun "The end of a run in the display case either means that there is actually a change in the style (run code) to be associated with the string or the end of this line has been reached. A check for any emphasis (underlining, for example) that may run the length of the run is done here before returning to displayLines: to do the next line" | runLength lastCharacter| lastIndex = line last ifTrue: [ "just displaying and at end of line". self checkEmphasis. ^true]. self checkEmphasis. runLength _ text runLengthFor: (lastIndex _ lastIndex + 1). self setStopConditions. runX _ destX. destY _ lineY + self fontAscentDelta. "fontAscent delta". (runStopIndex _ lastIndex + (runLength - 1)) > line last ifTrue: [runStopIndex _ line last]. ^false!onePixelBackspace "Increment destX by 1" destX _ (destX - 1) max: runX. lastIndex _ lastIndex + 1. ^false!onePixelSpace "Increment destX by 1" destX _ destX + 1. lastIndex _ lastIndex + 1. ^false!paddedSpace "Each space is a stop condition when the alignment = justified. Padding must be added to the base width of the space according to which space in the line this space is and according to the amount of space that remained at the end of the line when it was composed." spaceCount _ spaceCount + 1. destX _ destX + spaceWidth + (line justifiedPadFor: spaceCount). lastIndex _ lastIndex + 1. ^false!setStopConditions "Set the font and the stop conditions for the current run." | fontIndex displayFont | font _ textStyle fontAt: (text emphasisAt: lastIndex). super setStopConditions. stopConditions at: Space asInteger + 1 put: (textStyle alignment = Justified ifTrue: [#paddedSpace] ifFalse: [nil])!tab "This awfulness attempts to handle leading and internal tabs in a justified line. Leading tabs are considered legal and should be reflected on the display gracefully. Internal tabs (when the line is justified) are considered at the very best a misguided use of the character, and are reflected on the display the best we can." | leadingTab | leadingTab _ true. (line first to: lastIndex) do: [:index | (text at: index) = Space ifTrue: [leadingTab _ false]]. (textStyle alignment ~= Justified or: [leadingTab]) ifTrue: ["if a leading tab, just like a tab on a non-jusitified line" destX _ textStyle nextTabXFrom: destX leftMargin: leftMargin rightMargin: rightMargin] ifFalse: ["otherwise" destX _ destX + (textStyle tabWidth - (line justifiedTabDeltaFor: spaceCount)) max: destX]. lastIndex _ lastIndex + 1. ^false! !!DisplayScanner methodsFor: 'private'!checkEmphasis | emphasis sourceRect italicY lineSegment displayDestX displayRunX | (emphasis _ (font emphasis bitAnd: 7)) = 0 ifTrue: [^self]. displayDestX _ destX. displayRunX _ runX. emphasis >= 8 "overstrike" ifTrue: [destForm fill: ((displayRunX @ (lineY + textStyle baseline-3)) extent: (displayDestX - displayRunX) @ 1) rule: combinationRule mask: halftoneForm. emphasis _ emphasis - 8]. emphasis >= 4 "underlined" ifTrue: [lineSegment _ ((displayRunX @ (lineY + textStyle baseline + 1)) extent: (displayDestX - displayRunX) @ 1). lineSegment bottom <= (clipY+clipHeight) ifTrue: [destForm fill: lineSegment rule: combinationRule mask: halftoneForm]. emphasis _ emphasis - 4]. emphasis >= 2 "italic" ifTrue: [italicY _ lineY + textStyle lineGrid - 4. [italicY > lineY] whileTrue: [sourceRect _ displayRunX @ lineY extent: (displayDestX - displayRunX - 1) @ (italicY - lineY). destForm copyBits: sourceRect from: destForm at: (displayRunX+1) @ lineY clippingBox: sourceRect rule: Form over mask: nil. italicY _ italicY - 4]. emphasis _ emphasis - 2]. emphasis >= 1 "bold face" ifTrue: [sourceRect _ displayRunX @ lineY extent: (displayDestX - displayRunX - 1) @ textStyle lineGrid. destForm copyBits: sourceRect from: destForm at: (displayRunX+1) @ lineY clippingBox: sourceRect rule: Form under mask: nil]!doesDisplaying ^true!fontAscentDelta | currentFont previousFont actualAscent scriptFudge | scriptFudge _ 2. previousFont _ (textStyle fontAt: (text emphasisAt: ((lastIndex - 1) max: 1))). currentFont _ font. ((currentFont emphasis bitAt: SubscriptedBit) = 1) ifTrue: [^ textStyle baseline - scriptFudge] ifFalse: [((currentFont emphasis bitAt: SuperscriptedBit) = 1) ifTrue: [^ textStyle baseline - previousFont ascent - currentFont ascent + scriptFudge] ifFalse: [^ textStyle baseline - currentFont ascent]].!initializeFromParagraph: aParagraph clippedBy: clippingRectangle super initializeFromParagraph: aParagraph clippedBy: clippingRectangle! ! Form subclass: #DisplayScreen instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!DisplayScreen comment:'There is only one instance of me, CurrentDisplay. It is a global and is used to handle general user requests to deal with the whole display screen. Although I offer no protocol, my name provides a way to distinguish this special instance from all other Forms.'!!DisplayScreen methodsFor: 'displaying'!beDisplay "Tell the interpreter to use the receiver as the current display image. Fail if the form is too wide to fit on the physical display. Essential. See Object documentation whatIsAPrimitive." <primitive: 102> self primitiveFailed!flash: aRectangle "Complement twice the area of the screen defined by the argument, aRectangle." 2 timesRepeat: [self fill: aRectangle rule: Form reverse mask: Form black. (Delay forMilliseconds: 60) wait]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!DisplayScreen class instanceVariableNames: ''!!DisplayScreen class methodsFor: 'current display'!currentDisplay: form "Make the argument, form, be the form representing the current display screen. Create an error if form is not an instance of me." form class == self ifTrue: [form bits class == DisplayBitmap ifTrue: [Display become: form. Display beDisplay] ifFalse: [self error: 'bitmap should be DisplayBitmap']] ifFalse: [self error: 'form should be DisplayForm']!displayExtent: extent "Make the width and height of the current display screen form be extent." | w h | w _ extent x truncateTo: 32. h _ extent y truncateTo: 2. DisplayScreen currentDisplay: (DisplayScreen new extent: w @ 16 offset: 0 @ 0 bits: (DisplayBitmap new: w // 16 * 16)). "shrink to 16 to release old bitmap" DisplayScreen currentDisplay: (DisplayScreen new extent: w @ h offset: 0 @ 0 bits: (DisplayBitmap new: w // 16 * h)). "now grow to new size" ScheduledControllers restore!displayHeight: height "Make the height of the current display screen form be the argument, height." ^self displayExtent: self boundingBox width @ height! !!DisplayScreen class methodsFor: 'display box access'!boundingBox "Answer the bounding box for the form representing the current display screen." ^Display boundingBox! ! DisplayObject subclass: #DisplayText instanceVariableNames: 'text textStyle offset form ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Display Objects'!DisplayText comment:'I get used two different ways in the system.In the user interface I mainly hold onto some text which is viewed by some form of ParagraphEditor. However, as a DisplayObject, I may need to display efficiently, so form caches the bits for that purpose.'!!DisplayText methodsFor: 'accessing'!form form == nil ifTrue: [self composeForm]. ^form!lineGrid "Answer the relative space between lines of the receiver's text." ^textStyle lineGrid!numberOfLines "Answer the number of lines of text in the receiver." ^self height // text lineGrid!offset ^offset!offset: aPoint offset _ aPoint!string "Answer the string of the characters displayed by the receiver." ^text string!text "Answer the text displayed by the receiver." ^text!text: aText "Set the receiver to display the argument, aText." text _ aText. form _ nil. self changed.!textStyle "Answer the style by which the receiver displays its text." ^textStyle!textStyle: aTextStyle "Set the style by which the receiver should display its text." textStyle _ aTextStyle. form _ nil. self changed.! !!DisplayText methodsFor: 'displaying'!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm self form displayOn: aDisplayMedium at: aDisplayPoint + offset clippingBox: clipRectangle rule: ruleInteger mask: aForm!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: ruleInteger mask: aForm | absolutePoint | absolutePoint _ displayTransformation applyTo: relativePoint. absolutePoint _ absolutePoint x truncated @ absolutePoint y truncated. self displayOn: aDisplayMedium at: absolutePoint - alignmentPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm! !!DisplayText methodsFor: 'display box access'!boundingBox ^self form boundingBox!computeBoundingBox "Compute minimum enclosing rectangle around characters." | character font width carriageReturn lineWidth lineHeight | carriageReturn _ Character cr. width _ lineWidth _ 0. font _ textStyle defaultFont. lineHeight _ textStyle lineGrid. 1 to: text size do: [:i | character _ text at: i. character = carriageReturn ifTrue: [lineWidth _ lineWidth max: width. lineHeight _ lineHeight + textStyle lineGrid. width _ 0] ifFalse: [width _ width + (font widthOf: character)]]. lineWidth _ lineWidth max: width. ^offset extent: lineWidth @ lineHeight! !!DisplayText methodsFor: 'converting'!asParagraph "Answer a Paragraph whose text and style are identical to that of the receiver." ^Paragraph withText: text style: textStyle copy! !!DisplayText methodsFor: 'private'!composeForm form _ self asParagraph asForm!setText: aText textStyle: aTextStyle offset: aPoint text _ aText. textStyle _ aTextStyle. offset _ aPoint. form _ nil! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!DisplayText class instanceVariableNames: ''!!DisplayText class methodsFor: 'instance creation'!text: aText "Answer an instance of me such that the text displayed is aText according to the system's default textstyle." ^self new setText: aText textStyle: DefaultTextStyle copy offset: 0 @ 0!text: aText textStyle: aTextStyle "Answer an instance of me such that the text displayed is aText according to the style specified by aTextStyle." ^self new setText: aText textStyle: aTextStyle offset: 0 @ 0!text: aText textStyle: aTextStyle offset: aPoint "Answer an instance of me such that the text displayed is aText according to the style specified by aTextStyle. The display of the information should be offset by the amount given as the argument, aPoint." ^self new setText: aText textStyle: aTextStyle offset: aPoint! !!DisplayText class methodsFor: 'examples'!example "Continually prints two lines of text wherever you point with the cursor. Terminate by pressing any mouse button." | t | t _ 'this is a line of characters andthis is the second line.' asDisplayText. [Sensor anyButtonPressed] whileFalse: [t displayOn: Display at: Sensor cursorPoint] "DisplayText example."! ! View subclass: #DisplayTextView instanceVariableNames: 'rule mask editParagraph centered ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Views'!DisplayTextView comment:'I represent a view of an instance of DisplayText.Instance Variables: rule <Integer> according to which character display behaves: equal over, under, and reverse. mask <Form> with which each character is combined by the display scanner before applying the rule. editParagraph <Paragraph> the composed text ready for display'!!DisplayTextView methodsFor: 'initialize-release'!initialize super initialize. centered _ false! !!DisplayTextView methodsFor: 'accessing'!centered centered _ true. self centerText!isCentered ^centered!mask "Answer an instance of class Form that is to be used as the mask when displaying the receiver's model (a DisplayText)." mask == nil ifTrue: [^self defaultMask] ifFalse: [^mask]!mask: aForm "Set aForm to be the mask used when displaying the receiver's model." mask _ aForm!rule "Answer a number from 0 to 15 that indicates which of the sixteen display rules is to be used when blting the receiver's model (a DisplayText) onto the display screen." rule == nil ifTrue: [^self defaultRule] ifFalse: [^rule]!rule: anInteger "Set anInteger to be the rule used when displaying the receiver's model." rule _ anInteger! !!DisplayTextView methodsFor: 'controller access'!defaultController ^self defaultControllerClass newParagraph: editParagraph!defaultControllerClass ^ParagraphEditor! !!DisplayTextView methodsFor: 'window access'!defaultWindow ^((0@0 extent: editParagraph extent) expandBy: self paragraphInset) expandBy: borderWidth!window: aWindow super window: aWindow. self centerText! !!DisplayTextView methodsFor: 'model access'!model: aDisplayText super model: aDisplayText. editParagraph _ model asParagraph. self centerText! !!DisplayTextView methodsFor: 'displaying'!display self isUnlocked ifTrue: [self positionText]. super display!displayView self clearInside. (self controller isKindOf: ParagraphEditor ) ifTrue: [controller changeParagraph: editParagraph]. self isCentered ifTrue: [editParagraph displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox fixedPoint: editParagraph boundingBox center] ifFalse: [editParagraph displayOn: Display]! !!DisplayTextView methodsFor: 'deEmphasizing'!deEmphasizeView (self controller isKindOf: ParagraphEditor) ifTrue: [controller deselect]! !!DisplayTextView methodsFor: 'private'!centerText self isCentered ifTrue: [editParagraph align: editParagraph boundingBox center with: self getWindow center]!defaultMask ^Form black!defaultRule ^Form over!paragraphInset "Answer the amount to inset the paragraph from the border" ^6@0!positionText | box | box _ self insetDisplayBox origin + self paragraphInset extent: editParagraph boundingBox extent. editParagraph recomposeIn: box clippingBox: box. self centerText! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!DisplayTextView class instanceVariableNames: ''!!DisplayTextView class methodsFor: 'examples'!example1 "Creates a system view with a paragraph editor in it" | topView aDisplayTextView | aDisplayTextView _ DisplayTextView new model: 'test string' asDisplayText. aDisplayTextView insideColor: Form white. aDisplayTextView borderWidth: 2. topView _ StandardSystemView new. topView label: 'Text Editor'. topView addSubView: aDisplayTextView. topView controller open "DisplayTextView example1."!example2 "Creates a standarad system view with two parts, one editable, the other not." | topView aDisplayTextView | topView _ StandardSystemView new. topView label: 'Text Editor'. aDisplayTextView _ self new model: 'test string label' asDisplayText. aDisplayTextView controller: NoController new. aDisplayTextView window: (0 @ 0 extent: 100 @ 100). aDisplayTextView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. aDisplayTextView insideColor: Form white. topView addSubView: aDisplayTextView. aDisplayTextView _ self new model: 'test string' asDisplayText. aDisplayTextView window: (0 @ 0 extent: 100 @ 100). aDisplayTextView borderWidth: 2. aDisplayTextView insideColor: Form white. topView addSubView: aDisplayTextView align: aDisplayTextView viewport topLeft with: topView lastSubView viewport topRight. topView controller open "DisplayTextView example2."!example3 "Creates a passive view of some text on the screen." | view | view_ self new model: 'this is a test of one lineand the second line' asDisplayText. view translateBy: 100@100. view borderWidth: 2. view insideColor: Form white. view display. view release "DisplayTextView example3."!example4 "Creates four passive views of some text on the screen with fat borders." | view | view_ self new model: 'this is a test of one lineand the second line' asDisplayText. view translateBy: 100@100. view borderWidth: 5. view insideColor: Form white. view display. 3 timesRepeat: [view translateBy: 100@100. view display]. view release "DisplayTextView example4."! ! ParseNode subclass: #Encoder instanceVariableNames: 'scopeTable nTemps supered requestor class literalStream selectorSet litIndSet litSet sourceRanges lastTempPos ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!Encoder comment: 'I encode names and literals into tree nodes with byte codes for the compiler. Byte codes for literals are not assigned until the tree-sizing pass of the compiler, because only then is it known which literals are actually needed. I also keep track of sourceCode ranges during parsing and code generation so I can provide an inverse map for the debugger.scopeTable is a dictionary of (names->nodes)nTemps is the count of temporaries used so farsupered is true if super has been used in this methodrequestor is usually a parserclass is the class in which we are compiling - used to look up class and pool variablesliteralStream accumulates the literals used in this methodselectorSet is a dictionary of (selectors->nodes) predefined or used in this methodlitIndSet is a dictionary of (poolVars->nodes) used in this methodlitSet is a dictionary of (constants->nodes) used in this methodsourceRanges is a dictionary of (node->source interval)s'!!Encoder methodsFor: 'initialize-release'!fillDict: dict with: nodeClass mapping: keys to: codeArray | codeStream key | codeStream _ ReadStream on: codeArray. keys do: [:key | dict at: key put: (nodeClass new name: key key: key code: codeStream next)]!init: aClass context: aContext notifying: req | variable node n homeNode indexNode | requestor _ req. class _ aClass. nTemps _ 0. supered _ false. self initScopeAndLiteralTables. n _ -1. class allInstVarNames do: [:variable | node _ VariableNode new name: variable index: (n _ n + 1) type: LdInstType. scopeTable at: variable put: node]. aContext == nil ifFalse: [homeNode _ self bindTemp: 'homeContext'. "first temp = aContext passed as arg" n _ 0. aContext tempNames do: [:variable | indexNode _ self encodeLiteral: (n _ n + 1). node _ MessageNode new receiver: homeNode selector: #tempAt: arguments: (Array with: indexNode) precedence: 3 from: self. scopeTable at: variable put: node]]. sourceRanges _ Dictionary new: 32!initScopeAndLiteralTables scopeTable _ StdVariables copy. litSet _ StdLiterals copy. selectorSet _ StdSelectors copy. litIndSet _ Dictionary new: 16. literalStream _ WriteStream on: (Array new: 32)!noteSuper supered _ true!nTemps: n literals: lits class: cl "Decompile" class _ cl. nTemps _ n. literalStream _ ReadStream on: lits. literalStream position: lits size!release requestor _ nil! !!Encoder methodsFor: 'encoding'!cantStoreInto: varName ^ StdVariables includesKey: varName!encodeLiteral: object ^self name: object key: object class: LiteralNode type: LdLitType set: litSet!encodeSelector: selector ^self name: selector key: selector class: SelectorNode type: SendType set: selectorSet!encodeVariable: name ^scopeTable at: name ifAbsent: [self lookupInPools: name ifFound: [:assoc | ^ self global: assoc name: name]. requestor editor notNil ifTrue: [self undeclared: name] ifFalse: [self declareUndeclared: name]]!litIndex: literal | p | p _ literalStream position. p = 64 ifTrue: [self notify: 'More than 64 literals referenced. You must split or otherwise simplify this method'. ^nil]. literalStream nextPut: literal. ^p! !!Encoder methodsFor: 'temporaries'!autoBind: name "Declare a block argument as a temp if not already declared" | node assoc | node _ scopeTable at: name ifAbsent: [(self lookupInPools: name ifFound: [:assoc | assoc]) ifTrue: [self notify: 'Name already used in a Pool or Global']. ^self reallyBindTemp: name]. node isTemp ifFalse: [^self notify: 'Name already used in this class']. ^node!bindTemp: name "Declare a temporary; error not if a field or class variable." (scopeTable includesKey: name) ifTrue: [^self notify: 'Name is already defined']. ^self reallyBindTemp: name!maxTemp ^nTemps!newTemp: name nTemps _ nTemps + 1. ^VariableNode new name: name index: nTemps - 1 type: LdTempType!reallyBindTemp: name "private; assumes name not in scope yet" | node | node _ self newTemp: name. scopeTable at: name put: node. ^node! !!Encoder methodsFor: 'results'!associationFor: aClass | name | name _ Smalltalk keyAtValue: aClass ifAbsent: [^Association new value: aClass]. ^Smalltalk associationAt: name!associationForClass ^self associationFor: class!literals: primitive nArgs: nArgs (primitive > 0 or: [nArgs > 4]) ifTrue: [self litIndex: nArgs * 256 + primitive. self litIndex: (self associationForClass)] ifFalse: [supered ifTrue: [self litIndex: (self associationForClass)]]. ^literalStream contents!supered ^supered!tempNames | tempNodes | tempNodes _ (scopeTable values select: [:node | node isTemp]) asSortedCollection: [:n1 :n2 | n1 code <= n2 code]. ^tempNodes collect: [:node | node key]! !!Encoder methodsFor: 'error handling'!abort | req | requestor == nil ifFalse: [req _ requestor. self release. req abort]. ^false!notify: string | req | requestor == nil ifFalse: [req _ requestor. self release. req notify: string]. ^false! !!Encoder methodsFor: 'source mapping'!noteSourceRange: range forNode: node sourceRanges at: node put: range!sourceMap: numLits "Answer with a sorted set of associations (pc . range). Delta is the difference between the parsed number of literals (startpc) and the generated number of literals." | key delta | delta _ (numLits - literalStream position) * 2. ^(sourceRanges keys collect: [:key | Association key: key pc + delta value: (sourceRanges at: key)]) asSortedCollection! !!Encoder methodsFor: 'undeclared variables'!declareClassVar: name | sym | name first isUppercase ifFalse: [self notify: 'Capitalize globals or classVars']. sym _ name asSymbol. class addClassVarName: sym. Smalltalk changes changeClass: class. ^ self global: (class classPool associationAt: sym) name: sym!declareCorrect: name "Attempt to correct the spelling of an undeclared variable." | old lc names score bestScore guess | old _ name. lc _ old first asLowercase. names _ (scopeTable keys select: [:key | key first asLowercase = lc]). names addAll: (class allVarNamesSelect: [:key | key first asLowercase = lc]). bestScore _ 0. names do: [:name | (score _ name spellAgainst: old) > bestScore ifTrue: [bestScore _ score. guess _ name]]. bestScore > 50 ifFalse: [^ self notify: 'Couldn''t correct']. (self confirm: 'Confirm correction to ' , guess) ifTrue: [requestor replaceEditSelectionWith: guess. ^ self encodeVariable: guess] ifFalse: [^ self notify: 'Undeclared']!declareFailed: name self abort!declareGlobal: name | sym | name first isUppercase ifFalse: [self notify: 'Capitalize globals or classVars']. sym _ name asSymbol. Smalltalk at: sym put: nil. ^ self global: (Smalltalk associationAt: sym) name: sym!declareTemp: name requestor pasteTemp: name. ^ self reallyBindTemp: name!declareUndeclared: name | sym | sym _ name asSymbol. (Undeclared includesKey: name asSymbol) ifFalse: [Transcript show: ' (' , name , ' is Undeclared) '. Undeclared at: sym put: nil]. ^ self global: (Undeclared associationAt: sym) name: sym!undeclared: name | message messageLoc messageBox saveBits menu index | Cursor normal show. requestor selectVariable: name. index _ (menu _ ActionMenu labels: 'temp\class var\global\undeclared\correct it\abort' withCRs lines: #(4) selectors: #(declareTemp: declareClassVar: declareGlobal: declareUndeclared: declareCorrect: declareFailed:)) startUp: #anyButton withHeading: ' declare ' asText , (name contractTo: 20) asText allBold , ' as ' asText. index = 0 ifTrue: [^ self declareFailed: name]. ^ self perform: (menu selectorAt: index) with: name! !!Encoder methodsFor: 'private'!global: ref name: name ^self name: name key: ref class: VariableNode type: LdLitIndType set: litIndSet!lookupInPools: name ifFound: assocBlock | sym | Symbol hasInterned: name ifTrue: [:sym | ^class scopeHas: sym ifTrue: assocBlock]. ^false!name: name key: key class: leafNodeClass type: type set: dict | node | ^dict at: key ifAbsent: [node _ leafNodeClass new name: name key: key index: nil type: type. dict at: key put: node. ^node]! ! Object subclass: #Explainer instanceVariableNames: 'class selector instance context methodText ' classVariableNames: 'NewLine ' poolDictionaries: '' category: 'Interface-Support'!Explainer comment:'I try to determine what a piece of text represents, usually in the context of a method.'!!Explainer methodsFor: 'explaining'!class: aClass selector: aSymbol instance: anInstance context: aContext methodText: aText class _ aClass. selector _ aSymbol. instance _ anInstance. context _ aContext. methodText _ aText!explain: selection for: model "Try to shed some light on what kind of entity the current selection is. The selection must be a single token or construct. Insert the answer after the selection. Call private routines whose names begin with 'explain'. They return a String if they recognise the selection, else nil." | string tiVars cgVars selectors delimitors numbers symbol reply | Cursor execute showWhile: [selection isEmpty ifTrue: [reply _ ''] ifFalse: [string _ self explainScan: selection. "Remove space, tab, cr" "Temps and Instance vars need only test strings that are all letters" (string detect: [:char | (char isLetter or: [char isDigit]) not] ifNone: []) ~~ nil ifFalse: [tiVars _ self explainTemp: string. tiVars == nil ifTrue: [tiVars _ self explainInst: string]]. (tiVars == nil) ifTrue: [tiVars _ model explainSpecial: string]. tiVars == nil ifTrue: [tiVars _ ''] ifFalse: [tiVars _ tiVars , NewLine]. "Context, Class, Pool, and Global vars, and Selectors need only test symbols" (Symbol hasInterned: string ifTrue: [:symbol | symbol]) ifTrue: [cgVars _ self explainCtxt: symbol. cgVars == nil ifTrue: [cgVars _ self explainClass: symbol. cgVars == nil ifTrue: [cgVars _ self explainGlobal: symbol]]. "See if it is a Selector (sent here or not)" selectors _ self explainMySel: symbol. selectors == nil ifTrue: [selectors _ self explainPartSel: string. selectors == nil ifTrue: [selectors _ self explainAnySel: symbol]]] ifFalse: [selectors _ self explainPartSel: string]. cgVars == nil ifTrue: [cgVars _ ''] ifFalse: [cgVars _ cgVars , NewLine]. selectors == nil ifTrue: [selectors _ ''] ifFalse: [selectors _ selectors , NewLine]. string size = 1 ifTrue: ["single special characters" delimitors _ self explainChar: string] ifFalse: ["matched delimitors" delimitors _ self explainDelimitor: string]. numbers _ self explainNumber: string. numbers == nil ifTrue: [numbers _ '']. delimitors == nil ifTrue: [delimitors _ '']. reply _ tiVars , cgVars , selectors , delimitors , numbers]]. reply size = 0 ifTrue: [^ '"Sorry, I can''t explain that. Please select a single token, construct, or special character."']. ^ reply!explainAnySel: symbol "Is this any message selector?" | list reply | list _ Smalltalk allClassesImplementing: symbol. list size = 0 ifTrue: [^nil]. list size < 12 ifTrue: [reply _ ' is a message selector which is defined in these classes ' , list printString] ifFalse: [reply _ ' is a message selector which is defined in many classes']. ^'"' , symbol , reply , '."', NewLine, 'Smalltalk browseAllImplementorsOf: #' , symbol!explainChar: string "Does string start with a special character?" | char | char _ string at: 1. char = $. ifTrue: [^'"Period marks the end of a Smalltalk statement. A period in the middle of a number means a decimal point. (The number is an instance of Float). A period in the middle of a selector means a compound selector. (To the left is the superclass, to the right is the selector)."']. char = $' ifTrue: [^'"The characters between two single quotes are made into an instance of class String"']. char = $" ifTrue: [^'"Double quotes enclose a comment. Smalltalk ignores everything between double quotes."']. char = $# ifTrue: [^'"The characters following a hash mark are made into an instance of class Symbol. If parenthesis follow a hash mark, an instance of class Array is made."']. (char = $( or: [char = $)]) ifTrue: [^'"Expressions enclosed in parenthesis are evaluated first"']. (char = $[ or: [char = $]]) ifTrue: [^'"The code inside square brackets is an unevaluated block of code. It becomes an instance of BlockContext and is usually passed as an argument."']. (char = $< or: [char = $>]) ifTrue: [^'"<primitive: xx> means that this method is usually preformed directly by the virtual machine. If this method is primitive, its Smalltalk code is executed only when the primitive fails."']. char = $^ ifTrue: [^'"Uparrow means return from this method. The value returned is the expression following the ^"']. char = $| ifTrue: [^'"Vertical bars enclose the names of the temporary variables used in this method. In a block, the vertical bar separates the argument names from the rest of the code."']. char = $_ ifTrue: [^'"Left arrow means assignment. The value of the expression after the left arrow is stored into the variable before it."']. char = $; ifTrue: [^'"Semicolon means cascading. The message after the semicolon is sent to the same object which received the message before the semicolon."']. char = $: ifTrue: [^'"A colon at the end of a keyword means that an argument is expected to follow. Methods which take more than one argument have selectors with more than one keyword. (One keyword, ending with a colon, appears before each argument).', NewLine, NewLine, 'A colon before a variable name just inside a block means that the block takes an agrument. (When the block is evaluated, the argument will be assigned to the variable whose name appears after the colon)."']. char = $$ ifTrue: [^'"The single character following a dollar sign is made into an instance of class Character"']. char = $- ifTrue: [^'"A minus sign in front of a number means a negative number."']. char = $e ifTrue: [^'"An e in the middle of a number means that the exponent follows."']. char = $r ifTrue: [^'"An r in the middle of a bunch of digits is an instance of Integer expressed in a certain radix. The digits before the r denote the base and the digits after it express a number in that base."']. char = Character space ifTrue: [^'"the space Character"']. char = Character tab ifTrue: [^'"the tab Character"']. char = Character cr ifTrue: [^'"the carriage return Character"']. ^nil!explainClass: symbol "Is symbol a class variable or a pool variable?" | name pool reply classes | class == nil ifTrue: [^nil]. "no class is selected" classes _ ((class isKindOf: Metaclass) ifTrue: [class soleInstance] ifFalse: [class]) withAllSuperclasses. "class variables" reply _ classes detect: [:each | (each classVarNames detect: [:name | symbol = name] ifNone: []) ~~ nil] ifNone: []. reply == nil ifFalse: [^'"is a class variable; defined in class ' , reply printString, '"', NewLine, 'Smalltalk browseAllCallsOn: (', reply printString, ' classPool associationAt: #', symbol, ').']. "pool variables" classes do: [:each | (each sharedPools detect: [:pool | (pool includesKey: symbol) and: [reply _ pool. true]] ifNone: []) ~~ nil]. reply == nil ifTrue: [(Undeclared includesKey: symbol) ifTrue: [reply _ Undeclared]]. reply == nil ifFalse: [classes _ WriteStream on: Array new. Smalltalk allBehaviorsDo: [:each | (each sharedPools detect: [:pool | pool == reply] ifNone: []) ~~ nil ifTrue: [classes nextPut: each]]. "Perhaps not print whole list of classes if too long. (unlikely)" ^'"is a pool variable from the pool ' , (Smalltalk keyAtValue: reply), ', which is used by the following classes ' , classes contents printString , '"', NewLine, 'Smalltalk browseAllCallsOn: (', (Smalltalk keyAtValue: reply) printString, ' associationAt: #', symbol, ').']. ^nil!explainCtxt: symbol "Is symbol a context variable?" | reply classes text | symbol = #nil ifTrue: [reply _ '"is a constant. It is the only instance of class UndefinedObject. nil is the initial value of all variables."']. symbol = #true ifTrue: [reply _ '"is a constant. It is the only instance of class True and is the receiver of many control messages."']. symbol = #false ifTrue: [reply _ '"is a constant. It is the only instance of class False and is the receiver of many control messages."']. class == nil ifTrue: [^nil]. "no message selected" symbol = #self ifTrue: [classes _ class withAllSubclasses. classes size > 12 ifTrue: [text _ class printString , ' or a subclass'] ifFalse: [classes _ classes printString. text _ 'one of these classes' , (classes copyFrom: 4 to: classes size)]. reply _ '"is the receiver of this message; an instance of ' , text , '"']. symbol = #super ifTrue: [reply _ '"is just like self. Messages to super are looked up in the superclass (' , class superclass printString , ')"']. symbol = #thisContext ifTrue: [reply _ '"is a context variable. It''s value is always the MethodContext which is executing this method."']. ^reply!explainDelimitor: string "Is string enclosed in delimitors?" | str | (string at: 1) isLetter ifTrue: [^nil]. "only special chars" (string first = string last) ifTrue: [^ self explainChar: (String with: string first)] ifFalse: [(string first = $( and: [string last = $)]) ifTrue: [^ self explainChar: (String with: string first)]. (string first = $[ and: [string last = $]]) ifTrue: [^ self explainChar: (String with: string first)]. (string first = $< and: [string last = $>]) ifTrue: [^ self explainChar: (String with: string first)]. (string first = $# and: [string last = $)]) ifTrue: [^'"An instance of class Array. The Numbers, Characters, or Symbols between the parenthesis are the elements of the Array."']. string first = $# ifTrue: [^'"An instance of class Symbol."']. (string first = $$ and: [string size = 2]) ifTrue: [^'"An instance of class Character. This one is the character ', (String with: string last), '."']. (string first = $:) ifTrue: [str _ (string copyFrom: 2 to: string size). (self explainTemp: str) ~~ nil ifTrue: [^'"An argument to this block will be bound to the temporary variable ', str, '."']]]. ^ nil!explainGlobal: symbol "Is symbol a global variable?" | each pool reply classes | reply _ Smalltalk at: symbol ifAbsent: [^nil]. (reply isKindOf: Behavior) ifTrue: [^'"is a global variable. ' , symbol , ' is a class in category ', reply category, '."', NewLine, 'Browser newOnClass: ' , symbol , '.']. symbol == #Smalltalk ifTrue: [^'"is a global. Smalltalk is the only instance of SystemDictionary and holds all global variables."']. reply class == Dictionary ifTrue: [classes _ Set new. Smalltalk allBehaviorsDo: [:each | (each sharedPools detect: [:pool | pool == reply] ifNone: []) ~~ nil ifTrue: [classes add: each]]. classes _ classes printString. ^'"is a global variable. ' , symbol , ' is a Dictionary. It is a pool which is used by the following classes' , (classes copyFrom: 4 to: classes size) , '"']. ^'"is a global variable. ' , symbol , ' is ' , reply printString , '"'!explainInst: string "Is string an instance variable of this class?" | name each classes | class == nil ifTrue: [^nil]. "no class is selected" classes _ class withAllSuperclasses. classes _ classes detect: [:each | (each instVarNames detect: [:name | name = string] ifNone: []) ~~ nil] ifNone: [^nil]. classes _ classes printString. ^ '"is an instance variable of the receiver; defined in class ' , classes , '"', NewLine , classes , ' browseAllAccessesTo: ''' , string , '''.'!explainMySel: symbol "Is symbol the selector of this method? Is it sent by this method? If not, then expalin will call (explainPartSel:) to see if it is a fragment of a selector sent here. If not, explain will call (explainAnySel:) to catch any selector. " | lits classes | selector == nil ifTrue: [^nil]. "not in a message" classes _ Smalltalk allClassesImplementing: symbol. classes size > 12 ifTrue: [classes _ 'many classes'] ifFalse: [classes _ 'these classes ' , classes printString]. selector = symbol ifTrue: [^ '"' , symbol , ' is the selector of this very method!! It is defined in ', classes , '. To see the other definitions, go to the message list pane and use yellowbug to select ''implementors''."'] ifFalse: [lits _ (class compiledMethodAt: selector) messages. (lits detect: [:each | each == symbol] ifNone: []) == nil ifTrue: [^nil]. ^ '"' , symbol , ' is a message selector which is defined in ', classes , '. To see the definitions, go to the message list pane and use yellowbug to select ''messages''."'].!explainNumber: string "Is string a Number?" | strm c | (c _ string at: 1) isDigit ifFalse: [(c = $- and: [string size > 1]) ifFalse: [^nil]]. strm _ ReadStream on: string. c _ Number readFrom: strm. strm atEnd ifFalse: [^nil]. c printString = string ifTrue: [^'"' , string , ' is a ' , c class name , '"'] ifFalse: [^'"' , string , ' (= ' , c printString , ') is a ' , c class name , '"']!explainPartSel: string "Is this a fragment of a multiple-argument selector sent in this method?" | lits frag whole reply classes s | selector == nil ifTrue: [^nil]. "not in a message" string last == $: ifFalse: [^nil]. "Name of this method" lits _ Array with: selector. (whole _ lits detect: [:each | (each keywords detect: [:frag | frag = string] ifNone: []) ~~ nil] ifNone: []) ~~ nil ifTrue: [reply _ ', which is the selector of this very method!!'. s _ '. To see the other definitions, go to the message list pane and use yellowbug to select ''implementors''."'] ifFalse: ["Selectors called from this method" lits _ (class compiledMethodAt: selector) messages. (whole _ lits detect: [:each | (each keywords detect: [:frag | frag = string] ifNone: []) ~~ nil] ifNone: []) ~~ nil ifFalse: [string = 'primitive:' ifTrue: [^self explainChar: '<'] ifFalse: [^nil]]. reply _ '.'. s _ '. To see the definitions, go to the message list pane and use yellowbug to select ''messages''."']. classes _ Smalltalk allClassesImplementing: whole. classes size > 12 ifTrue: [classes _ 'many classes'] ifFalse: [classes _ 'these classes ' , classes printString]. ^ '"' , string , ' is one part of the message selector ' , whole, reply , ' It is defined in ' , classes , s!explainScan: string "remove beginning and trailing space, tab, cr" | c beg end | beg _ 1. end _ string size. [beg = end ifTrue: [^string copyFrom: 1 to: 1]. "if all blank, tell about the first" c _ string at: beg. c = Character space or: [c = Character tab or: [c = Character cr]]] whileTrue: [beg _ beg + 1]. [c _ string at: end. c = Character space or: [c = Character tab or: [c = Character cr]]] whileTrue: [end _ end - 1]. ^string copyFrom: beg to: end "Return purely visible characters"!explainTemp: string "Is string the name of a temporary variable (or block argument variable)?" | tempNames i reply methodNode method | selector == nil ifTrue: [^nil]. "no message is selected" tempNames _ class parserClass new parseArgsAndTemps: methodText notifying: nil. method _ class compiledMethodAt: selector. (i _ tempNames findFirst: [:each | each = string]) = 0 ifTrue: [ (method numTemps > tempNames size and: [Smalltalk frills]) ifTrue: ["It must be an undeclared block argument temporary" methodNode _ class compilerClass new parse: methodText in: class notifying: nil. tempNames _ methodNode tempNames] ifFalse: [^nil]]. (i _ tempNames findFirst: [:each | each = string]) > 0 ifTrue: [i > method numArgs ifTrue: [reply _ '"is a temporary variable in this method"'] ifFalse: [reply _ '"is an argument to this method"']]. ^reply! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Explainer class instanceVariableNames: ''!!Explainer class methodsFor: 'class initialization'!initialize "Explainer initialize" NewLine _ String with: Character cr! !Explainer initialize! ReadWriteStream subclass: #ExternalStream instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Files-Streams'!ExternalStream comment:'I represent an accessor for a sequence of objects that communicate to the outside world. My instances can contain non-homogenous elements. Assumes streaming on a collection of binary, byte-sized elements. My methods assume that a "word" consists of two-bytes.'!!ExternalStream methodsFor: 'accessing'!next: anInteger "Answer the next anInteger elements of my collection. Must override because default uses self contents species, which might involve a Large collection. " | newArray | newArray _ collection species new: anInteger. 1 to: anInteger do: [:index | newArray at: index put: self next]. ^newArray! !!ExternalStream methodsFor: 'nonhomogeneous positioning'!padTo: bsize "Pad (skip) to next boundary of bsize characters, and answer how many characters were skipped." self subclassResponsibility!padTo: bsize put: aCharacter "Pad using the argument, aCharacter, to the next boundary of bsize characters, and answer how many characters were written." self subclassResponsibility!padToNextWord "Make position even (on word boundary), answering the padding character if any." position even ifTrue: [^false] ifFalse: [^self next]!padToNextWordPut: char "Make position even on word boundary, writing the padding character, char, if necessary. Answer nil if already on a word boundary" position even ifTrue: [^nil] ifFalse: [^self nextPut: char]!skipWords: nWords "Position after nWords number of words." self skip: 2 * nWords!wordPosition "Answer the current position in words." ^self position / 2!wordPosition: wp "Set current position in words to be wp." self position: 2 * wp! !!ExternalStream methodsFor: 'nonhomogeneous accessing'!nextNumber: n "Answer the next n bytes as a positive Integer or LargePositiveInteger." | s | n <= 2 ifTrue: [s _ 0. n timesRepeat: [s _ s * 256 + self next]. ^s]. s _ LargePositiveInteger new: n. 1 to: n do: [:i | s at: n + 1 - i put: self next]. "reverse order of significance" ^s truncated!nextNumber: n put: v "Append to the receiver the argument, v, which is a positive SmallInteger or a LargePositiveInteger, as the next n bytes. Possibly pad with leading zeros." | vlen i | vlen _ v digitLength. n < vlen ifTrue: [self error: 'number too big'] ifFalse: [n > vlen ifTrue: [self next: n - vlen put: 0]]. "pad beginning with 0's" vlen = 1 ifTrue: [self nextPut: v] ifFalse: [(vlen = 2 and: [v isMemberOf: SmallInteger]) ifTrue: [self nextWordPut: v] ifFalse: ["LargeInteger (assume pos, no negative convention)" 1 to: vlen do: [:i | self nextPut: (v at: vlen + 1 - i)]]]!nextSignedInteger "Answer the next two bytes from the receiver as a signed Integer." | returnValue | self atEnd ifTrue: [^false]. returnValue _ self next asInteger. self atEnd ifTrue: [^false]. (returnValue _ returnValue * 256 + self next asInteger) highBit = 16 ifTrue: [^returnValue - 65536 "16-bit negative 0"] ifFalse: [^returnValue].!nextString "Read a string from the receiver. The first byte is the length of the string, unless it is greater than 192, in which case the first two bytes encode the length." | aString char length| length _ self next. "first byte." length >= 192 ifTrue: [length _ (length - 192) * 256 + self next]. aString _ String new: length. 1 to: length do: [:i | aString at: i put: self next asCharacter]. ^aString!nextStringPut: s "Append the string, s, to the receiver." | length | (length _ s size) < 192 ifTrue: [self nextPut: length] ifFalse: [self nextPut: (length // 256 + 192). self nextPut: (length \\ 256)]. s do: [:char | self nextPut: char asciiValue]. ^s!nextWord "Answer the next two bytes from the receiver as an Integer." | high low | high _ self next. high==nil ifTrue: [^false]. low _ self next. low==nil ifTrue: [^false]. ^(high asInteger bitShift: 8) + low asInteger!nextWordPut: aWord "Append to the receiver an Integer as the next two bytes." self nextPut: ((aWord bitShift: -8) bitAnd: 255). self nextPut: (aWord bitAnd: 255). ^aWord! !!ExternalStream methodsFor: 'positioning'!resetContents "Reset pointers so that can restart reading the collection over which the receiver streams." position _ 0. readLimit _ 0! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ExternalStream class instanceVariableNames: ''!!ExternalStream class methodsFor: 'instance creation'!new ^self basicNew! ! Boolean subclass: #False instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Objects'!False comment: 'I describe the behavior of my sole instance, false'!!False methodsFor: 'logical operations'!& alternativeObject "Evaluating conjunction -- answer false since receiver is false." ^self!not "Negation -- answer true since the receiver is false." ^true!| aBoolean "Evaluating disjunction (OR) -- answer with the argument, aBoolean." ^aBoolean! !!False methodsFor: 'controlling'!and: alternativeBlock "Nonevaluating conjunction -- answer with false since the receiver is false." ^self!ifFalse: alternativeBlock "Answer the value of alternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^alternativeBlock value!ifFalse: falseAlternativeBlock ifTrue: trueAlternativeBlock "Answer the value of falseAlternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^falseAlternativeBlock value!ifTrue: alternativeBlock "Since the condition is false, answer the value of the false alternative, which is nil. Execution does not actually reach here because the expression is compiled in-line." ^nil!ifTrue: trueAlternativeBlock ifFalse: falseAlternativeBlock "Answer the value of falseAlternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^falseAlternativeBlock value!or: alternativeBlock "Nonevaluating disjunction -- answer value of alternativeBlock." ^alternativeBlock value! !!False methodsFor: 'printing'!printOn: aStream "Print false." aStream nextPutAll: 'false'! ! Object subclass: #File instanceVariableNames: 'fileDirectory fileName pageCache serialNumber lastPageNumber binary readWrite error ' classVariableNames: '' poolDictionaries: 'FilePool ' category: 'Files-Abstract'!File comment:'I am an abstract representation of a collection of FilePages and a reference to a FileDirectory which contains me. My instance is usually uniquely identified both by an alphanumeric name (a String) and a serial number (a ByteArray).According to this Smalltalk model, a File System consists of coordinated subclass definitions for FilePage, File, and FileDirectory. User programs typically do not directly access a File or its FilePages but access it as a sequence of characters or bytes through a FileStream.Instance Variables: fileName <String> serialNumber <ByteArray> fileDirectory <FileDirectory> lastPageNumber <Integer> binary <Boolean> indicates binary or textual contents readWrite <Integer> tells if writing is allowed error <Symbol> an error condition pageCache not currently used.'!!File methodsFor: 'accessing'!size "Answer the receiver's size in pages; a file is a collection of pages." lastPageNumber isNil ifTrue: [^self findLastPageNumber] ifFalse: [^lastPageNumber]! !!File methodsFor: 'testing'!characterSize "Answer the size of the receiver in characters. The definitions characterSize and findLastPageNumber are circular; a subclass must define either or both." | page | page _ self readPageNumber: self size. ^lastPageNumber - 1 * page dataSize + page size! !!File methodsFor: 'comparing'!match: aFile "Answer whether the two strings, the receiver's file name and that of the argument, aFile, match. (See String|match:)." ^self fileName match: aFile fileName! !!File methodsFor: 'converting'!asFileStream "Answer a FileStream on the first page of the receiver." self open. ^FileStream on: (self readOrAddPageNumber: 1)! !!File methodsFor: 'printing'!printOn: aStream fileName printOn: aStream! !!File methodsFor: 'nonhomogeneous accessing'!read: aFilePage "Read aFilePage if it exists, else answer false. aFilePage contains a pageNumber and other information, e.g., a serialNumber necessary to obtain the page. It is possible that aFilePage pageNumber = 0 may or may not exist in some file systems. The pageNumber may be used to compute a byte range to be read, or to lookup a disk address in a table. In a file system where pages are linked, aFilePage may contain the address of the next page and may help reveal lastPageNumber." self subclassResponsibility!readOrAdd: aFilePage "Read aFilePage if it exists or extend File to create it as an empty page." | pageNumber filePage | filePage _ aFilePage. pageNumber _ filePage pageNumber. pageNumber <= lastPageNumber ifTrue: [^self read: filePage]. (lastPageNumber + 1 to: pageNumber - 1) do: ["write full intermediate pages" filePage pageNumber: pageNumber. filePage _ self write: filePage]. "return an empty last page" filePage pageNumber: pageNumber. filePage size: 0. ^filePage!readPageNumber: aPageNumber "Create a FilePage for page number, aPageNumber, and read into it." ^self read: (self initPageNumber: aPageNumber)!write: aFilePage "Write aFilePage, one that has been read or created (see File|readOrAdd:). If aFilePage pageNumber < lastPageNumber, make sure page is full. If aFilePage pageNumber = (lastPageNumber+1), then update file length. Page numbers greater than lastPageNumber+1 are illegal (use File|readOrAdd:). Answer the result of writing the page. In some implementations, at end of file, the next empty page is also written and answered." self subclassResponsibility! !!File methodsFor: 'file accessing'!beSnapshotFile self subclassResponsibility!directory "Answer the directory in which the receiver is referenced." ^fileDirectory!directory: aFileDirectory "Set the directory in which the receiver is referenced to be aFileDirectory." fileDirectory _ aFileDirectory!endFile: aFilePage "Make the file end with aFilePage, i.e., remove all file pages after aFilePage, and answer the result of writing aFilePage (File|write:). If the argument is nil, delete all of the receiver's pages." self subclassResponsibility!fileName "Answer the name of the receiver." ^fileName!fileName: aFileName "Set the name of the receiver to be aFileName." fileName _ aFileName!fullName "Answer the name of the receiver, including directory names if necessary." ^self directory fullName, self fileName!rename: newFileName "Change the name of the receiver to be newFileName." fileDirectory rename: self newName: newFileName! !!File methodsFor: 'file testing'!isBinary "Answer whether the information in the receiver is stored in binary format." ^binary!isText "Answer whether the information in the receiver is stored as ascii characters." ^binary == false! !!File methodsFor: 'file modes'!binary "Set the receiver's contents to be in binary format." binary _ true!readWrite "Answer the read/write status of the receiver." ^readWrite!readWrite: statusInteger "Set the read/write status of the receiver to be statusInteger." readWrite _ statusInteger!text "Set the receiver's contents to be in ascii character format." binary _ false! !!File methodsFor: 'file status'!close "Close the receiver. Subclasses may wish to update the leader page." self subclassResponsibility!open "Open the receiver." self findLastPageNumber!reinitialize "Reset the receiver to its initial status." lastPageNumber _ nil. error _ ''. serialNumber _ ByteArray new: 4. "text mode is default" binary isNil ifTrue: [binary _ false]!release "Release the receiver. This is a more forgiving version of close and should always be possible even if close isn't desired or doesn't work." self subclassResponsibility!reopen "Reopen the receiver by possibly looking it up in a file directory and then opening." self sameAsStoredFile ifFalse: [self reinitialize. fileDirectory findOrAdd: self]. self open! !!File methodsFor: 'page accessing'!serialNumber "Answer the receiver's serial number." ^serialNumber!serialNumber: aSerialNumber "Set the receiver's serial number to be aSerialNumber." serialNumber _ aSerialNumber! !!File methodsFor: 'error handling'!error "Answer a Symbol indicating the last error condition." ^error!error: e "Construct an error message using the argument, e." | s errorString | s _ WriteStream on: (String new: 50). s nextPutAll: fileName. s nextPutAll: ' '. s nextPutAll: e. s nextPutAll: ', '. s nextPutAll: error. errorString _ s contents. error _ ''. ^super error: errorString!errorString: anInteger "Construct an error string corresponding to the error code, anInteger." self subclassResponsibility! !!File methodsFor: 'file/page/directory implementation'!doCommand: command page: aFilePage error: errorString "The argument, command, is typically read or write; page is a FilePage containing data and possibly other information; errorString is a String to include in an error message (or if it is nil, no error is to be reported). Execute some disk primitive (which is usually another message). Answer aFilePage if successful. If an error occurs, answer false if errorString is nil. Otherwise, create an error message with errorString." self subclassResponsibility!initPage: aFilePage "Initialize the argument, aFilePage." aFilePage reinitialize. aFilePage serialNumber: serialNumber. ^aFilePage!initPageNumber: aPageNumber "Create and initialize the file page with page number, aPageNumber; serial number that of the receiver. Answer the new FilePage." | aFilePage | aFilePage _ self pageClass new file: self page: nil. binary ifTrue: [aFilePage binary] ifFalse: [aFilePage text]. aFilePage pageNumber: aPageNumber. aFilePage serialNumber: serialNumber. ^aFilePage!lastPageNumber "Answer the number of the last page of the receiver." ^self size!size: aPageNumber "Set the last page number of the receiver to be aPageNumber." lastPageNumber _ aPageNumber! !!File methodsFor: 'private'!findLastPageNumber "set and answer with the page number of my last page. see circularity comment for characterSize" ^lastPageNumber _ self pageNumberFrom: self size!pageClass "answer with the appropriate subclass of FilePage which I contain" self subclassResponsibility!pageNumberFrom: characterIndex "compute a page number from a character index" ^characterIndex - 1 // self pageClass new dataSize + 1!readOrAddPageNumber: aPageNumber "create aFilePage and read or extend into it" ^self readOrAdd: (self initPageNumber: aPageNumber)!sameAsStoredFile "Answer true if File instance is correct enough so that it doesn't have to be reinitialized. This allows reopen to go more quickly for certain implementations. For example, in a local file system, a write date and time may guarantee that it hasn't changed since we closed this file. This is the default. " ^false! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!File class instanceVariableNames: ''!!File class methodsFor: 'class initialization'!initialize "Subclasses of File may want to share variables in pools. Execute before filin: Smalltalk at: #XFilePool as: (Dictionary: 16). in XFile initialize." FilePool at: #Read put: 1. FilePool at: #Write put: 2. FilePool at: #Shorten put: 3! !!File class methodsFor: 'documentation'!documentation "Subclasses of File are expected to implement the following messages. Unless otherwise indicated, they are provided as self subclassResponsibilty testing [optional] characterSize fileStream accessing read: write: file accessing endFile: file status (these are implemented as returning self) close release error handling errorString: file/page/directory implementation doCommand:page:error: private [optional] findLastPageNumber (this has an implementation but is circular with characterSize so one or both must be reimplemented) pageClass"! !File initialize! Object subclass: #FileDirectory instanceVariableNames: 'directoryName closed ' classVariableNames: 'ExternalReferences ' poolDictionaries: 'FilePool ' category: 'Files-Abstract'!FileDirectory comment: 'A FileDirectory is uniquely identified by the device or server that it refers to. A FileDirectory is a collection of Files. It may also be found in some other dictionary or FileDirectory, though often this is implicit'!!FileDirectory methodsFor: 'testing'!includes: aFile "Answer whether aFile is in the receiver's list of files." ^(self find: aFile) notNil!includesKey: aFileName "Answer whether a file whose name is aFileName is included in the receiver." | file | file _ self find: (self initFileName: aFileName). file notNil ifTrue: [file release. "close the IFS connection, if an IFS leaf file" ^true]. ^false! !!FileDirectory methodsFor: 'adding'!add: aFile "Add the file, aFile, to the receiver. This creates a new version of the file rather than generating an error if a file with the same name exists." | old file | file _ aFile. self versionNumbers ifTrue: ["ignore explicit version and directory will create a next version" file _ self initFileName: (file fileName copyUpTo: $!!)] ifFalse: [(self find: file) notNil ifTrue: ["otherwise, if file already exists, rename it to name$, deleting that file first if it exists" old _ self initFileName: (file fileName copyWith: $$). self remove: old ifAbsentDo: [:f | false]. self rename: file newName: old fileName. file fileName: (file fileName copyUpTo: $$). (self find: file) notNil ifTrue: [file error: 'insert/rename ??']]]. self addNew: file. ^file!addKey: aFileName "If a file whose name is aFileName exists and the receiver does not know how to create a new version, the create an error. Otherwise create a new empty file." ^self add: (self initFileName: aFileName)!addNew: aFile "Add the argument, aFile, as a new file in the receiver." self subclassResponsibility! !!FileDirectory methodsFor: 'removing'!remove: aFile "Remove aFile if found in the receiver. Create an error if it is not." ^self remove: aFile ifAbsentDo: [:f | f error: 'file not found']!remove: aFileName ifAbsentDo: aBlock "Remove aFile if found in the receiver. Answer the result of evaluating aBlock if the file is not found." | f | f _ self find: aFileName ifAbsentDo: aBlock. f notNil ifTrue: [^self removeOld: f] ifFalse: [^aBlock value: f]!removeOld: aFile "If aFile exists, remove it." self subclassResponsibility! !!FileDirectory methodsFor: 'enumerating'!do: aBlock "Sequence over all possible files in the receiver, evaluating aBlock for each one." | aFile | self reset. [aFile _ self next. aFile notNil] whileTrue: [aBlock value: aFile]!reset "Set to the beginning of the directory." self subclassResponsibility! !!FileDirectory methodsFor: 'accessing'!directoryName "Answer the name of the receiver." ^directoryName!fullName "Answer the name of the receiver in a form recognized when parsing file names (i.e., using [...]). May be empty for a default directory." ^''!next "Answer the next file instance in the receiver (part of the streaming protocol)." self subclassResponsibility!versionNumbers "Answer true if versions numbers are supported." ^false "this is the default"! !!FileDirectory methodsFor: 'dictionary removing'!removeKey: aFileName "Remove and answer the file whose name is aFileName; create an error if not found." ^self remove: (self initFileName: aFileName) ifAbsentDo: [:f | f error: 'file not found']! !!FileDirectory methodsFor: 'printing'!listFilesOn: aStream "Write a list of each file name in the receiver onto the stream, aStream." self do: [:aFile | aStream cr. aFile fileName printOn: aStream]!printOn: aStream aStream nextPutAll: (self closed ifTrue: ['a closed '] ifFalse: ['an open ']). aStream nextPutAll: self class name. aStream nextPutAll: ' on '. directoryName printOn: aStream! !!FileDirectory methodsFor: 'file accessing'!checkName: aFileName fixErrors: aBoolean "Check a string aFileName for validity as a file name. If there are problems (e.g., illegal length or characters) and aBoolean is false, create an error; if there are problems and aBoolean is true, make the name legal (usually by truncating and/or tranforming characters) and answer the new name. Otherwise, answer the name. Default behavior is to get rid of ending period. Subclasses can do any kind of checking they want and answer either the name, or false if no good." aFileName isEmpty ifTrue: [aBoolean ifFalse: [self error: 'file name empty']]. aFileName last = $. ifTrue: [aBoolean ifFalse: [self error: 'file name ends in .']. ^aFileName copyFrom: 1 to: aFileName size - 1] ifFalse: [^aFileName]!checkNameOfFile: aFileName "See FileDirector|checkNameOfFile: aFileName fixErrors: false." ^self checkNameOfFile: aFileName fixErrors: false!checkNameOfFile: aFile fixErrors: aBoolean "See FileDirectory|checkNameOfFile: aFileName fixErrors: aBoolean. The first argument is the name of the file, aFile." ^self checkName: aFile fileName fixErrors: aBoolean!file: aFileName "Answer a FileStream on an old or new File whose name is aFileName." ^(self findOrAddKey: aFileName) asFileStream!fileClass "Answer the proper subclass of File of which the files in the receiver are instances." self subclassResponsibility!filesMatching: pattern "Answer an Array of the names of files that match the string, pattern." | names name | names _ WriteStream on: (Array new: 10). self do: [:each | name _ each fileName. (pattern match: name) ifTrue: [name last = $. ifTrue: [name _ name copyFrom: 1 to: name size - 1]. names nextPut: name]]. ^names contents!isLegalFileName: aString "Answer whether aString is a legal file name." ^(self checkName: aString fixErrors: true) = aString!isLegalOldFileName: aString "Answer whether aString is a legal file name." ^(self checkName: aString fixErrors: true) = aString and: [self includesKey: aString]!newFile: aFileName "Answer a FileStream on a new File whose name is aFileName; error if the argument is not a new file name." ^(self addKey: aFileName) asFileStream!oldFile: aFileName "Answer a FileStream on an old File whose name is aFileName; error if the argument is not an old name." ^(self findKey: aFileName) asFileStream!rename: aFile newName: newName "Rename the file, aFile, to have the name newName. Create an error if a file by the name, newName, already exists." self subclassResponsibility! !!FileDirectory methodsFor: 'file testing'!closed "Answer whether the receiver is closed." ^closed! !!FileDirectory methodsFor: 'file status'!close "Close the receiver if it is not already closed." closed ifFalse: [ExternalReferences remove: self ifAbsent: []. self release]!flush "Write any state on local storage." self subclassResponsibility!open "Open the directory." closed _ false. (ExternalReferences includes: self) ifFalse: [ExternalReferences addLast: self]!release "Release the receiver. a more forgiving version of close which should always be possible even if close isn't desired or doesn't work." closed _ true! !!FileDirectory methodsFor: 'file copying'!retrieve: aFileName "Copy the file whose name is aFileName to itself. Subclasses may want to overwrite this to redirect the directory on which a file of the same name is copied. See FileDirectory|retrieveFrom:copyTo:." ^self retrieveFrom: aFileName copyTo: aFileName!retrieveFrom: aFileName1 copyTo: aFileName2 "Copy file whose name is aFileName1 (usually from this receiver) to a file whose name is aFileName2 (usually a local directory)." | f1 f2 | f1 _ self oldFile: aFileName1. f1 readOnly. f2 _ self file: aFileName2. f2 nextPutAll: f1. f2 close. f1 close!store: aFileName "Store the file whose name is aFileName to itself. Subclasses may want to overwrite this to redirect the directory on which a file of the same name is copied. See FileDirectory|storeFrom:copyTo:." ^self storeFrom: aFileName copyTo: aFileName!storeFrom: aFileName1 copyTo: aFileName2 "Copy file whose name is aFileName1 (usually from a local directory) to a file whose name is aFileName2 (usually on the receiver)." | f1 f2 | f1 _ self oldFile: aFileName1. f1 readOnly. f2 _ self file: aFileName2. f2 nextPutAll: f1. f2 close. f1 close! !!FileDirectory methodsFor: 'page accessing'!allocate: aFilePage after: virtualDiskAddress "Answer aFilePage with its real disk address field filled in." self subclassResponsibility!allocateSN: aFile "Allocate a new serial number for the file, aFile." self subclassResponsibility!deallocate: aFilePage "Deallocate aFilePage at some real disk address." self subclassResponsibility!freePages "Answer the number of free pages remaining." self subclassResponsibility!newPage "Create a dummy file and a page from it." ^(self initFileName: '') initPageNumber: 0! !!FileDirectory methodsFor: 'private'!find: aFile ^self find: aFile ifAbsentDo: [:f | nil]!find: aFile ifAbsentDo: aBlock "return aFile (partially initialized) if found, otherwise false. this is a default implementation" | fname | "check file name" fname _ self checkNameOfFile: aFile. aFile fileName: fname. "iterate through non-deleted entries of directory, and return partially initialized file if found" self do: [:each | (fname sameAs: each fileName) ifTrue: [^each]]. "failure" ^aBlock value: aFile!findKey: aFileName ^self find: (self initFileName: aFileName) ifAbsentDo: [:file | file error: 'file not found']!findOrAdd: aFile "find an old file if it exists, or create one" | f | (f _ self find: aFile) notNil ifTrue: [^f] ifFalse: [^self addNew: aFile]!findOrAddKey: t1 ^self findOrAdd: (self initFileName: t1)!initFile: aFile aFile reinitialize. ^aFile!initFileName: aFileName | aFile | aFile _ self fileClass new. aFile directory: self. aFile fileName: aFileName. aFile reinitialize. ^aFile!setDirectory: aFileDirectory directoryName: aString "assume that the directory is implicit" directoryName _ aString. closed _ true! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FileDirectory class instanceVariableNames: ''!!FileDirectory class methodsFor: 'class initialization'!initialize self initializeExternalReferences "FileDirectory initialize"! !!FileDirectory class methodsFor: 'instance creation'!directory: aFileDirectory directoryName: aString "Answer an instance of me in directory aFileDirectory whose name is aString." ^self new setDirectory: aFileDirectory directoryName: aString!directoryFromName: fileDesignator setFileName: localNameBlock | directory stream | "Answer the file directory implied from the designator, presumably at the start of the designator, and evaluate the block with the rest of the designator (presumably the file name itself." directory _ Disk. stream _ ReadStream on: fileDesignator. localNameBlock value: (stream upTo: nil). ^directory! !!FileDirectory class methodsFor: 'external reference access'!addExternalReference: anElement "Add anElement as a file that is currently referenced in the system." (ExternalReferences includes: anElement) ifFalse: [ExternalReferences addLast: anElement]!initializeExternalReferences "ExternalReferences is an OrderedCollection of the files that are referenced in the system. Initialize this class variable." ExternalReferences _ OrderedCollection new!releaseExternalReferences "Remove and release all of the files referenced by the collection ExternalReferences." [ExternalReferences isEmpty] whileFalse: [ExternalReferences removeLast release]!removeExternalReference: anElement "Remove anElement as a file that is currently referenced in the system." ExternalReferences remove: anElement ifAbsent: []! !!FileDirectory class methodsFor: 'documentation'!documentation "subclasses are expected to implement the following messages which are implemented as self subclassResponsibility unless otherwise noted. file accessing fileClass [optional] rename:newName: [default] checkNameOfFile: (default makes no sense to me; for the abstract anything is okay) file status [optional] flush page accessing [optional] allocate:after: [optional] allocateSN [optional] deallocate: [optional] freePages dictionary adding addNew: dictionary removing removeOld: dictionary enumerating [optional] next [default] do: [optional] reset directory accessing [default] versionNumbers"! !FileDirectory initialize! FileModel subclass: #FileList instanceVariableNames: 'list myPattern isReading ' classVariableNames: 'FileMenu PatternMenu ' poolDictionaries: '' category: 'Interface-File Model'!FileList comment:'I an a FileModel that can be viewed as a filtered ListMenu of file names as well as the text of a file. Instance Variables list <OrderedCollection> of file names myPatytern <String> represtenting the filter to select the list'!!FileList methodsFor: 'pattern'!acceptPattern: aText from: aController "The text consists of file names and file name patterns separated by carriage returns. Patterns can include the characters * (any chars) and # (any single char). Make my new list be those file names on my directory which match the patterns." | testPattern readStream newList | Cursor execute showWhile: [myPattern _ aText string. readStream _ ReadStream on: myPattern. newList _ SortedCollection new. [readStream atEnd] whileFalse: [testPattern _ readStream upTo: Character cr. "get next name/pattern" testPattern last = $. ifTrue: [testPattern _ testPattern copyFrom: 1 to: testPattern size-1]. (testPattern includes: $*) | (testPattern includes: $#) ifTrue: [newList addAll: (self filesMatching: testPattern)] ifFalse: [(self isLegalFileName: testPattern) ifTrue: [newList add: testPattern]]]. list _ newList. list isEmpty ifTrue: [aController deselect; replaceSelectionWith: 'No matching files' asText; select]. self changed: #fileName]. ^true!pattern ^ myPattern!patternMenu "FileModel flushMenus" PatternMenu == nil ifTrue: [PatternMenu _ ActionMenu labels: 'again\undo\copy\cut\paste\accept\cancel' withCRs lines: #(2 5) selectors: #(again undo copySelection cut paste accept cancel)]. ^ PatternMenu! !!FileList methodsFor: 'file name list'!copyName ParagraphEditor new copySelection: fileName asText!deleteFile "Remove the selected file from its directory." | dir localName | dir _ FileDirectory directoryFromName: fileName setFileName: [:localName]. (dir includesKey: localName) ifTrue: [(self confirm: 'really remove the selected file?') ifFalse: [^self]. dir removeKey: localName]. list remove: fileName. self changed: #fileName.!fileListMenu fileName == nil ifTrue: [^nil]. FileMenu == nil ifTrue: [FileMenu _ ActionMenu labels: 'get contents\file in\copy name\rename\remove' withCRs lines: #(2 4) selectors: #(getFile fileInFile copyName renameFile deleteFile)]. ^ FileMenu "Evaluate this when you change this method: FileList flushMenus"!fileName ^ fileName!fileName: selection "If selection is not nil, it is the name of a file to be viewed" self setFileName: selection. isReading _ false. self changed: #text!fileNameList ^ list!getFile self changeRequest ifFalse: [^self]. isReading _ true. self changed: #text!isSelected ^isReading!renameFile | newList newName continue | fileName == nil ifTrue: [^nil]. self changeRequest ifFalse: [^nil]. continue _ true. [continue] whileTrue: [newName _ FillInTheBlank request: 'New name for file?' initialAnswer: fileName. newName isEmpty ifTrue: [^nil]. newName last = $. ifTrue: [newName _ newName copyFrom: 1 to: newName size-1]. ((self isLegalFileName: newName) and: [(Disk includesKey: newName) not]) ifTrue: [continue _ false] ifFalse: [(BinaryChoice message: 'File exists or bad file name. Try again?') ifFalse: [^nil]]]. Cursor execute showWhile: [newList _ list copyWithout: fileName. (Disk includesKey: fileName) ifTrue: [Disk rename: (Disk file: fileName) file newName: newName]. fileName _ newName. newList add: fileName. list _ newList. self changed: #fileName. self changed: #text]! !!FileList methodsFor: 'private'!filesMatching: pattern "Answer a list of file names matching the pattern string. Do this by asking the appropriate directory." | dir nameBody matches | dir _ FileDirectory directoryFromName: pattern setFileName: [:nameBody]. matches _ dir filesMatching: nameBody. ^matches!isLegalFileName: pattern "Answer whether pattern is a valid file name. Do this by asking the appropriate directory." | dir nameBody | dir _ FileDirectory directoryFromName: pattern setFileName: [:nameBody]. ^dir isLegalFileName: pattern!list: aList list _ aList. isReading _ false! !!FileList methodsFor: 'text'!text isReading ifTrue: [^super text] ifFalse: [^'' asText]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FileList class instanceVariableNames: ''!!FileList class methodsFor: 'instance creation'!open "FileList open" "Create and schedule a view of a new instance of me such that the instance references the files named in the argument, aFileNameList, that can be found in the directory, aFileDirectory." | topView aFileList patternView | aFileList _ self new list: OrderedCollection new. topView _ StandardSystemView model: aFileList label: 'File List' minimumSize: 200 @ 200. patternView _ CodeView on: aFileList aspect: #pattern change: #acceptPattern:from: menu: #patternMenu initialSelection: nil. topView addSubView: patternView in: (0@0 extent: 1@0.07) borderWidth: 1. patternView controller: AlwaysAcceptCodeController new. topView addSubView: (SelectionInListView on: aFileList aspect: #fileName change: #fileName: list: #fileNameList menu: #fileListMenu initialSelection: nil) in: (0@0.07 extent: 1@0.23) borderWidth: 1. topView addSubView: (OnlyWhenSelectedCodeView on: aFileList aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil selection: #isSelected) in: (0@0.3 extent: 1@0.7) borderWidth: 1. topView controller open!openOnFileNames: aFileNameList label: labelString "Create and schedule a view of a new instance of me such that the instance references the files named in the argument, aFileNameList." | topView aFileList | aFileList _ self new list: aFileNameList. topView _ StandardSystemView model: aFileList label: labelString minimumSize: 200 @ 200. topView addSubView: (SelectionInListView on: aFileList aspect: #fileName change: #fileName: list: #fileNameList menu: #fileListMenu initialSelection: nil) in: (0@0 extent: 1@0.2) borderWidth: 1. topView addSubView: (CodeView on: aFileList aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: (0@0.2 extent: 1@0.8) borderWidth: 1. topView controller open! !!FileList class methodsFor: 'class initialization'!flushMenus "FileList flushMenus." PatternMenu _ nil. FileMenu _ nil. super flushMenus! ! Object subclass: #FileModel instanceVariableNames: 'fileName ' classVariableNames: 'TextMenu ' poolDictionaries: '' category: 'Interface-File Model'!FileModel comment:'I represent an interface between a File and an editable view of it. As a StringHolder, the string is the contents of the File.Instance Variables: fileName <String> The name of the file I am viewing.'!!FileModel methodsFor: 'text'!text | dir localName | fileName == nil ifTrue: [^nil]. dir _ FileDirectory directoryFromName: fileName setFileName: [:localName]. (dir includesKey: localName) ifFalse: "don't create file" [^'-new file-' asText emphasizeFrom: 2 to: 9 with: 3]. ^Cursor read showWhile: [(FileStream oldFileNamed: fileName) contentsOfEntireFile asText]!textMenu "FileModel flushMenus" fileName == nil ifTrue: [^ nil]. TextMenu == nil ifTrue: [TextMenu _ ActionMenu labels: 'again\undo\copy\cut\paste\do it\print it\file it in\put\get' withCRs lines: #(2 5 8 10) selectors: #(again undo copySelection cut paste doIt printIt fileItIn:from: accept getNew:from:)]. ^ TextMenu! !!FileModel methodsFor: 'user protocol'!doItValue: ignored!fileInFile "Read the entire file as Smalltalk code." (FileStream oldFileNamed: fileName) fileIn.!fileItIn: fullText from: controller "Make a Stream on the text selection and fileIn it." | selection | selection _ controller selection. (ReadWriteStream on: selection from: 1 to: selection size) fileIn!getNew: ignoreText from: aController "Reinitialize the information the receiver models by re-reading the file stream." self changeRequest ifFalse: [^ aController view flash]. self changed: #text! !!FileModel methodsFor: 'doIt/accept/explain'!acceptText: aText from: aController "Update the contents of the file stream with the receiver's contents. If the file name does not include an explicit version number, create a new version." Cursor write showWhile: [((fileName includes: $!!) ifTrue: [FileStream fileNamed: fileName] ifFalse: [FileStream newFileNamed: fileName]) nextPutAll: aText string; close]. ^true!doItContext ^ nil!doItReceiver ^ nil! !!FileModel methodsFor: 'private'!setFileName: fullFileName fileName _ fullFileName!setFileStream: aStream aStream release. "close, since later a new file stream will be created" fileName _ aStream file fullName! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FileModel class instanceVariableNames: ''!!FileModel class methodsFor: 'instance creation'!fileStream: aFileStream "Answer an instance of me on the argument, aFileStream." ^self new setFileStream: aFileStream!open: aFileModel named: aString "Scheduled a view whose model is aFileModel and whose label is aString." | topView | topView _ StandardSystemView model: aFileModel label: aString minimumSize: 180 @ 180. topView addSubView: (CodeView on: aFileModel aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: (0@0 extent: 1@1) borderWidth: 1. topView controller open!open: aFileModel named: aString withController: aController "Scheduled a FileModel view with changes made in another editor." | topView textView | topView _ StandardSystemView model: aFileModel label: aString minimumSize: 180 @ 180. textView _ CodeView on: aFileModel aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil. textView controller: aController. topView addSubView: textView in: (0@0 extent: 1@1) borderWidth: 1. topView controller open! !!FileModel class methodsFor: 'initialization'!flushMenus TextMenu _ nil! ! Object subclass: #FilePage instanceVariableNames: 'file page binary ' classVariableNames: '' poolDictionaries: 'FilePool ' category: 'Files-Abstract'!FilePage comment:'I represent a fixed size page or record of data from a File. My instance is uniquely identified within its File by its pageNumber.The normal layout of a FilePage is as a ByteArray, which begins with some header information (e.g. serial number, page number, size), some data with possible leftover allocation, and some trailer information: pageSize = headerSize + size + (dataSize - size) + trailerSize. In the current implementations, all FilePages (except possibly the last page) of a File are full (i.e. no unused data allocation). This assumption is also reflected in File characterSize, and in FileStream positioning methods. Given the current implementation of ByteArrays and Strings, each page has a type (binary or text). The messages asStream: and fromStream: do the necessary conversion. Instance Variables: file <File> that contains the instance page <Integer> the number of the instance binary <Boolean> true if content of page is binary, else it is text'!!FilePage methodsFor: 'accessing'!at: aByteIndex "Answer the data byte associated with aByteIndex." ^page at: (self dataIndex: aByteIndex size: 1)!at: aByteIndex put: aByte "Put the date byte, aByte, at location aByteIndex. Answer aByte." ^page at: (self dataIndex: aByteIndex size: 1) put: aByte!size "Answer the number of data characters the receiver contains (0 <= self size <= self dataSize)" ^self subclassResponsibility!wordAt: aWordIndex "Answer the data word associated with aWordIndex." ^page wordAt: (self dataIndex: aWordIndex size: 2)!wordAt: aWordIndex put: aWord "Put aWord at location aWordIndex. Answer aWord." ^page wordAt: (self dataIndex: aWordIndex size: 2) put: aWord! !!FilePage methodsFor: 'testing'!isEmpty "Answer whether this page has no data." ^self size = 0! !!FilePage methodsFor: 'converting'!asFileStream: aStream "Initialize aStream (typically a FileStream) to access the data portion of the receiver -- this is the normal way to access characters and words. Pages which segment data and header can do this differently." | offset len sourceData destData | len _ self size. offset _ self headerSize. sourceData _ self dataString. binary ifTrue: [^aStream on: sourceData from: offset + 1 to: offset + len"self dataBeginning" "self dataEnd"]. destData _ String new: self dataSize. destData replaceFrom: 1 to: len withByteArray: sourceData startingAt: offset+1. ^aStream on: destData from: 1 to: len!fromFileStream: aStream "Copy data into page; pages which separate data and header can do this differently" | sourceData destData offset | binary ifFalse: [offset _ self headerSize. sourceData _ aStream contents. destData _ self dataString. destData replaceFrom: offset + 1 to: offset+ self size withString: sourceData startingAt: 1]! !!FilePage methodsFor: 'nonhomogeneous accessing'!headerWordAt: n "Answer the n-th header word; default is that it is at the beginning of page." ^page wordAt: n!headerWordAt: n put: v "Set and answer n-th header word." ^page wordAt: n put: v!pageWordAt: aWordIndex "Answer the word associated with aWordIndex in the page as a whole, ignoring header, data and trailer boundaries" ^page wordAt: aWordIndex!pageWordAt: aWordIndex put: aWord "Set and answer the word associated with aWordIndex in the page as a whole, ignoring header, data and trailer boundaries." ^page wordAt: aWordIndex put: aWord!readPageNumber: aPageNumber "Answer the result of file reading a page into the receiver." self pageNumber: aPageNumber. self size: 0. ^file read: self!write "Answer the result of writing the receiver onto its file." ^file write: self! !!FilePage methodsFor: 'file accessing'!endFile "Answer the result of making the receiver be the last page of its file." ^file endFile: self!file "Answer with the receiver's file." ^file! !!FilePage methodsFor: 'file testing'!isBinary "Answer whether the information in the receiver is stored in binary format." ^binary!isText "Answer whether the information in the receiver is stored as ascii characters." ^binary == false! !!FilePage methodsFor: 'file modes'!binary "Set the receiver's information type to be binary." binary _ true!text "Set the receiver's information type to be ascii characters." binary _ false! !!FilePage methodsFor: 'file status'!reinitialize "Reset the receiver to its initial status." page == nil ifTrue: [page _ self allocatePage]. self size: 0!reopen "Reopen the receiver's file and reinitialize the receiver onto it." file reopen. file initPage: self! !!FilePage methodsFor: 'page initialization'!file: aFile "Set the receiver's file to be aFile." file _ aFile!file: aFile page: aByteArray "Set the receiver's file to be aFile, and its page to contain aByteArray." file _ aFile. page _ aByteArray. self reinitialize!page: aByteArray "Set the receiver's page to contain aByteArray." page _ aByteArray! !!FilePage methodsFor: 'page accessing'!address "Answer the disk address for the receiver. This need only be defined for those subclasses which have access to an address, probably for local disks and not for remote file servers" self subclassResponsibility!address: addressNumber "Set the receiver's disk address." self subclassResponsibility!dataBeginning "Answer the index in the receiver for the first element of data-1." binary ifTrue: [^self headerSize] ifFalse: [^0]!dataEnd "Answer the character index for the last character of actual data." ^self dataBeginning + self size!dataEnd: aPageIndex "Set the end of the data in the receiver." ^self size: aPageIndex - self dataBeginning!dataMaxEnd "Answer the maximum possible data byte index." ^self dataBeginning + self dataSize!dataString "Answer a string containing the data." ^page!page "Answer the receiver's page" ^page!pageNumber "Answer the receiver's page number, an Integer." ^self subclassResponsibility!pageNumber: anInteger "Set the receiver's page number." ^self subclassResponsibility!serialNumber "Answer the serial number of the receiver's page." ^file serialNumber!serialNumber: aSN "Set the serial number of the receiver's page." ^self subclassResponsibility! !!FilePage methodsFor: 'page testing'!dataSize "Answer the maximum size of data (in characters) in the receiver's page." ^512!headerSize "Answer the size of the receiver's header in characters." ^0!isFull "Answer whether the receiver has no more room at the end for more data." ^self size = self dataSize!lastPage "Answer whether the receiver is at the last page in its file." ^self pageNumber >= file lastPageNumber!pageSize "Answer the total size of the receiver's page, in bytes." ^self headerSize + self dataSize + self trailerSize!trailerSize "Answer the size of trailer in bytes." ^0! !!FilePage methodsFor: 'file/page/directory implementation'!doCommand: command error: s "Answer the result of executing a command on the receiver." ^file doCommand: command page: self error: s!size: aByteIndex "Set the number of data characters the receiver contains to be aByteIndex. aByteIndex <= dataSize on last page; aByteIndex = dataSize on earlier pages)." ^self subclassResponsibility! !!FilePage methodsFor: 'private'!allocatePage "allocate a page buffer" ^ByteArray new: self pageSize"this is a default"!dataIndex: index size: nBytes "Answer with an index offset properly into page, unless index would be out of bounds. nBytes = 1 for characters; nBytes = 2 for words" (index > 0 and: [index <= (self size // nBytes)]) ifTrue: [^(self headerSize // nBytes) + index] ifFalse: [self error: 'index out of bounds']!readOrAddPageNumber: aPageNumber "answer with the result of file reading a page or creating a page into me" self pageNumber: aPageNumber. self size: 0. ^file readOrAdd: self! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FilePage class instanceVariableNames: ''!!FilePage class methodsFor: 'documentation'!documentation "My subclasses are expected to implement the following messages. These are provided as self subclassResponsibility. Some are optional for implementation, depending on the representation of the actual file page; for some, defaults are provided. testing size page initialization pageNumber: page accessing [optional] address [optional] address: [optional] pageNumber [optional] pageNumber: [optional] serialNumber: page testing [default] dataSize [default] headerSize [default] trailerSize file/page/directory implementation size:"! ! ExternalStream subclass: #FileStream instanceVariableNames: 'page rwmode closed ' classVariableNames: '' poolDictionaries: 'FilePool ' category: 'Files-Streams'!FileStream comment:'I represent a Stream that accesses a FilePage from a File. One use for my instance is to access larger "virtual Strings" than can be stored contiguously in main memory. I restrict the objects stored and retrieved to be Integers or Characters. An end of file pointer terminates reading; it can be extended by writing past it, or the file can be explicitly truncated.To use the file system for most applications, you typically create a FileStream. This is done by sending a message to a FileDirectory (file:, oldFile:, newFile:, rename:newName:) which creates an instance of me. Accesses to the file are then done via my instance.Instance variables page <FilePage> the current FilePage being accessed rwmode <Integer> denoting readOnly, readWrite, or readWriteShorten. readWriteShorten with textual contents is the default. closed <Boolean> false if the file is open'!!FileStream methodsFor: 'accessing'!contentsOfEntireFile "Read all of the contents of the receiver." | s | self readOnly. self reset. s _ self next: self size. self close. ^s!next (position >= readLimit and: [self atEnd]) ifTrue: [^nil] ifFalse: [^collection at: (position _ position + 1)]!next: anInteger | newCollection howManyRead increment | newCollection _ collection species new: anInteger. howManyRead _ 0. [howManyRead < anInteger] whileTrue: [ self atEnd ifTrue: [ (howManyRead + 1) to: anInteger do: [:i | newCollection at: i put: (self next)]. ^newCollection ]. increment _ (readLimit - position) min: (anInteger - howManyRead). newCollection replaceFrom: (howManyRead + 1) to: (howManyRead _ howManyRead + increment) with: collection startingAt: (position + 1). position _ position + increment. ]. ^newCollection!next: anInteger into: aCollection "Copy the next anInteger bytes from the receiver into aCollection." | howManyRead increment | howManyRead _ 0. [howManyRead < anInteger] whileTrue: [ self atEnd ifTrue: [ (howManyRead + 1) to: anInteger do: [:i | aCollection at: i put: (self next)]. ^aCollection ]. increment _ (readLimit - position) min: (anInteger - howManyRead). aCollection replaceFrom: (howManyRead + 1) to: (howManyRead _ howManyRead + increment) with: collection startingAt: (position + 1). position _ position + increment. ]. ^aCollection!nextPut: aByte | dmax | rwmode == nil ifTrue: [self readWriteShorten "default mode"]. (rwmode bitAnd: Write) = 0 ifTrue: [^self error: 'no writing allowed!!']. closed ifTrue: [self reopen]. position < writeLimit ifTrue: [^collection at: (position _ position + 1) put: aByte]. dmax _ page dataMaxEnd. writeLimit < dmax ifTrue: [writeLimit _ dmax] ifFalse: [self nextPage isNil ifTrue: [^self error: 'cannot write!!!!!!']. position = readLimit ifTrue: [writeLimit _ dmax]]. ^collection at: (position _ position + 1) put: aByte!nextPutAll: aCollection | dmax howManyWritten increment collectionSize | ((aCollection isKindOf: ByteArray) or: [aCollection isKindOf: String]) ifFalse: [^super nextPutAll: aCollection]. rwmode == nil ifTrue: [self readWriteShorten "default mode"]. (rwmode bitAnd: Write) = 0 ifTrue: [^self error: 'no writing allowed!!']. closed ifTrue: [self reopen]. howManyWritten _ 0. collectionSize _ aCollection size. dmax _ (page dataMaxEnd). [ increment _ (dmax - position) min: (collectionSize - howManyWritten). collection replaceFrom: (position + 1) to: (position _ position + increment) with: aCollection startingAt: (howManyWritten + 1). howManyWritten _ howManyWritten + increment. howManyWritten < collectionSize. ] whileTrue: [ self nextPage isNil ifTrue: [^self error: 'cannot write!!!!!!']. position = readLimit ifTrue: [writeLimit _ dmax]. ]. position > writeLimit ifTrue: [writeLimit _ dmax]. ^aCollection!size "return size of File in characters" self reopen. self fixEnd. "if on last page, return answer directly" page lastPage ifTrue: [^page pageNumber - 1 * page dataSize + page size] ifFalse: [^self file characterSize]! !!FileStream methodsFor: 'testing'!atEnd "Answer true if current position is >= end of file position." closed ifTrue: [self reopen]. position < readLimit ifTrue: [^false]. (page lastPage or: [self nextPage isNil]) ifTrue: [^true]. ^position = readLimit! !!FileStream methodsFor: 'positioning'!position "return current character position in File" ^self positionSize: 1!position: pos self position: pos size: 1!reset "set position to beginning of File" (self read: 1) isNil ifTrue: [self error: 'reset']!setToEnd "set position to end of File. logically: self position: self size" self reopen. (self read: (self file size max: page pageNumber)) isNil ifTrue: [self error: 'setToEnd']. position _ readLimit!skip: n | pos plen pageOffset | n = 0 ifTrue: [^self]. self reopen. pos _ position + n. (n > 0 ifTrue: [pos >= readLimit] ifFalse: [self fixEnd. "important on last page" pos < page dataBeginning]) ifTrue: [plen _ page dataSize. "assume p is not Large, otherwise use divMod:" pos _ pos - page dataBeginning. pageOffset _ pos // plen. (self positionPage: page pageNumber + pageOffset character: pos \\ plen) ifFalse: [self error: 'cannot skip ' , n printString]] ifFalse: ["same page" position _ pos]! !!FileStream methodsFor: 'printing'!printOn: aStream super printOn: aStream. aStream nextPutAll: ' on '. self file printOn: aStream! !!FileStream methodsFor: 'nonhomogeneous accessing'!nextPage "Answer the receiver as a FileStream on the next page or nil if there is no next page." ^self read: page pageNumber + 1!read: pageNumber "The receiver is formatted into pages. Access the information on page pageNumber. Normally called by pastEnd, position:size:, reopen, reset, setToEnd. Answer nil if the pageNumber does not exist in the receiver. Else answer the receiver as a FileStream on this new page." | p | pageNumber < 1 ifTrue: [^nil]. closed ifTrue: ["reopen the file, (re)read the page" page reopen. (p _ page readPageNumber: pageNumber) isNil ifTrue: [^nil] ifFalse: [^self on: p]]. (pageNumber = page pageNumber and: [page size > 0 or: [position > page dataBeginning]]) ifTrue: [self fixEnd. position _ page dataBeginning. ^self]. "current page has wrong page number or is empty (possibly from error)" self writing ifTrue: [((pageNumber > page pageNumber and: [page isFull == false]) ifTrue: ["fill up last page when positioning past it" position _ page dataMaxEnd. true] ifFalse: ["otherwise, fixEnd" position > page dataEnd]) ifTrue: [page dataEnd: (readLimit _ position)]. "write current page" page fromFileStream: self. p _ page write. p pageNumber = pageNumber ifFalse: ["read it or create it" p _ page readOrAddPageNumber: pageNumber"already have next page, e.g. at end of AltoFile"]] ifFalse: [p _ page readPageNumber: pageNumber]. p isNil ifTrue: [^nil]. (page _ p) asFileStream: self! !!FileStream methodsFor: 'nonhomogeneous positioning'!padTo: bsize | rem | rem _ bsize - ((page dataSize \\ bsize = 0 ifTrue: [position - page dataBeginning] ifFalse: [self position]) \\ bsize). rem = bsize ifTrue: [^0]. self skip: rem. ^rem!padTo: bsize put: aCharacter | rem | rem _ bsize - ((page dataSize \\ bsize = 0 ifTrue: [position - page dataBeginning] ifFalse: [self position]) \\ bsize). rem = bsize ifTrue: [^0]. self next: rem put: aCharacter. ^rem!wordPosition "return current position in words (2 characters)" ^self positionSize: 2!wordPosition: wpos "set current position in words" ^self position: wpos size: 2! !!FileStream methodsFor: 'editing'!edit "Create and schedule a FileView of the contents of the receiver. The label of the view is the name of the receiver." FileModel open: (FileModel fileStream: self) named: self file fullName! !!FileStream methodsFor: 'file accessing'!beSnapshotFile ^self file beSnapshotFile!directory "Answer the directory of the file for the page the receiver is currently streaming over." ^page file directory!file "Answer the file for the page the receiver is streaming over." ^page file!name "Answer the name of the file for the page the receiver is streaming over." ^page file fileName!page "Answer the page the receiver is streaming over." ^page! !!FileStream methodsFor: 'file testing'!closed "Answer the status of the file--false if open, true otherwise." ^closed!writing "Answer whether it is possible to write on the receiver." rwmode == nil ifTrue: [self readWriteShorten. "default mode" ^true]. ^(rwmode bitAnd: Write) = Write! !!FileStream methodsFor: 'file modes'!binary "Set the receiver's file to be binary mode." self file binary. "fix up current page" page binary. self on: page!readOnly "Set the receiver's mode so that pages are not flushed and reading stops at end of file." self setMode: Read!readWrite "Set the receiver's mode so that pages are flushed, end of file can be extended by writing, and closing does not truncate file." self setMode: Read + Write!readWriteShorten "Same as readWrite except close truncates file at current position." self setMode: Read + Write + Shorten!text "Set the receiver's file to be in text mode." self file text. "fix up current page" page text. self on: page!writeShorten "Allow write and shorten the receiver's file upon closing." self setMode: Write + Shorten! !!FileStream methodsFor: 'file status'!close "Set the receiver's file status to closed." closed ifFalse: [self writing ifTrue: [(rwmode bitAnd: Shorten) = Shorten ifTrue: [self shorten] ifFalse: [self flush]]. closed _ true. readLimit _ writeLimit _ 0. self file close. FileDirectory removeExternalReference: self]!flush "Write the current page back onto the file." self closed ifTrue: [^page] ifFalse: [self fixEnd. page fromFileStream: self. ^page write]!release "Set the receiver's status to closed, if it is not already, and do not allow any further reading or writing." closed ifFalse: [closed _ true. readLimit _ writeLimit _ 0. self file release]!reopen "Set the receiver's file to be open again, setting the position to its previous position. Create an error if the file can not be reopened." | pos | closed ifFalse: [^nil]. "reopen to previous position" pos _ position. (self read: page pageNumber) isNil ifTrue: ["that page doesn't exist, so go to last one that does. note that setToEnd would be recursive" (self read: self file size) isNil ifTrue: [^self error: 'cannot reopen or setToEnd']. position _ readLimit] ifFalse: [position _ pos min: readLimit]! !!FileStream methodsFor: 'fileIn/Out'!fileIn "Guarantee fileStream is readOnly before fileIn for efficiency and to eliminate remote sharing conflicts" Transcript refresh; cr; cr; show: 'Filing in from:'; crtab; show: self name; cr. self readOnly. ^super fileIn!fileOutChanges "Append to the receiver a description of all system changes." Transcript refresh; cr; cr; show: ('Filing out changes on:'); crtab; show: self name. super fileOutChanges!printOutChanges "Print out a description of all system changes." self fileOutChanges! !!FileStream methodsFor: 'private'!fixEnd (self writing and: [position > page dataEnd]) ifTrue: ["fix the end of page" page dataEnd: (readLimit _ position)]!on: aFilePage "initialize stream on aFilePage" page _ aFilePage. "some page from a File, usually page 1, or another FileStream" (page isKindOf: FileStream) ifTrue: [page _ page page]. page asFileStream: self. closed _ false. FileDirectory addExternalReference: self!position: objpos size: size "set the current character position and the current page from the position of an object of a given size (see positionSize:)" | len pn c pos newSize | len _ page dataSize. newSize _ size. "this may change at end of page" size = len ifTrue: ["page size" pn _ objpos + 1. c _ 0] ifFalse: [pos _ objpos. size = 1 ifFalse: [len \\ size = 0 ifTrue: ["page length is a multiple of size" len _ len // size] ifFalse: [pos _ objpos * size. newSize _ 1]]. "obtain quotient (page) and remainder (position)" pn _ 1 + (pos // len). c _ newSize * (pos \\ len)]. (self positionPage: pn character: c) ifTrue: [^objpos]. self error: 'cannot read page ' , pn printString!positionPage: pn character: c "normally accessed by position:size:, skip:" (self read: pn) notNil ifTrue: ["c assumed between 0 and page dataSize. position, readLimit were set in on:" position _ position + c. (position <= readLimit or: [self writing]) ifTrue: [^true] ifFalse: [position _ readLimit. ^false]] ifFalse: [c = 0 ifTrue: ["try end of previous page" ^self positionPage: pn - 1 character: page dataSize] ifFalse: [^false]]!positionSize: size "compute the position for an object of a given size, e.g. characters (1), words (2), fixed length (n), from the current character position and the current page" | len pos | len _ page dataSize. (size = 1 or: [len \\ size ~= 0]) ifTrue: [pos _ page pageNumber - 1 * len + (position - page dataBeginning). size = 1 ifTrue: [^pos] ifFalse: [^pos // size]] ifFalse: ["page length is a multiple of size" ^page pageNumber - 1 * (len // size) + (position - page dataBeginning // size)]!setMode: m rwmode = m "don't flush if first time or not write mode or continuing write mode" ifFalse: [(rwmode == nil or: [(rwmode bitAnd: Write) = 0 or: [(m bitAnd: Write) = Write]]) ifTrue: [rwmode _ m] ifFalse: [self flush. rwmode _ m]]!shorten "normally called by close and not directly by user" page dataEnd: (readLimit _ position). page fromFileStream: self. self on: page endFile. position _ readLimit! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FileStream class instanceVariableNames: ''!!FileStream class methodsFor: 'instance creation'!fileNamed: fileDesignator "Answer a FileStream on an old or new File designated by the string fileDesignator." | dir fName | dir _ FileDirectory directoryFromName: fileDesignator setFileName: [:fName]. ^(dir findOrAddKey: fName) asFileStream!newFileNamed: fileDesignator "Answer a FileStream on a new File designated by the string fileDesignator. Error if the argument is not a new file name." | dir fName | dir _ FileDirectory directoryFromName: fileDesignator setFileName: [:fName]. ^(dir addKey: fName) asFileStream!oldFileNamed: fileDesignator "Answer a FileStream on an old File designated by the string fileDesignator. Error if the argument is not an old file name." | dir fName | dir _ FileDirectory directoryFromName: fileDesignator setFileName: [:fName]. ^(dir findKey: fName) asFileStream!on: aFilePage ^self new on: aFilePage! ! StringHolder subclass: #FillInTheBlank instanceVariableNames: 'actionBlock actionTaken ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!FillInTheBlank comment:'I represent a request for information that will be applied as the argument of a block of actions.Instance Variables actionBlock <BlockContext> actionTaken <Boolean> whether the actonBlock has been evaluated at least once'!!FillInTheBlank methodsFor: 'initialize-release'!initialize super initialize. actionTaken _ false! !!FillInTheBlank methodsFor: 'accessing'!action: aBlock "The argument, aBlock, will be evaluated when the receiver is sent the message selectAction." actionBlock _ aBlock!actionTaken ^actionTaken!setAction: aBoolean actionTaken _ aBoolean! !!FillInTheBlank methodsFor: 'menu messages'!selectAction "Evaluate the receiver's assigned action block, if any, with the answer as the block argument." actionBlock notNil ifTrue: [actionBlock value: contents]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FillInTheBlank class instanceVariableNames: ''!!FillInTheBlank class methodsFor: 'instance creation'!action: aBlock initialAnswer: aString "Answer an instance of me whose action is aBlock and initial action argument is aString." | newBlank | newBlank _ self new initialize. newBlank action: aBlock. newBlank contents: aString. ^newBlank!message: messageString displayAt: aPoint centered: centered action: aBlock initialAnswer: aString "Answer an instance of me whose question is messageString. Once the user provides an answer, then evaluate aBlock. If centered, a Boolean, is false, display the view of the instance at aPoint; otherwise display it with its center at aPoint. " | newBlank | newBlank _ self new initialize. newBlank action: aBlock. newBlank contents: aString. FillInTheBlankView openOn: newBlank message: messageString displayAt: aPoint centered: centered!request: messageString "Create an instance of me whose question is messageString. Display it centered around the cursor. Simply return whatever the user accepts." ^self request: messageString initialAnswer: ''!request: messageString displayAt: aPoint centered: centered action: aBlock initialAnswer: aString ^self request: messageString displayAt: aPoint centered: centered action: aBlock initialAnswer: aString useCRController: true!request: messageString displayAt: aPoint centered: centered action: aBlock initialAnswer: aString useCRController: useCRController "Answer an instance of me whose question is messageString. Once the user provides an answer, then evaluate aBlock. If centered, a Boolean, is false, display the view of the instance at aPoint; otherwise display it with its center at aPoint. " | newBlank fillInView savedArea | newBlank _ self new initialize. newBlank action: aBlock. newBlank contents: aString. fillInView _ FillInTheBlankView on: newBlank message: messageString displayAt: aPoint centered: centered useCRController: useCRController. savedArea _ Form fromDisplay: fillInView displayBox. fillInView display. fillInView controller centerCursorInView. fillInView controller startUp. fillInView release. savedArea displayOn: Display at: fillInView viewport topLeft!request: messageString initialAnswer: aString "Create an instance of me whose question is messageString. Display it centered around the cursor. Supply aString as an initial answer. Simply return whatever the user accepts." self request: messageString displayAt: Sensor cursorPoint centered: true action: [:response | response] initialAnswer: aString. ^response! !!FillInTheBlank class methodsFor: 'examples'!example1 "Example waits for you to click red button somewhere on the screen. The view will show where you point. Terminate by choosing menu command accept." FillInTheBlank message: 'What is your name?' displayAt: Sensor waitButton centered: true action: [:answer | Transcript cr; show: answer] initialAnswer: '' "FillInTheBlank example1."!example2 "Example waits for you to click red button somewhere on the screen. The view will show where you point. Terminate by choosing menu command accept or typing carriage return." FillInTheBlank request: 'What is your name?' displayAt: Sensor waitButton centered: true action: [:answer | Transcript cr; show: answer] initialAnswer: '' "FillInTheBlank example2."!example3 "Try this example by choosing menu command print it" ^Text fromUser "FillInTheBlank example3."! ! StringHolderController subclass: #FillInTheBlankController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!FillInTheBlankController comment:'I am a StringHolderController for a FillInTheBlankView. The string is information that the user can type in and edit. Upon issuing the accept command, this information is used by my model in the evaluation of an action block.'!!FillInTheBlankController methodsFor: 'basic control sequence'!controlTerminate | topController | super controlTerminate. model actionTaken ifFalse: [^self]. topController _ view topView controller. (topController notNil & (topController isKindOf: StandardSystemController)) ifTrue: [topController close]. model selectAction! !!FillInTheBlankController methodsFor: 'control defaults'!isControlActive model actionTaken ifTrue: [^false]. ^super isControlActive!isControlWanted model actionTaken ifTrue: [^false]. ^super isControlActive! !!FillInTheBlankController methodsFor: 'menu messages'!accept super accept. model setAction: true! !!FillInTheBlankController methodsFor: 'initialize-release'!resetState "intercept to force selection of entire text" super resetState. stopBlock _ paragraph characterBlockForIndex: paragraph text size+1.! ! StringHolderView subclass: #FillInTheBlankView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Prompt/Confirm'!FillInTheBlankView comment:'I am a view of a FillInTheBlank--I display a query and an area in which the user can type some information.'!!FillInTheBlankView methodsFor: 'controller access'!defaultControllerClass ^FillInTheBlankController! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FillInTheBlankView class instanceVariableNames: ''!!FillInTheBlankView class methodsFor: 'instance creation'!on: aFillInTheBlank message: messageString displayAt: originPoint centered: centered "Answer an instance of me on the model aFillInTheBlank asking the question messageString. If the argument centered, a Boolean, is false, display the instance with top left corner at originPoint; otherwise, display it with its center at originPoint. If necessary, translate so the view is completely on the screen." ^self on: aFillInTheBlank message: messageString displayAt: originPoint centered: centered useCRController: true!on: aFillInTheBlank message: messageString displayAt: originPoint centered: centered useCRController: useCRController | topView messageView answerView | messageView _ self buildMessageView: messageString. answerView _ self buildAnswerView: aFillInTheBlank frameWidth: messageView window width. useCRController ifTrue: [answerView controller: CRFillInTheBlankController new]. topView _ View new model: aFillInTheBlank. topView controller: BinaryChoiceController new. topView addSubView: messageView. topView addSubView: answerView below: messageView. topView align: (centered ifTrue: [topView viewport center] ifFalse: [topView viewport topLeft]) with: originPoint. topView window: (0 @ 0 extent: messageView window width @ (messageView window height + answerView window height)). topView translateBy: (topView displayBox amountToTranslateWithin: Display boundingBox). ^topView!openOn: aFillInTheBlank message: messageString displayAt: originPoint centered: centered "Create and schedule an instance of me that displays aFillInTheBlank asking the question messageString. If the argument centered, a Boolean, is false, display the instance with top left corner at originPoint; otherwise, display it with its center at originPoint. Do not schedule, rather take control immediately and insist that the user respond." | topView messageView answerView | messageView _ self buildMessageView: messageString. answerView _ self buildAnswerView: aFillInTheBlank frameWidth: messageView window width. topView _ StandardSystemView new model: aFillInTheBlank. topView addSubView: messageView. topView addSubView: answerView below: messageView. topView align: (centered ifTrue: [topView viewport center] ifFalse: [topView viewport topLeft]) with: originPoint. topView label: 'Type a response'. topView window: (0@0 extent: messageView window width @ (messageView window height + 40)). topView controller openDisplayAt: originPoint! !!FillInTheBlankView class methodsFor: 'private'!buildAnswerView: aFillInTheBlank frameWidth: widthInteger | answerView | answerView _ self new model: aFillInTheBlank. answerView window: (0@0 extent: widthInteger @ 40). answerView borderWidth: 2. ^answerView!buildMessageView: messageString | messageView | messageView _ DisplayTextView new model: messageString asDisplayText. messageView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. messageView insideColor: Form white. messageView controller: NoController new. messageView window: (0@0 extent: (messageView window extent max: 200@30)). messageView centered. ^messageView! ! Number variableWordSubclass: #Float instanceVariableNames: '' classVariableNames: 'ExpPCoefficients ExpQCoefficients Fourthpi Halfpi Ln2 LnCoefficients Pi RadiansPerDegree SinCoefficients Sqrt2 TanCoefficients Twopi ' poolDictionaries: '' category: 'Numeric-Numbers'!Float comment:'I represent floating-point numbers in IEEE 32-bit format.These floating-point numbers are good for about 8 or 9 digits of accuracy, and the range is between plus and minus 10^32.Here are some valid floating-point examples: 8.0 13.3 0.3 2.5e6 1.27e-30 1.27e-31 -12.987654e12Mainly: no imbedded blanks, little e for tens power, and a digit on both sides of the decimal point.'!!Float methodsFor: 'arithmetic'!* aNumber "Multiply the receiver by the argument and return the result as a Float. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive." <primitive: 49> ^self retry: #* coercing: aNumber!+ aNumber "Add the receiver to the argument and return the result as a Float. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive. " <primitive: 41> ^self retry: #+ coercing: aNumber!- aNumber "Subtract the argument from the receiver and return the result as a Float. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive. " <primitive: 42> ^self retry: #- coercing: aNumber!/ aNumber "Divide the receiver by the argument and return the exact result as a Float. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive. " <primitive: 50> aNumber = 0 ifTrue: [self error: 'attempt to divide by zero'] ifFalse: [^self retry: #/ coercing: aNumber]!negated "Answer a Number that is the negation of the receiver." ^0.0 - self! !!Float methodsFor: 'mathematical functions'!arcCos "Answers with the angle in radians." ^Halfpi - self arcSin!arcSin "Answers with the angle in radians" self abs > 1.0 ifTrue: [self error: 'Value out of range']. self abs = 1.0 ifTrue: [^Halfpi] ifFalse: [^(self / (1 - (self * self)) sqrt) arcTan]!arcTan "Answers with the angle in radians" | theta term y eps i | self = 1.0 ifTrue: [^Fourthpi]. self = -1.0 ifTrue: [^Fourthpi negated]. self * self > 1.0 ifTrue: [theta _ Halfpi. y _ -1.0 / (self * self). term _ -1.0 / self abs] ifFalse: [theta _ 0.0. y _ 0.0 - (self * self). term _ self abs]. i _ 1. eps _ 1.0e-4. [term abs > eps] whileTrue: [theta _ theta + term. term _ term * y * i asFloat / (i + 2) asFloat. i _ i + 2]. ^self sign asFloat * theta!cos "Answers with the cosine of the receiver in radians." self < 0.0 ifTrue: [^(self + Halfpi) sin]. ^(Halfpi - self) sin!exp "see Computer Approximations, pp. 96-104, p. 205 (EXPB 1065)" | a n1 x x2 P Q | self abs > 9212.0 ifTrue: ["Float maxVal ln" "1.0 exp" self error: 'exp overflow'] ifFalse: [x _ self / Ln2. n1 _ 2.0 raisedTo: x truncated. (x _ x - x truncated) >= 0.5 ifTrue: [n1 _ n1 * Sqrt2. x _ x - 0.5]. x2 _ x * x. "compute 2.0 power: x" P _ Q _ 0.0. ExpPCoefficients do: [:a | P _ P * x2 + a]. ExpQCoefficients do: [:a | Q _ Q * x2 + a]. ^n1 * (Q + (x * P) / (Q - (x * P)))]!floorLog: radix "quick computation of (self log: radix) floor" | x | self < radix ifTrue: [^0]. "self assumed positive" self < radix squared ifTrue: [^1]. x _ 2 * (self floorLog: radix squared). "binary recursion like ipow" ^x + (self / (radix raisedTo: x) floorLog: radix)!ln "see Computer Approximations, pp. 105-111, p. 227 (LOGE 2663)" | expt x x2 n P | self <= 0.0 ifTrue: [self error: 'ln not valid for ' , self printString] ifFalse: [expt _ self exponent. n _ Ln2 * (expt - 0.5). "mantissa between 0.5 and 1.0" x _ self timesTwoPower: 0 - expt. x _ x * Sqrt2. x _ x - 1.0 / (x + 1.0). x2 _ x * x. P _ 0.0. LnCoefficients do: [:a | P _ P * x2 + a]. ^n + (x * P)]"2.718284 ln 1.0"!log "Base 10 logarithm" ^self ln / 10.0 ln!sin "Answers with the sine of the receiver in radians." | x x2 sum | "normalize to 0<=self<=(Pi/2)" self < 0.0 ifTrue: [^self negated sin negated]. self > Twopi ifTrue: [^(self \\ Twopi) sin]. self > Pi ifTrue: [^(self - Pi) sin negated]. self > Halfpi ifTrue: [^(Pi - self) sin]. sum _ x _ self. x2 _ x * x. SinCoefficients do: [:const | sum _ const * (x _ x * x2) + sum]. ^sum!sqrt | guess | self <= 0.0 ifTrue: [self = 0.0 ifTrue: [^0.0] ifFalse: [^self error: 'sqrt invalid for x < 0']]. "copy and halve the exponent for first guess" guess _ self timesTwoPower: 0 - (self exponent // 2). 5 timesRepeat: [guess _ self - (guess * guess) / (guess * 2.0) + guess]. ^guess!tan "Answer the ratio of the sine to cosine of the receiver in radians." | x x2 sum | "normalize to 0<=self<=(Pi/4)" self < 0.0 ifTrue: [^self negated tan negated]. self > Pi ifTrue: [^(self \\ Pi) tan]. self > Halfpi ifTrue: [^(Pi - self) tan negated]. self > Fourthpi ifTrue: [^1.0 / (Halfpi - self) tan]. sum _ x _ self. x2 _ x * x. TanCoefficients do: [:const | sum _ const * (x _ x * x2) + sum]. ^sum! !!Float methodsFor: 'comparing'!< aNumber "Compare the receiver with the argument and return true if the receiver is less than the argument. Otherwise return false. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive." <primitive: 43> ^self retry: #< coercing: aNumber!<= aNumber "Compare the receiver with the argument and return true if the receiver is less than or equal to the argument. Otherwise return false. Fail if the argument is not a Float. Optional. See Object documentation whatIsAPrimitive." <primitive: 45> ^super <= aNumber!= aNumber "Compare the receiver with the argument and return true if the receiver is equal to the argument. Otherwise return false. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive." <primitive: 47> ^self retry: #= coercing: aNumber!> aNumber "Compare the receiver with the argument and return true if the receiver is greater than the argument. Otherwise return false. Fail if the argument is not a Float. Essential. See Object documentation whatIsAPrimitive." <primitive: 44> ^self retry: #> coercing: aNumber!>= aNumber "Compare the receiver with the argument and return true if the receiver is greater than or equal to the argument. Otherwise return false. Fail if the argument is not a Float. Optional. See Object documentation whatIsAPrimitive. " <primitive: 46> ^super >= aNumber!hash "Hash is reimplemented because = is implemented." ^(self basicAt: 1) bitAnd: 16383 "High bits as an Integer"!~= aNumber "Compare the receiver with the argument and return true if the receiver is not equal to the argument. Otherwise return false. Fail if the argument is not a Float. Optional. See Object documentation whatIsAPrimitive." <primitive: 48> ^super ~= aNumber! !!Float methodsFor: 'truncation and round off'!fractionPart "Answer a new Float whose value is the difference between the receiver and the receiver's truncated value. Optional. See Object documentation whatIsAPrimitive." <primitive: 52> ^self - self truncated!integerPart "Answer with a new Float whose value is the receiver's truncated value." ^self - self fractionPart!rounded "Answer the integer nearest the receiver." self >= 0.0 ifTrue: [^(self + 0.5) truncated] ifFalse: [^(self - 0.5) truncated]!truncated "Answer with a SmallInteger equal to the value of the receiver without its fractional part. The primitive fails if the truncated value cannot be represented as a SmallInteger. In that case, the code below will compute a LargeInteger truncated value. Essential. See Object documentation whatIsAPrimitive. " <primitive: 51> ^(self quo: 16383.0) * 16383 + (self rem: 16383.0) truncated! !!Float methodsFor: 'coercing'!coerce: aNumber ^aNumber asFloat!generality ^80! !!Float methodsFor: 'converting'!asFloat "Answer with the receiver itself." ^self!asFraction "Answer with a new Fraction representing the receiver. This conversion uses the continued fraction method to approximate a floating point number." | num1 denom1 num2 denom2 int frac newD temp | num1 _ self truncated. "The first of two alternating numerators" denom1 _ 1. "The first of two alternating denominators" num2 _ 1. "The second numerator" denom2 _ 0. "The second denominator--will update" int _ num1. "The integer part of self" frac _ self fractionPart. "The fractional part of self" [frac = 0] whileFalse: ["repeat while the fractional part is not zero" newD _ 1.0 / frac. "Take reciprocal of the fractional part" int _ newD truncated. "get the integer part of this" frac _ newD fractionPart. "and save the fractional part for next time" temp _ num2. "Get old numerator and save it" num2 _ num1. "Set second numerator to first" num1 _ num1 * int + temp. "Update first numerator" temp _ denom2. "Get old denominator and save it" denom2 _ denom1. "Set second denominator to first" denom1 _ int * denom1 + temp. "Update first denominator" 10000.0 < denom1 ifTrue: ["Is ratio past float precision? If so, pick which of the two ratios to use" num2 = 0.0 ifTrue: ["Is second denominator 0?" ^Fraction numerator: num1 denominator: denom1]. ^Fraction numerator: num2 denominator: denom2]]. "If fractional part is zero, return the first ratio" denom1 = 1 ifTrue: ["Am i really an Integer?" ^num1"Yes, return Integer result"] ifFalse: ["Otherwise return Fraction result" ^Fraction numerator: num1 denominator: denom1]!degreesToRadians ^self * RadiansPerDegree!radiansToDegrees ^self / RadiansPerDegree! !!Float methodsFor: 'copying'!deepCopy ^self copy!shallowCopy ^self + 0.0! !!Float methodsFor: 'printing'!isLiteral ^true!printOn: aStream self printOn: aStream digits: 6! !!Float methodsFor: 'private'!absPrintOn: aStream digits: digits "Print me using digits significant figures." | fuzz x exp q i | "x is myself normalized to [1.0, 10.0), exp is my exponent" exp _ self < 1.0 ifTrue: [(10.0 / self floorLog: 10.0) negated] ifFalse: [self floorLog: 10.0]. x _ self / (10.0 raisedTo: exp). fuzz _ 10.0 raisedTo: 1 - digits. "round the last digit to be printed" x _ 0.5 * fuzz + x. x >= 10.0 ifTrue: ["check if rounding has unnormalized x" x _ x / 10.0. exp _ exp + 1]. (exp < 6 and: [exp > -4]) ifTrue: ["decimal notation" q _ 0. exp < 0 ifTrue: [1 to: 1 - exp do: [:i | aStream nextPut: ('0.0000' at: i)]]] ifFalse: ["scientific notation" q _ exp. exp _ 0]. [x >= fuzz] whileTrue: ["use fuzz to track significance" i _ x truncated. aStream nextPut: (48 + i) asCharacter. x _ x - i * 10.0. fuzz _ fuzz * 10.0. exp _ exp - 1. exp = -1 ifTrue: [aStream nextPut: $.]]. [exp >= -1] whileTrue: [aStream nextPut: $0. exp _ exp - 1. exp = -1 ifTrue: [aStream nextPut: $.]]. q ~= 0 ifTrue: [aStream nextPut: $e. q printOn: aStream]!exponent "Consider the receiver to be represented as a power of two multiplied by a mantissa (between one and two). Answer with the SmallInteger to whose power two is raised. Optional. See Object documentation whatIsAPrimitive." | positive | <primitive: 53> self >= 1.0 ifTrue: [^self floorLog: 2]. self > 0.0 ifTrue: [positive _ (1.0 / self) exponent. self = (1.0 / (1.0 timesTwoPower: positive)) ifTrue: [^positive negated] ifFalse: [^positive negated - 1]]. self = 0.0 ifTrue: [^-1]. ^self negated exponent!mantissa: nBits "Answer as an integer the most significant nBits of the mantissa of the receiver." ^(self abs timesTwoPower: nBits-self exponent-1) truncated!printOn: aStream digits: digits "Print me using digits significant figures." self > 0.0 ifTrue: [self absPrintOn: aStream digits: digits] ifFalse: [self = 0.0 ifTrue: [aStream nextPutAll: '0.0'] ifFalse: [aStream nextPutAll: '-'. self negated absPrintOn: aStream digits: digits]]!timesTwoPower: anInteger "Answer with the receiver mulitplied by 2.0 raised to the power of the argument. Optional. See Object documentation whatIsAPrimitive." <primitive: 54> ^self * (2.0 raisedToInteger: anInteger)! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Float class instanceVariableNames: ''!!Float class methodsFor: 'class initialization'!initialize "constants from Computer Approximations, pp. 182-183 Pi = 3.14159265358979323846264338327950288 Pi/2 = 1.57079632679489661923132169163975144 Pi/4 = 0.78539816339744830961566084581987572 Pi*2 = 6.28318530717958647692528676655900576 Pi/180 = 0.01745329251994329576923690768488612 2.0 ln = 0.69314718055994530941723212145817657 2.0 sqrt = 1.41421356237309504880168872420969808" Pi _ 3.14159. Halfpi _ Pi / 2.0. Fourthpi _ Pi / 4.0. Twopi _ Pi * 2.0. RadiansPerDegree _ Pi / 180.0. Ln2 _ 0.693147. Sqrt2 _ 1.41421. SinCoefficients _ #(-0.166667 0.00833333 -1.98409e-4 2.7526e-6 -2.39e-8 ). TanCoefficients _ #(0.333331 0.133392 0.0533741 0.0245651 0.00290052 0.00951681 ). ExpPCoefficients _ #(28.8756 2525.04 ). ExpQCoefficients _ #(1.0 375.022 7285.73 ). LnCoefficients _ #(0.237625 0.285254 0.400006 0.666667 2.0 ) "Float initialize."! !!Float class methodsFor: 'instance creation'!readFrom: aStream "Answer a new Float as described on the stream, aStream." ^(super readFrom: aStream) asFloat! !!Float class methodsFor: 'constants'!pi "Answer the constant, Pi." ^Pi! !Float initialize! DisplayMedium subclass: #Form instanceVariableNames: 'bits width height offset ' classVariableNames: 'OneBitForm ' poolDictionaries: '' category: 'Graphics-Display Objects'!Form comment: 'This class is a rectangular pattern of dots represented as a Smalltalk Bitmap.'!!Form methodsFor: 'initialize-release'!fromDisplay: aRectangle "Create a virtual bit map from a user specified rectangular area on the display screen. Reallocates bitmap only if aRectangle ~= the receiver's extent." (width = aRectangle width and: [height = aRectangle height]) ifFalse: [self extent: aRectangle extent]. self copyBits: (aRectangle origin extent: self extent) from: Display at: 0 @ 0 clippingBox: Display boundingBox rule: Form over mask: Form black! !!Form methodsFor: 'accessing'!extent: aPoint "Create a virtual bit map with width = (extent x) and height = (extent y) with the bits all zeros (white). The extent is guaranteed to be zero or a positive size." | nonZeroExtent extentSize | nonZeroExtent _ aPoint >= (0 @ 0) ifTrue: [aPoint] ifFalse: [0 @ 0]. extentSize _ nonZeroExtent y * (nonZeroExtent x + 15 // 16). self extent: nonZeroExtent offset: 0 @ 0 bits: (WordArray new: (extentSize min: WordArray maxSize))!extent: extentPoint offset: offsetPoint "Create a virtual bit map with width = (extent x) and height = (extent y) with the bits all zeros (white)." | normalizedPoint | normalizedPoint _ extentPoint >= (0 @ 0) ifTrue: [extentPoint] ifFalse: [0 @ 0]. self extent: normalizedPoint offset: offsetPoint bits: (WordArray new: normalizedPoint y * (normalizedPoint x + 15 // 16))!extent: extent offset: aPoint bits: aBitmap "Create a virtual bit map with width = (extent x) and height = (extent y) with the bits = aBitmap." width _ extent x. height _ extent y. offset _ aPoint. bits _ aBitmap!offset offset == nil ifTrue: [^0 @ 0] ifFalse: [^offset]!offset: aPoint offset _ aPoint!size "Answer the number of bits in the receiver's bitmap." ^bits size! !!Form methodsFor: 'copying'!deepCopy | newForm | newForm _ self shallowCopy. newForm bits: (WordArray new: self size). newForm copyBits: self boundingBox from: self at: 0 @ 0 clippingBox: newForm boundingBox rule: Form over mask: Form black. ^newForm! !!Form methodsFor: 'displaying'!copyBits: sourceRect from: sourceForm at: destOrigin clippingBox: clipRect rule: rule mask: aForm "Make up a BitBlt table and copy the bits." (BitBlt destForm: self sourceForm: sourceForm halftoneForm: aForm combinationRule: rule destOrigin: destOrigin sourceOrigin: sourceRect origin extent: sourceRect extent clipRect: clipRect) copyBits!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm aDisplayMedium copyBits: self boundingBox from: self at: aDisplayPoint + offset clippingBox: clipRectangle rule: ruleInteger mask: aForm!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: ruleInteger mask: aForm "Graphically, it means nothing to scale a Form by floating point values. Because scales and other display parameters are kept in floating point to minimize round off errors, we are forced in this routine to round off to the nearest integer." | absolutePoint scale magnifiedForm | absolutePoint _ displayTransformation applyTo: relativePoint. absolutePoint _ absolutePoint x truncated @ absolutePoint y truncated. displayTransformation noScale ifTrue: [magnifiedForm _ self] ifFalse: [scale _ displayTransformation scale. scale _ scale x rounded @ scale y rounded. (1@1 = scale) ifTrue: [scale _ nil. magnifiedForm _ self] ifFalse: [magnifiedForm _ self magnifyBy: scale]]. magnifiedForm displayOn: aDisplayMedium at: absolutePoint - alignmentPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm!drawLine: sourceForm from: beginPoint to: endPoint clippingBox: clipRect rule: anInteger mask: aForm | dotSetter | "set up an instance of BitBlt for display" dotSetter _ BitBlt destForm: self sourceForm: sourceForm halftoneForm: aForm combinationRule: anInteger destOrigin: beginPoint sourceOrigin: 0 @ 0 extent: sourceForm extent clipRect: clipRect. dotSetter drawFrom: beginPoint to: endPoint! !!Form methodsFor: 'display box access'!computeBoundingBox ^0 @ 0 extent: width @ height! !!Form methodsFor: 'pattern'!bits "Answer the receiver's Bitmap containing its bits." ^bits!bits: aBitmap "Reset the Bitmap containing the receiver's bits." bits _ aBitmap!valueAt: aPoint "Query whether a bit is on or off.... answer with 1 if the color at coordinate aPoint is black in the receiver and 0 if the color is white at coordinate aPoint" OneBitForm copyBits: (aPoint extent: 1 @ 1) from: self at: 0 @ 0 clippingBox: self boundingBox rule: Form over mask: Form black. (OneBitForm bits at: 1) = 0 ifTrue: [^0] ifFalse: [^1]!valueAt: aPoint put: maskCode "Set the bit in the receiver at coordinate aPoint to be white (0) or black (1)." maskCode = 0 ifTrue: [OneBitForm white] "OneBitForm is a class variable." ifFalse: [OneBitForm black]. self copyBits: OneBitForm boundingBox from: OneBitForm at: aPoint clippingBox: self boundingBox rule: Form over mask: Form black.! !!Form methodsFor: 'bordering'!borderWidth: anInteger "Set the width of the border for the receiver to be anInteger and paint it using Form black as the border color." self border: self boundingBox width: anInteger mask: Form black!borderWidth: anInteger mask: aMask "Set the width of the border for the receiver to be anInteger and paint it using aMask as the border color." self border: self boundingBox width: anInteger mask: aMask! !!Form methodsFor: 'coloring'!fill: aRectangle rule: anInteger mask: aForm "Replace a rectangular area of the receiver with the pattern described by aForm according to the rule anInteger." "Make up a BitBlt table and copy the bits" (BitBlt destForm: self sourceForm: nil halftoneForm: aForm combinationRule: anInteger destOrigin: aRectangle origin sourceOrigin: self boundingBox origin extent: aRectangle extent clipRect: self boundingBox) copyBits! !!Form methodsFor: 'image manipulation'!convexShapeFill: aMask "Fill the interior of the outtermost outlined region in the receiver. The outlined region must not be concave by more than 90 degrees." | destForm tempForm skew | destForm _ Form extent: self extent. tempForm _ Form extent: self extent. self displayOn: tempForm at: (0@0) - self offset. skew _ 1. [skew < width] whileTrue: [tempForm displayOn: tempForm at: skew@0 clippingBox: tempForm boundingBox rule: Form under mask: nil. skew _ skew+skew]. tempForm displayOn: destForm. self displayOn: tempForm at: (0@0) - self offset. skew _ 1. [skew < width] whileTrue: [tempForm displayOn: tempForm at: skew negated@0 clippingBox: tempForm boundingBox rule: Form under mask: nil. skew _ skew+skew]. tempForm displayOn: destForm at: 0@0 clippingBox: destForm boundingBox rule: Form and mask: nil. self displayOn: tempForm at: (0@0) - self offset. skew _ 1. [skew < height] whileTrue: [tempForm displayOn: tempForm at: 0@skew clippingBox: tempForm boundingBox rule: Form under mask: nil. skew _ skew+skew]. tempForm displayOn: destForm at: 0@0 clippingBox: destForm boundingBox rule: Form and mask: nil. self displayOn: tempForm at: (0@0) - self offset. skew _ 1. [skew < height] whileTrue: [tempForm displayOn: tempForm at: 0@skew negated clippingBox: tempForm boundingBox rule: Form under mask: nil. skew _ skew+skew]. tempForm displayOn: destForm at: 0@0 clippingBox: destForm boundingBox rule: Form and mask: nil. destForm displayOn: self at: 0@0 clippingBox: self boundingBox rule: Form over mask: aMask!copy: destRectangle from: sourcePt in: sourceForm rule: rule "Make up a BitBlt table and copy the bits" (BitBlt destForm: self sourceForm: sourceForm halftoneForm: nil combinationRule: rule destOrigin: destRectangle origin sourceOrigin: sourcePt extent: destRectangle extent clipRect: (0@0 extent: width@height)) copyBits" [Sensor redButtonPressed] whileFalse: [Display copy: (30@30 extent: 300@300) from: Sensor cursorPoint in: Display rule: Form over]."!magnifyBy: scale "Answer a new form created as a multiple of the receiver; the new form is larger, each bit in the receiver being blown up to extent=scale" | wideForm bigForm spacing | spacing _ 0 @ 0. wideForm _ Form new extent: (width * scale x) @ height. wideForm spread: self boundingBox from: self by: scale x spacing: spacing x direction: 1 @ 0. bigForm _ Form new extent: self extent * scale. bigForm spread: wideForm boundingBox from: wideForm by: scale y spacing: spacing y direction: 0 @ 1. ^bigForm "Check consistency of shrink and magnify: [Sensor redButtonPressed] whileFalse: [(((Form fromDisplay: (Sensor cursorPoint extent: 50@50)) magnifyBy: 3@5) shrinkBy: 3@5) displayAt: 100@100] "!nextLifeGeneration | nbr1 nbr2 nbr4 carry2 carry4 all delta | nbr1 _ Form extent: self extent. nbr2 _ Form extent: self extent. nbr4 _ Form extent: self extent. carry2 _ Form extent: self extent. carry4 _ Form extent: self extent. all _ self boundingBox. 1 to: 8 do: [:i | delta _ "delta is the offset of the eight neighboring cells" ((#(-1 0 1 1 1 0 -1 -1) at: i) @ (#(-1 -1 -1 0 1 1 1 0) at: i)). carry2 copy: all from: 0@0 in: nbr1 rule: 3. carry2 copy: all from: delta in: self rule: 1. "AND for carry into 2" nbr1 copy: all from: delta in: self rule: 6. "XOR for sum 1" carry4 copy: all from: 0@0 in: nbr2 rule: 3. carry4 copy: all from: 0@0 in: carry2 rule: 1. "AND for carry into 4" nbr2 copy: all from: 0@0 in: carry2 rule: 6. "XOR for sum 2" nbr4 copy: all from: 0@0 in: carry4 rule: 6]. "XOR for sum 4 (ignore carry into 8)" self copy: all from: 0@0 in: nbr2 rule: 1. nbr1 copy: all from: 0@0 in: nbr2 rule: 1. self copy: all from: 0@0 in: nbr1 rule: 7. self copy: all from: 0@0 in: nbr4 rule: 4 "compute next generation"" BitEditor magnifyOnScreen. | life | life _ Form fromUser. [Sensor redButtonPressed] whileFalse: [(life nextLifeGeneration magnifyBy: 8@8) displayAt: 0@0]"!reflect: spec "spec = 0@1 for vertical reflection, 1@0 for horizontal" | mask temp all newForm full half | all _ self boundingBox. mask _ Form extent: self extent. temp _ Form extent: self extent. full _ self extent*spec. mask black: (0@0 extent: self extent // (spec+1)). newForm _ self deepCopy. [full x + full y > 1] whileTrue: [half _ full // 2. temp copy: all from: 0@0 in: newForm rule: 3. temp copy: all from: full-half in: newForm rule: 6. temp copy: all from: 0@0 in: mask rule: 1. newForm copy: all from: 0@0 in: temp rule: 6. newForm copy: (all translateBy: full-half) from: 0@0 in: temp rule: 6. "Now refine the mask" mask copy: all from: half - (half//2) in: mask rule: 1. mask copy: (all translateBy: full-half) from: 0@0 in: mask rule: 7. full _ half]. ^ newForm" [Sensor redButtonPressed] whileFalse: [((Form fromDisplay: (Rectangle new origin: Sensor cursorPoint extent: 113@37)) reflect: 1@0) displayAt: 0@0]."!rotate2: direction "Destructively rotate a square Form of dimension 2^N by 90 degrees. direction = 1 for clockwise, -1 for counterclockwise" | mask temp all quad delta | all _ self boundingBox. mask _ Form extent: self extent. temp _ Form extent: self extent. mask white. "set up the first mask" mask black: (0@0 extent: mask extent//2). quad_ self width // 2. [quad >= 1] whileTrue: [delta _ direction=1 ifTrue: [quad@0] ifFalse: [0@quad]. temp copy: all from: 0@0 in: mask rule: 3. "First exchange left and right halves" temp copy: (all translateBy: delta transpose) from: 0@0 in: mask rule: 7. temp copy: all from: 0@0 in: self rule: 1. self copy: all from: 0@0 in: temp rule: 6. temp copy: all from: delta in: self rule: 6. self copy: all from: delta in: self rule: 7. self copy: (all translateBy: delta) from: 0@0 in: temp rule: 6. temp copy: all from: 0@0 in: self rule: 3. "then flip the diagonals" temp copy: all from: quad@quad in: self rule: 6. temp copy: all from: 0@0 in: mask rule: 1. self copy: all from: 0@0 in: temp rule: 6. self copy: all from: quad negated@quad negated in: temp rule: 6. mask copy: all from: (quad//2)@(quad//2) in: mask rule: 1. "Now refine the mask" mask copy: all from: quad negated@0 in: mask rule: 7. mask copy: all from: 0@quad negated in: mask rule: 7. quad_ quad//2]" [Sensor redButtonPressed] whileFalse: [((Form fromDisplay: (Rectangle new origin: Sensor cursorPoint extent: 128@128)) rotate2: 1) displayAt: 0@0]."!rotateBy: angle "Answer a copied Form rotated clockwise by angle in units of 90 degrees. angle = 0 means unchanged, 1 means clockwise 90 degrees, etc" | angle4 rotSize newForm rotForm all destPt sourcePt sourceDelta destDelta rotOrigin | angle4 _ angle \\ 4. angle = 0 ifTrue: [^self deepCopy]. "null rotation" angle = 2 ifTrue: [^(self reflect: 0@1) reflect: 1@0]. "two reflections does 180 degrees" "Break the problem up into squares of size 2^N, and rotate them" rotSize _ (width min: height) "minimum rotation size" max: 64. "but faster if we do larger chunks" rotSize _ 2 raisedTo: ((rotSize-1) asFloat floorLog: 2)+1. "force up to a power of 2" newForm _ Form extent: self extent transpose. rotForm _ Form extent: rotSize asPoint. all _ rotForm boundingBox. sourcePt _ 0@0. width >= height ifTrue: [sourceDelta _ rotSize@0. angle=1 ifTrue: [destPt _ 0@0. destDelta _ sourceDelta transpose. rotOrigin _ (rotSize-height)@0] ifFalse: [destPt _ 0@(width-rotSize). destDelta _ (0@0) - sourceDelta transpose. rotOrigin _ 0@0]] ifFalse: [sourceDelta _ 0@rotSize. angle=1 ifTrue: [destPt _ (height-rotSize)@0. destDelta _ (0@0) - sourceDelta transpose. rotOrigin _ 0@0] ifFalse: [destPt _ 0@0. destDelta _ sourceDelta transpose. rotOrigin _ 0@(rotSize-width)]]. (width max: height) - 1 // rotSize + 1 timesRepeat: [rotForm copy: all from: sourcePt in: self rule: 3. rotForm rotate2: (angle=1 ifTrue: [1] ifFalse: [-1]). newForm copy: (all translateBy: destPt) from: rotOrigin in: rotForm rule: 3. sourcePt _ sourcePt + sourceDelta. destPt _ destPt + destDelta]. ^ newForm" | f | [Sensor redButtonPressed] whileFalse: [f_ Form fromDisplay: (Sensor cursorPoint extent: 100@15). (f rotateBy: 0) displayAt: 100@100. (f rotateBy: 1) displayAt: 85@100. (f rotateBy: 2) displayAt: 0@85. (f rotateBy: 3) displayAt: 100@0]"!shapeFill: aMask interiorPoint: interiorPoint "Fill the interior of some outlined region according to mask and rule. InteriorPoint marks a location in the interior or the region. A mark is placed at this point as a seed, then the seed is smeared into a blob until there is no change in the blob when it fills the region. Uses the upper left corner of the display screen for computing the blob" | dirs smearForm previousSmear all cycle noChange | all _ self boundingBox. smearForm _ Form extent: self extent. smearForm valueAt: interiorPoint put: 1. "Place a seed in the interior" previousSmear _ smearForm deepCopy. dirs _ Array with: 1@0 with: -1@0 with: 0@1 with: 0@-1. cycle _ 0. [(cycle _ cycle+1) \\ 10 = 0 and: "check for no change every 10 smears" [previousSmear copy: all from: 0@0 in: smearForm rule: Form reverse. noChange _ previousSmear isAllWhite. previousSmear copy: all from: 0@0 in: smearForm rule: Form over. noChange]] whileFalse: [dirs do: [:dir | "smear in each of the four directions" smearForm copy: all from: dir in: smearForm rule: Form under. "After each smear, trim around the region border" smearForm copy: all from: 0@0 in: self rule: Form erase]]. "Now paint the filled region in me with aMask" smearForm displayOn: self at: 0@0 clippingBox: self boundingBox rule: Form under mask: aMask!shrinkBy: scale "Answer a scaled-down copy of the receiver. Each bit in the new form is a sample taken from the upper-left bit of a rectangle of extent = scale in the receiver. A more involved algorithm would count the bits in the rectangle and produce black only if more than half were black" | wideForm shrunkenForm saveOffset | saveOffset _ self offset. self offset: 0 @ 0. wideForm _ Form new extent: self width @ (self height // scale y). 0 to: wideForm height-1 do: [:index | wideForm copy: (0 @ index extent: wideForm width @ 1) from: 0 @ (index * scale y) in: self rule: Form over]. shrunkenForm _ Form new extent: self width // scale x @ wideForm height. 0 to: shrunkenForm width-1 do: [:index | shrunkenForm copy: (index @ 0 extent: 1 @ wideForm height) from: (index * scale x) @ 0 in: wideForm rule: Form over]. self offset: saveOffset. shrunkenForm offset: offset // scale. ^shrunkenForm!spread: rectangle from: sourceForm by: scale spacing: spacing direction: dir | slice sourcePt | slice _ 0 @ 0 corner: dir transpose * self extent + dir. sourcePt _ rectangle origin. 1 to: (rectangle extent dotProduct: dir) do: [:i | "slice up original area" self copy: slice from: sourcePt in: sourceForm rule: 3. sourcePt _ sourcePt + dir. slice moveBy: dir * scale]. 1 to: scale - spacing - 1 do: [:i | "smear out the slices, leave white space" self copy: (dir corner: self extent) from: 0 @ 0 in: self rule: 7]!wrapAround: aPoint "Answer a new form which contains the image of the receiver, but translated by deltaPoint, with wrap-around. Used for realigning halftone masks. Assumes the receiver is 16x16 with zero offset." | newForm delta | newForm _ Form extent: width@height. delta _ (aPoint x\\16)@(aPoint y\\16). delta = (0@0) ifTrue: [^self]. self displayOn: newForm at: delta-(16@16). self displayOn: newForm at: delta-(16@0). self displayOn: newForm at: delta-(0@16). self displayOn: newForm at: delta. ^newForm "[Sensor anyButtonPressed] whileFalse: [((Cursor normal wrapAround: Sensor cursorPoint) magnifyBy: 8@8) displayAt: 100@100]"! !!Form methodsFor: 'printing'!scanLineStringAt: y | form | form _ Form stringScanLineOfWidth: width. form copy: form boundingBox from: 0@y in: self rule: Form over. ^ form bits!storeOn: aStream "Store the receiver out in the form: Form extent:fromCompactArray:#()offset:" | stripe bitsWidth word | aStream nextPut: $(; nextPutAll: self species name; crtab: 1. aStream nextPutAll: 'extent: '; print: self extent; crtab: 1. aStream nextPutAll: 'fromCompactArray: #('. 1 to: height do: [:i | stripe _ self scanLineStringAt: i-1. stripe oldRunEncoded storeOn: aStream. aStream cr]. aStream nextPut: $); crtab: 1. aStream nextPutAll: 'offset: '; print: self offset; nextPut: $)" | s | s_ WriteStream on: (String new: 2000).Form fromUser storeOn: s.(Compiler evaluate: s contents) displayAt: 0@0. | f | f_ Disk file: 'screen.form'.Display storeOn: f.f close. f size"!storeOn: aStream base: anInteger "Store the receiver out in the form: Form newExtent:fromArray:#()offset:" aStream nextPut: $(. aStream nextPutAll: self species name. aStream crtab: 1. aStream nextPutAll: 'extent: '. self extent printOn: aStream. aStream crtab: 1. aStream nextPutAll: 'fromArray: #('. 1 to: self bits size do: [:index | anInteger = 10 ifTrue: [aStream space] ifFalse: [aStream crtab: 2; nextPutAll: anInteger printString; nextPut: $r]. (self bits at: index) printOn: aStream base: anInteger]. aStream nextPut: $). aStream crtab: 1. aStream nextPutAll: 'offset: '. self offset printOn: aStream. aStream nextPut: $)! !!Form methodsFor: 'fileIn/Out'!writeOn: fileName "Saves the receiver on the file fileName in the format--fileCode, extent, offset, bits." | file fileCode filePosition | fileCode _ 1. "This indicates that the instance is a Form. Should probably be changed when better methods for permanent storage are devised." file _ FileStream fileNamed: fileName. file binary. file nextWordPut: fileCode. file nextWordPut: width. file nextWordPut: height. file nextWordPut: offset x. file nextWordPut: offset y. filePosition _ 0. 1 to: width + 15 // 16 do: [:j | 1 to: height do: [:i | file nextWordPut: (bits at: (filePosition _ filePosition + 1))]]. file close.! !!Form methodsFor: 'editing'!bitEdit "Create and schedule a view located in an area designated by the user that contains a view of the receiver magnified by 8@8 that can be modified using the Bit Editor. It also contains a view of the original form." BitEditor openOnForm: self "Note that using direct messages to BitEditor, fixed locations and scales can be created. That is, also try BitEditor openOnForm: self at: <some point>. BitEditor openOnForm: self at: <some point> scale: <some point>."!bitEditAt: magnifiedLocation "Create and schedule a view whose top left corner is magnifiedLocation and that contains a view of the receiver magnified by 8@8 that can be modified using the Bit Editor. It also contains a view of the original form." BitEditor openOnForm: self at: magnifiedLocation!bitEditAt: magnifiedFormLocation scale: scaleFactor "Create and schedule a view whose top left corner is magnifiedLocation and that contains a view of the receiver magnified by scaleFactor that can be modified using the Bit Editor. It also contains a view of the original form." BitEditor openOnForm: self at: magnifiedFormLocation scale: scaleFactor!edit "Start up an instance of the FormEditor on this form. Typically the form is not visible on the screen. The editor menu is located at the bottom of the form editing frame. The form is displayed centered in the frame. YellowButtonMenu accept is used to modify the form to reflect the changes made on the screen version; cancel restores the original form to the screen. Note that the changes are clipped to the original size of the form." FormEditor openOnForm: self!editAt: originPoint "Start up an instance of the FormEditor on this form in an area whose top left corrner is originPoint. Typically the form is not visible on the screen. The editor menu is located at the bottom of the form editing frame. The form is displayed centered in the frame. YellowBugMenu accept is used to modify the form to reflect the changes made on the screen version; cancel restores the original form to the screen. Note that the changes are clipped to the original size of the form." FormEditor openOnForm: self at: originPoint! !!Form methodsFor: 'private'!isAllWhite | count | count _ bits countBits. count = 0 ifTrue: [^true]. count > 0 ifTrue: [^false]. bits do: [:data | data ~= 0 ifTrue: [^false]]. ^true!setExtent: extentPoint fromArray: anArray setOffset: offsetPoint width _ extentPoint x. height _ extentPoint y. offset _ offsetPoint. bits _ WordArray new: width + 15 // 16 * height. 1 to: anArray size do: [:index | bits at: index put: (anArray at: index)]!setExtent: extentPoint fromCompactArray: anArray setOffset: offsetPoint | stripe index | width _ extentPoint x. height _ extentPoint y. offset _ offsetPoint. bits _ WordArray new: width + 15 // 16 * height. stripe _ Form stringScanLineOfWidth: width. 1 to: anArray size do: [:index | (anArray at: index) oldRunDecodeOn: (WriteStream on: stripe bits). self copy: (0@(index-1) extent: width@1) from: 0@0 in: stripe rule: Form over].! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Form class instanceVariableNames: 'whiteMask darkGrayMask grayMask blackMask lightGrayMask veryLightGrayMask '!!Form class methodsFor: 'class initialization'!initialize self initializeMasks. OneBitForm _ Form new extent: 1 @ 1 "Form initialize."!initializeMasks | anArray | anArray _ Array new: 16. anArray atAllPut: 0. whiteMask _ Form extent: 16 @ 16 fromArray: anArray offset: 0 @ 0. anArray atAllPut: 65535. blackMask _ Form extent: 16 @ 16 fromArray: anArray offset: 0 @ 0. anArray atAll: (1 to: anArray size by: 2) put: 21845. anArray atAll: (2 to: anArray size by: 2) put: 43690. grayMask _ Form extent: 16 @ 16 fromArray: anArray offset: 0 @ 0. anArray atAll: (1 to: anArray size by: 2) put: 30583. anArray atAll: (2 to: anArray size by: 2) put: 56797. darkGrayMask _ Form extent: 16 @ 16 fromArray: anArray offset: 0 @ 0. lightGrayMask _ darkGrayMask deepCopy reverse. anArray atAll: (1 to: anArray size by: 4) put: 34952. anArray atAll: (2 to: anArray size by: 2) put: 0. anArray atAll: (3 to: anArray size by: 4) put: 8738. veryLightGrayMask _ Form extent: 16 @ 16 fromArray: anArray offset: 0 @ 0 "Form initializeMasks"! !!Form class methodsFor: 'instance creation'!dotOfSize: diameter "Create a form which contains a round black dot." | radius form bite circle | radius _ diameter//2. form _ Form new extent: diameter@diameter offset: (0@0) - (radius@radius). diameter <= 9 ifTrue: "special case for speed" [form black. diameter <= 2 ifTrue: [^form]. bite _ diameter//3. form white: (0@0 extent: bite@1). form white: (0@(diameter-1) extent: bite@1). form white: (diameter-bite@0 extent: bite@1). form white: (diameter-bite@(diameter-1) extent: bite@1). form white: (0@0 extent: 1@bite). form white: (0@(diameter-bite) extent: 1@bite). form white: (diameter-1@0 extent: 1@bite). form white: (diameter-1@(diameter-bite) extent: 1@bite). ^form]. radius _ diameter-1//2. "so circle fits entirely" (Circle new center: radius@radius radius: radius) displayOn: form. form convexShapeFill: Form black. "fill the circle with black" ^form "(Form dotOfSize: 8) displayAt: Sensor cursorPoint"!extent: extentPoint "Answer an instance of me with blank bitmap." ^self basicNew setExtent: extentPoint fromArray: Array new setOffset: 0@0!extent: extentPoint fromArray: anArray offset: offsetPoint "Answer an instance of me with bitmap initialized from anArray." ^self basicNew setExtent: extentPoint fromArray: anArray setOffset: offsetPoint!extent: extentPoint fromCompactArray: anArray offset: offsetPoint "Answer an instance of me with bitmap initialized from anArray." ^self basicNew setExtent: extentPoint fromCompactArray: anArray setOffset: offsetPoint!fromDisplay: aRectangle "Answer an instance of me with bitmap initialized from the area of the display screen defined by aRectangle." ^self new fromDisplay: aRectangle!fromUser "Answer an instance of me with bitmap initialized from the area of the display screen designated by the user. The grid for selecting an area is 1@1." ^self fromUser: 1 @ 1!fromUser: aPoint "Answer an instance of me with bitmap initialized from the area of the display screen designated by the user. The grid for selecting an area is aPoint." | aRectangle | aRectangle _ Rectangle fromUser: aPoint. ^self new fromDisplay: aRectangle!readFormFile: file "Answer an instance of me with bitmap initialized from the external file. The file format is: fileCode(1), extent, offset, bits." | newForm newWidth newHeight theBits filePosition offsetX offsetY | file readOnly; binary. file nextWord = 1 ifFalse: [^(Form new extent: 8 @ 8) black]. "reads fileCode" newForm _ self new. newWidth _ file nextWord. newHeight _ file nextWord. newForm extent: newWidth @ newHeight. offsetX _ file nextWord. offsetY _ file nextWord. offsetX > 32767 ifTrue: [offsetX _ offsetX - 65536]. "stored two's-complement" offsetY > 32767 ifTrue: [offsetY _ offsetY - 65536]. "stored two's-complement" newForm offset: offsetX @ offsetY. theBits _ WordArray new: newWidth + 15 // 16 * newHeight. filePosition _ 0. 1 to: newWidth + 15 // 16 do: [:j | 1 to: newHeight do: [:i | theBits at: (filePosition _ filePosition + 1) put: file nextWord]]. newForm bits: theBits. file close. ^newForm!readFrom: fileName "Answer an instance of me with bitmap initialized from the external file named fileName." | file code | file _ FileStream oldFileNamed: fileName. file readOnly; binary. code _ file nextWord. "reads fileCode" code = 1 ifTrue: [^self readFormFile: file]. file close. ^nil!stringScanLineOfWidth: width ^self new extent: width@1 offset: 0@0 bits: (String new: width+15//16*2)! !!Form class methodsFor: 'mode constants'!and "Answer the integer denoting the logical 'and' combination rule." ^1!erase "Answer the integer denoting mode erase." ^4!over "Answer the integer denoting mode over." ^3!paint "Answer the integer denoting the 'paint' combination rule." ^16!reverse "Answer the integer denoting mode reverse." ^6!under "Answer the integer denoting mode under." ^7! !!Form class methodsFor: 'mask constants'!black "Answer the form denoting black mask." ^blackMask!darkGray "Answer the form denoting dark gray mask." ^darkGrayMask!gray "Answer the form denoting gray mask." ^grayMask!lightGray "Answer the form denoting light gray mask." ^lightGrayMask!veryLightGray "Answer the form denoting very light gray mask." ^veryLightGrayMask!white "Answer the form denoting white mask." ^whiteMask! !!Form class methodsFor: 'examples'!exampleEdits "In Form category editing are messages edit and bitEdit that make it possible to create editors on instances of Form. This is the general form editor-- |f| f _ Form fromUser. f edit. and the bit editor |f | f _ Form fromUser. f bitEdit. "!exampleMagnify [Sensor redButtonPressed] whileFalse: [((Form fromDisplay: (Sensor cursorPoint extent: 50@50)) magnifyBy: 3 @ 3) displayAt: 0 @ 0] "Form exampleMagnify."!exampleShrink [Sensor redButtonPressed] whileFalse: [((Form fromDisplay: (Sensor cursorPoint extent: 150@150)) shrinkBy: 3 @ 3) displayAt: 0 @ 0] "Form exampleShrink."!exampleSketch "This is a simple drawing algorithm to get a sketch on the display screen. After executing, just keep the mouse button depressed and a pen will let you scribble." | aPen | aPen _ Pen new. Sensor waitButton. aPen place: Sensor cursorPoint. aPen down. [Sensor anyButtonPressed] whileTrue: [aPen goto: Sensor cursorPoint] "Form exampleSketch."!exampleSpaceFill "This example demonstrates the area filling algorithm. The example starts by having the user sketch on the screen and then select a rectangular area of the screen which includes all off the area to be filled. Finally, (with crosshair cursor), the user points as the interior of the region to be filled, and the filling begins with that place as its seed" | f r interiorPoint | Form exampleSketch. "sketch a little area with an enclosed region" r _ Rectangle fromUser. f _ Form fromDisplay: r. Cursor crossHair showWhile: [interiorPoint _ Sensor waitButton - r origin]. Cursor execute showWhile: [f shapeFill: Form gray interiorPoint: interiorPoint]. f displayOn: Display at: r origin "Form exampleSpaceFill."! !Form initialize! Object subclass: #FormButtonCache instanceVariableNames: 'offset form value initialState ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Editors'!FormButtonCache comment: 'I am used to save information needed to construct the menu for the form editor. A collection of my instances is an class variable of FormMenuView.'!!FormButtonCache methodsFor: 'accessing'!form "Answer the receiver's form, the image of the button on the screen." ^form!form: aForm "Set the receiver's form to be the argument." form _ aForm!initialState "Answer the receiver's initial state, on or off." ^initialState!initialState: aBoolean "Set the receiver's initial state, on or off, to be the argument." initialState _ aBoolean!offset "Answer the receiver's offset, its relative position for displaying the button." ^offset!offset: anInteger "Set the receiver's offset." offset _ anInteger!value "Answer the receiver's value, the keyboard key that selects the button." ^value!value: aCharacter "Set the receiver's key character." value _ aCharacter! ! MouseMenuController subclass: #FormEditor instanceVariableNames: 'form tool grid togglegrid mode previousTool color unNormalizedColor xgridOn ygridOn toolMenu underToolMenu ' classVariableNames: 'BitEditKey BlackKey BlockKey ChangeGridsKey CurveKey DarkGrayKey EraseKey FlashCursor GrayKey InKey LightGrayKey LineKey OutKey OverKey RepeatCopyKey ReverseKey SelectKey SingleCopyKey TogglexGridKey ToggleyGridKey UnderKey WhiteKey YellowButtonMenu YellowButtonMessages ' poolDictionaries: '' category: 'Graphics-Editors'!FormEditor comment: 'This is the basic Form Editor provided in Smalltalk for creating and modifying Forms. This is intended to be an easy to use general-purpose picture (bitMap) editor.'!!FormEditor methodsFor: 'initialize-release'!initialize super initialize. self setVariables. self initializeYellowButtonMenu!release super release. toolMenu notNil ifTrue: [toolMenu view release]. toolMenu _ form _ nil! !!FormEditor methodsFor: 'basic control sequence'!controlInitialize toolMenu notNil ifTrue: "check for Galley compatibility" [toolMenu view align: toolMenu view displayBox topCenter with: view displayBox bottomCenter+(0@1). toolMenu view translateBy: (toolMenu view displayBox amountToTranslateWithin: Display boundingBox) x @ 0. underToolMenu _ Form fromDisplay: toolMenu view displayBox. toolMenu view display]. self normalizeColor: unNormalizedColor. sensor waitNoButton!controlTerminate view updateDisplay. toolMenu notNil ifTrue: "check for Galley compatibility" [underToolMenu displayAt: toolMenu view displayBox origin. underToolMenu _ nil].! !!FormEditor methodsFor: 'control defaults'!controlActivity (toolMenu notNil "Galley compatibility" and: [toolMenu isControlWanted]) ifTrue: [^toolMenu startUp]. self viewHasCursor ifTrue: [sensor redButtonPressed ifTrue: [^self redButtonActivity]. sensor yellowButtonPressed ifTrue: [^self yellowButtonActivity]. sensor blueButtonPressed ifTrue: [^self blueButtonActivity]. self dragForm]!isControlActive ^(toolMenu notNil "Galley compatibility" and: [toolMenu isControlWanted]) or: [sensor noButtonPressed or: [sensor blueButtonPressed not and: [self viewHasCursor]]]!isControlWanted ^(toolMenu notNil "Galley compatibility" and: [toolMenu isControlWanted]) or: [self viewHasCursor]! !!FormEditor methodsFor: 'editing tools'!block "Allow the user to fill a rectangle with the gray tone and mode currently selected." | rectangle | rectangle _ Rectangle fromUser: grid. rectangle isNil ifFalse: [Display fill: (rectangle intersect: view insetDisplayBox) rule: mode mask: color]!changeGridding "Allow the user to change the values of the horizontal and(or) vertical grid modules. Does not change the primary tool." | response gridInteger | response _ self promptRequest: 'Current horizontal gridding is: ' , togglegrid x printString , '.Type new horizontal gridding.'. response isEmpty ifFalse: [gridInteger _ Integer readFromString: response. togglegrid x: ((gridInteger max: 1) min: Display extent x)]. response _ self promptRequest: 'Current vertical gridding is: ' , togglegrid y printString , '.Type new vertical gridding.'. response isEmpty ifFalse: [gridInteger _ Integer readFromString: response. togglegrid y: ((gridInteger max: 1) min: Display extent y)]. xgridOn ifTrue: [grid x: togglegrid x]. ygridOn ifTrue: [grid y: togglegrid y]. tool _ previousTool!changeTool: aCharacter "Changes the value of the instance variable tool to be the tool corresponding to aCharacter. Typically sent from a Switch in a FormMenuView. " previousTool _ tool. tool _ self selectTool: aCharacter. (#(singleCopy repeatCopy line curve block) includes: tool) ifFalse: [self perform: tool]!colorBlack "Set the mask (color) to black. Leaves the tool set in its previous state." self normalizeColor: Form black. tool _ previousTool!colorDarkGray "Set the mask (color) to dark gray. Leaves the tool set in its previous state." self normalizeColor: Form darkGray. tool _ previousTool!colorGray "Set the mask (color) to gray. Leaves the tool set in its previous state." self normalizeColor: Form gray. tool _ previousTool!colorLightGray "Set the mask (color) to light gray. Leaves the tool set in its previous state." self normalizeColor: Form lightGray. tool _ previousTool!colorWhite "Set the mask (color) to white. Leaves the tool set in its previous state." self normalizeColor: Form white. tool _ previousTool!curve "Conic-section specified by three points from the mouse. the resultant curve on the display is displayed according to the current form and mode." | firstPoint secondPoint curve | firstPoint _ self cursorPoint. form displayOn: Display at: firstPoint clippingBox: view insetDisplayBox rule: mode mask: color. secondPoint _ self trackFormUntil: [sensor noButtonPressed]. curve _ self rubberBandCurve: firstPoint to: secondPoint until: [sensor redButtonPressed]. curve displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: mode mask: color. sensor waitNoButton!eraseMode "Set the mode for the tools that copy the form onto the display to erase. Leaves the tool set in its previous state." mode _ 4. tool _ previousTool!fileInForm "Ask the user for a file name and then recalls the Form in that file as the current source Form (form). Does not change the tool." | inName directory localName trying newForm | trying _ true. [trying] whileTrue: [inName _ self promptRequest: 'type a name for recalling a source Form . . . '. directory _ FileDirectory directoryFromName: inName setFileName: [:localName]. (((directory isLegalFileName: localName) and: [directory includesKey: localName]) and: [(newForm _ Form readFrom: inName) ~~ nil]) ifTrue: [trying _ false] ifFalse: [trying _ BinaryChoice message: 'File name illegal, or file not found, or file not valid form file.Try again?']]. newForm ~~ nil ifTrue: [form _ newForm]. tool _ previousTool.!fileOutForm "Ask the user for a file name and then save the current source form (form) under that name. Does not change the tool." | outName answer directory localName trying | trying _ true. [trying] whileTrue: [outName _ self promptRequest: 'type a name for saving the source Form . . . '. directory _ FileDirectory directoryFromName: outName setFileName: [:localName]. (directory isLegalFileName: outName) ifTrue: [(directory includesKey: localName) ifTrue: [(BinaryChoice message: 'writing over old file--okay?') ifTrue: [form writeOn: outName]] ifFalse: [form writeOn: outName]. trying _ false] ifFalse: [trying _ BinaryChoice message: 'Bad file name, try again?']]. tool _ previousTool.!line "Rubber-band line is specified by two points from the mouse. The resultant line on the display is displayed according to the current form and mode." | firstPoint endPoint | firstPoint _ self cursorPoint. endPoint _ self rubberBandFrom: firstPoint until: [sensor noButtonPressed]. (Line from: firstPoint to: endPoint withForm: form) displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: mode mask: color!magnify "Allow for bit editing of an area of the Form. The user designates a rectangular area that is scaled by 5 to allow individual screens dots to be modified. red button is used to set a bit to black and yellow button is used to set a bit to white. Editing continues until the user depresses any key on the keyboard." | smallRect smallForm scaleFactor tempRect | scaleFactor _ 8@8. smallRect _ (Rectangle fromUser: grid) intersect: view insetDisplayBox. smallRect isNil ifTrue: [^self]. smallForm _ Form fromDisplay: smallRect. "Do this computation here in order to be able to save the existing display screen." tempRect _ BitEditor locateMagnifiedView: smallForm scale: scaleFactor. BitEditor openScreenViewOnForm: smallForm at: smallRect topLeft magnifiedAt: tempRect topLeft scale: scaleFactor. tool _ previousTool!newSourceForm "Allow the user to define a new sourceForm for the FormEditor. Copying the sourceForm onto the display is the primary graphical operation. Resets the tool to be repeatCopy." form _ Form fromUser: grid. tool _ previousTool!overMode "Set the mode for the tools that copy the form onto the display to over. Leaves the tool set in its previous state." mode _ Form over. tool _ previousTool!repeatCopy "As long as the red button is pressed, copy the source form onto the display screen." [sensor redButtonPressed] whileTrue: [form displayOn: Display at: self cursorPoint clippingBox: view insetDisplayBox rule: mode mask: color]!reverseMode "Set the mode for the tools that copy the form onto the display to reverse. Leaves the tool set in its previous state." mode _ Form reverse. tool _ previousTool!singleCopy form displayOn: Display at: self cursorPoint clippingBox: view insetDisplayBox rule: mode mask: color. sensor waitNoButton!togglexGridding "Turns x (horizontal) gridding off, if it is on, and turns it on, if it is off. Does not change the primary tool." xgridOn ifTrue: [grid x: 1. xgridOn _ false] ifFalse: [grid x: togglegrid x. xgridOn _ true]. tool _ previousTool!toggleyGridding "Turns y (vertical) gridding off, if it is on, and turns it on, if it is off. Does not change the primary tool." ygridOn ifTrue: [grid y: 1. ygridOn _ false] ifFalse: [grid y: togglegrid y. ygridOn _ true]. tool _ previousTool!underMode "Sets the mode for the tools that copy the form onto the display to under. Leaves the tool set in its previous state." mode _ Form under. tool _ previousTool! !!FormEditor methodsFor: 'menu messages'!accept "The edited information should now be accepted by the view." view updateDisplay. view accept!cancel "The edited informatin should be forgotten by the view." view cancel!redButtonActivity Cursor blank showWhile: [self perform: tool]! !!FormEditor methodsFor: 'cursor'!cursorPoint "Answer the mouse coordinate data gridded according to the receiver's grid." ^sensor cursorPoint grid: grid! !!FormEditor methodsFor: 'private'!dragForm tool = #block ifTrue: [Cursor origin showWhile: [[sensor anyButtonPressed or: [sensor keyboardPressed or: [self viewHasCursor not]]] whileFalse: []]. ^ self cursorPoint] ifFalse: [^Cursor blank showWhile: [self trackFormUntil: [sensor anyButtonPressed or: [sensor keyboardPressed or: [self viewHasCursor not]]]]].!initializeYellowButtonMenu self yellowButtonMenu: YellowButtonMenu yellowButtonMessages: YellowButtonMessages!normalizeColor: halftoneForm unNormalizedColor _ halftoneForm. color _ unNormalizedColor wrapAround: view insetDisplayBox origin.!promptRequest: outputMessage "Answers with a string typed by the user on the keyboard. keyboard input is terminated by a line feed character. Typing feedback happens in a window that is at least 100 bits wide and 50 bits high." | answer | FillInTheBlank request: outputMessage displayAt: view insetDisplayBox topCenter + (0@80) centered: true action: [:answer] initialAnswer: ''. ^answer!rubberBandCurve: startPoint to: endPoint until: aBlock | curve previousApex apex | "Return a curve" curve _ Curve new. curve firstPoint: startPoint. curve secondPoint: (previousApex _ self cursorPoint). curve thirdPoint: endPoint. curve form: form. curve displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: Form reverse mask: Form black. [aBlock value] whileFalse: [(apex _ self cursorPoint) = previousApex ifFalse: [curve displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: Form reverse mask: Form black. curve secondPoint: apex. curve displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: Form reverse mask: Form black. previousApex _ apex]]. curve displayOn: Display at: 0 @ 0 clippingBox: view insetDisplayBox rule: Form reverse mask: Form black. ^ curve!rubberBandFrom: startPoint until: aBlock "Show an xor line from startPoint to the cursor point until aBlock evaluates to true, then remove the line and answer the endPoint." | line endPoint | line _ Line from: startPoint to: startPoint withForm: form. line displayOn: Display at: 0@0 clippingBox: view insetDisplayBox rule: Form reverse mask: nil. "display" [aBlock value] whileFalse: [(endPoint _ self cursorPoint) = line endPoint ifFalse: [line displayOn: Display at: 0@0 clippingBox: view insetDisplayBox rule: Form reverse mask: nil. "erase" line endPoint: endPoint. line displayOn: Display at: 0@0 clippingBox: view insetDisplayBox rule: Form reverse mask: nil. "display" ]]. line displayOn: Display at: 0@0 clippingBox: view insetDisplayBox rule: Form reverse mask: nil. "erase" ^line endPoint!selectTool: aCharacter "A new tool has been selected. It is denoted by aCharacter. Set the tool." "This code is written out in long hand (i.e., rather than dispatching on a table of options) so that it is obvious what is happening." aCharacter = SingleCopyKey ifTrue: [^#singleCopy]. aCharacter = RepeatCopyKey ifTrue: [^#repeatCopy]. aCharacter = LineKey ifTrue: [^#line]. aCharacter = CurveKey ifTrue: [^#curve]. aCharacter = BlockKey ifTrue: [^#block]. aCharacter = SelectKey ifTrue: [^#newSourceForm]. aCharacter = OverKey ifTrue: [^#overMode]. aCharacter = UnderKey ifTrue: [^#underMode]. aCharacter = ReverseKey ifTrue: [^#reverseMode]. aCharacter = EraseKey ifTrue: [^#eraseMode]. aCharacter = ChangeGridsKey ifTrue: [^#changeGridding]. aCharacter = TogglexGridKey ifTrue: [^#togglexGridding]. aCharacter = ToggleyGridKey ifTrue: [^#toggleyGridding]. aCharacter = BitEditKey ifTrue: [^#magnify]. aCharacter = WhiteKey ifTrue: [^#colorWhite]. aCharacter = LightGrayKey ifTrue: [^#colorLightGray]. aCharacter = GrayKey ifTrue: [^#colorGray]. aCharacter = DarkGrayKey ifTrue: [^#colorDarkGray]. aCharacter = BlackKey ifTrue: [^#colorBlack]. aCharacter = OutKey ifTrue: [^#fileOutForm]. aCharacter = InKey ifTrue: [^#fileInForm]. ^ #singleCopy!setVariables tool _ #repeatCopy. previousTool _ tool. grid _ 1 @ 1. togglegrid _ 8 @ 8. xgridOn _ false. ygridOn _ false. mode _ Form over. unNormalizedColor _ color _ Form black. form _ Form new extent: 8 @ 8. form black!toolMenu: aController toolMenu _ aController. "Note that the GalleyFormEditor does not set this"!trackFormUntil: aBlock | previousPoint cursorPoint | previousPoint _ self cursorPoint. form displayOn: Display at: previousPoint rule: Form reverse. [aBlock value] whileFalse: [cursorPoint _ self cursorPoint. (FlashCursor or: [cursorPoint ~= previousPoint]) ifTrue: [form displayOn: Display at: previousPoint rule: Form reverse. form displayOn: Display at: cursorPoint rule: Form reverse. previousPoint _ cursorPoint]]. form displayOn: Display at: previousPoint rule: Form reverse. ^ previousPoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FormEditor class instanceVariableNames: ''!!FormEditor class methodsFor: 'class initialization'!flashCursor: aBoolean FlashCursor _ aBoolean "FormEditor flashCursor: true."!initialize "FormEditor initialize." FlashCursor _ false. self setKeyboardMap. YellowButtonMenu _ PopUpMenu labels: 'acceptcancel'. YellowButtonMessages _ #(accept cancel) "FormEditor initialize"! !!FormEditor class methodsFor: 'instance creation'!createOnForm: aForm "Creates a StandardSystemView for a FormEditor on aForm." | formView formEditor menuView topView extent | formView _ FormHolderView new model: aForm. formEditor _ self new. formView controller: formEditor. menuView _ FormMenuView new makeFormEditorMenu model: formEditor. menuView insideColor: Form lightGray. menuView borderWidth: 1. menuView window: (menuView defaultWindow expandBy: 16). formEditor toolMenu: menuView controller. topView _ StandardSystemView new. topView model: aForm. topView addSubView: formView. topView label: 'Form Editor'. topView borderWidth: 2. extent _ topView viewport extent. topView minimumSize: extent. topView maximumSize: extent. ^topView!openFullScreenForm "Create and schedule an instance of me on the form whose extent is the extent of the display screen." | topView | topView _ self createFullScreenForm. topView controller openDisplayAt: (topView viewport extent//2) "FormEditor openFullScreenForm."!openOnForm: aForm "Create and schedule an instance of me on the form aForm." | topView | topView _ self createOnForm: aForm. topView controller open!openOnForm: aForm at: originPoint "Create and schedule an instance of me on the form aForm whose view origin is originPoint." | topView | topView _ self createOnForm: aForm. topView controller openDisplayAt: originPoint + (topView viewport extent//2)! !!FormEditor class methodsFor: 'examples'!formFromDisplay "Create an instance of me on a new form designated by the user at a location designated by the user." Form fromUser edit "FormEditor formFromDisplay."!fullScreen "Create an instance of me on a new form that fills the full size of the display screen." FormEditor openFullScreenForm "FormEditor fullScreen."!newForm "Create an instance of me on a new form at a location designated by the user." (Form new extent: 300@300) edit "FormEditor newForm."!newFormAtOrigin "Create an instance of me on a new form at location 100,100." (Form new extent: 300@300) editAt: 100@100 "FormEditor newFormAtOrigin."! !!FormEditor class methodsFor: 'private'!createFullScreenForm "Create a StandardSystemView for a FormEditor on the form whole screen." ^self createOnForm: (Form new extent: (Display extent x @ (Display extent y - 112)))!setKeyboardMap "Keyboard Mapping" SelectKey_$a. SingleCopyKey_$s. "tools" RepeatCopyKey_$d. LineKey_$f. CurveKey_$g. BlockKey_$h. OverKey_$j. "modes" UnderKey_$k. ReverseKey_$l. EraseKey_$;. InKey_$'. "file In" BitEditKey_$z. WhiteKey_$x. "colors" LightGrayKey_$c. GrayKey_$v. DarkGrayKey_$b. BlackKey_$n. TogglexGridKey_$m. "gridding" ToggleyGridKey_$,. ChangeGridsKey_$.. OutKey_$/ "file Out"! !FormEditor initialize! FormView subclass: #FormHolderView instanceVariableNames: 'displayedForm ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Views'!FormHolderView comment:'I represent a view of a Form. Editing takes place by modifying a working version of the Form. The message accept is used to copy the working version into the Form; the message cancel copies the Form into the working version.Instance Variables: displayedForm <Form> a working version of the Form for cancelable editing'!!FormHolderView methodsFor: 'initialize-release'!release super release. displayedForm release. displayedForm _ nil! !!FormHolderView methodsFor: 'model access'!changeValueAt: location put: anInteger displayedForm valueAt: location put: anInteger. displayedForm changed: self!model: aForm super model: aForm. displayedForm _ aForm deepCopy!workingForm "Answer the Form that is currently being displayed--the working version in which edits are carried out." ^displayedForm! !!FormHolderView methodsFor: 'displaying'!displayView "This method displays the Form associated with this View according to the rule and mask specifed by this class." | oldOffset | oldOffset _ displayedForm offset. displayedForm offset: 0@0. displayedForm displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox rule: self rule mask: self mask. displayedForm offset: oldOffset!updateDisplay "The working version is redefined by copying the bits displayed in the receiver's display area." displayedForm fromDisplay: self insetDisplayBox. displayedForm changed: self.! !!FormHolderView methodsFor: 'menu messages'!accept model copyBits: displayedForm boundingBox from: displayedForm at: 0 @ 0 clippingBox: model boundingBox rule: Form over mask: Form black. model changed: self!cancel displayedForm become: model deepCopy. displayedForm changed: self. self display! ! Controller subclass: #FormMenuController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Editors'!FormMenuController comment: 'Adds keyboard mapping to the menu selection.'!!FormMenuController methodsFor: 'control defaults'!controlActivity "Pass control to a subView corresponding to a pressed keyboard key or to a mouse button pressed, if any." sensor keyboardPressed ifTrue: [self processMenuKey] ifFalse: [self controlToNextLevel]!isControlActive "Answer false if the blue mouse button is pressed and the cursor is outside of the inset display box of the Controller's view; answer true, otherwise." ^sensor keyboardPressed | (view containsPoint: sensor cursorPoint) & sensor blueButtonPressed not!isControlWanted "Answer true if the cursor is inside the inset display box (see View|insetDisplayBox) of the receiver's view, and answer false, otherwise. It is sent by Controller|controlNextLevel in order to determine whether or not control should be passed to this receiver from the Controller of the superView of this receiver's view." ^sensor keyboardPressed | self viewHasCursor!processMenuKey "The user typed a key on the keyboard. Give control to the subView that is selected by this key." | aView | aView _ view subViewContainingCharacter: sensor keyboard. aView ~~ nil ifTrue: [aView controller sendMessage]! ! View subclass: #FormMenuView instanceVariableNames: '' classVariableNames: 'BorderForm FormButtons SpecialBorderForm ' poolDictionaries: '' category: 'Graphics-Editors'!FormMenuView comment:'I represent a View whose subViews are Switches (Buttons or OneOnSwitches) whose actions set the mode, color, and tool for editing a Form on the screen. The default controller of my instances is FormMenuController.'!!FormMenuView methodsFor: 'initialize-release'!makeFormEditorMenu | button buttonCache form aSwitchView aSwitchController| "Now get those forms into the subviews" self makeButton: 1. "form source" self makeConnections: (2 to: 6). "tools" self makeConnections: (7 to: 10). "modes" self makeButton: 11. "filing in" self makeButton: 12. "bit editing" self makeColorConnections: (13 to: 17). "colors" self makeGridSwitch: 18. "toggle x" self makeGridSwitch: 19. "toggle y" self makeButton: 20. "setting grid" self makeButton: 21 "filing out"! !!FormMenuView methodsFor: 'subView access'!subViewContainingCharacter: aCharacter "Answer the receiver's subView that corresponds to the key, aCharacter. Answer nil if no subView is selected by aCharacter." self subViews reverseDo: [:aSubView | (aSubView containsKey: aCharacter) ifTrue: [^aSubView]]. ^nil! !!FormMenuView methodsFor: 'controller access'!defaultControllerClass ^FormMenuController! !!FormMenuView methodsFor: 'private'!makeButton: index | button buttonCache aSwitchView| buttonCache _ FormButtons at: index. button _ Button newOff. button onAction: [model changeTool: buttonCache value]. aSwitchView _ self makeViews: buttonCache for: button. aSwitchView controller: IndicatorOnSwitchController new!makeColorConnections: indexInterval | connector button buttonCache aSwitchView | connector _ Object new. "A dummy model for connecting dependents" indexInterval do: [:index | buttonCache _ FormButtons at: index. buttonCache initialState = #true ifTrue: [button _ OneOnSwitch newOn] ifFalse: [button _ OneOnSwitch newOff]. button onAction: [model changeTool: buttonCache value]. button connection: connector. aSwitchView _ self makeViews: buttonCache for: button. aSwitchView highlightForm: BorderForm. aSwitchView borderWidthLeft: 1 right: 0 top: 1 bottom: 1. aSwitchView controller selector: #turnOn]. aSwitchView highlightForm: SpecialBorderForm. aSwitchView borderWidth: 1.!makeConnections: indexInterval | connector button buttonCache aSwitchView | connector _ Object new. "A dummy model for connecting dependents." indexInterval do: [:index | buttonCache _ FormButtons at: index. buttonCache initialState = #true ifTrue: [button _ OneOnSwitch newOn] ifFalse: [button _ OneOnSwitch newOff]. button onAction: [model changeTool: buttonCache value]. button connection: connector. aSwitchView _ self makeViews: buttonCache for: button. aSwitchView borderWidthLeft: 1 right: 0 top: 1 bottom: 1. aSwitchView controller selector: #turnOn]. aSwitchView borderWidth: 1.!makeGridSwitch: index | button buttonCache | buttonCache _ FormButtons at: index. buttonCache initialState = #true ifTrue: [button _ Switch newOn] ifFalse: [button _ Switch newOff]. button onAction: [model changeTool: buttonCache value]. button offAction: [model changeTool: buttonCache value]. self makeViews: buttonCache for: button!makeSwitch: index | button buttonCache | buttonCache _ FormButtons at: index. buttonCache initialState = #true ifTrue: [button _ Switch newOn] ifFalse: [button _ Switch newOff]. button onAction: [model changeTool: buttonCache value]. self makeViews: buttonCache for: button!makeViews: cache for: aSwitch | form aSwitchView | form _ cache form. aSwitchView _ SwitchView new model: aSwitch. aSwitchView key: cache value. aSwitchView label: form. aSwitchView window: (0@0 extent: form extent). aSwitchView translateBy: cache offset. aSwitchView borderWidth: 1. aSwitchView insideColor: Form white. self addSubView: aSwitchView. ^aSwitchView! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FormMenuView class instanceVariableNames: ''!!FormMenuView class methodsFor: 'class initialization'!initialize "The forms for the menu are typically stored on files. In order to avoid reading them every time, they are stored in a collection that is a class variable, along with the offset, tool value, and initial visual state (on or off), that makes up the view of the form in the menu view." | offsets keys names formButton states | offsets _ OrderedCollection new: 21. #( 0 64 96 128 160 192 256 288 320 352 420) do: [:i | offsets addLast: i@0]. "First row" #( 0 64 96 128 160 192 256 304 352 420) do: [:i | offsets addLast: i@48]. "Second row" offsets _ offsets asArray. keys _ #($a $s $d $f $g $h $j $k $l $; $' $z $x $c $v $b $n $m $, $. $/ ). "Keyboard" states _ #(false false true false false false true false false false false false false false false false true false false false false ). "Initial states of buttons" names _ #('select.form.' 'singlecopy.form.' 'repeatcopy.form.' 'line.form.' 'curve.form.' 'block.form' 'over.form.' 'under.form.' 'reverse.form.' 'erase.form.' 'in.form.' 'magnify.form.' 'white.form' 'lightgray.form' 'gray.form' 'darkgray.form' 'black.form' 'xgrid.form.' 'ygrid.form.' 'togglegrids.form.' 'out.form.' ). "Files of button images" FormButtons _ OrderedCollection new. 1 to: 21 do: [:index | formButton _ FormButtonCache new. formButton form: (Form readFrom: (names at: index)). formButton offset: (offsets at: index). formButton value: (keys at: index). formButton initialState: (states at: index). FormButtons addLast: formButton]. SpecialBorderForm _ Form readFrom: 'specialborderform.form'. BorderForm _ Form readFrom: 'borderform.form' "FormMenuView initialize"! !FormMenuView initialize! View subclass: #FormView instanceVariableNames: 'rule mask ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Views'!FormView comment: 'This class has as its model a Form. It is used mainly to allow display of Forms on the display screen in the model-view-controller metaphor.'!!FormView methodsFor: 'accessing'!mask "Answer an instance of class Form that is the mask used when displaying the receiver's model (a Form) on the display screen (see BitBlt for the meaning of this mask)." mask == nil ifTrue: [^self defaultMask] ifFalse: [^mask]!mask: aForm "Set the display mask for displaying the receiver's model." mask _ aForm!rule "Answer a number from 0 to 15 that indicates which of the sixteen display rules (logical function of two boolean values) is to be used when copying the receiver's model (a Form) onto the display screen." rule == nil ifTrue: [^self defaultRule] ifFalse: [^rule]!rule: anInteger "Set the display rule for the receiver." rule _ anInteger! !!FormView methodsFor: 'controller access'!defaultControllerClass ^FormEditor! !!FormView methodsFor: 'model access'!changeValueAt: location put: anInteger "The receiver's model is a Form which has an array of bits. Change the bit at index location to be anInteger (either 1 or 0). Inform all objects that depend on the model that it has changed." model valueAt: location put: anInteger. model changed: self! !!FormView methodsFor: 'window access'!defaultWindow ^(Rectangle origin: 0 @ 0 extent: model extent) expandBy: borderWidth! !!FormView methodsFor: 'displaying'!displayView | oldOffset | super displayView. insideColor == nil ifFalse: [Display fill: self insetDisplayBox mask: insideColor]. oldOffset _ model offset. model offset: 0@0. model displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox rule: self rule mask: self mask. model offset: oldOffset! !!FormView methodsFor: 'updating'!update: aFormView self == aFormView ifFalse: [self display]! !!FormView methodsFor: 'menu messages'!accept "The receiver's model is set to the working version, the one in which edits are carried out." ^self!cancel "Set the working form to be a copy of the model." ^self! !!FormView methodsFor: 'private'!defaultMask "The default display mask, blackMask, is a 16x16 Form that is all ones" ^Form black!defaultRule "This is the default display rule (3=over or storing)" ^Form over! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!FormView class instanceVariableNames: ''!!FormView class methodsFor: 'examples'!exampleOne "Frame a Form (specified by the user) with a border of 5 bits in width and display it offset 100 x 100 from the corner of the display screen." | f view | f _ Form fromUser. view _ self new model: f. view translateBy: 100 @ 100. view borderWidth: 2. view insideColor: Form white. view display. view release "FormView exampleOne."!exampleTwo "Frame a Form (specified by the user) that is scaled by 2. The border is 2 bits in width. Displays at locatoin 100,100." | f view | f _ Form fromUser. view _ self new model: f. view scaleBy: 2.0. "if you eliminate this message, no inside border displays" view translateBy: 100 @ 100. view borderWidth: 2. view insideColor: Form white. view display. view release "FormView exampleTwo."! ! Number subclass: #Fraction instanceVariableNames: 'numerator denominator ' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Numbers'!Fraction comment: 'I represent some rational number as a fraction. All public arithmetic operations return reduced fractions.'!!Fraction methodsFor: 'arithmetic'!* aFraction (aFraction isMemberOf: Fraction) ifTrue: [^(Fraction numerator: numerator * aFraction numerator denominator: denominator * aFraction denominator) reduced] ifFalse: [^self retry: #* coercing: aFraction]!+ aFraction | commonDenominator newNumerator | (aFraction isMemberOf: Fraction) ifTrue: [denominator = aFraction denominator ifTrue: [^(Fraction numerator: numerator + aFraction numerator denominator: denominator) reduced]. commonDenominator _ denominator lcm: aFraction denominator. newNumerator _ numerator * (commonDenominator / denominator) + (aFraction numerator * (commonDenominator / aFraction denominator)). ^(Fraction numerator: newNumerator denominator: commonDenominator) reduced] ifFalse: [^self retry: #+ coercing: aFraction]!- aFraction (aFraction isMemberOf: Fraction) ifTrue: [^self + aFraction negated] ifFalse: [^self retry: #- coercing: aFraction]!/ aFraction (aFraction isMemberOf: Fraction) ifTrue: [^self * aFraction reciprocal] ifFalse: [^self retry: #/ coercing: aFraction]!negated ^Fraction numerator: numerator negated denominator: denominator!reciprocal numerator = 0 ifTrue: [self error: '0 has no reciprocal']. numerator = 1 ifTrue: [^denominator]. numerator = -1 ifTrue: [^denominator negated]. ^Fraction numerator: denominator denominator: numerator! !!Fraction methodsFor: 'comparing'!< aFraction (aFraction isMemberOf: Fraction) ifTrue: [aFraction numerator = 0 ifTrue: [^numerator < 0] ifFalse: [^self - aFraction < 0]] ifFalse: [^self retry: #< coercing: aFraction]!= aFraction (aFraction isMemberOf: Fraction) ifTrue: [aFraction numerator = 0 ifTrue: [^numerator = 0] ifFalse: [^aFraction numerator = numerator and: [aFraction denominator = denominator]]] ifFalse: [^self retry: #= coercing: aFraction]!hash "Hash is reimplemented because = is implemented." ^numerator bitXor: denominator! !!Fraction methodsFor: 'truncation and round off'!truncated ^numerator quo: denominator! !!Fraction methodsFor: 'coercing'!coerce: aNumber ^aNumber asFraction!generality ^60! !!Fraction methodsFor: 'converting'!asFloat "Answer with a new Float that represents the same value as does the receiver." ^numerator asFloat / denominator asFloat!asFraction "Answer with the receiver itself." ^self! !!Fraction methodsFor: 'printing'!printOn: aStream aStream nextPut: $(. numerator printOn: aStream. aStream nextPut: $/. denominator printOn: aStream. aStream nextPut: $)! !!Fraction methodsFor: 'private'!denominator ^denominator!numerator ^numerator!reduced | gcd numer denom | numerator = 0 ifTrue: [^0]. gcd _ numerator gcd: denominator. numer _ numerator // gcd. denom _ denominator // gcd. denom = 1 ifTrue: [^numer]. ^Fraction numerator: numer denominator: denom!setNumerator: n denominator: d d = 0 ifTrue: [self error: 'denominator cannot be zero'] ifFalse: [numerator _ n truncated. denominator _ d truncated abs. "keep sign in numerator" d < 0 ifTrue: [numerator _ numerator negated]]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Fraction class instanceVariableNames: ''!!Fraction class methodsFor: 'instance creation'!numerator: numInteger denominator: denInteger "Answer a new Fraction denInteger/numInteger." ^self new setNumerator: numInteger denominator: denInteger! ! Dictionary variableSubclass: #IdentityDictionary instanceVariableNames: 'valueArray ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Unordered'!IdentityDictionary comment: 'I am a subclass of Dictionary in which the lookup is done using == rather than =. I am represented as two parallel ordered collections of keys and values, rather than as a single collection of associations.'!!IdentityDictionary methodsFor: 'accessing'!associationAt: key ifAbsent: aBlock "Answer with an Association consisting of key and my value at that key. If key is not found, evaluate aBlock." | index | index _ self findKey: key ifAbsent: [^aBlock value]. ^Association key: (self basicAt: index) value: (valueArray at: index)!at: key ifAbsent: aBlock "Answer with the value at key. If key is not found, evaluate aBlock." | index | index _ self findKey: key ifAbsent: [^aBlock value]. ^valueArray at: index!at: key put: value "Set the value at key to be value." | index | index _ self findKeyOrNil: key. (self basicAt: index) == nil ifTrue: [tally _ tally + 1. self basicAt: index put: key]. valueArray at: index put: value. self fullCheck. ^value!keyAtValue: value ifAbsent: exceptionBlock "Answer the key whose value equals the argument, value. If there is none, answer the result of evaluating exceptionBlock." | theKey | 1 to: self basicSize do: [:index | value == (valueArray at: index) ifTrue: [(theKey _ self basicAt: index) == nil ifFalse: [^theKey]]]. ^exceptionBlock value! !!IdentityDictionary methodsFor: 'adding'!add: anAssociation self at: anAssociation key put: anAssociation value! !!IdentityDictionary methodsFor: 'copying'!copy | v copy | v _ valueArray. valueArray _ valueArray shallowCopy. copy _ super shallowCopy. valueArray _ v. ^copy! !!IdentityDictionary methodsFor: 'enumerating'!do: aBlock 1 to: self basicSize do: [:index | (self basicAt: index) == nil ifFalse: [aBlock value: (valueArray at: index)]]! !!IdentityDictionary methodsFor: 'dictionary removing'!removeKey: key ifAbsent: errorBlock self removeDangerouslyKey: key ifAbsent: [^errorBlock value]! !!IdentityDictionary methodsFor: 'dictionary enumerating'!associationsDo: aBlock "Evaluate aBlock for associations consisting of my keys and their values." 1 to: self basicSize do: [:index | (self basicAt: index) == nil ifFalse: [aBlock value: (Association key: (self basicAt: index) value: (valueArray at: index))]]! !!IdentityDictionary methodsFor: 'private'!findKeyOrNil: key | index length probe pass | length _ self basicSize. pass _ 1. index _ key asOop \\ length + 1. [(probe _ self basicAt: index) == nil or: [probe == key]] whileFalse: [(index _ index + 1) > length ifTrue: [index _ 1. pass _ pass + 1. pass > 2 ifTrue: [^self grow findKeyOrNil: key]]]. ^index!noCheckAdd: anAssociation ^self noCheckAdd: anAssociation key with: anAssociation value!noCheckAdd: key with: value | index | index _ self findKeyOrNil: key. self basicAt: index put: key. tally _ tally + 1. ^valueArray at: index put: value!removeDangerouslyKey: key ifAbsent: errorBlock | location oldKey length entry | location _ self findKeyOrNil: key. (self basicAt: location) == nil ifTrue: [^errorBlock value]. self basicAt: location put: nil. valueArray at: location put: nil. tally _ tally - 1. length _ self basicSize. [location _ location = length ifTrue: [1] ifFalse: [location + 1]. (self basicAt: location) == nil] whileFalse: [oldKey _ self findKeyOrNil: (self basicAt: location). location = oldKey ifFalse: [self swap: location with: oldKey]]!setTally super setTally. valueArray _ Array new: self basicSize!swap: oneElement with: otherElement super swap: oneElement with: otherElement. valueArray swap: oneElement with: otherElement! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!IdentityDictionary class instanceVariableNames: ''!!IdentityDictionary class methodsFor: 'instance creation'!new: size "Answer with a new instance of me, whose initial capacity is size. Size must be a power of 2." (size bitAnd: size - 1) = 0 ifFalse: [self error: 'size must be a power of 2']. size >= 1 ifFalse: [self error: 'size must be >= 1']. ^super new: size! ! Set variableSubclass: #IdentitySet instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Unordered'!IdentitySet comment:'Just like Set, but uses == instead of = for comparisons'!!IdentitySet methodsFor: 'private'!findElementOrNil: anObject "Copied from Set with equality check changed to identity" | index length probe pass | length _ self basicSize. pass _ 1. index _ anObject hash \\ length + 1. [(probe _ self basicAt: index) == nil or: [probe == anObject]] whileFalse: [(index _ index + 1) > length ifTrue: [index _ 1. pass _ pass + 1. pass > 2 ifTrue: [^self grow findElementOrNil: anObject]]]. ^index! ! SwitchController subclass: #IndicatorOnSwitchController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!IndicatorOnSwitchController comment:'I am a SwitchController that has its View (a SwitchView) highlighted while the model (a Switch) handles the messages it is sent.'!!IndicatorOnSwitchController methodsFor: 'basic control sequence'!sendMessage arguments size = 0 ifTrue: [view indicatorOnDuring: [model perform: selector]] ifFalse: [view indicatorOnDuring: [model perform: selector withArguments: arguments]]! ! DisplayObject subclass: #InfiniteForm instanceVariableNames: 'patternForm ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!InfiniteForm comment:'I represent a Form obtained by replicating a pattern form indefinitely in all directions.'!!InfiniteForm methodsFor: 'accessing'!form: aForm patternForm _ aForm!offset ^0 @ 0! !!InfiniteForm methodsFor: 'displaying'!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "This is the real display message, but it doesn't get used until the new display protocol is installed." | targetBox patternBox | (aForm == Form black and: [patternForm extent = (16 @ 16)]) ifTrue: ["Use patternForm as a mask for BitBlt" aDisplayMedium fill: clipRectangle rule: ruleInteger mask: patternForm] ifFalse: ["Do it iteratively" targetBox _ aDisplayMedium boundingBox intersect: clipRectangle. patternBox _ patternForm boundingBox. (targetBox left truncateTo: patternBox width) to: targetBox right - 1 by: patternBox width do: [:x | (targetBox top truncateTo: patternBox height) to: targetBox bottom - 1 by: patternBox height do: [:y | patternForm displayOn: aDisplayMedium at: x @ y clippingBox: clipRectangle rule: ruleInteger mask: aForm]]]! !!InfiniteForm methodsFor: 'display box access'!computeBoundingBox ^0 @ 0 corner: SmallInteger maxVal @ SmallInteger maxVal! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!InfiniteForm class instanceVariableNames: ''!!InfiniteForm class methodsFor: 'instance creation'!with: aForm ^self new form: aForm! ! Object subclass: #InputSensor instanceVariableNames: 'keyboardMap ' classVariableNames: 'CurrentCursor CurrentInputState DefaultKeyboardMap ' poolDictionaries: '' category: 'System-Support'!InputSensor comment:'I represent an interface to the user input devices. There is at least one instance of me named Sensor in the system. keyboardMap - <String> indexed by (256 * meta key state + ASCII code + 1)'!!InputSensor methodsFor: 'keyboard'!flushKeyboard "Remove all characters from the keyboard buffer." [self keyboardPressed] whileTrue: [self keyboard]!keyboard "Answer the next character from the keyboard buffer as a fully decoded (ASCII) character." ^self mapKeyboardEvent: self primKbdNext!keyboardEvent "Answer the next character from the keyboard buffer as a KeyboardEvent." ^self primKbdNext!keyboardPeek "Answer the next character in the keyboard buffer or false if it is empty. self keyboardPressed must be true, else an error is created." self keyboardPressed ifTrue: [^self mapKeyboardEvent: self primKbdPeek]. self error: 'Cant peek when nothing there'!keyboardPressed "Answer false if the keyboard buffer is empty, else true." ^self primKbdPeek notNil "The keyboard queue only contains real keystrokes, so just test if it is non-empty."!leftShiftDown "Answer true if the left shift key on the keyboard is being held down." ^self primLeftShiftDown!mapKeyboardEvent: aKeyboardEvent "Answer the character corresponding to the character in aKeyboardEvent" | meta | meta _ aKeyboardEvent hasShift ifTrue: [256] ifFalse: [0]. aKeyboardEvent hasCtrl ifTrue: [meta _ meta + 512]. meta = 0 ifTrue: [aKeyboardEvent hasLock ifTrue: [meta _ 1024]]. ^keyboardMap at: aKeyboardEvent keyCharacter asciiValue + meta + 1! !!InputSensor methodsFor: 'mouse'!anyButtonPressed "Answer whether a mouse button is being pressed." ^self buttons > 0!blueButtonPressed "Answer whether only the blue mouse button is being pressed." ^self buttons = 1!mousePoint "Answer a Point indicating the coordinates of the current mouse location." ^self primMousePt!mousePointNext "Answer the next mouse point if red button or tablet is down; false otherwise." self redButtonPressed ifTrue: [^self mousePoint]. ^false!noButtonPressed "Answer whether any mouse button is not being pressed." ^self anyButtonPressed == false!redButtonPressed "Answer whether only the red mouse button is being pressed." ^self buttons = 4!waitButton "Wait for the user to press any mouse button and then answer with the current location of the cursor." [self anyButtonPressed] whileFalse. ^self cursorPoint!waitClickButton "Wait for the user to click (press and then release) any mouse button and then answer with the current location of the cursor." self waitButton. ^self waitNoButton!waitNoButton "Wait for the user to release any mouse button and then answer with the current location of the cursor." [self anyButtonPressed] whileTrue. ^self cursorPoint!yellowButtonPressed "Answer whether only the yellow mouse button is being pressed." ^self buttons = 2! !!InputSensor methodsFor: 'current cursor'!currentCursor "Answer the instance of Cursor currently displayed." ^CurrentCursor!currentCursor: newCursor "Set newCursor to be the displayed Cursor form." CurrentCursor offset = newCursor offset ifFalse: [self primCursorLocPut: self cursorPoint + newCursor offset]. CurrentCursor _ newCursor. Cursor currentCursor: CurrentCursor!cursorPoint "Answer a Point indicating the cursor location." ^self mousePoint - CurrentCursor offset!cursorPoint: aPoint "Set aPoint to be the current cursor location." ^self primCursorLocPut: aPoint + CurrentCursor offset! !!InputSensor methodsFor: 'private'!buttons ^self primMouseButtons!initMap "Initialize a new instance with the default keyboard map" keyboardMap _ DefaultKeyboardMap!primCursorLocPut: pt CurrentInputState cursorPoint: pt!primKbdNext ^CurrentInputState keyboardNext!primKbdPeek ^CurrentInputState keyboardPeek!primLeftShiftDown ^CurrentInputState leftShiftDown!primMouseButtons ^CurrentInputState mouseButtons!primMousePt "Poll the mouse to find out its position. Return a Point. Fail if event-driven tracking is used instead of polling. Optional. See Object documentation whatIsAPrimitive. " <primitive: 90> ^CurrentInputState mousePoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!InputSensor class instanceVariableNames: ''!!InputSensor class methodsFor: 'class initialization'!initialize | map base array | map _ String new: 256*5. 1 to: map size do: [:i | map at: i put: 255 asCharacter]. "Unassigned" #( "Unshifted characters" (0 8 (8 9 30 255 255 13 255 255 255 255 255 255 255 255 255 255 255 255 255 160)) (0 32 ' !!"#$%&''()*+,-./0123456789:;<=>?') (0 64 '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_') (0 96 '`abcdefghijklmnopqrstuvwxyz{|}~') (0 127 (173)) (0 140 (158 29 25 174 187 190)) "Shift" (256 8 (8 9 30 255 255 13 255 255 255 255 255 255 255 255 255 255 255 255 255 160)) (256 32 ' ') (256 $' '"') (256 $, '<') (256 $- (21)) (256 $. '>?') (256 $0 ')!!@#$%~&*(') (256 $; ':') (256 $= '+') (256 $[ '{|}') (256 $_ '^') (256 $a 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') (256 127 (173)) (256 140 (22 29 25 238 253 254)) "Control" (512 8 (8 9 30 255 255 141 255 255 255 255 255 255 255 255 255 255 255 255 255 160)) (512 32 (32 255 255 255 255 255 255 15 255 255 255 255 1 137 18 27 135 159 144 143 128 127 129 131 180 149 255 3 255 6 255 255)) (512 $[ (7 14 23 255 17)) (512 $a "through $z" (1 166 3 132 130 12 231 179 150 165 136 153 182 14 15 138 17 18 19 11 21 134 145 151 178 167)) (512 127 (173)) (512 140 (222 229 225 174 187 190)) "Shift+control" (768 8 (8 9 30 255 255 13 255 255 255 255 255 255 255 255 255 255 255 255 255 160)) (768 32 (32 255 255 255 255 255 255 219 255 255 255 255 218 201 233 203 199 223 208 207 192 191 193 195 244 213 255 3 255 14 255 255)) (768 $[ (249 204 220 255 236)) (768 $a "through $z" (212 230 228 196 194 226 241 243 214 229 200 217 246 245 216 202 210 239 211 240 197 198 209 215 242 231)) (768 127 (173)) (768 140 (22 24 25 238 253 254)) "Upper case lock" (1024 8 (8 9 30 255 255 13 255 255 255 255 255 255 255 255 255 255 255 255 255 160)) (1024 32 ' !!"#$%&''()*+,-./0123456789:;<=>?') (1024 64 '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_') (1024 96 '`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~') (1024 127 (173)) (1024 140 (158 29 25 174 187 190)) ) do: [:part | base _ (part at: 1) + (part at: 2) asInteger. array _ part at: 3. 1 to: array size do: [:i | map at: base + i put: (array at: i) asCharacter]]. DefaultKeyboardMap _ map "InputSensor initialize; install. Sensor initMap."!install "Create an instance of InputState for accessing the hardware, and save it in the class variable CurrentInputState." CurrentInputState _ InputState new. CurrentInputState install! !!InputSensor class methodsFor: 'instance creation'!new ^super new initMap! !!InputSensor class methodsFor: 'constants'!default "Answer the default system InputSensor, Sensor." ^Sensor!initSensor "Create the default system InputSensor, Sensor." Sensor _ InputSensor new! !InputSensor initialize! Object subclass: #InputState instanceVariableNames: 'x y bitState lshiftState rshiftState ctrlState lockState metaState keyboardQueue deltaTime baseTime timeProtect ' classVariableNames: 'BitMax BitMin CtrlKey InputProcess InputSemaphore LockKey LshiftKey RshiftKey ' poolDictionaries: '' category: 'System-Support'!InputState comment:'I represent the state of the user input devices.Instance Variables: x <Integer> mouse X location y <Integer> mouse Y location bitState <Integer> mouse button and keyset state lshiftState <1 or 0> state of left shift key rshiftState <1 or 0> state of right shift key ctrlState <2 or 0> state of ctrl key lockState <4 or 0> state of shift-lock key metaState <Integer> combined state of the meta keys keyboardQueue <SharedQueue> of keyboard characters deltaTime <Integer> sampling ticks since last setting of baseTime baseTime <Integer> millisecond timer at last resync '!!InputState methodsFor: 'initialize-release'!install "Initialize and connect the receiver to the hardware. Terminate the old input process if any." InputProcess == nil ifFalse: [InputProcess terminate]. self initState. InputSemaphore _ Semaphore new. InputProcess _ [self run] newProcess. InputProcess priority: Processor lowIOPriority. InputProcess resume. self primInputSemaphore: InputSemaphore! !!InputState methodsFor: 'keyboard'!keyboardNext "Remove and answer the next key in the keyboard buffer." ^keyboardQueue next!keyboardPeek "Answer the next key in the keyboard buffer but do not remove it." ^keyboardQueue peek!leftShiftDown "Answer whether the left shift key is down." ^lshiftState ~= 0! !!InputState methodsFor: 'mouse'!mouseButtons "Answer the status of the mouse buttons--an Integer between 0 and 7." ^bitState bitAnd: 7!mousePoint "Answer the coordinates of the mouse location." ^self primMousePt! !!InputState methodsFor: 'cursor'!cursorPoint: aPoint "Set the current cursor position to be aPoint." self primCursorLocPut: aPoint. x _ aPoint x. y _ aPoint y! !!InputState methodsFor: 'time'!currentTime "Answer the time on the system clock in milliseconds since midnight." timeProtect critical: [deltaTime = 0 ifFalse: [baseTime _ baseTime + (deltaTime * 1000 // 60). deltaTime _ 0]]. ^baseTime! !!InputState methodsFor: 'private'!initState timeProtect _ Semaphore forMutualExclusion. timeProtect critical: [deltaTime _ baseTime _ 0]. x _ y _ 0. keyboardQueue _ SharedQueue new: 50. ctrlState _ lshiftState _ rshiftState _ lockState _ metaState _ 0. bitState _ 0!keyAt: index put: value | mask | index < 8r200 ifTrue: "Not a potential special character" [value ~= 0 ifTrue: [(index = $c asciiValue and: [ctrlState ~= 0]) ifTrue: [lshiftState ~= 0 ifTrue: [self forkEmergencyEvaluatorAt: Processor userInterruptPriority] ifFalse: [[ScheduledControllers interruptName: 'User Interrupt'] fork]] ifFalse: [^keyboardQueue nextPut: (KeyboardEvent code: index meta: metaState)]]] ifFalse: [index = CtrlKey ifTrue: [ctrlState _ value bitShift: 1] ifFalse: [index = LshiftKey ifTrue: [lshiftState _ value] ifFalse: [index = RshiftKey ifTrue: [rshiftState _ value] ifFalse: [index = LockKey ifTrue: [lockState _ value bitShift: 2] ifFalse: [(index >= BitMin and: [index <= BitMax]) ifTrue: [mask _ 1 bitShift: index - BitMin. value = 1 ifTrue: [bitState _ bitState bitOr: mask] ifFalse: [bitState _ bitState bitAnd: -1 - mask]] ifFalse: [value ~= 0 ifTrue: [keyboardQueue nextPut: (KeyboardEvent code: index meta: metaState)]]]]]]. metaState _ (ctrlState bitOr: (lshiftState bitOr: rshiftState)) bitOr: lockState]!nextEvent: type with: param "Process a single input event, aside from mouse X/Y" | highTime lowTime | type = 0 "Delta time" ifTrue: [timeProtect critical: [deltaTime _ deltaTime + param]] ifFalse: [type = 3 "Key down" ifTrue: [self keyAt: param put: 1] ifFalse: [type = 4 "Key up" ifTrue: [self keyAt: param put: 0] ifFalse: [type = 5 "Reset time" ifTrue: [InputSemaphore wait. highTime _ self primInputWord. InputSemaphore wait. lowTime _ self primInputWord. timeProtect critical: [baseTime _ (highTime bitShift: 16) + lowTime. deltaTime _ 0]] ifFalse: [self error: 'Bad event type']]]]!primCursorLocPut: aPoint "Move the cursor to the screen location specified by the argument. Fail if the argument is not a Point. Essential. See Object documentation whatIsAPrimitive. " <primitive: 91> ^self primCursorLocPutAgain: aPoint rounded!primCursorLocPutAgain: aPoint "By this time, aPoint better be an integer or get out of here" <primitive: 91> ^self primitiveFailed!primInputSemaphore: aSemaphore "Install the argument (a Semaphore) as the object to be signalled whenever an input event occurs. The semaphore will be signaled once for every word placed in the input buffer by an I/O device. Fail if the argument is neither a Semaphore nor nil. Essential. See Object whatIsAPrimitive." <primitive: 93> ^self primitiveFailed!primInputWord "Return the next word from the input buffer and remove the word from the buffer. This message should be sent just after the input semaphore finished a wait (was sent a signal by an I/O device). Fail of the input buffer is empty. Essential. See Object documentation whatIsAPrimitive." <primitive: 95> ^self primitiveFailed!primMousePt "Poll the mouse to find out its position. Return a Point. Fail if event-driven tracking is used instead of polling. Optional. See Object documentation whatIsAPrimitive. " <primitive: 90> ^x @ y!primSampleInterval: anInteger "Set the minimum time span between event driven mouse position samples. The argument is a number of milliseconds. Fail if the argument is not a SmallInteger. Essential. See Object documentation whatIsAPrimitive. " <primitive: 94> ^self primitiveFailed!run "This is the loop that actually processes input events." | word type param | [true] whileTrue: [InputSemaphore wait. "Test for mouse X/Y events here to avoid an activation." word _ self primInputWord. type _ word bitShift: -12. param _ word bitAnd: 4095. type = 1 ifTrue: [x _ param "Mouse X"] ifFalse: [type = 2 ifTrue: [y _ param "Mouse Y"] ifFalse: [self nextEvent: type with: param]]]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!InputState class instanceVariableNames: ''!!InputState class methodsFor: 'class initialization'!initialize "Define parameters" BitMin _ 8r200. "Min mouse/keyset bit code" BitMax _ 8r207. "Max mouse/keyset bit code" LshiftKey _ 8r210. RshiftKey _ 8r211. CtrlKey _ 8r212. LockKey _ 8r213! !InputState initialize! Object subclass: #Inspector instanceVariableNames: 'object field ' classVariableNames: 'ListMenu TextMenu ' poolDictionaries: '' category: 'Interface-Inspector'!Inspector comment:'I represent a query path into the internal representation of an object. The value of fieldscan be inspected by selecting the field name, and can be changed using ''accept''.Instance Variables: object any object to be queried field <String> name of field being viewed'!!Inspector methodsFor: 'initialization'!inspect: anObject anObject == object ifTrue: [^ self update]. object _ anObject. self changed: #field!object "Answer the object being inspected by the receiver." ^object! !!Inspector methodsFor: 'field list'!field ^ field!field: selection field _ selection. self changed: #text!fieldIndex "Answer the offset corresponding to the currently selected field." field first isDigit ifTrue: [^ Integer readFromString: field] ifFalse: [^ object class allInstVarNames indexOf: field]!fieldList "Answer an Array consisting of 'self' and the instance variable names of the inspected object. Up to 40 indices are given for variable length objects." | max | max _ object basicSize. ^(Array with: 'self'), object class allInstVarNames, ((max <= 40 ifTrue: [1 to: max] ifFalse: [(1 to: 30) , (max-10 to: max)]) collect: [:i | i printString])!fieldMenu "Inspector flushMenus" field == nil ifTrue: [^ nil]. ListMenu == nil ifTrue: [ListMenu _ ActionMenu labels: 'inspect' selectors: #(inspectField)]. ^ ListMenu!fieldValue field = 'self' ifTrue: [^object]. field first isDigit ifTrue: [^object basicAt: self fieldIndex] ifFalse: [^object instVarAt: self fieldIndex]!printItems "Answer whether the elements of the fieldList need to be converted to strings" ^false! !!Inspector methodsFor: 'text'!text field == nil ifTrue: [^ Text new]. ^ self fieldValue printString asText!textMenu "Inspector flushMenus" TextMenu == nil ifTrue: [TextMenu _ ActionMenu labels: 'again\undo\copy\cut\paste\do it\print it\accept\cancel' withCRs lines: #(2 5 7) selectors: #(again undo copySelection cut paste doIt printIt accept cancel)]. ^ TextMenu! !!Inspector methodsFor: 'doIt/accept/explain'!acceptText: aText from: aController | val | object class == CompiledMethod ifTrue: [^false]. field == nil ifTrue: [^false]. val _ self evaluateText: aText string from: aController ifFail: [^ false]. field first isLetter ifTrue: [object instVarAt: self fieldIndex put: val] ifFalse: [object basicAt: self fieldIndex put: val]. self changed: #text. ^ true!doItContext ^ nil!doItReceiver "Answer the object that should be informed of the result of evaluating a text selection." ^object!doItValue: ignored!evaluateText: aText from: aController ifFail: failBlock ^ Compiler new evaluate: aText in: self doItContext to: self doItReceiver notifying: aController ifFail: failBlock! !!Inspector methodsFor: 'updating'!update "Reshow contents, assuming selected value may have changed" field ~~ nil ifTrue: [self changed: #text]! !!Inspector methodsFor: 'menu commands'!inspectField self fieldValue inspect! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Inspector class instanceVariableNames: ''!!Inspector class methodsFor: 'instance creation'!inspect: anObject "Answer an instance of me to provide an inspector for anObject." ^self new inspect: anObject! !!Inspector class methodsFor: 'initialization'!flushMenus ListMenu _ TextMenu _ nil! ! StandardSystemView subclass: #InspectorView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Inspector'!InspectorView comment:'I am a StandardSystemView that provides initialization methods (messages to myself) to create and schedule the interface to an object Inspector. I have two subViews, an InspectListView and an InspectCodeView.'!"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!InspectorView class instanceVariableNames: ''!!InspectorView class methodsFor: 'instance creation'!inspector: anInspector "Answer an instance of me on the model, anInspector. Label and minimum size are not set." | anInspectorView | anInspectorView _ InspectorView new. anInspectorView model: anInspector. self view: anInspector in: (0@0 extent: 1@1) of: anInspectorView. ^anInspectorView!open: anInspector "Create and schedule an instance of me on the model, anInspector." (self buildScheduledView: anInspector) controller open!view: anInspector in: area of: superView "Create proportioned List and Code views on anInspector in area of superView" | mid | mid _ area left + (area width * 0.3). superView addSubView: (SelectionInListView on: anInspector printItems: anInspector printItems oneItem: false aspect: #field change: #field: list: #fieldList menu: #fieldMenu initialSelection: #field) in: (area copy right: mid) borderWidth: 1. superView addSubView: (CodeView on: anInspector aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: nil) in: (area copy left: mid) borderWidth: 1! !!InspectorView class methodsFor: 'private'!buildScheduledView: anInspector | topView | topView _ self model: anInspector label: anInspector object class name minimumSize: 180 @ 180. self view: anInspector in: (0@0 extent: 1@1) of: topView. ^ topView! ! InstructionStream subclass: #InstructionPrinter instanceVariableNames: 'stream oldPC ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'!InstructionPrinter comment: 'Instance Variables: stream <WriteStream> accumulates symbolic output oldPC <integer> remembers where current instruction startedAn InstructionPrinter can print the object code of a CompiledMethod in symbolic format. It prints into stream, and uses oldPC to know how many bytes to print in the listing.The inherited variable "sender" is used in an ugly way to hold the method being printed.'!!InstructionPrinter methodsFor: 'initialize-release'!printInstructionsOn: aStream "Append to the stream, aStream, a description of each bytecode in the instruction stream." | end | stream _ aStream. end _ self method endPC. oldPC _ pc. [pc <= end] whileTrue: [super interpretNextInstructionFor: self]! !!InstructionPrinter methodsFor: 'instruction decoding'!blockReturnTop "Print the ReturnTopOfStack bytecode." self print: 'blockReturn'!doDup "Print the Duplicate Top of Stack bytecode." self print: 'dup'!doPop "Print the Remove Top of Stack bytecode." self print: 'pop'!jump: offset "Print the Unconditional Jump bytecode." self print: 'jumpTo: ' , (pc + offset) printString!jump: offset if: condition "Print the Conditional Jump bytecode." self print: (condition ifTrue: ['jumpTrue: '] ifFalse: ['jumpFalse: ']) , (pc + offset) printString!methodReturnConstant: value "Print the Return Constant bytecode." self print: 'return: ' , value printString!methodReturnReceiver "Print the Return Self bytecode." self print: 'returnSelf'!methodReturnTop "Print the Return Top of Stack bytecode." self print: 'returnTop'!popIntoLiteralVariable: anAssociation "Print the Removes the Top of the Stack and Stores it into a Literal Variable bytecode." self print: 'popIntoLit: ' , anAssociation key!popIntoReceiverVariable: offset "Print the Removes the Top of the Stack and Stores it into an Instance Variable bytecode." self print: 'popIntoRcvr: ' , offset printString!popIntoTemporaryVariable: offset "Print the Removes the Top of the Stack and Stores it into a Temporary Variable bytecode." self print: 'popIntoTemp: ' , offset printString!pushActiveContext "Print the Push the Active Context on the Top of its Own Stack bytecode." self print: 'pushThisContext: '!pushConstant: value "Print the Push the Constant, value, on the Top of the Stack bytecode." self print: 'pushConstant: ' , value printString!pushLiteralVariable: anAssociation "Print the Push the Contents of anAssociation on the Top of the Stack bytecode." self print: 'pushLit: ' , anAssociation key!pushReceiver "Print the Push the Active Context's Receiver on the Top of the Stack bytecode." self print: 'self'!pushReceiverVariable: offset "Print the Push the Contents of the Receiver's Instance Variable whose Index is the argument, offset, on the Top of the Stack bytecode." self print: 'pushRcvr: ' , offset printString!pushTemporaryVariable: offset "Print the Push the Contents of the Temporary Variable whose Index is the argument, offset, on the Top of the Stack bytecode." self print: 'pushTemp: ' , offset printString!send: selector super: supered numArgs: numberArguments "Print the Send a Message with Selector, selector, bytecode. The argument, supered, indicates whether the receiver of the message is specified with 'super' in the source method. The arguments of the message are found in the top numArguments locations on the stack and the receiver just below them." self print: (supered ifTrue: ['superSend: '] ifFalse: ['send: ']) , selector!storeIntoLiteralVariable: anAssociation "Print the Store the Top of the Stack into a Literal Variable of the Method bytecode." self print: 'storeIntoLit: ' , anAssociation key!storeIntoReceiverVariable: offset "Print the Store the Top of the Stack into an Instance Variable of the Method bytecode." self print: 'storeIntoRcvr: ' , offset printString!storeIntoTemporaryVariable: offset "Print the Store the Top of the Stack into a Temporary Variable of the Method bytecode." self print: 'storeIntoTemp: ' , offset printString! !!InstructionPrinter methodsFor: 'printing'!print: instruction "Append to the receiver a description of the bytecode, instruction." | code | stream print: oldPC; space. stream nextPut: $<. oldPC to: pc - 1 do: [:i | code _ (self method at: i) storeStringRadix: 16. stream nextPut: (code size < 5 ifTrue: [$0] ifFalse: [code at: 4]). stream nextPut: code last; space]. stream skip: -1. stream nextPut: $>. stream space. stream nextPutAll: instruction. stream cr. oldPC _ pc "(InstructionPrinter compiledMethodAt: #print:) symbolic."! ! Object subclass: #InstructionStream instanceVariableNames: 'sender pc ' classVariableNames: 'SpecialConstants ' poolDictionaries: '' category: 'Kernel-Methods'!InstructionStream comment: 'Instance Variables: sender <Context>, sometimes <CompiledMethod> pc <Integer> pointing into my methodAs a superclass of contexts, I store the return pointer in sender, and the current position in my method in pc.This class by itself has the ability to interpret the byte-encoded Smalltalk instruction set and maintains a program counter (pc) for streaming through CompiledMethods. Contexts thus inherit all this capability and, for other users, sender can hold a method to be similarly interpreted. The unclean re-use of sender to hold the method was to avoid a trivial subclass for the stand-alone scanning funtion.'!!InstructionStream methodsFor: 'testing'!willReturn "Answer whether the next bytecode is a return." ^(self method at: pc) between: 120 and: 125!willSend "Answer whether the next bytecode is a message-send." | byte | byte _ self method at: pc. byte < 128 ifTrue: [^ false]. byte >= 176 "special send or short send" ifTrue: [^ byte ~= 200]. "but not blockCopy" ^ byte between: 131 and: 134 "long sends"!willStorePop "Answer whether the next bytecode is a store-pop." | byte | byte _ self method at: pc. ^byte = 130 or: [byte between: 96 and: 111]! !!InstructionStream methodsFor: 'decoding'!interpretJump | t | t _ self method at: pc. (t between: 144 and: 151) ifTrue: [pc _ pc + 1. ^t - 143]. (t between: 160 and: 167) ifTrue: [pc _ pc + 2. ^(t - 164) * 256 + (self method at: pc - 1)]. ^nil!interpretNextInstructionFor: client "Send to the argument, client, a message that specifies the type of the the next instruction." | byte type offset method | method_ self method. byte_ method at: pc. type_ byte // 16. offset_ byte \\ 16. pc_ pc+1. type=0 ifTrue: [^client pushReceiverVariable: offset]. type=1 ifTrue: [^client pushTemporaryVariable: offset]. type=2 ifTrue: [^client pushConstant: (method literalAt: offset+1)]. type=3 ifTrue: [^client pushConstant: (method literalAt: offset+17)]. type=4 ifTrue: [^client pushLiteralVariable: (method literalAt: offset+1)]. type=5 ifTrue: [^client pushLiteralVariable: (method literalAt: offset+17)]. type=6 ifTrue: [offset<8 ifTrue: [^client popIntoReceiverVariable: offset] ifFalse: [^client popIntoTemporaryVariable: offset-8]]. type=7 ifTrue: [offset=0 ifTrue: [^client pushReceiver]. offset<8 ifTrue: [^client pushConstant: (SpecialConstants at: offset)]. offset=8 ifTrue: [^client methodReturnReceiver]. offset<12 ifTrue: [^client methodReturnConstant: (SpecialConstants at: offset-8)]. offset=12 ifTrue: [^client methodReturnTop]. offset=13 ifTrue: [^client blockReturnTop]. offset>13 ifTrue: [^self error: 'unusedBytecode']]. type=8 ifTrue: [^self interpretExtension: offset in: method for: client]. type=9 ifTrue: "short jumps" [offset<8 ifTrue: [^client jump: offset+1]. ^client jump: offset-8+1 if: false]. type=10 ifTrue: "long jumps" [byte_ method at: pc. pc_ pc+1. offset<8 ifTrue: [^client jump: offset-4*256 + byte]. ^client jump: (offset bitAnd: 3)*256 + byte if: offset<12]. type=11 ifTrue: [^client send: (Smalltalk specialSelectorAt: offset+1) super: false numArgs: (Smalltalk specialNargsAt: offset+1)]. type=12 ifTrue: [^client send: (Smalltalk specialSelectorAt: offset+17) super: false numArgs: (Smalltalk specialNargsAt: offset+17)]. type>12 ifTrue: [^client send: (method literalAt: offset+1) super: false numArgs: type-13]! !!InstructionStream methodsFor: 'scanning'!addFieldIndexTo: set "If this instruction is an instVar reference, add its index (offset+1) to set." | byte byte2 | byte _ self method at: pc. byte < 16 ifTrue: [^ set add: byte + 1]. "load field" (byte >= 96 and: [byte <= 130]) ifTrue: [(byte between: 96 and: 103) ifTrue: "short store-pop" [^ set add: byte - 96 + 1]. (byte between: 128 and: 130) ifTrue: "extended field access" [byte2 _ self method at: pc+1. byte2 < 64 ifTrue: [^ set add: byte2 \\ 64 + 1]]]!addSelectorTo: set "If this instruction is a send, add its selector to set." | byte literalNumber | byte _ self method at: pc. byte < 128 ifTrue: [^self]. byte >= 176 ifTrue: ["special byte or short send" byte >= 208 ifTrue: [set add: (self method literalAt: (byte bitAnd: 15) + 1)] ifFalse: [set add: (Smalltalk specialSelectorAt: byte - 176 + 1)]] ifFalse: [(byte between: 131 and: 134) ifTrue: [literalNumber _ byte odd ifTrue: [(self method at: pc + 1) \\ 32] ifFalse: [self method at: pc + 2]. set add: (self method literalAt: literalNumber + 1)]]!followingByte "Answer the following bytecode." ^self method at: pc + 1!method "Answer the compiled method that supplies the receiver's bytecodes." ^sender "method access when used alone (not as part of a context)"!nextByte "Answer the next bytecode." ^self method at: pc!pc "Answer the index of the next bytecode." ^pc!scanFor: scanBlock "Answer the index of the first bytecode for which scanBlock answer true when supplied with that bytecode." | method end byte type | method _ self method. end _ method endPC. [pc <= end] whileTrue: [(scanBlock value: (byte _ method at: pc)) ifTrue: [^true]. type _ byte // 16. pc _ type = 8 ifTrue: ["extensions" pc + (#(2 2 2 2 3 2 3 1 1 1 ) at: byte \\ 16 + 1)] ifFalse: [type = 10 ifTrue: [pc + 2"long jumps"] ifFalse: [pc + 1]]]. ^false! !!InstructionStream methodsFor: 'private'!interpretExtension: offset in: method for: client | numberArguments literalNumber type offset2 | "pc has already been incremented by 1" offset < 3 ifTrue: ["extended pushes and pops" type _ (method at: pc) // 64. offset2 _ (method at: pc) \\ 64. pc _ pc + 1. offset = 0 ifTrue: [type = 0 ifTrue: [^client pushReceiverVariable: offset2]. type = 1 ifTrue: [^client pushTemporaryVariable: offset2]. type = 2 ifTrue: [^client pushConstant: (method literalAt: offset2 + 1)]. type = 3 ifTrue: [^client pushLiteralVariable: (method literalAt: offset2 + 1)]]. offset = 1 ifTrue: [type = 0 ifTrue: [^client storeIntoReceiverVariable: offset2]. type = 1 ifTrue: [^client storeIntoTemporaryVariable: offset2]. type = 2 ifTrue: [self error: 'illegalStore']. type = 3 ifTrue: [^client storeIntoLiteralVariable: (method literalAt: offset2 + 1)]]. offset = 2 ifTrue: [type = 0 ifTrue: [^client popIntoReceiverVariable: offset2]. type = 1 ifTrue: [^client popIntoTemporaryVariable: offset2]. type = 2 ifTrue: [self error: 'illegalStore']. type = 3 ifTrue: [^client popIntoLiteralVariable: (method literalAt: offset2 + 1)]]]. offset < 7 ifTrue: ["extended sends" offset odd ifTrue: [numberArguments _ (method at: pc) // 32. literalNumber _ (method at: pc) \\ 32. pc _ pc + 1] ifFalse: [numberArguments _ method at: pc. literalNumber _ method at: pc + 1. pc _ pc + 2]. ^client send: (method literalAt: literalNumber + 1) super: offset > 4 numArgs: numberArguments]. offset = 7 ifTrue: [^client doPop]. offset = 8 ifTrue: [^client doDup]. offset = 9 ifTrue: [^client pushActiveContext]. self error: 'unusedBytecode'!method: method pc: startpc sender _ method. "allows this class to stand alone as a method scanner" pc _ startpc! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!InstructionStream class instanceVariableNames: ''!!InstructionStream class methodsFor: 'class initialization'!initialize "Initialize an array of special constants returned by single-bytecode returns." SpecialConstants _ (Array with: true with: false with: nil) , (Array with: -1 with: 0 with: 1 with: 2) "InstructionStream initialize."! !!InstructionStream class methodsFor: 'instance creation'!on: method "Answer a new InstructionStream on the argument, method." ^self new method: method pc: method initialPC! !InstructionStream initialize! Number subclass: #Integer instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Numbers'!Integer comment:'I am a common abstract superclass for all Integer implementations. My implementation subclasses are SmallInteger, LargePositiveInteger, and LargeNegativeInteger.'!!Integer methodsFor: 'testing'!even ^((self digitAt: 1) bitAnd: 1) = 0!isInteger ^true! !!Integer methodsFor: 'comparing'!< anInteger "Compare the receiver with the argument and return true if the receiver is less than the argument. Otherwise return false." anInteger isInteger ifTrue: [self negative == anInteger negative ifTrue: [self negative ifTrue: [^(self digitCompare: anInteger) > 0] ifFalse: [^(self digitCompare: anInteger) < 0]] ifFalse: [^self negative]] ifFalse: [^self retry: #< coercing: anInteger]!<= anInteger "Compare the receiver with the argument and return true if the receiver is less than or equal to the argument. Otherwise return false." ^super <= anInteger!= anInteger "Compare the receiver with the argument and return true if the receiver is equal to the argument. Otherwise return false." anInteger isInteger ifTrue: [anInteger positive & self positive | (anInteger negative & self negative) ifTrue: [^(self digitCompare: anInteger) = 0] ifFalse: [^false]] ifFalse: [^self retry: #= coercing: anInteger]!> anInteger "Compare the receiver with the argument and return true if the receiver is greater than the argument. Otherwise return false." anInteger isInteger ifTrue: [self negative == anInteger negative ifTrue: [self negative ifTrue: [^(self digitCompare: anInteger) < 0] ifFalse: [^(self digitCompare: anInteger) > 0]] ifFalse: [^anInteger negative]] ifFalse: [^self retry: #> coercing: anInteger]!>= anInteger "Compare the receiver with the argument and return true if the receiver is greater than or equal to the argument. Otherwise return false." ^super >= anInteger!hash ^(self lastDigit bitShift: 8) + (self digitAt: 1)!~= anInteger "Compare the receiver with the argument and return true if the receiver is not equal to the argument. Otherwise answer false." ^super ~= anInteger! !!Integer methodsFor: 'arithmetic'!* aNumber "Multiply the receiver by the argument and answer with the result." aNumber isInteger ifTrue: [^(self digitMultiply: aNumber neg: self negative ~~ aNumber negative) truncated] ifFalse: [^self retry: #* coercing: aNumber]!+ aNumber "Add the receiver to the argument and answer with the result." aNumber isInteger ifTrue: [self negative == aNumber negative ifTrue: [^(self digitAdd: aNumber) truncated] ifFalse: [^self digitSubtract: aNumber]] ifFalse: [^self retry: #+ coercing: aNumber]!- aNumber "Subtract the argument from the receiver and answer with the result." aNumber isInteger ifTrue: [self negative == aNumber negative ifTrue: [^self digitSubtract: aNumber] ifFalse: [^self digitAdd: aNumber]] ifFalse: [^self retry: #- coercing: aNumber]!/ aNumber "Divide the receiver by the argument and answer with the result if the division is exact." | quoRem | aNumber isInteger ifTrue: [quoRem _ self digitDiv: aNumber neg: self negative ~~ aNumber negative. (quoRem at: 2) = 0 ifTrue: [^(quoRem at: 1) truncated] ifFalse: [^(Fraction numerator: self denominator: aNumber) reduced]] ifFalse: [^self retry: #/ coercing: aNumber]!// aNumber "Divide the receiver by the argument and return the result. Round the result down towards negative infinity to make it a whole integer." | q | aNumber = 0 ifTrue: [^self error: 'division by 0']. self = 0 ifTrue: [^0]. q _ self quo: aNumber. (q negative ifTrue: [q * aNumber ~= self] ifFalse: [q = 0 and: [self negative ~= aNumber negative]]) ifTrue: [^q - 1"Truncate towards minus infinity"] ifFalse: [^q]!quo: aNumber "Divide the receiver by the argument and return the result. Round the result down towards zero to make it a whole integer." | ng quo | aNumber isInteger ifTrue: [ng _ self negative == aNumber negative == false. quo _ (self digitDiv: aNumber neg: ng) at: 1. (quo lastDigit = 0 and: [quo digitLength >= 2]) ifTrue: [^(quo growby: -1) truncated]. ^quo truncated] ifFalse: [^self retry: #quo: coercing: aNumber]!\\ aNumber "Take the receiver modulo the argument and return the result. The result is the remainder rounded towards negative infinity, of the receiver divided by the argument. The remainder is defined in terms of //. The result has the same sign as the argument: e.g. 9\\4 = 1, -9\\4 = 3, 9\\-4 = -3, -9\\-4 = -1 " ^self - (self // aNumber * aNumber)! !!Integer methodsFor: 'truncation and round off'!ceiling!floor!rounded!truncated! !!Integer methodsFor: 'enumerating'!timesRepeat: aBlock "Evaluate the argument, aBlock, the number of times represented by the receiver." | count | count _ 1. [count <= self] whileTrue: [aBlock value. count _ count + 1]! !!Integer methodsFor: 'factorization and divisibility'!factorial "Answer the factorial of the receiver. For example, 6 factorial == 6*5*4*3*2*1. Signal an error if the receiver is less than 0." self > 0 ifTrue: [^self * (self - 1) factorial]. self = 0 ifTrue: [^1]. self error: 'factorial invalid for: ' , self printString!gcd: anInteger "Answer the greatest common divisor of the receiver and anInteger. Uses Roland Silver's algorithm" | m n d t | m _ self abs max: anInteger abs. n _ self abs min: anInteger abs. m \\ n = 0 ifTrue: [^n]. "easy test, speeds up rest" d _ 0. [n even and: [m even]] whileTrue: [d _ d + 1. n _ n bitShift: -1. m _ m bitShift: -1]. [n even] whileTrue: [n _ n bitShift: -1]. [m even] whileTrue: [m _ m bitShift: -1]. [m = n] whileFalse: [m > n ifTrue: [m _ m - n] ifFalse: [t _ m. m _ n - m. n _ t]. "Make sure larger gets replaced" [m even] whileTrue: [m _ m bitShift: -1]]. d = 0 ifTrue: [^m]. ^m bitShift: d!lcm: n "Answer the least common multiple of the receiver and n." ^self // (self gcd: n) * n! !!Integer methodsFor: 'bit manipulation'!allMask: mask "Treat the argument as a bit mask. Answer true if all of the bits that are 1 in the argument are 1 in the receiver." ^mask = (self bitAnd: mask)!anyMask: mask "Treat the argument as a bit mask. Answer true if any of the bits that are 1 in the argument are 1 in the receiver." ^0 ~= (self bitAnd: mask)!bitAnd: aNumber "Logical AND the twos-complement representation of the receiver with the twos-complement representation of the argument and return the result." | anInteger | anInteger _ aNumber truncated. ^self digitLogic: anInteger op: #bitAnd: length: (self digitLength max: anInteger digitLength)!bitAt: i "Answer the bit at the ith position." ^(self bitAnd: (1 bitShift: i - 1)) = 0 ifTrue: [0] ifFalse: [1]!bitInvert "Answer an integer whose bits are the complement of the receiver." ^-1 - self!bitOr: aNumber "Logical OR the twos-complement representation of the receiver with the twos-complement representation of the argument and return the result." | anInteger | anInteger _ aNumber truncated. ^self digitLogic: anInteger op: #bitOr: length: (self digitLength max: anInteger digitLength)!bitShift: anInteger "Logical SHIFT the twos-complement representation of the receiver with the twos-complement representation of the argument and return the result. Shift left if the argument is positive, right if the argument is negative. Zeros are shifted in from the right in left shifts. The sign bit is extended in right shifts." | result abs | anInteger >= 0 ifTrue: [^(self digitLshift: (anInteger bitAnd: 7) bytes: (anInteger bitShift: -3) lookfirst: true) truncated]. abs _ 0 - anInteger. result _ (self digitRshift: (abs bitAnd: 7) bytes: (abs bitShift: -3) lookfirst: self digitLength) truncated. (self negative and: [self anyBitTo: abs]) ifTrue: [result _ result - 1]. ^result!bitXor: aNumber "Logical XOR the twos-complement representation of the receiver with the twos-complement representation of the argument and return the result." | anInteger | anInteger _ aNumber truncated. ^self digitLogic: anInteger op: #bitXor: length: (self digitLength max: anInteger digitLength)!highBit "Answer with the index of the high order bit of the binary representation of the receiver." self subclassResponsibility!noMask: mask "Treat the argument as a bit mask. Answer true if none of the bits that are 1 in the argument are 1 in the receiver." ^0 = (self bitAnd: mask)! !!Integer methodsFor: 'printing'!isLiteral ^true!printOn: aStream self printOn: aStream base: 10 "default print radix"!printOn: aStream base: b "Print a representation of the receiver on the stream, aStream, in base b where 2<=b<=256." | digits source dest i j pos t rem | i _ self digitLength. "Estimate size of result, conservatively" digits _ Array new: i * 8. pos _ 0. dest _ i <= 1 ifTrue: [self] ifFalse: [LargePositiveInteger new: i]. source _ self. [i > 1] whileTrue: [rem _ 0. j _ i. [j > 0] whileTrue: [t _ (rem bitShift: 8) + (source digitAt: j). dest digitAt: j put: t // b. rem _ t \\ b. j _ j - 1]. pos _ pos + 1. digits at: pos put: rem. source _ dest. (source digitAt: i) = 0 ifTrue: [i _ i - 1]]. (dest digitAt: 1) printOn: aStream base: b. [pos > 0] whileTrue: [aStream nextPut: (Character digitValue: (digits at: pos)). pos _ pos - 1]!printStringRadix: radix "Answer a String representing the receiver as a base radix integer." | aStream | aStream _ WriteStream on: (String new: 16). self printOn: aStream base: radix. ^aStream contents!storeStringRadix: radix "Answer a String representing the receiver as a base radix integer in Smalltalk syntax (e.g. 8r377)." | aStream | aStream _ WriteStream on: (String new: 16). radix ~= 10 ifTrue: [radix printOn: aStream. aStream nextPutAll: 'r']. self printOn: aStream base: radix. ^aStream contents! !!Integer methodsFor: 'converting'!asCharacter "Answer the Character whose value is the receiver." ^Character value: self!asFloat "Answer with a Float that represents the receiver." | factor sum | sum _ 0.0. factor _ self sign asFloat. 1 to: self size do: [:i | sum _ (self digitAt: i) * factor + sum. factor _ factor * 256.0]. ^sum!asFraction "Answer with a Fraction that represents the receiver." ^Fraction numerator: self denominator: 1!asInteger "Answer with the receiver itself." ^self! !!Integer methodsFor: 'coercing'!coerce: aNumber ^aNumber truncated!generality ^40! !!Integer methodsFor: 'system primitives'!lastDigit "Answer the last digit of the integer." ^self digitAt: self digitLength!lastDigitGet: digit "Store the argument, digit, as the last digit of the integer." ^self at: self digitLength put: digit! !!Integer methodsFor: 'private'!anyBitTo: pos "Answer true if any bit from 1 to pos is non-zero, for testing for loss of significant bits when shifting right" 1 to: pos - 1 // 8 do: [:i | (self digitAt: i) ~= 0 ifTrue: [^true]]. ^(self digitAt: pos + 7 // 8) anyMask: (#(1 3 7 15 31 63 127 255) at: pos - 1 \\ 8 + 1)!copyto: x 1 to: (self digitLength min: x digitLength) do: [:i | x digitAt: i put: (self digitAt: i)]. ^x!denominator ^1!digitAdd: arg | len arglen i accum sum | accum _ 0. (len _ self digitLength) < (arglen _ arg digitLength) ifTrue: [len _ arglen]. "Open code max: for speed" sum _ Integer new: len neg: self negative. i _ 1. [i <= len] whileTrue: [accum _ (accum bitShift: -8) + (self digitAt: i) + (arg digitAt: i). sum digitAt: i put: (accum bitAnd: 255). i _ i + 1]. accum > 255 ifTrue: [sum _ sum growby: 1. sum lastDigitGet: (accum bitShift: -8)]. ^sum!digitCompare: arg | len arglen t5 t6 | len _ self digitLength. (arglen _ arg digitLength) ~= len ifTrue: [arglen > len ifTrue: [^-1] ifFalse: [^1]]. [len > 0] whileTrue: [(t5 _ arg digitAt: len) ~= (t6 _ self digitAt: len) ifTrue: [t5 < t6 ifTrue: [^1] ifFalse: [^-1]]. len _ len - 1]. ^0!digitDiv: arg neg: ng "Answer with an array of (quotient, remainder)" | quo rem ql d div dh dnh dl qhi qlo i j k l hi lo r3 a t | l _ self digitLength - arg digitLength + 1. l <= 0 ifTrue: [^Array with: 0 with: self]. d _ 8 - arg lastDigit highBit. rem _ self digitLshift: d bytes: 0 lookfirst: false. "makes a copy and shifts" div _ arg digitLshift: d bytes: 0 lookfirst: false. "shifts so high order word is >=128" quo _ Integer new: l neg: ng. dl _ div digitLength - 1. "Last actual byte of data" ql _ l. dh _ div digitAt: dl. dnh _ dl = 1 ifTrue: [0] ifFalse: [div digitAt: dl - 1]. 1 to: ql do: [:k | "maintain quo*arg+rem=self" "Estimate rem/div by dividing the leading to bytes of rem by dh." "The estimate is q = qhi*16+qlo, where qhi and qlo are nibbles." j _ rem digitLength + 1 - k. "r1 _ rem digitAt: j." (rem digitAt: j) = dh ifTrue: [qhi _ qlo _ 15"i.e. q=255"] ifFalse: ["Compute q = (r1,r2)//dh, t = (r1,r2)\\dh. Note that r1,r2 are bytes, not nibbles. Be careful not to generate intermediate results exceeding 13 bits." "r2 _ (rem digitAt: j - 1)." t _ ((rem digitAt: j) bitShift: 4) + ((rem digitAt: j - 1) bitShift: -4). qhi _ t // dh. t _ (t \\ dh bitShift: 4) + ((rem digitAt: j - 1) bitAnd: 15). qlo _ t // dh. t _ t \\ dh. "Next compute (hi,lo) _ q*dnh" hi _ qhi * dnh. lo _ qlo * dnh + ((hi bitAnd: 15) bitShift: 4). hi _ (hi bitShift: -4) + (lo bitShift: -8). lo _ lo bitAnd: 255. "Correct overestimate of q. Max of 2 iterations through loop -- see Knuth vol. 2" r3 _ j < 3 ifTrue: [0] ifFalse: [rem digitAt: j - 2]. [(t < hi or: [t = hi and: [r3 < lo]]) and: ["i.e. (t,r3) < (hi,lo)" qlo _ qlo - 1. lo _ lo - dnh. lo < 0 ifTrue: [hi _ hi - 1. lo _ lo + 256]. hi >= dh]] whileTrue: [hi _ hi - dh]. qlo < 0 ifTrue: [qhi _ qhi - 1. qlo _ qlo + 16]]. "Subtract q*div from rem" l _ j - dl. a _ 0. 1 to: div digitLength do: [:i | hi _ (div digitAt: i) * qhi. lo _ a + (rem digitAt: l) - ((hi bitAnd: 15) bitShift: 4) - ((div digitAt: i) * qlo). rem digitAt: l put: (lo bitAnd: 255). a _ (lo bitShift: -8) - (hi bitShift: -4). l _ l + 1]. a < 0 ifTrue: ["Add div back into rem, decrease q by 1" qlo _ qlo - 1. l _ j - dl. a _ 0. 1 to: div digitLength do: [:i | a _ (a bitShift: -8) + (rem digitAt: l) + (div digitAt: i). rem digitAt: l put: (a bitAnd: 255). l _ l + 1]]. quo digitAt: quo digitLength + 1 - k put: (qhi bitShift: 4) + qlo]. rem _ rem digitRshift: d bytes: 0 lookfirst: dl. ^Array with: quo with: rem!digitLogic: arg op: op length: len | result i neg1 neg2 rneg z1 z2 rz b1 b2 b rdigits | neg1 _ self negative. neg2 _ arg negative. rneg _ ((neg1 ifTrue: [-1] ifFalse: [0]) perform: op with: (neg2 ifTrue: [-1] ifFalse: [0])) < 0. result _ Integer new: len neg: rneg. rz _ z1 _ z2 _ true. rdigits _ 1. 1 to: result digitLength do: [:i | b1 _ self digitAt: i. neg1 ifTrue: [b1 _ z1 ifTrue: [b1 = 0 ifTrue: [0] ifFalse: [z1 _ false. 256 - b1]] ifFalse: [255 - b1]]. b2 _ arg digitAt: i. neg2 ifTrue: [b2 _ z2 ifTrue: [b2 = 0 ifTrue: [0] ifFalse: [z2 _ false. 256 - b2]] ifFalse: [255 - b2]]. b _ b1 perform: op with: b2. b = 0 ifTrue: [result digitAt: i put: 0] ifFalse: [rdigits _ i. result digitAt: i put: (rneg ifTrue: [rz ifTrue: [rz _ false. 256 - b] ifFalse: [255 - b]] ifFalse: [b])]]. rdigits ~= result digitLength ifTrue: [^(result growto: rdigits) truncated]. ^result truncated!digitLshift: n bytes: b lookfirst: a | x f m len r digit | "shift by 8*b+n bits, 0<=n<8. a true means check for a leading zero byte in the result " x _ 0. f _ n - 8. m _ 255 bitShift: 0 - n. len _ self digitLength + 1 + b. (a and: [(self lastDigit bitShift: f) = 0]) ifTrue: [len _ len - 1]. r _ Integer new: len neg: self negative. 1 to: b do: [:i | r digitAt: i put: 0]. 1 to: len - b do: [:i | digit _ self digitAt: i. r digitAt: i + b put: (((digit bitAnd: m) bitShift: n) bitOr: x). "Avoid values > 8 bits" x _ digit bitShift: f]. ^r!digitMultiply: arg neg: ng | prod pl carry digit i j k xh xl low high | ((arg digitAt: 1) = 0 and: [arg digitLength = 1]) ifTrue: [^0]. pl _ self digitLength + arg digitLength. prod _ Integer new: pl neg: ng. "prod starts out all zero" 1 to: self digitLength do: [:i | (digit _ self digitAt: i) ~= 0 ifTrue: [k _ i. carry _ 0. xh _ digit bitShift: -4. xl _ digit bitAnd: 15. "Loop invariant: 0<=carry<=0377, k=i+j-1" 1 to: arg digitLength do: [:j | high _ (arg digitAt: j) * xh. "Do double-precision multiply in two parts. Integers must be at least 13 bits for this to work." low _ (arg digitAt: j) * xl + ((high bitAnd: 15) bitShift: 4) + carry + (prod digitAt: k). carry _ (high bitShift: -4) + (low bitShift: -8). prod digitAt: k put: (low bitAnd: 255). k _ k + 1]. prod digitAt: k put: carry]]. (prod digitAt: pl) = 0 ifTrue: [^(prod growby: -1) truncated]. ^prod truncated!digitRshift: anInteger bytes: b lookfirst: a "shift right 8*b+anInteger bits, 0<=n<8. Discard all digits beyond a, and all zeroes at or below a." | n x i r f m digit count| n _ 0 - anInteger. x _ 0. f _ n + 8. i _ a. m _ 255 bitShift: 0 - f. digit _ self digitAt: i. [((digit bitShift: n) bitOr: x) = 0 and: [i ~= 1]] whileTrue: [x _ digit bitShift: f "Can't exceed 8 bits". i _ i - 1. digit _ self digitAt: i]. i <= b ifTrue: [^Integer new: 0 neg: self negative]. "All bits lost" r _ Integer new: i - b neg: self negative. count _ i. x _ (self digitAt: b + 1) bitShift: n. b + 1 to: count do: [:i | digit _ self digitAt: i + 1. r digitAt: i - b put: (((digit bitAnd: m) bitShift: f) bitOr: x) "Avoid values > 8 bits". x _ digit bitShift: n]. ^r!digitSubtract: arg | smaller larger i z sum sl al ng lastdigit | sl _ self digitLength. al _ arg digitLength. (sl = al ifTrue: [[(self digitAt: sl) = (arg digitAt: sl) and: [sl > 1]] whileTrue: [sl _ sl - 1]. al _ sl. (self digitAt: sl) < (arg digitAt: sl)] ifFalse: [sl < al]) ifTrue: [larger _ arg. smaller _ self. ng _ self negative == false. sl _ al] ifFalse: [larger _ self. smaller _ arg. ng _ self negative]. sum _ Integer new: sl neg: ng. lastdigit _ 1. z _ 0. "Loop invariant is -1<=z<=1" i _ 1. [i <= sl] whileTrue: [z _ z + (larger digitAt: i) - (smaller digitAt: i). (sum digitAt: i put: (z bitAnd: 255)) ~= 0 ifTrue: [lastdigit _ i]. z _ z bitShift: -8. i _ i + 1]. lastdigit = sl ifFalse: [sum _ sum growto: lastdigit]. ^sum truncated!growby: n ^self growto: self digitLength + n!growto: n ^self copyto: (self species new: n)!numerator ^self! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Integer class instanceVariableNames: ''!!Integer class methodsFor: 'instance creation'!new: length neg: neg "Answer an instance of a large integer whose size is length. neg is a flag determining whether the integer is negative or not." neg ifTrue: [^LargeNegativeInteger new: length] ifFalse: [^LargePositiveInteger new: length]!readFrom: aStream "Answer a new Integer as described on the stream, aStream." ^self readFrom: aStream radix: 10!readFrom: aStream radix: radix "Answer an instance of one of my concrete subclasses. Initial minus sign accepted, and bases > 10 use letters A-Z. imbedded radix specifiers not allowed - use Integer class readFrom: for that. Answer zero (not an error) if there are no digits." | digit value neg | neg _ aStream peekFor: $-. value _ 0. [aStream atEnd] whileFalse: [digit _ aStream next digitValue. (digit < 0 or: [digit >= radix]) ifTrue: [aStream skip: -1. neg ifTrue: [^value negated truncated"catch 0 minVal"]. ^value] ifFalse: [value _ value * radix + digit]]. neg ifTrue: [^value negated truncated"catch 0 minVal"]. ^value! ! SequenceableCollection subclass: #Interval instanceVariableNames: 'start stop step ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Sequenceable'!Interval comment: 'I represent a finite arithmetic progression'!!Interval methodsFor: 'comparing'!= anInterval "Answer true if my species and anInterval species are equal, and if our starts, steps and sizes are equal." self species == anInterval species ifTrue: [^start = anInterval first and: [step = anInterval increment and: [self size = anInterval size]]] ifFalse: [^false]!hash ^(((start hash bitShift: 2) bitOr: stop hash) bitShift: 1) bitOr: self size!hashMappedBy: map "My hash is independent of my oop" ^ self hash! !!Interval methodsFor: 'accessing'!at: anInteger "Answer the anInteger'th element." (anInteger >= 1 and: [anInteger <= self size]) ifTrue: [^start + (step * (anInteger - 1))] ifFalse: [self errorSubscriptBounds: anInteger]!at: anInteger put: anObject "Storing into an Interval is not allowed." self error: 'you can not store into an interval'!first ^start!increment "Answer the receiver's interval increment." ^step!last ^stop - (stop - start \\ step)!size step < 0 ifTrue: [start < stop ifTrue: [^0] ifFalse: [^stop - start // step + 1]] ifFalse: [stop < start ifTrue: [^0] ifFalse: [^stop - start // step + 1]]! !!Interval methodsFor: 'adding'!add: newObject "Adding to an Interval is not allowed." self shouldNotImplement! !!Interval methodsFor: 'removing'!remove: newObject "Removing from an Interval is not allowed." self error: 'elements cannot be removed from an Interval'! !!Interval methodsFor: 'copying'!copy "Return a copy of me. I override this message because my species is Array and copy, as inherited from SequenceableCollection, uses copyFrom:to:, which creates a new object of my species" ^self shallowCopy! !!Interval methodsFor: 'enumerating'!collect: aBlock | nextValue i result | result _ self species new: self size. nextValue _ start. i _ 1. step < 0 ifTrue: [[stop <= nextValue] whileTrue: [result at: i put: (aBlock value: nextValue). nextValue _ nextValue + step. i _ i + 1]] ifFalse: [[stop >= nextValue] whileTrue: [result at: i put: (aBlock value: nextValue). nextValue _ nextValue + step. i _ i + 1]]. ^result!do: aBlock | aValue | aValue _ start. step < 0 ifTrue: [[stop <= aValue] whileTrue: [aBlock value: aValue. aValue _ aValue + step]] ifFalse: [[stop >= aValue] whileTrue: [aBlock value: aValue. aValue _ aValue + step]]!reverseDo: aBlock "Evaluate aBlock for each element of my interval, in reverse order." | aValue | aValue _ stop. step < 0 ifTrue: [[start >= aValue] whileTrue: [aBlock value: aValue. aValue _ aValue - step]] ifFalse: [[start <= aValue] whileTrue: [aBlock value: aValue. aValue _ aValue - step]]! !!Interval methodsFor: 'printing'!printOn: aStream aStream nextPut: $(. start printOn: aStream. aStream nextPutAll: ' to: '. stop printOn: aStream. step ~= 1 ifTrue: [aStream nextPutAll: ' by: '. step printOn: aStream]. aStream nextPut: $)!storeOn: aStream "This is possible because we know numbers store and print the same" self printOn: aStream! !!Interval methodsFor: 'private'!setFrom: startInteger to: stopInteger by: stepInteger start _ startInteger. stop _ stopInteger. step _ stepInteger!species ^Array! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Interval class instanceVariableNames: ''!!Interval class methodsFor: 'instance creation'!from: startInteger to: stopInteger "Answer a new instance of me, starting at startInteger, ending and stopInteger, and with an interval increment of 1." ^self new setFrom: startInteger to: stopInteger by: 1!from: startInteger to: stopInteger by: stepInteger "Answer a new instance of me, starting at startInteger, ending and stopInteger, and with an interval increment of stepInteger." ^self new setFrom: startInteger to: stopInteger by: stepInteger!new "Create and answer with a new instance of the receiver (a class) with no indexable fields. Fail if the class is indexable. Override SequenceableCollection new. Essential. See Object documentation whatIsAPrimitive." <primitive: 70> self isVariable ifTrue: [^self new: 0]. self primitiveFailed! ! Object subclass: #KeyboardEvent instanceVariableNames: 'keyCharacter metaState ' classVariableNames: '' poolDictionaries: '' category: 'System-Support'!KeyboardEvent comment:'I represent a keyboard event consisting of a non-meta key being struck plus the state of the meta keys at that moment. Only InputState creates instances of me.Instance Variables: keyCharacter "<Integer> non-meta key character" metaState "<Integer> combined state of meta keys" '!!KeyboardEvent methodsFor: 'accessing'!keyCharacter "Answer the keyboard character of the receiver." ^keyCharacter!metaState "Answer the state of the special keyboard characters--control, shift, lock." ^metaState! !!KeyboardEvent methodsFor: 'testing'!hasCtrl "Answer whether a control key was pressed." ^metaState anyMask: 2!hasLock "Answer whether the shift key is locked." ^metaState anyMask: 4!hasShift "Answer whether a shift key was pressed." ^metaState anyMask: 1! !!KeyboardEvent methodsFor: 'private'!key: anInteger meta: meta keyCharacter _ anInteger asCharacter. metaState _ meta! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!KeyboardEvent class instanceVariableNames: ''!!KeyboardEvent class methodsFor: 'instance creation'!code: code meta: meta "Answer an instance of me, with code the regular key and meta the special keys--ctrl, shift, lock." ^self new key: code meta: meta! ! Integer variableByteSubclass: #LargeNegativeInteger instanceVariableNames: '' classVariableNames: 'MinHi ' poolDictionaries: '' category: 'Numeric-Numbers'!LargeNegativeInteger comment:'A negative large integer. Nearly all the work is done in Integer: LargeNegativeInteger just overrides a few messages.'!!LargeNegativeInteger methodsFor: 'arithmetic'!abs ^self negated!negated ^self copyto: (LargePositiveInteger new: self digitLength)! !!LargeNegativeInteger methodsFor: 'bit manipulation'!highBit self error: 'highBit not defined for negative numbers'! !!LargeNegativeInteger methodsFor: 'testing'!negative ^true!positive ^false! !!LargeNegativeInteger methodsFor: 'converting'!asObject "This is the inverse of Object.asOop; look there for details. Only Stretch should encounter this code." self >= -16384 ifTrue: [self even ifTrue: [^ self // 2] "even --> negative" ifFalse: [^ (self+1) // -2]] "odd --> positive" ifFalse: [^ #NonExistentObject]! !!LargeNegativeInteger methodsFor: 'printing'!printOn: aStream base: b aStream nextPut: $-. super printOn: aStream base: b! !!LargeNegativeInteger methodsFor: 'system primitives'!digitAt: index "Answer the value of an indexable field in the receiver. Fail if the argument (the index) is not an Integer or is out of bounds. Essential. See Object documentation whatIsAPrimitive." <primitive: 60> self digitLength < index ifTrue: [^0] ifFalse: [^super at: index]!digitAt: index put: value "Store the second argument (value) in the indexable field of the receiver indicated by index. Fail if the value is negative or is larger than 255. Fail if the index is not an Integer or is out of bounds. Answer the value that was stored. Essential. See Object documentation whatIsAPrimitive." <primitive: 61> ^super at: index put: value!digitLength "Answer the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Essential. See Object documentation whatIsAPrimitive." <primitive: 62> self primitiveFailed! !!LargeNegativeInteger methodsFor: 'truncation and round off'!truncated "If I can be represented as a SmallInteger, return the converted result. This message should really be called something else, since it is only used internally after arithmetic and bit operations." | size partial maxSize | size _ self digitLength. size = 0 ifTrue: [^0]. partial _ self digitAt: size. partial = 0 ifTrue: [^(self growby: -1) truncated]. maxSize _ SmallInteger maxBytes. (size < maxSize or: [size = maxSize and: [partial < MinHi or: [partial = MinHi and: [(self anyBitTo: maxSize - 1 * 8) not]]]]) ifTrue: ["Convert back to a SmallInteger." partial _ 0 - partial. [(size _ size - 1) > 0] whileTrue: [partial _ (partial bitShift: 8) - (self digitAt: size)]. "Can't overflow" ^partial]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!LargeNegativeInteger class instanceVariableNames: ''!!LargeNegativeInteger class methodsFor: 'class initialization'!initialize "If a LargeNegativeInteger is exactly SmallInteger maxBytes in size, and its high-order byte does not exceed MaxHi, the number should be a SmallInteger." SmallInteger initialize. MinHi _ (SmallInteger minVal bitShift: (SmallInteger maxBytes - 1 * -8)) negated "LargeNegativeInteger initialize."! !LargeNegativeInteger initialize! Integer variableByteSubclass: #LargePositiveInteger instanceVariableNames: '' classVariableNames: 'MaxHi ' poolDictionaries: '' category: 'Numeric-Numbers'!LargePositiveInteger comment:'A positive large integer. Nearly all the work is done in Integer: LargePositiveInteger just overrides a few messages.'!!LargePositiveInteger methodsFor: 'arithmetic'!* anInteger "Multiply the receiver by the argument and answer with an Integer result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive. " <primitive: 29> ^super * anInteger!+ anInteger "Add the receiver to the argument and answer with an Integer result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 21> ^super + anInteger!- anInteger "Subtract the argument from the receiver and answer with an Integer result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive. " <primitive: 22> ^super - anInteger!/ anInteger "Divide the receiver by the argument and answer with the result if the division is exact. Fail if the result is not a whole integer. Fail if the argument is 0. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive. " <primitive: 30> ^super / anInteger!// anInteger "Divide the receiver by the argument and return the result. Round the result down towards negative infinity to make it a whole integer. Fail if the argument is 0. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive. " <primitive: 32> ^super // anInteger!abs!negated | minVal | ((self digitAt: 1) = 0 and: [self digitLength = 1]) ifTrue: [^self]. "Zero" minVal _ SmallInteger minVal. ((self digitAt: 2) = (0 - (minVal // 256)) and: [(self digitAt: 1) = 0]) ifTrue: [^minVal]. ^self copyto: (LargeNegativeInteger new: self digitLength)!quo: anInteger "Divide the receiver by the argument and return the result. Round the result down towards zero to make it a whole integer. Fail if the argument is 0. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 33> ^super quo: anInteger!\\ anInteger "Take the receiver modulo the argument. The result is the remainder rounded towards negative infinity, of the receiver divided by the argument. Fail if the argument is 0. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 31> ^super \\ anInteger! !!LargePositiveInteger methodsFor: 'bit manipulation'!bitAnd: anInteger "Logical AND the twos-complement representation of the receiver with the argument and return the result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 34> ^super bitAnd: anInteger!bitOr: anInteger "Logical OR the twos-complement representation of the receiver with the argument and return the result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 35> ^super bitOr: anInteger!bitShift: anInteger "Answer with a Integer whose value (in twos-complement representation) is the receiver's value (in twos-complement representation) shifted left by the number of bits indicated by the argument. Negative arguments shift right. Zeros are shifted in from the right in left shifts. The sign bit is extended in right shifts. Fail if the result cannot be represented as a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 37> ^super bitShift: anInteger!bitXor: anInteger "Logical XOR the twos-complement representation of the receiver with the argument and return the result. Fail if either the argument or the result is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 36> ^super bitXor: anInteger!highBit "Answer with the index of the high order bit of the binary representation of this number " ^self lastDigit highBit + (8 * (self digitLength - 1))! !!LargePositiveInteger methodsFor: 'testing'!negative ^false!positive ^true! !!LargePositiveInteger methodsFor: 'comparing'!< anInteger "Compare the receiver with the argument and return true if the receiver is less than the argument. Otherwise return false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 23> ^super < anInteger!<= anInteger "Compare the receiver with the argument and return true if the receiver is less than or equal to the argument. Otherwise return false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 25> ^super <= anInteger!= anInteger "Compare the receiver with the argument and return true if the receiver is equal to the argument. Otherwise return false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 27> ^super = anInteger!> anInteger "Compare the receiver with the argument and return true if the receiver is greater than the argument. Otherwise return false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 24> ^super > anInteger!>= anInteger "Compare the receiver with the argument and answer with true if the receiver is greater than or equal to the argument. Otherwise return false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 26> ^super >= anInteger!~= anInteger "Compare the receiver with the argument and answer true if the receiver is not equal to the argument. Otherwise answer false. Fail if the argument is not a SmallInteger or a LargePositiveInteger less than 65536. Optional. See Object documentation whatIsAPrimitive." <primitive: 28> ^super ~= anInteger! !!LargePositiveInteger methodsFor: 'converting'!asObject "This is the inverse of Object.asOop; look there for details." <primitive: 76> self < 32768 ifTrue: [^ (self-32768) asObject]. "16K...32K-1 synonym for -16K...-1" self < 49152 ifTrue: [^ self-32768]. "32K...48K-1 --> SmallIntegers 0...16K-1" self < 65536 ifTrue: [^ self-65536]. "48K...64K-1 --> SmallIntegers -16K...-1" ^ #NonExistentObject! !!LargePositiveInteger methodsFor: 'system primitives'!digitAt: index "Answer with the value of an indexable field in the receiver. Fail if the argument (the index) is not an Integer or is out of bounds. Essential. See Object documentation whatIsAPrimitive." <primitive: 60> self digitLength < index ifTrue: [^0] ifFalse: [^super at: index]!digitAt: index put: value "Store the second argument (value) in the indexable field of the receiver indicated by index. Fail if the value is negative or is larger than 255. Fail if the index is not an Integer or is out of bounds. Answer with the value that was stored. Essential. See Object documentation whatIsAPrimitive." <primitive: 61> ^super at: index put: value!digitLength "Answer with the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Essential. See Object documentation whatIsAPrimitive." <primitive: 62> self primitiveFailed! !!LargePositiveInteger methodsFor: 'truncation and round off'!truncated "If I can be represented as a SmallInteger, return the converted result. This message should really be called something else, since it is only used internally after arithmetic and bit operations, and in a few external places that construct LargePositiveIntegers in non- standard ways." | size partial maxSize | size _ self digitLength. size = 0 ifTrue: [^0]. partial _ self digitAt: size. partial = 0 ifTrue: [^(self growby: -1) truncated]. maxSize _ SmallInteger maxBytes. (size < maxSize or: [size = maxSize and: [partial <= MaxHi]]) ifTrue: ["Convert back to a SmallInteger." [(size _ size - 1) > 0] whileTrue: [partial _ (partial bitShift: 8) + (self digitAt: size)]. "Can't overflow" ^partial]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!LargePositiveInteger class instanceVariableNames: ''!!LargePositiveInteger class methodsFor: 'class initialization'!initialize "If a LargePositiveInteger is exactly SmallInteger maxBytes in size, and its high-order byte does not exceed MaxHi, the number should be a SmallInteger." SmallInteger initialize. MaxHi _ SmallInteger maxVal bitShift: (SmallInteger maxBytes - 1 * -8) "LargePositiveInteger initialize."! !LargePositiveInteger initialize! ParseNode subclass: #LeafNode instanceVariableNames: 'key code ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!LeafNode comment: 'I represent a leaf node of the compiler parse tree. I am abstract. Types (defined in class ParseNode): 1 LdInstType (which uses class VariableNode) 2 LdTempType (which uses class VariableNode) 3 LdLitType (which uses class LiteralNode) 4 LdLitIndType (which uses class VariableNode) 5 SendType (which uses class SelectorNode)'!!LeafNode methodsFor: 'initialize-release'!key: object code: byte key _ object. code _ byte!key: object index: i type: type self key: object code: (self code: i type: type)!name: ignored key: object code: byte key _ object. code _ byte!name: literal key: object index: i type: type self key: object index: i type: type! !!LeafNode methodsFor: 'accessing'!key ^key! !!LeafNode methodsFor: 'code generation'!code ^code!emitForEffect: stack on: strm ^self!emitLong: mode on: aStream "emit extended variable access" | type index | code < 256 ifTrue: [code < 16 ifTrue: [type _ 0. index _ code] ifFalse: [code < 32 ifTrue: [type _ 1. index _ code - 16] ifFalse: [code < 96 ifTrue: [type _ code // 32 + 1. index _ code \\ 32] ifFalse: [self error: 'Sends should be handled in SelectorNode']]]] ifFalse: [index _ code \\ 256. type _ code // 256 - 1]. aStream nextPut: mode. aStream nextPut: type * 64 + index!reserve: encoder "if this is a yet unused literal of type -code, reserve it" code < 0 ifTrue: [code _ self code: (encoder litIndex: key) type: 0 - code]!size: encoder ^self sizeForValue: encoder!sizeForEffect: encoder ^0!sizeForValue: encoder self reserve: encoder. code < 256 ifTrue: [^1]. ^2! !!LeafNode methodsFor: 'private'!code: index type: type index isNil ifTrue: [^type negated]. (CodeLimits at: type) > index ifTrue: [^(CodeBases at: type) + index]. ^type * 256 + index! ! Path subclass: #Line instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!Line comment: 'This Class is a Line specified by two points. This is a sub-class of path though the two points that determine the line are called begin and end. '!!Line methodsFor: 'accessing'!beginPoint "Answer the first end point of the receiver." ^self first!beginPoint: aPoint "Set the first end point of the receiver. Answer the argument, aPoint." self at: 1 put: aPoint. ^aPoint!endPoint "Answer the first end point of the receiver." ^self last!endPoint: aPoint "Set the first end point of the receiver." self at: 2 put: aPoint. ^aPoint! !!Line methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm "The form associated with this Path will be displayed, according to one of the sixteen functions of two logical variables (rule), at each point on the Line. Also the source form will be first anded with aForm as a mask. Does not effect the state of the Path." collectionOfPoints size < 2 ifTrue: [self error: 'a line must have two points']. aDisplayMedium drawLine: self form from: self beginPoint + aPoint to: self endPoint + aPoint clippingBox: clipRect rule: anInteger mask: aForm!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm | newPath newLine | newPath _ aTransformation applyTo: self. newLine _ Line new. newLine beginPoint: newPath firstPoint. newLine endPoint: newPath secondPoint. newLine form: self form. newLine displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRect rule: anInteger mask: aForm! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Line class instanceVariableNames: ''!!Line class methodsFor: 'instance creation'!from: beginPoint to: endPoint withForm: aForm | newSelf | newSelf _ super new: 2. newSelf add: beginPoint. newSelf add: endPoint. newSelf form: aForm. ^newSelf!new | newSelf | newSelf _ super new: 2. newSelf add: 0@0. newSelf add: 0@0. ^newSelf! !!Line class methodsFor: 'examples'!example "Designate two places on the screen by clicking any mouse button. A straight path with a square black form will be displayed connecting the two selected points." | aLine aForm | aForm _ Form new extent: 20@20. "make a form one quarter of inch square" aForm black. "turn it black" aLine _ Line new. aLine form: aForm. "use the black form for display" aLine beginPoint: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aLine beginPoint. aLine endPoint: Sensor waitButton. aLine displayOn: Display. "display the line" "Line example."! ! Path subclass: #LinearFit instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!LinearFit comment: 'A subclass of Path that is a piece-wise linear approximation to a set of points in the plane.'!!LinearFit methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm | pt line | line _ Line new. line form: self form. 1 to: self size - 1 do: [:i | line beginPoint: (self at: i). line endPoint: (self at: i + 1). line displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm]!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm | newLinearFit transformedPath | "get the scaled and translated Path." transformedPath _ aTransformation applyTo: self. newLinearFit _ LinearFit new. transformedPath do: [:point | newLinearFit add: point]. newLinearFit form: self form. newLinearFit displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRect rule: anInteger mask: aForm! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!LinearFit class instanceVariableNames: ''!!LinearFit class methodsFor: 'examples'!example "Select points on a Path using the red button. Terminate by selecting any other button. Creates a Path from the points and displays it as a piece-wise linear approximation." | aLinearFit aForm flag | aLinearFit _ LinearFit new. aForm _ Form new extent: 1 @ 40. aForm black. aLinearFit form: aForm. flag _ true. [flag] whileTrue: [Sensor waitButton. Sensor redButtonPressed ifTrue: [aLinearFit add: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aLinearFit last] ifFalse: [flag_false]]. aLinearFit displayOn: Display "LinearFit example."! ! Object subclass: #Link instanceVariableNames: 'nextLink ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Support'!Link comment: 'I am a simple record of a pointer to another Link'!!Link methodsFor: 'accessing'!nextLink "Answer the Link to which the receiver points." ^nextLink!nextLink: aLink "Store the argument, as the Link to which the receiver refers." ^nextLink _ aLink! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Link class instanceVariableNames: ''!!Link class methodsFor: 'instance creation'!nextLink: aLink "Answer a new instance of me referring to the argument, aLink." ^self new nextLink: aLink! ! SequenceableCollection subclass: #LinkedList instanceVariableNames: 'firstLink lastLink ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Sequenceable'!LinkedList comment: 'I implement ordered collections using a chain of elements. I can be initialized using LinkedList with: Link new'!!LinkedList methodsFor: 'accessing'!first "Answer the first link; create an error if the receiver is empty." self emptyCheck. ^firstLink!last "Answer the last link; create an error if the receiver is empty." self emptyCheck. ^lastLink!size "Answer how many elements the receiver contains." | tally | tally _ 0. self do: [:each | tally _ tally + 1]. ^tally! !!LinkedList methodsFor: 'testing'!isEmpty ^firstLink == nil! !!LinkedList methodsFor: 'adding'!add: aLink "Add aLink to the end of the receiver's list." ^self addLast: aLink!addFirst: aLink "Add aLink to the beginning of the receiver's list." self isEmpty ifTrue: [lastLink _ aLink]. aLink nextLink: firstLink. firstLink _ aLink. ^aLink!addLast: aLink "Add aLink to the end of the receiver's list." self isEmpty ifTrue: [firstLink _ aLink] ifFalse: [lastLink nextLink: aLink]. lastLink _ aLink. ^aLink! !!LinkedList methodsFor: 'removing'!remove: aLink ifAbsent: aBlock "Remove aLink from the receiver. If it is not there, answer the result of evaluating aBlock." | tempLink | aLink == firstLink ifTrue: [firstLink _ aLink nextLink. aLink == lastLink ifTrue: [lastLink _ nil]] ifFalse: [tempLink _ firstLink. [tempLink == nil ifTrue: [^aBlock value]. tempLink nextLink == aLink] whileFalse: [tempLink _ tempLink nextLink]. tempLink nextLink: aLink nextLink. aLink == lastLink ifTrue: [lastLink _ tempLink]]. aLink nextLink: nil. ^aLink!removeFirst "Remove the first element. If the receiver is empty, cause an error; otherwise answer the removed element. Using the sequence addFirst:/removeFirst causes the receiver to behave as a stack; using addLast:/removeFirst causes the receiver to behave as a queue." | oldLink | self emptyCheck. oldLink _ firstLink. firstLink == lastLink ifTrue: [firstLink _ nil. lastLink _ nil] ifFalse: [firstLink _ oldLink nextLink]. oldLink nextLink: nil. ^oldLink!removeLast "Remove the receiver's last element. If the receiver is empty, cause an error; otherwise answer the removed element. Using addLast:/removeLast causes the receiver to behave as a stack; using addFirst:/removeLast causes the receiver to behave as a queue." | oldLink aLink | self emptyCheck. oldLink _ lastLink. firstLink == lastLink ifTrue: [firstLink _ nil. lastLink _ nil] ifFalse: [aLink _ firstLink. [aLink nextLink == oldLink] whileFalse: [aLink _ aLink nextLink]. aLink nextLink: nil. lastLink _ aLink]. oldLink nextLink: nil. ^oldLink! !!LinkedList methodsFor: 'enumerating'!do: aBlock | aLink | aLink _ firstLink. [aLink == nil] whileFalse: [aBlock value: aLink. aLink _ aLink nextLink]! ! ScrollController subclass: #ListController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Lists'!ListController comment:'I am a kind of ScrollController that assumes that the view is a kind of ListView. Therefore, scrolling means moving the items in a textual list (menu) up or down. In addition, I provide the red button activity of determining when the red button is selecting an item in the list.'!!ListController methodsFor: 'control defaults'!isControlActive ^super isControlActive & sensor blueButtonPressed not! !!ListController methodsFor: 'marker adjustment'!computeMarkerRegion | viewList | viewList _ view list. ^ 0@0 extent: 10@ ((viewList clippingRectangle height asFloat / viewList compositionRectangle height * scrollBar inside height) rounded min: scrollBar inside height)!markerDelta | viewList | viewList _ view list. ^(marker top - scrollBar inside top) - ((viewList clippingRectangle top - viewList compositionRectangle top) asFloat / viewList compositionRectangle height asFloat * scrollBar inside height asFloat) rounded! !!ListController methodsFor: 'scrolling'!canScroll | viewList | viewList _ view list. ^viewList compositionRectangle height - viewList clippingRectangle height > (viewList lineGrid // 2)!scrollAmount ^sensor cursorPoint y - scrollBar inside top!scrollView: anInteger | viewList maximumAmount minimumAmount amount | viewList _ view list. maximumAmount _ viewList clippingRectangle top - viewList compositionRectangle top max: 0. minimumAmount _ viewList clippingRectangle bottom - viewList compositionRectangle bottom min: 0. amount _ (anInteger min: maximumAmount) max: minimumAmount. amount ~= 0 ifTrue: [view deselect. viewList scrollBy: amount negated. view isSelectionBoxClipped "ifTrue: [ self changeModelSelection: 0] compile this code to deselect when the selection is scrolled outside of the visible region" ifFalse: [ view displaySelectionBox ]]!scrollViewDown self scrollView: self scrollAmount.!scrollViewUp self scrollView: (self scrollAmount) negated.!viewDelta | viewList | viewList _ view list. ^(viewList clippingRectangle top - viewList compositionRectangle top - ((marker top - scrollBar inside top) asFloat / scrollBar inside height asFloat * viewList compositionRectangle height asFloat)) roundTo: viewList lineGrid! !!ListController methodsFor: 'menu messages'!redButtonActivity | noSelectionMovement oldSelection trialSelection nextSelection | noSelectionMovement _ true. oldSelection _ view selection. [sensor redButtonPressed] whileTrue: [trialSelection _ view findSelection: sensor cursorPoint. trialSelection ~~ nil ifTrue: [nextSelection _ trialSelection. view moveSelectionBox: nextSelection. nextSelection ~= oldSelection ifTrue: [noSelectionMovement _ false]]]. nextSelection ~~ nil & (nextSelection = oldSelection ifTrue: [noSelectionMovement] ifFalse: [true]) ifTrue: [self changeModelSelection: nextSelection]! !!ListController methodsFor: 'private'!changeModelSelection: anInteger model toggleListIndex: anInteger! ! View subclass: #ListView instanceVariableNames: 'list selection topDelimiter bottomDelimiter lineSpacing isEmpty ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Lists'!ListView comment:'I am an abstract View of a list of items. I provide support for storing a selection of one item, as well as formatting the list for presentation on the screen. My default controller is ListController.Instance Variables: list <Array> of Strings, each one an item selection <Integer> index into the array, list topDelimiter <String>, usually ------------, indicating the top of the list bottomDelimiter <String>, usually ------------, indicating the bottom of the list lineSpacing <Integer> the amount of extra space between line items isEmpty <Boolean> true if the list is empty '!!ListView methodsFor: 'initialize-release'!initialize super initialize. insideColor _ Form white. topDelimiter _ '------------'. bottomDelimiter _ '------------'. lineSpacing _ 0. isEmpty _ true! !!ListView methodsFor: 'list access'!list "Answer the list of items the receiver displays." ^list!list: itemCollection "Create the textList corresponding to the items in itemCollection." isEmpty _ itemCollection isNil. list _ TextList onList: (topDelimiter == nil ifTrue: [itemCollection] ifFalse: [(Array with: topDelimiter) , itemCollection , (Array with: bottomDelimiter)]). selection _ 0. self positionList!reset "Set the list of items displayed to be empty." isEmpty _ true. self list: Array new!resetAndDisplayView "Set the list of items displayed to be empty and redisplay the receiver." isEmpty ifFalse: [self reset. self displayView]! !!ListView methodsFor: 'delimiters'!bottomDelimiter "Answer the string used to indicate the bottom of the list." ^bottomDelimiter!bottomDelimiter: aString "Set the string used to indicate the bottom of the list." bottomDelimiter _ aString!noBottomDelimiter "Set the string used to indicate the bottom of the list to be nothing." bottomDelimiter _ nil!noTopDelimiter "Set the string used to indicate the top of the list to be nothing." topDelimiter _ nil!topDelimiter "Answer the string used to indicate the top of the list." ^topDelimiter!topDelimiter: aString "Set the string used to indicate the top of the list." topDelimiter _ aString! !!ListView methodsFor: 'displaying'!display list == nil ifTrue: [self list: Array new]. self isUnlocked ifTrue: [self positionList]. super display!displayView self clearInside. list displayOn: Display. self displaySelectionBox! !!ListView methodsFor: 'deEmphasizing'!deEmphasizeView | aRectangle newForm | self deselect. selection ~= 0 ifTrue: [aRectangle _ (self selectionBox intersect: self clippingBox). aRectangle _ aRectangle insetOriginBy: 0@-1 cornerBy: 0@0. newForm _ Form fromDisplay: aRectangle. newForm displayOn: Display at: (aRectangle topLeft + (1@0)) clippingBox: aRectangle rule: Form under mask: Form black. Display fill: aRectangle rule: Form under mask: Form lightGray]! !!ListView methodsFor: 'controller access'!defaultControllerClass ^ListController! !!ListView methodsFor: 'display box access'!boundingBox ^list boundingBox! !!ListView methodsFor: 'clipping box access'!clippingBox "Answer the rectangle in which the model can be displayed--this is the insetDisplayBox inset by the height of a line for an item." ^self insetDisplayBox insetBy: (Rectangle left: 0 right: 0 top: 0 bottom: self insetDisplayBox height \\ list lineGrid)! !!ListView methodsFor: 'selecting'!deselect "If the receiver has a selection, then it is highlighted. Remove the highlighting." selection ~= 0 ifTrue: [Display reverse: (self selectionBox intersect: self clippingBox)]!displaySelectionBox "If the receiver has a selection and that selection is visible on the display screen, then highlight it." (selection ~= 0 and: [self selectionBox intersects: self clippingBox]) ifTrue: [Display reverse: (self selectionBox intersect: self clippingBox)]!findSelection: aPoint "Determine which selection is displayed in an area containing the point, aPoint. Answer the selection if one contains the point, answer nil otherwise." | trialSelection | (self clippingBox containsPoint: aPoint) ifFalse: [^nil]. trialSelection _ aPoint y - list compositionRectangle top // list lineGrid + 1. trialSelection < self minimumSelection | (trialSelection > self maximumSelection) ifTrue: [^nil] ifFalse: [^trialSelection - self minimumSelection + 1]!isSelectionBoxClipped "Answer whether there is a selection and whether the selection is visible on the screen." ^selection ~= 0 & (self selectionBox intersects: self clippingBox) not!maximumSelection "Answer which selection is the last possible one." topDelimiter == nil ifTrue: [^list numberOfLines] ifFalse: [^list numberOfLines - 1]!minimumSelection "Answer which selection is the first possible one." topDelimiter == nil ifTrue: [^1] ifFalse: [^2]!moveSelectionBox: anInteger "Presumably the selection has changed to be anInteger. Deselect the previous selection and display the new one, highlighted." selection ~= anInteger ifTrue: [self deselect. selection _ anInteger. self displaySelectionBox]!selection "Answer the receiver's current selection." ^selection!selectionBox "Answer the rectangle in which the current selection is displayed." ^(self insetDisplayBox left @ (list compositionRectangle top + self selectionBoxOffset) extent: self insetDisplayBox width @ list lineGrid) insetBy: (Rectangle left: 1 right: 1 top: 1 bottom: 0)!selectionBoxOffset "Answer an integer that determines the y position for the display box of the current selection." ^selection - 1 + self minimumSelection - 1 * list lineGrid! !!ListView methodsFor: 'updating'!update: aSymbol aSymbol == #list ifTrue: [self list: model list. self displayView. ^self]. aSymbol == #listIndex ifTrue: [self moveSelectionBox: model listIndex. ^self]! !!ListView methodsFor: 'private'!positionList list repositionAt: (self wrappingBox topLeft) clippingBox: self clippingBox!wrappingBox | aRectangle | aRectangle _ self insetDisplayBox. selection = 0 ifTrue: [^aRectangle topLeft + (4 @ 0) extent: list compositionRectangle extent] ifFalse: [^aRectangle left + 4 @ (aRectangle top - (self selectionBoxOffset min: ((list height - aRectangle height + list lineGrid truncateTo: list lineGrid) max: 0))) extent: list compositionRectangle extent]! ! Dictionary variableSubclass: #LiteralDictionary instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!LiteralDictionary comment:'LiteralDictionaries check not only for equality but also for same class of their keys.This avoids the problem of 0 being considered = to 0.0 as in Dictionaries, and italso avoids the problem of 1.3 not being == to 1.3 (necessarily), as in IdentityDictionaries.'!!LiteralDictionary methodsFor: 'private'!findKeyOrNil: key | location length probe pass | length _ self basicSize. pass _ 1. location _ key hash \\ length + 1. [(probe _ self basicAt: location) == nil or: [probe key class == key class and: [probe key = key]]] whileFalse: [(location _ location + 1) > length ifTrue: [location _ 1. pass _ pass + 1. pass > 2 ifTrue: [^self grow findKeyOrNil: key]]]. ^location! ! LeafNode subclass: #LiteralNode instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!LiteralNode comment: 'I am a parse tree leaf representing a literal string or number'!!LiteralNode methodsFor: 'code generation'!emitForValue: stack on: strm code < 256 ifTrue: [strm nextPut: code] ifFalse: [self emitLong: LdInstLong on: strm]. stack push: 1! !!LiteralNode methodsFor: 'printing'!printOn: aStream indent: level key storeOn: aStream! ! ListController subclass: #LockedListController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Lists'!LockedListController comment:'I am a kind of ListController that blocks new selections if the model is locked--i.e., has been changed in some way that still requires completion.'!!LockedListController methodsFor: 'control defaults'!controlActivity self normalResponseTest ifTrue: [^super controlActivity]. self feedbackResponseTest ifTrue: [^view flash]! !!LockedListController methodsFor: 'model access'!feedbackResponseTest "Answer whether the receiver should respond to any user button requests." ^sensor anyButtonPressed | self scrollBarContainsCursor!normalResponseTest "Answer whether the receiver can proceed with selections--depends on whether the model is locked." ^model isUnlocked! ! SwitchController subclass: #LockedSwitchController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!LockedSwitchController comment:'I am a SwitchController that will not take control if the model (a Switch) is locked. As an indication, the view (a SwitchView) flashes.'!!LockedSwitchController methodsFor: 'control defaults'!isControlWanted model isLocked ifTrue: [view flash. ^false]. ^super isControlWanted! ! Magnitude subclass: #LookupKey instanceVariableNames: 'key ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Support'!LookupKey comment: 'I serve as the key for looking up entries in a Dictionary. Subclasses of me are dictionary entries. An available example is Association.'!!LookupKey methodsFor: 'comparing'!< aLookupKey ^key < aLookupKey key!= aLookupKey self species = aLookupKey species ifTrue: [^key = aLookupKey key] ifFalse: [^false]!hash ^key hash!hashMappedBy: map "Answer what my hash would be if oops changed according to map" ^ key hashMappedBy: map! !!LookupKey methodsFor: 'accessing'!key "Answer the lookup key of the receiver." ^key!key: anObject "Store the argument, anObject, as the lookup key of the receiver." key _ anObject! !!LookupKey methodsFor: 'printing'!printOn: aStream key printOn: aStream! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!LookupKey class instanceVariableNames: ''!!LookupKey class methodsFor: 'instance creation'!key: aKey "Answer a new instance of me with the argument as the lookup up." ^self new key: aKey! ! Object subclass: #Magnitude instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Magnitudes'!Magnitude comment: 'This abstract class assists subclasses which measure something linear like dates or times.'!!Magnitude methodsFor: 'comparing'!< aMagnitude "Compare the receiver with the argument and answer with true if the receiver is less than the argument. Otherwise answer false." ^self subclassResponsibility!<= aMagnitude "Compare the receiver with the argument and answer with true if the receiver is less than or equal to the argument. Otherwise answer false." ^(self > aMagnitude) not!= aMagnitude "Compare the receiver with the argument and answer with true if the receiver is equal to the argument. Otherwise answer false." ^self subclassResponsibility!> aMagnitude "Compare the receiver with the argument and answer with true if the receiver is greater than the argument. Otherwise answer false." ^aMagnitude < self!>= aMagnitude "Compare the receiver with the argument and answer with true if the receiver is greater than or equal to the argument. Otherwise answer false." ^(self < aMagnitude) not!between: min and: max "Answer whether the receiver is less than or equal to the argument, max, and greater than or equal to the argument, min." ^self >= min and: [self <= max]!hash "Hash must be redefined whenever = is redefined." ^self subclassResponsibility!hashMappedBy: map "My hash is independent of my oop" ^ self hash!max: aMagnitude "Answer the receiver or the argument, whichever has the greater magnitude." self > aMagnitude ifTrue: [^self] ifFalse: [^aMagnitude]!min: aMagnitude "Answer the receiver or the argument, whichever has the lesser magnitude." self < aMagnitude ifTrue: [^self] ifFalse: [^aMagnitude]! ! Collection subclass: #MappedCollection instanceVariableNames: 'domain map ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Sequenceable'!MappedCollection comment: 'I am re-ordering or subcollecting of a writeable SequenceableCollection.'!!MappedCollection methodsFor: 'accessing'!at: anIndex ^domain at: (map at: anIndex)!at: anIndex put: anObject ^domain at: (map at: anIndex) put: anObject!contents "Answer the receiver's domain for mapping, a SequenceableCollection." ^map collect: [:mappedIndex | domain at: mappedIndex]!size ^map size! !!MappedCollection methodsFor: 'adding'!add: newObject self shouldNotImplement! !!MappedCollection methodsFor: 'copying'!copy "This returns another MappedCollection whereas copyFrom:to: will return an object like my domain" ^MappedCollection collection: domain map: map! !!MappedCollection methodsFor: 'printing'!storeOn: aStream aStream nextPut: $(. domain storeOn: aStream. aStream nextPutAll: ' mappedBy: '. map storeOn: aStream. aStream nextPut: $)! !!MappedCollection methodsFor: 'private'!setCollection: aCollection map: aDictionary domain _ aCollection. map _ aDictionary!species ^domain species! !!MappedCollection methodsFor: 'enumerating'!collect: aBlock | aStream | aStream _ WriteStream on: (self species new: self size). self do: [:domainValue | aStream nextPut: (aBlock value: domainValue)]. ^aStream contents!do: aBlock map do: [:mapValue | aBlock value: (domain at: mapValue)]!select: aBlock | aStream | aStream _ WriteStream on: (self species new: self size). self do: [:domainValue | (aBlock value: domainValue) ifTrue: [aStream nextPut: domainValue]]. ^aStream contents! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MappedCollection class instanceVariableNames: ''!!MappedCollection class methodsFor: 'instance creation'!collection: aCollection map: aSequenceableCollection "Answer a new instance of me that maps aCollection by aSequenceableCollection." ^self basicNew setCollection: aCollection map: aSequenceableCollection!new self error: 'MappedCollections must be created using the collection:map: message'! ! Object subclass: #Message instanceVariableNames: 'selector args ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'!Message comment: 'I represent a selector and its argument values. Generally, the system does not use instances of Message. However, when a message is not understood by its receiver, the interpreter will make up a Message (to capture the information involved in an actual message transmission) and send it as an argument with the message doesNotUnderstand:.'!!Message methodsFor: 'accessing'!arguments "Answer the arguments of the receiver." ^args!selector "Answer the selector of the receiver." ^selector! !!Message methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'a Message with selector: '. selector printOn: aStream. aStream nextPutAll: ' and arguments: '. args printOn: aStream. ^aStream!storeOn: aStream aStream nextPut: $(. aStream nextPutAll: 'Message selector: '. selector storeOn: aStream. aStream nextPutAll: ' arguments: '. args storeOn: aStream. aStream nextPut: $)! !!Message methodsFor: 'private'!setSelector: aSymbol arguments: anArray selector _ aSymbol. args _ anArray! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Message class instanceVariableNames: ''!!Message class methodsFor: 'instance creation'!selector: aSymbol "Answer an instance of me with unary selector, aSymbol." ^self new setSelector: aSymbol arguments: (Array new: 0)!selector: aSymbol argument: anObject "Answer an instance of me whose selector is aSymbol and single argument is anObject." ^self new setSelector: aSymbol arguments: (Array with: anObject)!selector: aSymbol arguments: anArray "Answer an instance of me with selector, aSymbol, and arguments, anArray." ^self new setSelector: aSymbol arguments: anArray! ! ParseNode subclass: #MessageNode instanceVariableNames: 'receiver selector precedence special arguments sizes pc ' classVariableNames: 'MacroEmitters MacroSelectors MacroSizers MacroTransformers ThenFlag ' poolDictionaries: '' category: 'System-Compiler'!MessageNode comment: 'I represent a receiver and its message.Precedence codes: 1 unary 2 binary 3 keyword 4 otherIf special>0, I compile special code in-line instead of sending messages with literal methods as remotely copied contexts.'!!MessageNode methodsFor: 'initialize-release'!receiver: rcvr selector: selNode arguments: args precedence: p "decompile" self receiver: rcvr arguments: args precedence: p. special _ MacroSelectors indexOf: selNode key. selector _ selNode!receiver: rcvr selector: selName arguments: args precedence: p from: encoder "compile" self receiver: rcvr arguments: args precedence: p. special _ MacroSelectors indexOf: selName. (self transform: encoder) ifTrue: [selector _ SelectorNode new key: (MacroSelectors at: special) code: #macro] ifFalse: [selector _ encoder encodeSelector: selName. rcvr == NodeSuper ifTrue: [encoder noteSuper]]!receiver: rcvr selector: selName arguments: args precedence: p from: encoder sourceRange: range "compile" encoder noteSourceRange: range forNode: self. ^self receiver: rcvr selector: selName arguments: args precedence: p from: encoder! !!MessageNode methodsFor: 'testing'!canCascade ^(receiver == NodeSuper or: [special > 0]) not!isReturningIf ^(special between: 3 and: 4) and: [arguments first returns and: [arguments last returns]]! !!MessageNode methodsFor: 'expression types'!cascadeReceiver "nil out rcvr (to indicate cascade) and return what it had been" | rcvr | rcvr _ receiver. receiver _ nil. ^rcvr! !!MessageNode methodsFor: 'code generation'!emitForEffect: stack on: strm special > 0 ifTrue: [self perform: (MacroEmitters at: special) with: stack with: strm with: false. pc _ 0] ifFalse: [super emitForEffect: stack on: strm. pc _ strm position]!emitForValue: stack on: strm | argument | special > 0 ifTrue: [self perform: (MacroEmitters at: special) with: stack with: strm with: true. pc _ 0] ifFalse: [receiver ~~ nil ifTrue: [receiver emitForValue: stack on: strm]. arguments do: [:argument | argument emitForValue: stack on: strm]. selector emit: stack args: arguments size on: strm super: receiver == NodeSuper. pc _ strm position]!emitIf: stack on: strm value: forValue "Emit code for <A> ifTrue: <B> ifFalse: <C>, with some optimizations" | thenExpr thenSize elseExpr elseSize | thenSize _ sizes at: 1. elseSize _ sizes at: 2. thenExpr _ arguments at: 1. elseExpr _ arguments at: 2. forValue ifTrue: ["Everything is straightforward for value: <A> bfp-C <B> jmp-end <C>" receiver emitForValue: stack on: strm. self emitBranch: thenSize pop: stack on: strm. thenExpr emitForEvaluatedValue: stack on: strm. stack pop: 1. thenExpr returns ifFalse: [self emitJump: elseSize on: strm]. elseExpr emitForEvaluatedValue: stack on: strm] ifFalse: ["If value not needed, check for possible shortcuts" (thenSize=0) & (elseSize=0) "null conditional" ifTrue: [^ receiver emitForEffect: stack on: strm]. (elseSize = 0) | (thenSize = 0) ifTrue: [receiver emitForValue: stack on: strm. (elseSize = 0) ifTrue: ["Shortcut for ifTrue: only: <A> bfp-end <B>" self emitBranch: thenSize pop: stack on: strm. thenExpr emitForEvaluatedEffect: stack on: strm] ifFalse: ["Shortcut for ifFalse: only <A> btp-end <C>" self emitTrueBranch: elseSize pop: stack on: strm. elseExpr emitForEvaluatedEffect: stack on: strm]] ifFalse: ["If no shortcuts, then compile for value followed by pop" super emitForEffect: stack on: strm]]!emitWhile: stack on: strm value: forValue "Size code for <A> whileTrue: <B>, or <A> whileFalse: <B>" | stmt stmtSize loopSize | stmt _ arguments at: 1. stmtSize _ sizes at: 1. "Includes loop-back jump" loopSize _ sizes at: 2. receiver emitForEvaluatedValue: stack on: strm. selector key == #whileTrue: ifTrue: [self emitBranch: stmtSize pop: stack on: strm] ifFalse: [self emitTrueBranch: stmtSize pop: stack on: strm]. stmt emitForEvaluatedEffect: stack on: strm. self emitJump: 0 - loopSize on: strm. forValue ifTrue: [strm nextPut: LdNil. stack push: 1]!pc "used by encoder source mapping" ^pc!sizeForEffect: encoder special > 0 ifTrue: [^self perform: (MacroSizers at: special) with: encoder with: false]. ^super sizeForEffect: encoder!sizeForValue: encoder | arg total argSize | special > 0 ifTrue: [^self perform: (MacroSizers at: special) with: encoder with: true]. receiver == NodeSuper ifTrue: [selector _ selector copy "only necess for splOops"]. total _ selector size: encoder args: arguments size super: receiver == NodeSuper. receiver == nil ifFalse: [total _ total + (receiver sizeForValue: encoder)]. sizes _ arguments collect: [:arg | argSize _ arg sizeForValue: encoder. total _ total + argSize. argSize]. ^total!sizeIf: encoder value: forValue "Size code for <A> ifTrue: <B> ifFalse: <C>, with some optimizations" | thenExpr thenSize elseExpr elseSize noElse noThen | thenExpr _ arguments at: 1. elseExpr _ arguments at: 2. forValue ifTrue: ["Everything is straightforward for value: <A> bfp-C <B> jmp-end <C>" elseSize _ elseExpr sizeForEvaluatedValue: encoder. thenSize _ (thenExpr sizeForEvaluatedValue: encoder) + (thenExpr returns ifTrue: [0] ifFalse: [self sizeJump: elseSize])] ifFalse: ["If value not needed, check for possible shortcuts" (noElse _ elseExpr isJust: NodeNil) | (noThen _ thenExpr isJust: NodeNil) ifFalse: "If no shortcuts, then compile for value followed by pop" [^ super sizeForEffect: encoder]. elseSize _ noElse ifTrue: [0] ifFalse: [elseExpr sizeForEvaluatedEffect: encoder]. thenSize _ noThen ifTrue: [0] ifFalse: [thenExpr sizeForEvaluatedEffect: encoder]]. sizes _ Array with: thenSize with: elseSize. (thenSize=0) & (elseSize=0) "null conditional" ifTrue: [^ receiver sizeForEffect: encoder]. ^ (receiver sizeForValue: encoder) + (thenSize=0 ifTrue: [2 "BTP is long"] ifFalse: [self sizeBranch: thenSize]) + thenSize + elseSize!sizeWhile: encoder value: forValue "Size code for <A> whileTrue: <B>, or <A> whileFalse: <B>" | cond stmt branchSize stmtSize loopSize | stmt _ arguments at: 1. stmtSize _ (stmt sizeForEvaluatedEffect: encoder) + 2. "loop jump is 2 bytes" selector key == #whileTrue: ifTrue: [branchSize _ self sizeBranch: stmtSize] ifFalse: [branchSize _ 2 "BTP is always 2 bytes"]. loopSize _ (receiver sizeForEvaluatedValue: encoder) + branchSize + stmtSize. sizes _ Array with: stmtSize with: loopSize. ^ loopSize + (forValue ifTrue: [1] ifFalse: [0]) "push nil (for value) takes 1 byte"! !!MessageNode methodsFor: 'debugger temp access'!isTemp "Sorry, folks, for now you cant use remote temps in blocks" "This could be fixed by supporting store protocol for the case of assignment into virtual fields in BlockNode sizeForValue and emitForValue" ^ false!store: expr from: encoder "ctxt tempAt: n -> ctxt tempAt: n put: expr (see Assignment). For assigning into temps of a context being debugged" selector key ~= #tempAt: ifTrue: [^self error: 'cant transform this message']. ^MessageNode new receiver: receiver selector: #tempAt:put: arguments: (arguments copyWith: expr) precedence: precedence from: encoder! !!MessageNode methodsFor: 'printing'!precedence ^precedence!printIfOn: aStream indent: level (arguments last isJust: NodeNil) ifTrue: [^self printKeywords: #ifTrue: arguments: (Array with: arguments first) on: aStream indent: level]. (arguments last isJust: NodeFalse) ifTrue: [^self printKeywords: #and: arguments: (Array with: arguments first) on: aStream indent: level]. (arguments first isJust: NodeNil) ifTrue: [^self printKeywords: #ifFalse: arguments: (Array with: arguments last) on: aStream indent: level]. (arguments first isJust: NodeTrue) ifTrue: [^self printKeywords: #or: arguments: (Array with: arguments last) on: aStream indent: level]. self printKeywords: #ifTrue:ifFalse: arguments: arguments on: aStream indent: level!printKeywords: key arguments: args on: aStream indent: level | keywords part prev arg indent thisKey | args size = 0 ifTrue: [aStream space; nextPutAll: key. ^self]. keywords _ key keywords. prev _ receiver. 1 to: args size do: [:part | arg _ args at: part. thisKey _ keywords at: part. (prev isMemberOf: BlockNode) | ((prev isMemberOf: MessageNode) and: [prev precedence >= 3]) | ((arg isMemberOf: BlockNode) and: [arg isComplex and: [thisKey ~= #do:]]) | (args size > 2) | (key = #ifTrue:ifFalse:) ifTrue: [aStream crtab: level+1. indent _ 1] "newline after big args" ifFalse: [aStream space. indent _ 0]. aStream nextPutAll: thisKey; space. arg printOn: aStream indent: level + 1 + indent precedence: (precedence = 2 ifTrue: [1] ifFalse: [precedence]). prev _ arg]!printOn: aStream indent: level receiver == nil ifFalse: [receiver printOn: aStream indent: level precedence: precedence]. (special between: 1 and: 6) ifTrue: [self printIfOn: aStream indent: level] ifFalse: [self printKeywords: selector key arguments: arguments on: aStream indent: level]!printOn: strm indent: level precedence: p | parenthesize | parenthesize _ precedence > p or: [p = 3 and: [precedence = 3 "both keywords"]]. parenthesize ifTrue: [strm nextPutAll: '(']. self printOn: strm indent: level. parenthesize ifTrue: [strm nextPutAll: ')']! !!MessageNode methodsFor: 'private'!checkBlock: node as: nodeName from: encoder node canBeSpecialArgument ifTrue: [^node isMemberOf: BlockNode]. ((node isKindOf: BlockNode) and: [node numberOfArguments > 0]) ifTrue: [^encoder notify: '<- ', nodeName , ' of ' , (MacroSelectors at: special) , ' must be 0-argument block'] ifFalse: [^encoder notify: '<- ', nodeName , ' of ' , (MacroSelectors at: special) , ' must be a block or variable']!receiver: rcvr arguments: args precedence: p receiver _ rcvr. arguments _ args. sizes _ Array new: arguments size. precedence _ p!transform: encoder special = 0 ifTrue: [^false]. (self perform: (MacroTransformers at: special) with: encoder) ifTrue: [^true] ifFalse: [special _ 0. ^false]!transformAnd: encoder (self transformBoolean: encoder) ifTrue: [arguments _ Array with: (arguments at: 1) with: (BlockNode new statements: (Array with: NodeFalse) returns: false). ^true] ifFalse: [^false]!transformBoolean: encoder ^self checkBlock: (arguments at: 1) as: 'argument' from: encoder!transformIfFalse: encoder (self transformBoolean: encoder) ifTrue: [arguments _ Array with: (BlockNode new statements: (Array with: NodeNil) returns: false) with: (arguments at: 1). ^true] ifFalse: [^false]!transformIfFalseIfTrue: encoder ((self checkBlock: (arguments at: 1) as: 'False arg' from: encoder) and: [self checkBlock: (arguments at: 2) as: 'True arg' from: encoder]) ifTrue: [selector _ #ifTrue:ifFalse:. arguments swap: 1 with: 2. ^true] ifFalse: [^false]!transformIfTrue: encoder (self transformBoolean: encoder) ifTrue: [arguments _ Array with: (arguments at: 1) with: (BlockNode new statements: (Array with: NodeNil) returns: false). ^true] ifFalse: [^false]!transformIfTrueIfFalse: encoder ^(self checkBlock: (arguments at: 1) as: 'True arg' from: encoder) and: [self checkBlock: (arguments at: 2) as: 'False arg' from: encoder]!transformOr: encoder (self transformBoolean: encoder) ifTrue: [arguments _ Array with: (BlockNode new statements: (Array with: NodeTrue) returns: false) with: (arguments at: 1). ^true] ifFalse: [^false]!transformWhile: encoder ^(self transformBoolean: encoder) and: [self checkBlock: receiver as: 'receiver' from: encoder]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MessageNode class instanceVariableNames: ''!!MessageNode class methodsFor: 'class initialization'!initialize "MessageNode initialize." MacroSelectors _ #(ifTrue: ifFalse: ifTrue:ifFalse: ifFalse:ifTrue: and: or: whileFalse: whileTrue: ). MacroTransformers _ #(transformIfTrue: transformIfFalse: transformIfTrueIfFalse: transformIfFalseIfTrue: transformAnd: transformOr: transformWhile: transformWhile: ). MacroEmitters _ #(emitIf:on:value: emitIf:on:value: emitIf:on:value: emitIf:on:value: emitIf:on:value: emitIf:on:value: emitWhile:on:value: emitWhile:on:value: ). MacroSizers _ #(sizeIf:value: sizeIf:value: sizeIf:value: sizeIf:value: sizeIf:value: sizeIf:value: sizeWhile:value: sizeWhile:value: )! !MessageNode initialize! Magnitude subclass: #MessageTally instanceVariableNames: 'class method tally receivers ' classVariableNames: 'HowOften ObservedProcess TargetBlock Timer ' poolDictionaries: '' category: 'System-Support'!MessageTally comment:'See the comment for spyOn: in MessageTally class for an example of how to use the spy.MessageTallies represent nodes in a tree which gathers statistics on the time spent in various parts of the system. Specifically, each node represents a message being sent. During the evaluation of an expression, a timer periodically interrupts the execution of the various methods involved, and tallies these probes in the tree of MessageTallies which it constructs. When evaluation of the expression is complete, a detailed report is produced indicating where in the system most of the time was spent.Instance variables: class <Behavior> the class of the receiver of the message method <CompiledMethod> which was running when probe occurred tally <Integer> number of probes which hit this method or others called by it receivers <Collection of MessageTally> sons of this node in the tree, representing tallies of methods called from this one. If this field is nil, it indicates tallies due to in-line primitivesMessageTallies may be taken on only one block at a time. Spying on two blocks at once does not work. The block upon which the MessageTally is spying can be stopped and started. See spyEvery:on:.'!!MessageTally methodsFor: 'initialize-release'!close (Timer isMemberOf: Process) ifTrue: [Timer terminate]. Timer _ ObservedProcess _ nil. class _ method _ tally _ receivers _ nil!continueSpying | myDelay value active | myDelay _ Delay forMilliseconds: HowOften. active _ true. Timer _ [[active] whileTrue: [myDelay wait. active ifTrue: [self tally: ObservedProcess suspendedContext]]. nil] newProcess. Timer priority: Processor userInterruptPriority. "activate the probe and evaluate the block" Timer resume. value _ TargetBlock value. active _ false. "Timer will fire once more, not tally, and terminate itself" ^value "return the block's value"!defaultInterval "Answer the number of ticks between sampling." Smalltalk frills ifTrue: [^16] ifFalse: [^60]!reportOn: aStream "Default cutoff percentage is 2%." self reportOn: aStream cutoff: 2!reportOn: aStream cutoff: perCent "Print a report on the stream. perCent should be a number like 2 or 3" tally = 0 ifTrue: [aStream nextPutAll: ' - no tallies obtained'] ifFalse: [aStream nextPutAll: ' - '; print: tally; nextPutAll: ' tallies.'; cr; cr. self fullPrintOn: aStream cutoff: perCent]!spyEvery: millisecs on: aBlock "Create a spy on the given block at the specified rate. Don't run it yet" (aBlock isMemberOf: BlockContext) ifFalse: [self error: 'spy needs a block here']. self class: aBlock receiver class method: aBlock method. "set up the probe" ObservedProcess _ Processor activeProcess. HowOften _ millisecs. TargetBlock _ aBlock"Set a block up for spying, and accumulate the tallies from several executions | spy | spy _ MessageTally new. spy spyEvery: spy defaultInterval on: ['this block contains your code'. 30 factorial]. 10 timesRepeat: [spy continueSpying]. spy report: 'spy.results'. spy close. (Disk file: 'spy.results') edit.If there are no tallies reported, the block executes faster than the delay"!spyOn: aBlock "Spy on the evaluation of aBlock. Browse the results in a workspace." | val reportStream | "Set up the block" self spyEvery: self defaultInterval on: aBlock. "Run the block and take the tallies" val _ self continueSpying. "Report it" reportStream _ WriteStream on: (String new: 5000). self reportOn: reportStream. self close. StringHolderView open: (StringHolder new contents: reportStream contents) label: 'Spy Results'. ^val "Never gets returned due to window scheduling"!spyOn: aBlock to: fileName "Spy on the evaluation of aBlock. Write the data collected on a file named fileName." | val aFileStream | "Set up the block" self spyEvery: self defaultInterval on: aBlock. "Run the block and take the tallies" val _ self continueSpying. "Report it" aFileStream _ FileStream fileNamed: fileName. aFileStream timeStamp; nextPutAll: fileName; space. self reportOn: aFileStream. self close. aFileStream close. ^val! !!MessageTally methodsFor: 'comparing'!< aMessageTally ^tally > aMessageTally tally!= aMessageTally ^aMessageTally method == method!> aMessageTally ^tally < aMessageTally tally!hash ^method asOop!sonsOver: threshold | hereTally last sons | (receivers == nil or: [receivers size = 0]) ifTrue: [^#()]. hereTally _ tally. sons _ receivers select: "subtract subNode tallies for primitive hits here" [:son | hereTally _ hereTally - son tally. son tally > threshold]. hereTally > threshold ifTrue: [last _ MessageTally new class: class method: method. ^sons copyWith: (last primitives: hereTally)]. ^sons! !!MessageTally methodsFor: 'tallying'!bump tally _ tally + 1!tally: context "Explicitly tally the specified context and its stack." | root | context method == method ifTrue: [^self bump]. (root _ context home sender) == nil ifTrue: [^self bump tallyPath: context]. ^(self tally: root) tallyPath: context!tallyPath: context | aMethod path | aMethod _ context method. receivers do: [:aMessageTally | aMessageTally method == aMethod ifTrue: [path _ aMessageTally]]. path == nil ifTrue: [path _ MessageTally new class: context receiver class method: aMethod. receivers _ receivers copyWith: path]. ^path bump! !!MessageTally methodsFor: 'collecting leaves'!bump: anInteger tally _ tally + anInteger!into: aDictionary | aMessageTally index | index _ aDictionary find: self ifAbsent: [aDictionary add: (aMessageTally _ MessageTally new class: class method: method). ^aMessageTally bump: tally]. (aDictionary basicAt: index) bump: tally!leaves: leafDictionary | aBreakDown | aBreakDown _ self sonsOver: 0. aBreakDown size = 0 ifTrue: [self into: leafDictionary] ifFalse: [aBreakDown do: [:aMessageTally | aMessageTally leaves: leafDictionary]]! !!MessageTally methodsFor: 'printing'!fullPrintOn: aStream cutoff: perCent | threshold | threshold _ (perCent asFloat / 100 * tally) rounded. aStream nextPutAll: '**Tree**'; cr. self treePrintOn: aStream tabs: OrderedCollection new thisTab: '' total: tally over: threshold. aStream nextPut: Character newPage; cr. aStream nextPutAll: '**Leaves**'; cr. self leavesPrintOn: aStream over: threshold.!leavesPrintOn: aStream over: threshold | aSet | aSet _ Set new: 128. self leaves: aSet. (aSet asOrderedCollection select: [:node | node tally > threshold]) asSortedCollection do: [:node | node printOn: aStream total: tally]!printOn: aStream total: total | aSelector aClass | aStream print: (tally asFloat / total * 100.0 roundTo: 0.1); space. receivers == nil ifTrue: [aStream nextPutAll: 'primitives'] ifFalse: [aSelector _ class selectorAtMethod: method setClass: [:aClass]. aStream nextPutAll: aClass name; space; nextPutAll: aSelector]. aStream cr!treePrintOn: aStream tabs: tabs thisTab: myTab total: total over: threshold | sons sonTab | tabs do: [:tab | aStream nextPutAll: tab]. tabs size > 0 ifTrue: [self printOn: aStream total: total]. sons _ self sonsOver: threshold. sons isEmpty ifFalse: [tabs addLast: myTab. sons _ sons asSortedCollection. (1 to: sons size) do: [:i | sonTab _ i < sons size ifTrue: [' |'] ifFalse: [' ']. (sons at: i) treePrintOn: aStream tabs: tabs thisTab: sonTab total: total over: threshold]. tabs removeLast]! !!MessageTally methodsFor: 'private'!class: aClass method: aMethod class _ aClass. method _ aMethod. tally _ 0. receivers _ Array new: 0!method ^method!primitives: anInteger tally _ anInteger. receivers _ nil!tally ^tally! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MessageTally class instanceVariableNames: ''!!MessageTally class methodsFor: 'spying'!spyOn: aBlock "An execution profile of the execution of aBlock is obtained. For example: MessageTally spyOn: [Pen example]. The execution profile is presented in a workspace (user is prompted for area). No value is returned" | spy val reportStream | spy _ self new. "Set up the block" spy spyEvery: spy defaultInterval on: aBlock. "Run the block and take the tallies" val _ spy continueSpying. "Report it" reportStream _ WriteStream on: (String new: 5000). spy reportOn: reportStream; close. StringHolderView open: (StringHolder new contents: reportStream contents) label: 'Spy Results'. ^val "Never gets returned due to window scheduling"!spyOn: aBlock to: fileName "Spy on the evaluation of aBlock. Write the data collected on a file named fileName. The value of the block is returned as the value of this method. For example: MessageTally spyOn: [Smalltalk asSortedCollection] to: 'spy.results'. (FileStream oldFileNamed: 'spy.results') edit. " | spy val aFileStream | spy _ self new. "Set up the block" spy spyEvery: spy defaultInterval on: aBlock. "Run the block and take the tallies" val _ spy continueSpying. "Report it" aFileStream _ FileStream fileNamed: fileName. aFileStream timeStamp; nextPutAll: fileName; space. spy reportOn: aFileStream; close. aFileStream close. ^val! ! ClassDescription subclass: #Metaclass instanceVariableNames: 'thisClass ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Classes'!Metaclass comment:'Instance Variables: thisClass <Class> the chief instance of me, which I describe Metaclasses add instance-specific behavior to various classes in the system. This typically includes messages for initializing class variables and instance creation messages particular to that class. There is only one instance of a metaclass, namely the class (thisClass) which is being described. A metaclass shares the class variables of its instance.[Subtle] In general, the superclass hierarchy for metaclasses parallels that for classes. Thus, Integer superclass == Number, and Integer class superclass == Number class.However there is a singularity at Object. Here the class hierarchy terminates, but the metaclass hierarchy must wrap around to Class, since ALL metaclasses are subclasses of Class. Thus, Object superclass == nil, and Object class superclass == Class.'!!Metaclass methodsFor: 'initialize-release'!instanceVariableNames: instVarString "Declare additional variables for my instances." | newMeta invalid ok | newMeta _ self copyForValidation. invalid _ newMeta subclassOf: superclass oldClass: self instanceVariableNames: instVarString variable: false words: true pointers: true ifBad: [^false]. invalid ifTrue: [ok _ newMeta validateFrom: self in: Smalltalk instanceVariableNames: true methods: true. Smalltalk changes changeClass: self. ^ok]!newNamed: aSymbol "Answer a new instance of me whose name is the argument, aSymbol." ^(Metaclass subclassOf: self) new superclass: Object methodDict: MethodDictionary new format: -8192 name: aSymbol organization: ClassOrganizer new instVarNames: nil classPool: nil sharedPools: nil!newNamed: aSymbol otherSupers: others "Answer a new instance of me whose name is the argument, aSymbol." ^ (MetaclassForMultipleInheritance subclassOf: self and: others) new superclass: Object methodDict: MethodDictionary new format: -8192 name: aSymbol organization: ClassOrganizer new instVarNames: nil classPool: nil sharedPools: nil!obsolete "Invalidate and recycle local messages. Remove the receiver from its superclass' subclass list." thisClass_ nil. super obsolete!subclassOf: superMeta "Change the receiver to be a subclass of the argument, superMeta, a metaclass. Reset the receiver's method dictionary and properties." superclass _ superMeta. methodDict _ MethodDictionary new. format _ superMeta format. instanceVariables _ nil!superclass: superMeta "Change the receiver's superclass to be the argument, superMeta, a metaclass." superclass _ superMeta! !!Metaclass methodsFor: 'accessing'!name "Answer a String that is the name of the receiver, either Metaclass or the name of the receiver's class followed by the ' class'." thisClass == nil ifTrue: [^'a Metaclass'] ifFalse: [^thisClass name , ' class']!soleInstance "The receiver has only one instance. Answer it." ^thisClass! !!Metaclass methodsFor: 'testing'!isMeta ^ true!isObsolete "Answer whether the receiver is an obsolete metaclass." ^thisClass == nil or: [thisClass ~~ (Smalltalk at: thisClass name ifAbsent: [nil])] "should only be true for obsolete metaclass"! !!Metaclass methodsFor: 'copying'!copy "Make a copy of the receiver without a list of subclasses. Share the reference to the sole instance." | copy t | t _ thisClass. thisClass _ nil. copy _ super copy. thisClass _ t. ^copy!copyForValidation "Special copy for ClassDescription validateFrom:in:fields:methods:. Answer a copy of the receiver without the subclasses." ^super copy! !!Metaclass methodsFor: 'instance creation'!new "The receiver can only have one instance. Create it or complain that one already exists." thisClass == nil ifTrue: [^thisClass _ super new] ifFalse: [self error: 'A Metaclass should only have one instance!!']! !!Metaclass methodsFor: 'instance variables'!addInstVarName: aString "Add the argument, aString, as one of the receiver's instance variables." | fullString | fullString _ aString. self instVarNames do: [:aString2 | fullString _ aString2 , ' ' , fullString]. self instanceVariableNames: fullString!removeInstVarName: aString "Remove the argument, aString, as one of the receiver's instance variables." | newArray newString | (self instVarNames includes: aString) ifFalse: [self error: aString , ' is not one of my instance variables']. newArray _ self instVarNames copyWithout: aString. newString _ ''. newArray do: [:aString2 | newString _ aString2 , ' ' , newString]. self instanceVariableNames: newString! !!Metaclass methodsFor: 'class variables'!addClassVarName: aString ^thisClass addClassVarName: aString!classPool "Answer the dictionary of class variables." ^thisClass classPool! !!Metaclass methodsFor: 'class hierarchy'!instHasMultipleSuperclasses ^false!name: newName inEnvironment: environ subclassOf: sup and: others instanceVariableNames: instVarString variable: v words: w pointers: p classVariableNames: classVarString poolDictionaries: poolString category: categoryName comment: commentString changed: changed "Create a new metaclass from the information provided in the arguments. Create an error if the name does not begin with an uppercase letter or if a class of the same name already exists." | wasPresent oldClass newClass invalidFields invalidMethods | newName first isUppercase ifFalse: [self error: 'Class names must be capitalized'. ^false]. (wasPresent _ environ includesKey: newName) ifTrue: [oldClass _ environ at: newName. (oldClass isKindOf: Behavior) ifFalse: [self error: newName , ' already exists!! Proceed will store over it'. wasPresent _ false. oldClass _ self newNamed: newName otherSupers: others]] ifFalse: [oldClass _ self newNamed: newName otherSupers: others]. newClass _ oldClass copy. invalidFields _ changed | (newClass subclassOf: sup oldClass: oldClass instanceVariableNames: instVarString variable: v words: w pointers: p ifBad: [^false]). invalidFields ifFalse: [newClass obsolete. newClass _ oldClass]. invalidMethods _ invalidFields | (newClass declare: classVarString) | (newClass sharing: poolString). commentString == nil ifFalse: [newClass comment: commentString]. (environ includesKey: newName) ifFalse: [environ declare: newName from: Undeclared. environ at: newName put: newClass]. SystemOrganization classify: newClass name under: categoryName asSymbol. newClass validateFrom: oldClass in: environ instanceVariableNames: invalidFields methods: invalidMethods. "update subclass lists" newClass superclasses do: [:sup | sup removeSubclass: oldClass; addSubclass: newClass]. "Update Changes" wasPresent ifTrue: [Smalltalk changes changeClass: newClass] ifFalse: [Smalltalk changes addClass: newClass]. "Now check for possible conflicting definitions in superclasses" invalidFields ifTrue: [newClass copyMethods. newClass class copyMethods]. ^newClass!name: newName inEnvironment: environ subclassOf: sup instanceVariableNames: instVarString variable: v words: w pointers: p classVariableNames: classVarString poolDictionaries: poolString category: categoryName comment: commentString changed: changed "Create a new metaclass from the information provided in the arguments. Create an error if the name does not begin with an uppercase letter or if a class of the same name already exists." | wasPresent oldClass newClass invalidFields invalidMethods | newName first isUppercase ifFalse: [self error: 'Class names must be capitalized'. ^false]. (wasPresent _ environ includesKey: newName) ifTrue: [oldClass _ environ at: newName. (oldClass isKindOf: Behavior) ifFalse: [self error: newName , ' already exists!! Proceed will store over it'. wasPresent _ false. oldClass _ self newNamed: newName]] ifFalse: [oldClass _ self newNamed: newName]. newClass _ oldClass copy. invalidFields _ changed | (newClass subclassOf: sup oldClass: oldClass instanceVariableNames: instVarString variable: v words: w pointers: p ifBad: [^false]). invalidFields ifFalse: [newClass obsolete. newClass _ oldClass]. invalidMethods _ invalidFields | (newClass declare: classVarString) | (newClass sharing: poolString). commentString == nil ifFalse: [newClass comment: commentString]. (environ includesKey: newName) ifFalse: [environ declare: newName from: Undeclared. environ at: newName put: newClass]. SystemOrganization classify: newClass name under: categoryName asSymbol. newClass validateFrom: oldClass in: environ instanceVariableNames: invalidFields methods: invalidMethods. "update subclass lists" newClass superclass removeSubclass: oldClass. newClass superclass addSubclass: newClass. "Update Changes" wasPresent ifTrue: [Smalltalk changes changeClass: newClass] ifFalse: [Smalltalk changes addClass: newClass]. ^newClass!subclasses "Answer the receiver's subclasses." | temp | self == Class class ifTrue: ["Meta-Object is exceptional subclass of Class" temp _ thisClass subclasses copy. temp remove: Object class. ^temp collect: [:aSubClass | aSubClass class]]. thisClass == nil ifTrue: [^Set new] ifFalse: [^thisClass subclasses collect: [:aSubClass | aSubClass class]]! !!Metaclass methodsFor: 'compiling'!scopeHas: name ifTrue: assocBlock ^thisClass scopeHas: name ifTrue: assocBlock! !!Metaclass methodsFor: 'printing'!definition "Answer with a string that defines me" | aStream names | aStream _ WriteStream on: (String new: 300). self printOn: aStream. aStream nextPutAll: ' instanceVariableNames: '''. names _ self instVarNames. 1 to: names size do: [:i | aStream nextPutAll: (names at: i); space]. aStream nextPut: $'. ^ aStream contents! !!Metaclass methodsFor: 'fileIn/Out'!fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex "File me out on aFileStream." super fileOutOn: aFileStream moveSource: moveSource toFile: fileIndex. (methodDict includesKey: #initialize) ifTrue: [aFileStream cr. aFileStream cr. aFileStream nextChunkPut: thisClass name , ' initialize'. aFileStream cr]!nonTrivial ^self instVarNames size > 0 or: [methodDict size > 0 or: [self comment size > 0]]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Metaclass class instanceVariableNames: ''!!Metaclass class methodsFor: 'instance creation'!subclassOf: superMeta "Answer a metaclass that is a subclass of metaclass superMeta." ^self new subclassOf: superMeta! ! Metaclass subclass: #MetaclassForMultipleInheritance instanceVariableNames: 'otherSuperclasses ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Classes'!MetaclassForMultipleInheritance comment:'This metaclass has an additional field and protocol to support multiple inheritance.The field, otherSupers, contains a collection of additional superclasses (other than the normal dynamic one) from which traits are to be inherited. Since the otherSupers appears in the metaclass, classes must ask their metas for other supers (sort of the way metas ask their thisClasses for subs).It would have been more natural to put otherSupers into a class ClassWithMultSupers, but this would have had to inherit both the multiple supers AND the normal metaclassinheritance, thus posing a bootstrapping need for multiple inheritance.'!!MetaclassForMultipleInheritance methodsFor: 'class hierarchy'!instHasMultipleSuperclasses ^true!otherSuperclasses ^ otherSuperclasses!setOtherSuperclasses: others otherSuperclasses _ others!superclasses ^ (Array with: superclass) , (otherSuperclasses collect: [:sup | sup class])! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MetaclassForMultipleInheritance class instanceVariableNames: ''!!MetaclassForMultipleInheritance class methodsFor: 'superclass access'!subclassOf: sup and: others | newMeta | newMeta _ super subclassOf: sup. newMeta setOtherSuperclasses: others. ^newMeta! ! ClassRelatedChange subclass: #MethodChange instanceVariableNames: 'selector category ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!MethodChange comment:'Represents a change to a method (new definition or removal).'!!MethodChange methodsFor: 'accessing'!category ^category!category: aSymbol category _ aSymbol asSymbol!parameters ^Array with: className with: selector!selector ^selector!selector: aSymbol selector _ aSymbol asSymbol! ! ContextPart variableSubclass: #MethodContext instanceVariableNames: 'method receiverMap receiver ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'!MethodContext comment:'My instances hold all the dynamic state associated with the execution of a CompiledMethod. In addition to their inherited state, this includes the receiver, a method, and temporary space in the variable part of the context.MethodContexts, though normal in their variable size, are actually only used in two sizes, small and large, which are determined by the temporary space required by the method being executed.Instance Variables: *indexed* method <CompiledMethod> receiverMap unused (we expect to use it later for multiple inheritance) receiver <Object>'!!MethodContext methodsFor: 'initialize-release'!restart "Reinitialize the receiver so that it is in the state it was at its creation." pc _ method initialPC. stackp _ method numArgs + method numTemps!restartWith: aCompiledMethod "Reinitialize the receiver as though it had been for a different method. Used by a Debugger when one of the methods to which it refers is recompiled." method _ aCompiledMethod. ^self restart! !!MethodContext methodsFor: 'accessing'!home ^self!method ^method!receiver ^receiver!removeSelf "Nil the receiver pointer and answer the former value." | tempSelf | tempSelf _ receiver. receiver _ nil. ^tempSelf! !!MethodContext methodsFor: 'temporaries'!tempAt: index ^self at: index!tempAt: index put: value ^self at: index put: value! !!MethodContext methodsFor: 'private'!setSender: s receiver: r method: m arguments: args "Create the receiver's initial state." sender _ s. receiver _ r. method _ m. pc _ method initialPC. stackp _ method numTemps. 1 to: args size do: [:i | self at: i put: (args at: i)]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MethodContext class instanceVariableNames: ''!!MethodContext class methodsFor: 'instance creation'!sender: s receiver: r method: m arguments: args ^(self new: m frameSize) setSender: s receiver: r method: m arguments: args! ! MethodChange subclass: #MethodDefinitionChange instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!MethodDefinitionChange comment:'I represent a change to the text of a method (as opposed to a category change or a removal).'!!MethodDefinitionChange methodsFor: 'accessing'!accept: newText notifying: requestor "Check to make sure the current definition is valid" | methodNode | methodNode _ Compiler new compile: newText in: (Smalltalk at: className ifAbsent: [^nil]) notifying: requestor ifFail: [^nil]. methodNode generate: #(0 0 0). ^self class new text: self text; className: className; selector: methodNode selector; category: category!name ^className, ' ', selector! !!MethodDefinitionChange methodsFor: 'file accessing'!fileName file isNil ifTrue: [^'current system'] ifFalse: [^super fileName]! !!MethodDefinitionChange methodsFor: 'source code'!getSource "Get the source code for this method from information currently in the system." self sourceFileAndPosition: [:aFile :aPosition | file _ aFile. position _ aPosition]!sourceFileAndPosition: aBlock "Get the source code for this method from information currently in the system." | class method fileIndex pos | (class _ self classObject) isNil ifTrue: [^nil]. (class includesSelector: selector) ifFalse: [^nil]. method _ class compiledMethodAt: selector. SourceFiles isNil ifTrue: [^nil]. (fileIndex _ method fileIndex) > SourceFiles size ifTrue: [^nil]. "The following code should be in CompiledMethod ..." pos _ (method at: method size) bitAnd: 63. pos _ pos * 256 + (method at: method size - 1). pos _ pos * 256 + (method at: method size - 2). pos = 0 ifTrue: [^nil]. ^aBlock value: (SourceFiles at: method fileIndex) value: pos!text | aStream numArgs | file == nil ifTrue: [aStream _ WriteStream on: (String new: 60). (numArgs _ selector numArgs) = 0 ifTrue: [aStream nextPutAll: selector] ifFalse: [selector keywords with: (1 to: numArgs) do: [:word :i | aStream nextPutAll: word; nextPutAll: ' t'; print: i; space]]. aStream cr; tab; nextPutAll: '"Source code not available"'. ^aStream contents]. ^super text! !!MethodDefinitionChange methodsFor: 'checking'!checkWith: aChecker | systemVersion oldChanges | aChecker changesAt: self name add: self. aChecker checkSystem ifTrue: [self isInSystem ifFalse: [systemVersion _ self class new className: className; category: category; selector: selector. systemVersion sourceFileAndPosition: [:aFile :aPosition | systemVersion file: aFile position: aPosition. (aChecker equalWithoutComments: self text and: systemVersion text) ifFalse: [oldChanges _ aChecker changesAt: self name. oldChanges size > 1 ifTrue: [oldChanges do: [:c | c isInSystem ifTrue: [^self]]]. aChecker changesAt: self name add: systemVersion]]]]!isInSystem self sourceFileAndPosition: [:aFile :aPosition | (file = aFile and: [position = aPosition]) ifTrue: [^true]]. ^false! !!MethodDefinitionChange methodsFor: 'fileIn/Out'!fileIn | class | class _ self classObject. class isNil ifTrue: [self error: 'Class ', className, ' does not exist in this system'] ifFalse: [class compile: self text classified: category. Transcript show: className , '<' , category , '']!fileOutHeaderOn: aStream aStream nextPut: $!!; nextPutAll: className; nextPutAll: ' methodsFor: '; store: category asString; nextPut: $!!; cr; cr!fileOutOn: aStream self fileOutHeaderOn: aStream. aStream nextChunkPut: self text; space; nextPut: $!!; cr; cr!fileOutOn: aStream previous: previousChange next: nextChange ((previousChange isKindOf: MethodDefinitionChange) and: [previousChange className == className and: [previousChange category == category]]) ifFalse: [self fileOutHeaderOn: aStream]. aStream nextChunkPut: self text. ((nextChange isKindOf: MethodDefinitionChange) and: [nextChange className == className and: [nextChange category == category]]) ifFalse: [aStream space; nextPut: $!!]. aStream cr; cr! ! Object subclass: #MethodDescription instanceVariableNames: 'status whichClass selector ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'!MethodDescription comment:'I model the result of looking up a selector name. Usually I simply identify an existing method in some class in the system. However, the lookup may fail, in which case I know the message would not be understood. Also, in multiple inheritance situations, the lookup may yield conflicting results, in which case I will know that as well.'!!MethodDescription methodsFor: 'accessing'!method ^whichClass compiledMethodAt: selector!selector ^selector!sourceCode ^whichClass sourceCodeAt: selector!whichClass ^whichClass! !!MethodDescription methodsFor: 'comparing'!= descr self isConflictingMethods ifTrue: [^descr isConflictingMethods]. self isMethodNotImplemented ifTrue: [^descr isMethodNotImplemented]. ^(whichClass == descr whichClass) & (selector == descr selector)! !!MethodDescription methodsFor: 'testing'!isBad ^status == #conflictingMethods or: [status == #methodNotImplemented]!isConflictingMethods ^status == #conflictingMethods!isMethodNotImplemented ^status == #methodNotImplemented! !!MethodDescription methodsFor: 'printing'!printOn: strm status==#methodNotImplemented ifTrue: [strm nextPutAll: 'MethodDescription(methodNotImplemented)'. ^self]. status==#conflictingMethods ifTrue: [strm nextPutAll: 'MethodDescription(conflictingMethods)'. ^self]. strm nextPutAll: 'MethodDescription('; nextPutAll: whichClass name; nextPut: $, ; nextPutAll: selector; nextPut: $)! !!MethodDescription methodsFor: 'private'!setStatus: s status _ s!setWhichClass: c setSelector: s whichClass _ c. selector _ s! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!MethodDescription class instanceVariableNames: ''!!MethodDescription class methodsFor: 'instance creation'!makeConflictingMethods ^self new setStatus: #conflictingMethods!makeMethodNotImplemented ^self new setStatus: #methodNotImplemented!whichClass: c selector: s ^self new setWhichClass: c setSelector: s! ! IdentityDictionary variableSubclass: #MethodDictionary instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Support'!MethodDictionary comment:'MethodDictionaries behave just the same as IdentityDictionaries, except thatremoval is implemented as an atomic operation. This allows the interpreterto access methodDictionaries removal without getting confused.'!!MethodDictionary methodsFor: 'dictionary removing'!methodArray ^valueArray!removeKey: key ifAbsent: errorBlock "Remove the key from a copy and then use become: to effect and atomic update" self become: (self copy removeDangerouslyKey: key ifAbsent: [^errorBlock value])! ! Browser subclass: #MethodListBrowser instanceVariableNames: 'methodList methodName ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Browser'!MethodListBrowser comment:'I represent a list of methods to be browsed.'!!MethodListBrowser methodsFor: 'initialization'!on: aList methodList _ aList! !!MethodListBrowser methodsFor: 'method list'!methodList ^ methodList!methodMenu selector == nil ifTrue: [^ nil]. ^ super selectorMenu!methodName ^ methodName!methodName: selection | aStream aSymbol | methodName _ selection. selection == nil ifTrue: [selector _ nil. ^ self textMode: #unclassified]. aStream _ ReadStream on: selection. className _ (aStream upTo: $ ) asSymbol. aSymbol _ (aStream upTo: $ ) asSymbol. (meta _ (aSymbol == #class) & aStream atEnd not) ifTrue: [aSymbol _ (aStream upTo: $ ) asSymbol]. protocol _ self selectedClass organization categoryOfElement: aSymbol. self selector: aSymbol! !!MethodListBrowser methodsFor: 'method functions'!removeMethod (super removeMethod) ifTrue: [methodList _ methodList copyWithout: methodName. self changed: #methodName]! !!MethodListBrowser methodsFor: 'doIt/accept/explain'!acceptText: aText from: aController textMode == #unclassified ifTrue: [self notify: 'A method must be selected to suggest class and protocol'. ^ false]. ^ super acceptText: aText from: aController! ! ParseNode subclass: #MethodNode instanceVariableNames: 'selectorOrFalse precedence arguments block literals primitive encoder temporaries ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!MethodNode comment: 'I am the root of the parse tree.'!!MethodNode methodsFor: 'initialize-release'!selector: selOrFalse arguments: args precedence: p temporaries: temps block: blk encoder: anEncoder primitive: prim encoder _ anEncoder. selectorOrFalse _ selOrFalse. precedence _ p. arguments _ args. temporaries _ temps. block _ blk. primitive _ prim! !!MethodNode methodsFor: 'code generation'!generate: trailer "I am the root of a parse tree; answer with an instance of CompiledMethod." | blkSize method nLits lit stack strm nArgs i | self generateIfQuick: [:method | 1 to: 3 do: [:i | method at: method size - 3 + i put: (trailer at: i)]. method cacheTempNames: self tempNames. ^method]. nArgs _ arguments size. blkSize _ block sizeForEvaluatedValue: encoder. literals _ encoder literals: primitive nArgs: nArgs. encoder maxTemp > 31 ifTrue: [^self error: 'Too many temporary variables']. (nLits _ literals size) > 63 ifTrue: [^self error: 'Too many literals referenced']. method _ CompiledMethod "Dummy to allocate right size" newBytes: blkSize flags: ((nArgs <= 4 and: [primitive = 0]) ifTrue: [nArgs] ifFalse: [7]) nTemps: encoder maxTemp nStack: 0 nLits: nLits. strm _ ReadWriteStream with: method. strm position: method initialPC - 1. stack _ ParseStack new init. block emitForEvaluatedValue: stack on: strm. stack position ~= 1 ifTrue: [^self error: 'Compiler stack discrepancy']. strm position ~= (method size - 3) ifTrue: [^self error: 'Compiler code size discrepancy']. 1 to: nLits do: [:lit | method literalAt: lit put: (literals at: lit)]. method needsStack: stack size encoder: encoder. 1 to: 3 do: [:i | method at: method size - 3 + i put: (trailer at: i)]. method cacheTempNames: self tempNames. ^method!generateIfQuick: methodBlock | v | (primitive = 0 and: [arguments size = 0 and: [block isQuick]]) ifTrue: [v _ block code. v < 0 ifTrue: [^self]. v = LdSelf ifTrue: [^methodBlock value: CompiledMethod toReturnSelf]. v < ((CodeBases at: LdInstType) + (CodeLimits at: LdInstType)) ifTrue: [^methodBlock value: (CompiledMethod toReturnField: v)]. (v // 256 = 1 and: [v \\ 256 < 32]) ifTrue: [^methodBlock value: (CompiledMethod toReturnField: v \\ 256)]]!generateNoQuick "Assumes would have been quick. Forces numArgs > 0 so will compile real code. The debugger needs this to look simulate a quick return" arguments _ Array new: 1. ^ self generate: #(0 0 0)!selector (selectorOrFalse isMemberOf: Symbol) ifTrue: [^selectorOrFalse]. ^selectorOrFalse key!sourceMap "I am the root of a parse tree; answer with a sorted collection of associations of the form: pc (byte offset in me) -> sourceRange (an Interval) in source text. Because the number of my literals may grow during generation and therefore the pc's may be off, I must pass my generated number of literals to the encoder." | numLits | numLits _ (self generate: #(0 0 0 )) numLiterals. ^encoder sourceMap: numLits! !!MethodNode methodsFor: 'converting'!decompileString | aStream | aStream _ WriteStream on: (String new: 1000). self printOn: aStream. ^aStream contents! !!MethodNode methodsFor: 'printing'!printOn: aStream | s args | precedence = 1 ifTrue: [aStream nextPutAll: self selector] ifFalse: [args _ ReadStream on: arguments. self selector keywords do: [:s | aStream nextPutAll: s. aStream space; nextPutAll: args next key. aStream space]]. comment == nil ifFalse: [aStream crtab: 1. self printCommentOn: aStream indent: 1. aStream cr]. temporaries size > 0 ifTrue: [aStream crtab: 1. aStream nextPutAll: '| '. temporaries do: [:s | aStream nextPutAll: s key. aStream space]. aStream nextPut: $|]. primitive > 0 ifTrue: [aStream crtab: 1. aStream nextPutAll: '<primitive: '; print: primitive; nextPutAll: '>']. aStream crtab: 1. ^block printStatementsOn: aStream indent: 1!tempNames ^encoder tempNames! ! MethodChange subclass: #MethodOtherChange instanceVariableNames: 'type ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!MethodOtherChange comment:'Represents a change to a method other than new definition or removal.'!!MethodOtherChange methodsFor: 'accessing'!name ^type, ' ', className, ' ', selector!type ^type!type: aSymbol type _ aSymbol! !!MethodOtherChange methodsFor: 'checking'!checkWith: aChecker aChecker changesAt: self name add: self. aChecker addDoIt: self! ! Controller subclass: #MouseMenuController instanceVariableNames: 'redButtonMenu redButtonMessages yellowButtonMenu yellowButtonMessages blueButtonMenu blueButtonMessages ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Support'!MouseMenuController comment:'I am a Controller that modifies the scheduling of user activities so that the three mouse buttons can be used to make selections or display menus. The menu items are unary messages to the value of sending my instance the message menuMessageReceiver.Instance Variables: redButtonMenu <PopUpMenu> redButtonMessages <Array> of Symbols, unary messages yellowButtonMenu <PopUpMenu> yellowButtonMessages <Array> of Symbols, unary messages blueButtonMenu <PopUpMenu> blueButtonMessages <Array> of Symbols, unary messages '!!MouseMenuController methodsFor: 'initialize-release'!release super release. redButtonMenu release. yellowButtonMenu release. blueButtonMenu release!reset "Eliminate references to all mouse button menus." redButtonMenu _ nil. redButtonMessages _ nil. yellowButtonMenu _ nil. yellowButtonMessages _ nil. blueButtonMenu _ nil. blueButtonMessages _ nil! !!MouseMenuController methodsFor: 'control defaults'!controlActivity sensor redButtonPressed & self viewHasCursor ifTrue: [^self redButtonActivity]. sensor yellowButtonPressed & self viewHasCursor ifTrue: [^self yellowButtonActivity]. sensor blueButtonPressed & self viewHasCursor ifTrue: [^self blueButtonActivity]. super controlActivity!isControlActive ^view containsPoint: sensor cursorPoint! !!MouseMenuController methodsFor: 'menu setup'!blueButtonMenu: aSystemMenu blueButtonMessages: anArray "Initialize the pop-up menu that should appear when the user presses the blue mouse button to be aSystemMenu. The corresponding messages that should be sent are listed in the array, anArray." blueButtonMenu release. blueButtonMenu _ aSystemMenu. blueButtonMessages _ anArray!redButtonMenu: aSystemMenu redButtonMessages: anArray "Initialize the pop-up menu that should appear when the user presses the red mouse button to be aSystemMenu. The corresponding messages that should be sent are listed in the array, anArray." redButtonMenu release. redButtonMenu _ aSystemMenu. redButtonMessages _ anArray!yellowButtonMenu: aSystemMenu yellowButtonMessages: anArray "Initialize the pop-up menu that should appear when the user presses the yellow mouse button to be aSystemMenu. The corresponding messages that should be sent are listed in the array, anArray." yellowButtonMenu release. yellowButtonMenu _ aSystemMenu. yellowButtonMessages _ anArray! !!MouseMenuController methodsFor: 'menu messages'!blueButtonActivity "Determine which item in the blue button pop-up menu is selected. If one is selected, then send the corresponding message to the object designated as the menu message receiver." | index | blueButtonMenu ~~ nil ifTrue: [index _ blueButtonMenu startUpBlueButton. index ~= 0 ifTrue: [self menuMessageReceiver perform: (blueButtonMessages at: index)]] ifFalse: [super controlActivity]!menuMessageReceiver "Answer the object that should be sent a message when a menu item is selected." ^ self!redButtonActivity "Determine which item in the red button pop-up menu is selected. If one is selected, then send the corresponding message to the object designated as the menu message receiver." | index | redButtonMenu ~~ nil ifTrue: [index _ redButtonMenu startUpRedButton. index ~= 0 ifTrue: [self menuMessageReceiver perform: (redButtonMessages at: index)]] ifFalse: [super controlActivity]!yellowButtonActivity "Determine which item in the yellow button pop-up menu is selected. If one is selected, then send the corresponding message to the object designated as the menu message receiver." | index | yellowButtonMenu ~~ nil ifTrue: [index _ yellowButtonMenu startUpYellowButton. index ~= 0 ifTrue: [self menuMessageReceiver perform: (yellowButtonMessages at: index)]] ifFalse: [super controlActivity]! ! Controller subclass: #NoController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Framework'!NoController comment:'I represent a controller that never wants control. I am the controller for views that are non-interactive.'!!NoController methodsFor: 'basic control sequence'!startUp "I do nothing." ^self! !!NoController methodsFor: 'control defaults'!isControlActive ^false!isControlWanted ^false! ! StandardSystemController subclass: #NotifierController instanceVariableNames: '' classVariableNames: 'NotifierYellowButtonMenu NotifierYellowButtonMessages ' poolDictionaries: '' category: 'Interface-Debugger'!NotifierController comment:'I am a kind of MouseMenuController that creates a yellow button menu for proceeding an interrupted process or for creating and scheduling a debugger on the interrupted machine state. I give up control if a blue button is pressed or if the cursor is not inside the view.'!!NotifierController methodsFor: 'initialize-release'!initialize super initialize. self initializeYellowButtonMenu! !!NotifierController methodsFor: 'menu messages'!correct "Attempt to correct the spelling of the not-understood message and resend." self controlTerminate. model correct: self. self controlInitialize!debug "Open a Debugger on the receiver's model." self controlTerminate. view erase. Debugger openFullViewOn: model label: view label. self closeAndUnscheduleNoErase. Processor terminateActive!proceed "Proceed execution of the receiver's model." self controlTerminate. model proceed. self controlInitialize! !!NotifierController methodsFor: 'model access'!model: aDebugger "Intercept to possible enable spelling correction." super model: aDebugger. model interruptedContext selector == #doesNotUnderstand: ifTrue: [self yellowButtonMenu: (PopUpMenu labels: 'proceeddebugcorrect' lines: #(2)) yellowButtonMessages: #(proceed debug correct)]! !!NotifierController methodsFor: 'private'!initializeYellowButtonMenu self yellowButtonMenu: NotifierYellowButtonMenu yellowButtonMessages: NotifierYellowButtonMessages! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!NotifierController class instanceVariableNames: ''!!NotifierController class methodsFor: 'class initialization'!initialize NotifierYellowButtonMenu _ PopUpMenu labels: 'proceeddebug'. NotifierYellowButtonMessages _ #(proceed debug ) "NotifierController initialize."! !NotifierController initialize! StandardSystemView subclass: #NotifierView instanceVariableNames: 'contents ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Debugger'!NotifierView comment:'I am a view of interrupted machine state. The interruption occurred in order to notify the user that some action to be taken is dangerous, perhaps because it is not recoverable. I contain one subView in which the notification information is displayed. My default controller is NotifierController.Instance Variables: contents <String> the notification information'!!NotifierView methodsFor: 'initialize-release'!initialize super initialize. self insideColor: Form white! !!NotifierView methodsFor: 'accessing'!contents "Answer the information displayed in the receiver." ^contents!contents: aString "Set aString to be the information that is displayed in the receiver." contents _ aString asParagraph. self centerContents! !!NotifierView methodsFor: 'controller access'!defaultControllerClass ^NotifierController! !!NotifierView methodsFor: 'window access'!defaultWindow contents == nil ifTrue: [^super defaultWindow] ifFalse: [^contents boundingBox expandBy: 6]!window: aWindow super window: aWindow. self centerContents! !!NotifierView methodsFor: 'displaying'!displayView contents displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox fixedPoint: contents boundingBox center. super displayView! !!NotifierView methodsFor: 'private'!centerContents contents ~~ nil ifTrue: [contents align: contents boundingBox center with: self getWindow center]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!NotifierView class instanceVariableNames: ''!!NotifierView class methodsFor: 'instance creation'!openContext: haltContext label: aString contents: contentsString "Create and schedule an instance of me viewing a Debugger on haltContext. The view will be labeled with aString, and shows a short sender stack." | displayPoint | ErrorRecursion ifTrue: [ErrorRecursion _ false. self primitiveError: aString]. ErrorRecursion _ true. displayPoint _ ScheduledControllers activeController == nil ifTrue: [Display boundingBox center] ifFalse: [ScheduledControllers activeController view displayBox center]. self openDebugger: (Debugger context: haltContext) contents: contentsString label: aString displayAt: displayPoint. ErrorRecursion _ false. Processor activeProcess suspend!openInterrupt: aString onProcess: interruptedProcess "Create and schedule an instance of me whose model is a Debugger on interruptedProcess. Sent to notify the user that the system is low in space or that the user typed ctrl c. The label of the scheduled view is aString." | debugger topView | debugger _ Debugger interruptProcess: interruptedProcess. topView _ self openDebugger: debugger contents: debugger interruptedContext shortStack label: aString displayAt: Display boundingBox center. ^topView! !!NotifierView class methodsFor: 'private'!openDebugger: aDebugger contents: aString1 label: aString2 displayAt: aPoint | notifierView | Cursor normal show. Cursor cursorLink: true. notifierView _ self new model: aDebugger. notifierView contents: aString1. notifierView label: aString2. notifierView borderWidth: 2. notifierView minimumSize: notifierView defaultWindow width @ notifierView defaultWindow height. notifierView controller openNoTerminateDisplayAt: aPoint. ^notifierView! ! Magnitude subclass: #Number instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Numbers'!Number comment:'The abstract class Number is at the top of the number hierarchy. Its subclasses are Float, Fraction, and Integer.'!!Number methodsFor: 'arithmetic'!* aNumber "Answer the result of multiplying the receiver by aNumber." self subclassResponsibility!+ aNumber "Answer the sum of the receiver and aNumber." self subclassResponsibility!- aNumber "Answer the difference between the receiver and aNumber." self subclassResponsibility!/ aNumber "Answer the result of dividing receiver by aNumber." self subclassResponsibility!// aNumber "Integer quotient defined by division with truncation toward negative infinity. 9//4 = 2, -9//4 = -3. -0.9//0.4 = -3. \\ answers the remainder from this division." ^(self / aNumber) floor!abs "Answer a Number that is the absolute value (positive magnitude) of the receiver." self < 0 ifTrue: [^self negated] ifFalse: [^self]!negated "Answer a Number that is the negation of the receiver." ^0 - self!quo: aNumber "Integer quotient defined by division with truncation toward zero. -9 quo: 4 = -2, -0.9 quo: 0.4 = -2. rem: answers the remainder from this division." ^(self / aNumber) truncated!reciprocal "Answer 1 divided by the receiver. Create an error if the receiver is 0." self = 0 ifTrue: [^self error: 'zero has no reciprocal'] ifFalse: [^1 / self]!rem: aNumber "Remainder defined in terms of quo:. Answer a Number with the same sign as self. e.g. 9 rem: 4 = 1, -9 rem: 4 = -1. 0.9 rem: 0.4 = 0.1" ^self - ((self quo: aNumber) * aNumber)!\\ aNumber "modulo. Remainder defined in terms of //. Answer a Number with the same sign as aNumber. e.g. 9\\4 = 1, -9\\4 = 3, 9\\-4 = -3, 0.9\\0.4 = 0.1" ^self - (self // aNumber * aNumber)! !!Number methodsFor: 'mathematical functions'!arcCos ^self asFloat arcCos!arcSin "Answer with the angle in radians." ^self asFloat arcSin!arcTan "Answer with the angle in radians." ^self asFloat arcTan!cos "Answer with the angle in radians." ^self asFloat cos!exp "Answer the exponential of the receiver as a floating point number." ^self asFloat exp!floorLog: radix "Answer the floor of the log base radix of the receiver." ^self asFloat floorLog: radix!ln "Answer the natural log of the receiver." ^self asFloat ln!log: aNumber "Answer the log base aNumber of the receiver." ^self ln / aNumber ln!raisedTo: aNumber "Answer the receiver raised to aNumber." aNumber isInteger ifTrue: ["Do the special case of integer power" ^self raisedToInteger: aNumber]. aNumber = 0 ifTrue: [^1]. "Special case of exponent=0" aNumber = 1 ifTrue: [^self]. "Special case of exponent=1" ^(aNumber * self ln) exp "Otherwise raise it to the power using logarithms"!raisedToInteger: anInteger "Answer the receiver raised to the power anInteger where the argument must be a kind of Integer. This is a special case of raisedTo:." anInteger isInteger ifFalse: [^self error: 'raisedToInteger: only works for integral arguments']. anInteger = 0 ifTrue: [^1]. anInteger = 1 ifTrue: [^self]. anInteger > 1 ifTrue: [^(self * self raisedToInteger: anInteger // 2) * (self raisedToInteger: anInteger \\ 2)]. ^(self raisedToInteger: anInteger negated) reciprocal!sin "Answer with the angle in radians." ^self asFloat sin!sqrt "Answer the square root of the receiver." ^self asFloat sqrt!squared "Answer the receiver multipled by itself." ^self * self!tan "Answer with the angle in radians." ^self asFloat tan! !!Number methodsFor: 'testing'!even "Answer whether the receiver is an even number." ^self \\ 2 = 0!negative "Answer whether the receiver is less than 0." ^self < 0!odd "Answer whether the receiver is an odd number." ^self even == false!positive "Answer whether the receiver is greater than or equal to 0." ^self >= 0!sign "Answer 1 if the receiver is greater than 0, -1 if less than 0, else 0." self > 0 ifTrue: [^1]. self < 0 ifTrue: [^-1]. ^0!strictlyPositive "Answer whether the receiver is greater than 0." ^self > 0! !!Number methodsFor: 'truncation and round off'!ceiling "Answer the integer nearest the receiver toward positive infinity." self <= 0.0 ifTrue: [^self truncated] ifFalse: [^self negated floor negated]!floor "Answer the integer nearest the receiver toward negative infinity." | truncation | truncation _ self truncated. self >= 0 ifTrue: [^truncation]. self = truncation ifTrue: [^truncation] ifFalse: [^truncation - 1]!rounded "Answer the integer nearest the receiver." ^(self + (self sign / 2)) truncated!roundTo: aNumber "Answer the integer that is a multiple of aNumber that is nearest the receiver." ^(self / aNumber) rounded * aNumber!truncated "Answer an integer nearest the receiver toward zero." ^self quo: 1!truncateTo: aNumber "Answer the next multiple of aNumber toward zero that is nearest the receiver." ^(self quo: aNumber) * aNumber! !!Number methodsFor: 'coercing'!coerce: aNumber "Answer with a number representing the argument, aNumber, that is represented the same kind of Number as is the receiver. Must be defined by all Number classes." self subclassResponsibility!generality "Answer the number representing the ordering of the receiving in the generality hierarchy. A number in this hierarchy coerces to numbers higher in hierarhcy (i.e., with larger generality numbers)." self subclassResponsibility!retry: aSymbol coercing: aNumber "Arithmetic represented by the symbol, aSymbol, could not be performed with the receiver and the argument, aNumber, because of the differences in representation. Coerce either the receiver or the argument, depending on which has higher generality, and try again. If the symbol is the equals sign, answer false if the argument is not a Number. If the generalities are the same, create an error message." (aSymbol == #= and: [(aNumber isKindOf: Number) == false]) ifTrue: [^false]. self generality < aNumber generality ifTrue: [^(aNumber coerce: self) perform: aSymbol with: aNumber]. self generality > aNumber generality ifTrue: [^self perform: aSymbol with: (self coerce: aNumber)]. self error: 'coercion attempt failed'! !!Number methodsFor: 'converting'!@ y "Answer a new Point whose x value is the receiver and whose y value is the argument. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 18> ^Point x: self y: y!asInteger "Answer an integer nearest the receiver toward zero." ^self truncated!asPoint "Answer a new Point with the receiver as both coordinates; often used to supply the same value in two dimensions, as with symmetrical gridding or scaling." ^self @ self!degreesToRadians "The receiver is assumed to represent degrees. Answer the conversion to radians." ^self asFloat degreesToRadians!radiansToDegrees "The receiver is assumed to represent radians. Answer the conversion to degrees." ^self asFloat radiansToDegrees! !!Number methodsFor: 'intervals'!to: stop "Answer an Interval from the receiver up to the argument, stop, incrementing by 1." ^Interval from: self to: stop by: 1!to: stop by: step "Answer an Interval from the receiver up to the argument, stop, incrementing by step." ^Interval from: self to: stop by: step!to: stop by: step do: aBlock "Create an Interval from the receiver up to the argument, stop, incrementing by step. For each element of the interval, evaluate the block, aBlock." | nextValue | nextValue _ self. step < 0 ifTrue: [[stop <= nextValue] whileTrue: [aBlock value: nextValue. nextValue _ nextValue + step]] ifFalse: [[stop >= nextValue] whileTrue: [aBlock value: nextValue. nextValue _ nextValue + step]]!to: stop do: aBlock "Create an Interval from the receiver up to the argument, stop, incrementing by 1. For each element of the interval, evaluate the block, aBlock." | nextValue | nextValue _ self. [nextValue <= stop] whileTrue: [aBlock value: nextValue. nextValue _ nextValue + 1]! !!Number methodsFor: 'printing'!storeOn: aStream "Numbers print in a form which is recognized by the compiler." self printOn: aStream! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Number class instanceVariableNames: ''!!Number class methodsFor: 'instance creation'!readFrom: aStream "Answer an instance of me as described on the stream, aStream" | value radix fraction fracpos | radix _ 10. value _ Integer readFrom: aStream. (aStream peekFor: $r) ifTrue: ["<radix>r<integer>" (radix _ value) < 2 ifTrue: [^self error: 'INVALID RADIX']. value _ Integer readFrom: aStream radix: radix]. (aStream peekFor: $.) ifTrue: ["<integer>.<fraction>" (aStream atEnd not and: [aStream peek digitValue between: 0 and: radix - 1]) ifTrue: [fracpos _ aStream position. fraction _ Integer readFrom: aStream radix: radix. radix _ radix asFloat. fraction _ fraction asFloat / (radix raisedTo: aStream position - fracpos). value _ value asFloat + (value < 0 ifTrue: [fraction negated] ifFalse: [fraction])] ifFalse: ["oops - just <integer>." aStream skip: -1. "un-gobble the period" ^value "Number readFrom: (ReadStream on: '3r-22.2')"]]. (aStream peekFor: $e) ifTrue: ["<integer>e<exponent>" ^value * (radix raisedTo: (Integer readFrom: aStream))]. ^value! ! nil subclass: #Object instanceVariableNames: '' classVariableNames: 'DependentsFields ErrorRecursion ' poolDictionaries: '' category: 'Kernel-Objects'!Object comment: 'Object is the superclass of all classes. It thus provides default behavior common to all objects, such as class access, copying and printing.'!!Object methodsFor: 'initialize-release'!release "Remove references to objects that may refer to the receiver. Answers self. This message should be overidden by subclasses with any cycles, in which case the subclass should also include the expression super release." self breakDependents! !!Object methodsFor: 'accessing'!at: index "Answer the value of an indexable field in the receiver. Fail if the argument index is not an Integer or is out of bounds. Essential. See documentation in Object metaclass." <primitive: 60> index isInteger ifTrue: [self errorSubscriptBounds: index]. (index isKindOf: Number) ifTrue: [^self at: index truncated] ifFalse: [self errorNonIntegerIndex]!at: index put: value "Store the argument value in the indexable field of the receiver indicated by index. Fail if the index is not an Integer or is out of bounds. Or fail if the value is not of the right type for this kind of collection. Answer the value that was stored. Essential. See documentation in Object metaclass." <primitive: 61> index isInteger ifTrue: [(index >= 1 and: [index <= self size]) ifTrue: [self errorImproperStore] ifFalse: [self errorSubscriptBounds: index]]. (index isKindOf: Number) ifTrue: [^self at: index truncated put: value] ifFalse: [self errorNonIntegerIndex]!basicAt: index "Answer the value of an indexable field in the receiver. Fail if the argument index is not an Integer or is out of bounds. Essential. See documentation in Object metaclass. Do not override this message in any subclass." <primitive: 60> (index isKindOf: Integer) ifTrue: [self errorSubscriptBounds: index]. (index isKindOf: Number) ifTrue: [^self basicAt: index truncated] ifFalse: [self errorNonIntegerIndex]!basicAt: index put: value "Store the second argument value in the indexable field of the receiver indicated by index. Fail if the index is not an Integer or is out of bounds. Or fail if the value is not of the right type for this kind of collection. Answer the value that was stored. Essential. See documentation in Object metaclass. Do not override in a subclass." <primitive: 61> (index isKindOf: Integer) ifTrue: [(index >= 1 and: [index <= self size]) ifTrue: [self errorImproperStore] ifFalse: [self errorSubscriptBounds: index]]. (index isKindOf: Number) ifTrue: [^self basicAt: index truncated put: value] ifFalse: [self errorNonIntegerIndex]!basicSize "Answer the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Essential. See documentation in Object metaclass. Do not override in any subclass." <primitive: 62> "The number of indexable fields of fixed-length objects is 0" ^0!readFromString: aString "Create an object based on the contents of aString." ^self readFrom: (ReadStream on: aString)!size "Answer the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Essential. See documentation in Object metaclass. " <primitive: 62> "The number of indexable fields of fixed-length objects is 0" ^0!yourself "Answer self."! !!Object methodsFor: 'testing'!isInteger "Coerces Integers to true and everything else to false. Integer overrides with ^true" ^false!isNil "Coerces nil to true and everything else to false. UndefinedObject overrides with ^true" ^false!notNil "Coerces nil to false and everything else to true. UndefinedObject overrides with ^false" ^true! !!Object methodsFor: 'comparing'!= anObject "Answer true if the receiver and the argument represent the same object and false otherwise. If = is redefined in any subclass, consider also redefining the message hash." ^self == anObject!== anObject "Answer true if the receiver and the argument are the same object (have the same object pointer) and false otherwise. Do not redefine the message == in any other class!! Essential. No Lookup. See documentation in Object metaclass." <primitive: 110> self primitiveFailed!hash "Answer a SmallInteger whose value is half of the receiver's object pointer (interpreting object pointers as 16-bit signed quantities). Fails if the receiver is a SmallInteger. Essential. See documentation in Object metaclass." <primitive: 75> self primitiveFailed!hashMappedBy: map "Answer what my hash would be if oops changed according to map" ^ map newHashFor: self hash!~= anObject "Answer true if the receiver and the argument do not represent the same object and false otherwise." ^self = anObject == false!~~ anObject "Answer true if the receiver and the argument are not the same object (have the same object pointer) and false otherwise." ^(self == anObject) not! !!Object methodsFor: 'copying'!copy "Answer another instance just like the receiver. Subclasses typically override this method; they typically do not override shallowCopy" ^self shallowCopy!deepCopy "Answer a copy of the receiver with its own copy of each instance variable." | newObject class index | class _ self class. (class == Object) ifTrue: [^self]. class isVariable ifTrue: [index _ self basicSize. newObject _ class basicNew: index. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index) deepCopy. index _ index - 1]] ifFalse: [newObject _ class basicNew]. index _ class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index) deepCopy. index _ index - 1]. ^newObject!shallowCopy "Answer a copy of the receiver which shares the receiver's instance variables. " | class newObject index | class _ self class. "I don't understand why the following check is here. Object is not supposed to have any instances at all." class == Object ifTrue: [^self]. class isVariable ifTrue: [index _ self basicSize. newObject _ class basicNew: index. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index). index _ index - 1]] ifFalse: [newObject _ class basicNew]. index _ class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index). index _ index - 1]. ^newObject! !!Object methodsFor: 'dependents access'!addDependent: anObject "Add anObject as one of the receiver's dependents." (DependentsFields at: self ifAbsent: [self setDependents]) add: anObject. ^anObject!dependents "Answer an OrderedCollection of the objects that are dependent on the receiver, that is, the objects that should be notified if the receiver changes." ^ DependentsFields at: self ifAbsent: [OrderedCollection new]!removeDependent: anObject "Remove the argument, anObject, as one of the receiver's dependents." | dependents | dependents _ DependentsFields at: self ifAbsent: [^ anObject]. dependents remove: anObject ifAbsent: []. dependents isEmpty ifTrue: [self breakDependents]. ^anObject! !!Object methodsFor: 'updating'!broadcast: aSymbol "Send the argument, aSymbol, as a unary message to all of the receiver's dependents." self dependents ~~ nil ifTrue: [self dependents do: [:aDependent | aDependent perform: aSymbol]]!broadcast: aSymbol with: anObject "Send the argument, aSymbol, as a keyword message with argument anObject to all of the receiver's dependents." self dependents ~~ nil ifTrue: [self dependents do: [:aDependent | aDependent perform: aSymbol with: anObject]]!changed "Receiver changed in a general way; inform all the dependents by sending each dependent an update: message." self changed: self!changed: aParameter "Receiver changed. The change is denoted by the argument aParameter. Usually the argument is a Symbol that is part of the dependent's change protocol. Inform all of the dependents." self dependents do: [:aDependent | aDependent update: aParameter]!changeRequest "Receiver wants to change; check with all dependents that it is OK." self dependents do: [:dep | dep updateRequest ifFalse: [^false]]. ^true!changeRequestFrom: requestor "Receiver wants to change; check with all dependents (other than requestor) that it is OK." self dependents do: [:dep | (dep == requestor or: [dep updateRequest]) ifFalse: [^false]]. ^true!update: aParameter "Receive a change notice from an object of whom the receiver is a dependent. The default behavior is to do nothing; a subclass might want to change itself in some way." ^self!updateRequest "Default behavior is to grant update requests; a subclass might want to override this behavior if it is in the middle of making another change." ^ true! !!Object methodsFor: 'printing'!isLiteral "Answer whether the receiver has a literal text form recognized by the compiler." ^false!printOn: aStream "Append to the argument aStream a sequence of characters that identifies the receiver." | title | title _ self class name. aStream nextPutAll: ((title at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']) , title!printString "Answer a String whose characters are a description of the receiver." | aStream | aStream _ WriteStream on: (String new: 16). self printOn: aStream. ^aStream contents!storeOn: aStream "Append to the argument aStream a sequence of characters that is an expression whose evaluation creates an object similar to the receiver." aStream nextPut: $(. self class isVariable ifTrue: [aStream nextPutAll: '(', self class name, ' basicNew: '; store: self basicSize; nextPutAll: ') '] ifFalse: [aStream nextPutAll: self class name, ' basicNew']. 1 to: self class instSize do: [:i | aStream nextPutAll: ' instVarAt: '; store: i; nextPutAll: ' put: '; store: (self instVarAt: i); nextPut: $;]. 1 to: self basicSize do: [:i | aStream nextPutAll: ' basicAt: '; store: i; nextPutAll: ' put: '; store: (self basicAt: i); nextPut: $;]. aStream nextPutAll: ' yourself)'!storeString "Answer a String representation of the receiver from which the receiver can be reconstructed." | aStream | aStream _ WriteStream on: (String new: 16). self storeOn: aStream. ^aStream contents! !!Object methodsFor: 'class membership'!class "Answer the object which is the receiver's class. Essential. See documentation in Object metaclass." <primitive: 111> self primitiveFailed!isKindOf: aClass "Answer a Boolean as to whether the class, aClass, is a superclass or class of the receiver." self class == aClass ifTrue: [^true] ifFalse: [^self class inheritsFrom: aClass]!isMemberOf: aClass "Answer a Boolean as to whether the receiver is an instance of the class, aClass." ^self class == aClass!respondsTo: aSymbol "Answer a Boolean as to whether the method dictionary of the receiver's class contains aSymbol as a message selector." ^self class canUnderstand: aSymbol! !!Object methodsFor: 'message handling'!perform: aSymbol "Send the receiver the unary message indicated by the argument. The argument is the selector of the message. Invoke messageNotUnderstood: if the number of arguments expected by the selector is not zero. Optional. See documentation in Object metaclass." <primitive: 83> ^self perform: aSymbol withArguments: (Array new: 0)!perform: aSymbol with: anObject "Send the receiver the keyword message indicated by the arguments. The first argument is the selector of the message. The other argument is the argument of the message to be sent. Invoke messageNotUnderstood: if the number of arguments expected by the selector is not one. Optional. See documentation in Object metaclass." <primitive: 83> ^self perform: aSymbol withArguments: (Array with: anObject)!perform: aSymbol with: firstObject with: secondObject "Send the receiver the keyword message indicated by the arguments. The first argument is the selector of the message. The other arguments are the arguments of the message to be sent. Invoke messageNotUnderstood: if the number of arguments expected by the selector is not two. Optional. See documentation in Object metaclass." <primitive: 83> ^self perform: aSymbol withArguments: (Array with: firstObject with: secondObject)!perform: aSymbol with: firstObject with: secondObject with: thirdObject "Send the receiver the keyword message indicated by the arguments. The first argument is the selector of the message. The other arguments are the arguments of the message to be sent. Invoke messageNotUnderstood: if the number of arguments expected by the selector is not three. Optional. See documentation in Object metaclass." <primitive: 83> ^self perform: aSymbol withArguments: (Array with: firstObject with: secondObject with: thirdObject)!perform: selector withArguments: anArray "Send the receiver the keyword message indicated by the arguments. The argument selector is the selector of the message. The arguments of the message are the elements of anArray. Invoke messageNotUnderstood: if the number of arguments expected by the selector is not the same as the length of anArray. Essential. See documentation in Object metaclass." <primitive: 84> self primitiveFailed! !!Object methodsFor: 'error handling'!confirm: aString "Create and start up a BinaryChoice menu with the argument as the message in order to determine true or false. Answers true or false." | answer | answer _ false. BinaryChoice message: aString displayAt: Sensor cursorPoint centered: true ifTrue: [answer _ true] ifFalse: [answer _ false]. ^answer!conflictingInheritanceError "Browse to the method which called this, redefine it appropriately, and then restart that calling method. " self error: 'Conflicting methods due to multiple inheritance'!doesNotUnderstand: aMessage "First check for a compound selector. If found, try copying down code into the receiver's class. If this is unsuccessful, announce that the receiver does not understand the argument, aMessage, as a message. The default behavior is to create a Notifier containing the appropriate message and to allow the user to open a Debugger. Subclasses can override this message in order to modify this behavior." | status gripe | status _ self class tryCopyingCodeFor: aMessage selector. status==#OK ifTrue: [^self perform: aMessage selector withArguments: aMessage arguments]. gripe _ status==#HierarchyViolation ifTrue: [aMessage selector classPart , ' is not one of my superclasses: '] ifFalse: ['Message not understood: ']. NotifierView openContext: thisContext label: gripe , aMessage selector contents: thisContext shortStack. "Try the message again if the programmer decides to proceed." ^self perform: aMessage selector withArguments: aMessage arguments "3 zork."!error: aString "The default behavior for error: is the same as halt:. This additional message is the one a subclass should override in order to change the handling of errors." NotifierView openContext: thisContext label: aString contents: thisContext shortStack "nil error: 'error message'."!halt "This is a simple message to use for inserting breakpoints during debugging." NotifierView openContext: thisContext label: 'Halt encountered.' contents: thisContext shortStack "nil halt."!halt: aString "This message can be used for inserting breakpoints during debugging. It creates and schedules a Debugger with the argument, aString, as the label." NotifierView openContext: thisContext label: aString contents: thisContext shortStack "nil halt: 'Test of halt:.'."!notify: aString "Create and schedule a Notifier with the argument as the message in order to request confirmation before a process can proceed." NotifierView openContext: thisContext label: 'Notifier' contents: aString "nil notify: 'confirmation message'."!primitiveFailed "Announce that a primitive has failed and there is no appropriate Smalltalk code to run." self error: 'a primitive has failed'!shouldNotImplement "Announce that although the receiver inherits this message, it should not implement it." self error: 'This message is not appropriate for this object'!subclassResponsibility "This message sets up a framework for the behavior of the class' subclasses. Announce that the subclass should have implemented this message." self error: 'My subclass should have overridden one of my messages.'! !!Object methodsFor: 'user interface'!basicInspect "Create and schedule an Inspector in which the user can examine the receiver's variables. This method should not be overwritten." InspectorView open: (Inspector inspect: self)!inspect "Create and schedule an Inspector in which the user can examine the receiver's variables." self basicInspect! !!Object methodsFor: 'system primitives'!asOop "Answer an Integer which is unique to me. See below. Essential. See also documentation in Object metaclass." <primitive: 75> self primitiveFailed " Non-Stretch mapping between objects and asOop value: oops 0...16K-1 --> 0...16K-1 oops 16K...32K-1 --> -16K...-1 SmallIntegers 0...16K --> 32K...48K-1 SmallIntegers -16K...0 --> 48K...64K-1 Stretch mapping between objects and asOop value: oops 0...48K-1 --> 0...48K-1 SmallIntegers -8K...-1 --> -16K...-2 even SmallIntegers 0...8K-1 --> -(16K-1)...-1 odd Non-Stretch Consistency check: | obj | -16384 to: 16383 do: [:i | obj _ i asObject. (obj == #NonExistentObject or: [obj asOop = i]) ifFalse: [self error: 'inconsistency']]. 32768 to: 65536 do: [:i | obj _ i asObject. (obj == #NonExistentObject or: [obj asOop = i]) ifFalse: [self error: 'inconsistency']]. Stretch Consistency check: | obj | -16384 to: 49151 do: [:i | obj _ i asObject. (obj == #NonExistentObject or: [obj asOop = i]) ifFalse: [self error: 'inconsistency']]. "!become: otherObject "Swap the instance pointers of the receiver and the argument, otherObject. All variables in the entire system that used to point to the receiver now point to the argument, and vice-versa. Fails if either object in a SmallInteger. Answer the argument which is now the same instance pointer that formerly denoted the receiver. Essential. See documentation in Object metaclass." <primitive: 72> self primitiveFailed!instVarAt: index "Answer a fixed variable in an object. The numbering of the variables corresponds to the named instance variables. Fail if the index is not an Integer or is not the index of a fixed variable. Essential. See documentation in Object metaclass." <primitive: 73> "Access beyond fixed variables." ^self basicAt: index - self class instSize!instVarAt: anInteger put: anObject "Store a value into a fixed variable in the receiver. The numbering of the variables corresponds to the named instance variables. Fail if the index is not an Integer or is not the index of a fixed variable. Answer the value stored as the result. Using this message violates the principle that each object has sovereign control over the storing of values into its instance variables. Essential. See documentation in Object metaclass." <primitive: 74> "Access beyond fixed fields" ^self basicAt: anInteger - self class instSize put: anObject!nextInstance "Answer the next instance after the receiver in the enumeration of all instances of this class. Fails if all instances have been enumerated. Essential. See documentation in Object metaclass." <primitive: 78> ^nil! !!Object methodsFor: 'system simulation'!tryPrimitive0 "Warning!!!! This is not a real primitive. This method is a template that the Smalltalk simulator uses to execute primitives with no arguments. See ContextPart class initPrimitives and ContextPart doPrimitive:receiver:args:." <primitive: 007> ^#primitiveFail!tryPrimitive1: arg1 "Warning!!!! This is not a real primitive. This method is a template that the Smalltalk simulator uses execute primitives with one argument. See ContextPart class|initPrimitives and ContextPart|doPrimitive:receiver:args:." <primitive: 007> ^#primitiveFail!tryPrimitive2: arg1 with: arg2 "Warning!!!! This is not a real primitive. This method is a template that the Smalltalk simulator uses execute primitives with two arguments. See ContextPart class|initPrimitives and ContextPart|doPrimitive:receiver:args:." <primitive: 007> ^#primitiveFail!tryPrimitive3: arg1 with: arg2 with: arg3 "Warning!!!! This is not a real primitive. This method is a template that the Smalltalk simulator uses execute primitives with three arguments. See ContextPart class|initPrimitives and ContextPart|doPrimitive:receiver:args:." <primitive: 007> ^#primitiveFail!tryPrimitive4: arg1 with: arg2 with: arg3 with: arg4 "Warning!!!! This is not a real primitive. This method is a template that the Smalltalk simulator uses execute primitives with four arguments. See ContextPart class|initPrimitives and ContextPart|doPrimitive:receiver:args:." <primitive: 007> ^#primitiveFail! !!Object methodsFor: 'private'!breakDependents "Deallocate the soft field for the receiver's dependents." DependentsFields removeKey: self ifAbsent: []!errorImproperStore "Create an error notification that an improper store was attempted." self error: 'Improper store into indexable object'!errorNonIntegerIndex "Create an error notification that an improper object was used as an index." self error: 'only integers should be used as indices'!errorSubscriptBounds: index "Create an error notification that an improper integer was used as an index." self error: 'subscript is out of bounds: ' , index printString!forkEmergencyEvaluatorAt: priority "Fork a process running a simple Smalltalk evaluator using as little of the system as possible. Used for desperate debugging. may be invoked by control-shift-C." | stream char | [Display white: (0@0 extent: 1024@36). 'EMERGENCY EVALUATOR (priority ', priority printString, ') -- type an expression terminated by ESC' displayAt: 50@0. Display reverse: (0@0 extent: 1024@36). stream _ WriteStream on: String new. [[Sensor keyboardPressed] whileFalse. (char _ Sensor keyboard) = 160 asCharacter] whileFalse: [char = Character backspace ifTrue: [stream skip: -1. Display black: (0@18 extent: 1024@18)] ifFalse: [stream nextPut: char]. stream contents displayAt: 50@18]. Display black: (0@0 extent: 1024@18). (Compiler evaluate: stream contents) printString displayAt: 50@0] forkAt: priority!mustBeBoolean "Catches attempts to test truth of non-Booleans. This message is sent from the interpreter." self error: 'NonBoolean receiver--proceed for truth.'. ^true!nilFields "Store nil into all pointer fields of the receiver." self class isPointers ifFalse: [^self]. 1 to: self basicSize do: [:index | self basicAt: index put: nil]. 1 to: self class instSize do: [:index | self instVarAt: index put: nil].!primitiveError: aString "This method is called when the error handling results in a recursion in calling on error: or halt or halt:." | context key | Transcript cr. Transcript show: '**System Error Handling Failed** '. Transcript show: aString. Transcript cr. context _ thisContext sender sender. 3 timesRepeat: [context == nil ifFalse: [Transcript print: (context _ context sender); cr]]. [Transcript show: '**type <s> for more stack; anything else restarts scheduler**'. Transcript cr. key _ Sensor keyboard. key = $s | (key = $S)] whileTrue: [5 timesRepeat: [context == nil ifFalse: [Transcript print: (context _ context sender); cr]]]. ScheduledControllers searchForActiveController!setDependents "Allocate the soft field for the receiver's dependents." | dependents | dependents _ OrderedCollection new. DependentsFields add: (Association key: self value: dependents). ^ dependents!species "Answer the preferred class for reconstructing the receiver. For example, collections create new collections whenever enumeration messages such as collect: or select: are invoked. The new kind of collection is determined by the species of the original collection. Species and class are not always the same. For example, the species of Interval is Array." ^self class! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Object class instanceVariableNames: ''!!Object class methodsFor: 'class initialization'!initialize (self confirm: 'Do you really want to initializeclass Object? It will reset all dependents.') ifTrue: [self initializeDependentsFields. self initializeErrorRecursion] "Object initialize"! !!Object class methodsFor: 'instance creation'!readFrom: aStream "Create an object based on the contents of aStream." | object | object _ Compiler evaluate: aStream. (object isKindOf: self) ifFalse: [self error: self name, ' expected']. ^object! !!Object class methodsFor: 'documentation'!howToModifyPrimitives "You are allowed to write methods which specify primitives, but please use caution. If you make a subclass of a class which contains a primitive method, the subclass inherits the primitive. The message which is implemented primitively may be overridden in the subclass (E.g., see at:put: in String's subclass Symbol). The primitive behavior can be invoked using super (see Symbol string:). A class which attempts to mimic the behavior of another class without being its subclass may or may not be able to use the primitives of the original class. In general, if the instance variables read or written by a primitive have the same meanings and are in the same fields in both classes, the primitive will work. For certain frequently used 'special selectors', the compiler emits a send-special-selector bytecode instead of a send-message bytecode. Special selectors were created because they offer two advantages. Code which sends special selectors compiles into fewer bytes than normal. For some pairs of receiver classes and special selectors, the interpreter jumps directly to a primitive routine without looking up the method in the class. This is much faster than a normal message lookup. A selector which is a special selector solely in order to save space has a normal behavior. Methods whose selectors are special in order to gain speed contain the comment, 'No Lookup'. When the interpreter encounters a send-special-selector bytecode, it checks the class of the receiver and the selector. If the class-selector pair is a no-lookup pair, then the interpreter swiftly jumps to the routine which implements the corresponding primitive. (A special selector whose receiver is not of the right class to make a no-lookup pair, is looked up normally). The pairs are listed below. No-lookup methods contain a primitive number specification, <primitive: xx>, which is redundant. Since the method is not normally looked up, deleting the primitive number specification cannot prevent this primitive from running. If a no-lookup primitive fails, the method is looked up normally, and the expressions in it are executed. No Lookup pairs of (class, selector) SmallInteger with any of + - * / \\ bitOr: bitShift: bitAnd: // SmallInteger with any of = ~= > < >= <= Any class with == Any class with @ Point with either of x y ContextPart with blockCopy: BlockContext with either of value value: " self error: 'comment only'!whatIsAPrimitive "Some messages in the system are responded to primitively. A primitive response is performed directly by the interpreter rather than by evaluating expressions in a method. The methods for these messages indicate the presence of a primitive response by including <primitive: xx> before the first expression in the method. Primitives exist for several reasons. Certain basic or 'primitive' operations cannot be performed in any other way. Smalltalk without primitives can move values from one variable to another, but cannot add two SmallIntegers together. Many methods for arithmetic and comparison between numbers are primitives. Some primitives allow Smalltalk to communicate with I/O devices such as the disk, the display, and the keyboard. Some primitives exist only to make the system run faster; each does the same thing as a certain Smalltalk method, and its implementation as a primitive is optional. When the Smalltalk interpreter begins to execute a method which specifies a primitive response, it tries to perform the primitive action and to return a result. If the routine in the interpreter for this primitive is successful, it will return a value and the expressions in the method will not be evaluated. If the primitive routine is not successful, the primitive 'fails', and the Smalltalk expressions in the method are executed instead. These expressions are evaluated as though the primitive routine had not been called. The Smalltalk code that is evaluated when a primitive fails usually anticipates why that primitive might fail. If the primitive is optional, the expressions in the method do exactly what the primitive would have done (See Number @). If the primitive only works on certain classes of arguments, the Smalltalk code tries to coerce the argument or appeals to a superclass to find a more general way of doing the operation (see SmallInteger +). If the primitive is never supposed to fail, the expressions signal an error (see SmallInteger asFloat). Each method that specifies a primitive has a comment in it. If the primitive is optional, the comment will say 'Optional'. An optional primitive that is not implemented always fails, and the Smalltalk expressions do the work instead. If a primitive is not optional, the comment will say, 'Essential'. Some methods will have the comment, 'No Lookup'. See Object howToModifyPrimitives for an explanation of special selectors which are not looked up. For the primitives for +, -, *, and bitShift: in SmallInteger, and truncated in Float, the primitive constructs and returns a 16-bit LargePositiveInteger when the result warrants it. Returning 16-bit LargePositiveIntegers from these primitives instead of failing is optional in the same sense that the LargePositiveInteger arithmetic primitives are optional. The comments in the SmallInteger primitives say, 'Fails if result is not a SmallInteger', even though the implementor has the option to construct a LargePositiveInteger. For further information on primitives, see the 'Primitive Methods' part of the chapter on the formal specification of the interpreter in the Smalltalk book." self error: 'comment only'! !!Object class methodsFor: 'private'!initializeDependentsFields DependentsFields _ IdentityDictionary new: 4 "Object initializeDependentsFields"!initializeErrorRecursion ErrorRecursion _ false "Object initializeErrorRecursion"! !Object initialize! Switch subclass: #OneOnSwitch instanceVariableNames: 'connection ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!OneOnSwitch comment:'I am a kind of Switch that can be connected to some related object, typically to a collection of my instances. When my instance is created, its connection is set to a particular object. When the object changes because an instance is turned on, an update message is broadcasted. All the connected OneOnSwitches, except the changed one, turn off. This allows OneOnSwitches to maintain the constraint that at most one of them will be on at any time. OneOnSwitches can thus be made to act like "car radio" switches.Instance Variables: connection any object'!!OneOnSwitch methodsFor: 'initialize-release'!release super release. self isConnectionSet ifTrue: [connection removeDependent: self]! !!OneOnSwitch methodsFor: 'state'!turnOn "Does nothing if it is already on. If it is not, it is set to 'on', its dependents are notified of the change, its connection is notified, and its action is executed." self isOff ifTrue: [on _ true. self changed. self notifyConnection. self doAction: onAction]! !!OneOnSwitch methodsFor: 'connection'!connection "Answer the object that connects the receiver to other Switches." ^connection!connection: anObject "Set anObject to be the connection among two or more Switches." connection _ anObject. connection addDependent: self!isConnectionSet "Answer whether the receiver is connected to an object that coordinates updates among switches." connection == nil ifTrue: [^false] ifFalse: [^true]!notifyConnection "Send the receiver's connection (if it exists) the message 'changed: self' in order for the connection to broadcast the change to other objects connected by the connection. " self isConnectionSet ifTrue: [self connection changed: self]! !!OneOnSwitch methodsFor: 'updating'!update: aOneOnSwitch "Does nothing if aOneOnSwitch is identical to this object. If it is not, this object is turned off. Is sent by the connection (an Object) when some related OneOnSwitch (possibly this one) has changed. This allows a group of related OneOnSwitches to maintain the constraint that at most one will be on at any time. " self ~~ aOneOnSwitch ifTrue: [self turnOff]! ! CodeController subclass: #OnlyWhenSelectedCodeController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!OnlyWhenSelectedCodeController comment:'I am a code controller that will not take control unless my model has some selection.'!!OnlyWhenSelectedCodeController methodsFor: 'control defaults'!isControlWanted view isSelected ifFalse: [sensor yellowButtonPressed ifTrue: [view flash]. self deselect. ^false]. ^self viewHasCursor! ! CodeView subclass: #OnlyWhenSelectedCodeView instanceVariableNames: 'selectionMsg ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!OnlyWhenSelectedCodeView comment:'I am a code view for an OnlyWhenSelectedCodeController.'!!OnlyWhenSelectedCodeView methodsFor: 'initialization'!selectionMsg: selMsg selectionMsg _ selMsg! !!OnlyWhenSelectedCodeView methodsFor: 'controller access'!defaultControllerClass ^OnlyWhenSelectedCodeController! !!OnlyWhenSelectedCodeView methodsFor: 'control'!isSelected ^model perform: selectionMsg! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!OnlyWhenSelectedCodeView class instanceVariableNames: ''!!OnlyWhenSelectedCodeView class methodsFor: 'instance creation'!on: anObject aspect: m1 change: m3 menu: m4 initialSelection: sel selection: selMsg "Create an instance viewing anObject. See super method in TextView for full explanation. initialSelection (if not nil) is a string which will be searched for, and then highlighted if found, whenever the viewed text changes." ^(super on: anObject aspect: m1 change: m3 menu: m4) selectionMsg: selMsg! ! DisplayObject subclass: #OpaqueForm instanceVariableNames: 'figure shape ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!OpaqueForm comment:'OpaqueForms include a shape as well as a figure form. The shape indicates what part of the background should get occluded in displaying, so that patterns other than black in the figure form will still appear opaque.'!!OpaqueForm methodsFor: 'accessing'!figure ^ figure!offset ^ figure offset!shape ^ shape! !!OpaqueForm methodsFor: 'displaying'!copyBits: copyRect from: sourceForm at: destPoint clippingBox: clipRect rule: rule mask: mask | sourceFigure sourceShape | (sourceForm isMemberOf: OpaqueForm) ifTrue: [sourceFigure _ sourceForm figure. sourceShape _ sourceForm shape] ifFalse: [sourceFigure _ sourceShape _ sourceForm]. figure copyBits: copyRect from: sourceFigure at: destPoint clippingBox: clipRect rule: rule mask: mask. shape copyBits: copyRect from: sourceShape at: destPoint clippingBox: clipRect rule: rule mask: mask!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "This is the real display message, but it doesn't get used until the new display protocol is installed." shape displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: Form erase mask: nil. figure displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: Form under mask: aForm!displayOn: Display transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: ruleInteger mask: aForm "See comment in Form." shape displayOn: Display transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: Form erase mask: nil. figure displayOn: Display transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: Form under mask: aForm! !!OpaqueForm methodsFor: 'copying'!deepCopy ^ self shallowCopy setFigure: figure deepCopy shape: shape deepCopy! !!OpaqueForm methodsFor: 'display box access'!computeBoundingBox ^figure boundingBox! !!OpaqueForm methodsFor: 'pattern'!valueAt: aPoint "0 and 1 are white and black; 2 is transparent. 3 is a weird value which look like 1" (shape valueAt: aPoint) = 1 ifTrue: [^ figure valueAt: aPoint] "opaque" ifFalse: [^ 2 + (figure valueAt: aPoint)] "background shows through"!valueAt: aPoint put: value "0 and 1 are white and black; 2 is transparent. 3 is a weird value which look like 1" shape valueAt: aPoint put: 1 - (value//2). figure valueAt: aPoint put: value\\2! !!OpaqueForm methodsFor: 'editing'!bitEdit "Create and schedule a view located in an area designated by the user that contains a view of the receiver magnified by 8@8 that can be modified using the Bit Editor. It also contains a view of the original form." BitEditor openOnForm: self "OpaqueForm makeStar bitEdit."! !!OpaqueForm methodsFor: 'printing'!storeOn: aStream aStream nextPutAll: 'OpaqueForm figure: ('. figure storeOn: aStream. aStream nextPutAll: ') shape: ('. shape storeOn: aStream. aStream nextPutAll: ')'! !!OpaqueForm methodsFor: 'private'!setFigure: figureForm shape: shapeForm figure _ figureForm. shape _ shapeForm! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!OpaqueForm class instanceVariableNames: ''!!OpaqueForm class methodsFor: 'instance creation'!figure: figureForm shape: shapeForm ^ self new setFigure: figureForm shape: shapeForm!shape: aSolidForm "Results in a form which is black where aSolidForm is black and transparent where aSolidForm is white." ^ self new setFigure: aSolidForm shape: aSolidForm! !!OpaqueForm class methodsFor: 'examples'!example Cursor blank showWhile: [self makeStar follow: [Sensor cursorPoint] while: [Sensor noButtonPressed]] "OpaqueForm example" "OpaqueForm makeStar bitEdit"!makeStar | figure shape pen formRect | formRect_ 0@0 extent: 50@50. pen _ Pen new. pen defaultNib: 2. Display fill: formRect mask: Form white. pen north; place: formRect center; spiral: 45 angle: 144. shape _ Form fromDisplay: formRect. pen white; north; place: formRect center; spiral: 30 angle: 144. figure _ Form fromDisplay: formRect. ^ OpaqueForm figure: figure shape: shape! ! SequenceableCollection variableSubclass: #OrderedCollection instanceVariableNames: 'firstIndex lastIndex ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Sequenceable'!OrderedCollection comment: 'I am an ordered collection of elements.'!!OrderedCollection methodsFor: 'accessing'!after: oldObject "Answer the element after oldObject. If the receiver does not contain oldObject or if the receiver contains no elements after oldObject, create an error message." | index | index _ self find: oldObject. index = lastIndex ifTrue: [^self errorLastObject] ifFalse: [^self basicAt: index + 1]!at: anInteger "Answer with my element at index anInteger. at: is used by a knowledgeable client to access an existing element" (anInteger < 1 or: [anInteger + firstIndex - 1 > lastIndex]) ifTrue: [self errorNoSuchElement] ifFalse: [^super at: anInteger + firstIndex - 1]!at: anInteger put: anObject "Put anObject at element index anInteger. at:put: can not be used to append, front or back, to an ordered collection; it is used by a knowledgeable client to replace an element" | index | index _ anInteger truncated. (index < 1 or: [index + firstIndex - 1 > lastIndex]) ifTrue: [self errorNoSuchElement] ifFalse: [^super at: index + firstIndex - 1 put: anObject]!before: oldObject "Answer the element before oldObject. If the receiver does not contain oldObject or if the receiver contains no elements before oldObject, create an error message." | index | index _ self find: oldObject. index = firstIndex ifTrue: [^self errorFirstObject] ifFalse: [^self basicAt: index - 1]!first "Answer the first element. If the receiver is empty, create an errror message. This is a little faster than the implementation in the superclass" self emptyCheck. ^self basicAt: firstIndex!last "Answer the last element. If the receiver is empty, create an errror message. This is a little faster than the implementation in the superclass" self emptyCheck. ^self basicAt: lastIndex!size ^lastIndex - firstIndex + 1! !!OrderedCollection methodsFor: 'copying'!copyEmpty "Answer a copy of the receiver that contains no elements." ^self species new!copyFrom: startIndex to: endIndex "Answer a copy of the receiver that contains elements from position startIndex to endIndex." | targetCollection index | endIndex < startIndex ifTrue: [^self species new: 0]. targetCollection _ self species new: endIndex + 1 - startIndex. startIndex to: endIndex do: [:index | targetCollection add: (self at: index)]. ^targetCollection!copyReplaceFrom: start to: stop with: replacementCollection "Answer a copy of the receiver with replacementCollection's elements in place of the receiver's start'th to stop'th elements. This does not expect a 1-1 map from replacementCollection to the start to stop elements, so it will do an insert or append." | newOrderedCollection delta newIndex index mySize startIndex stopIndex | "if start is less than 1, ignore stop and assume this is inserting at the front. if start greater than self size, ignore stop and assume this is appending. otherwise, it is replacing part of me and start and stop have to be within my bounds. " delta _ 0. startIndex _ start. stopIndex _ stop. start < 1 ifTrue: [startIndex _ stopIndex _ 0] ifFalse: [startIndex > self size ifTrue: [startIndex _ stopIndex _ self size + 1] ifFalse: [(stopIndex < (startIndex - 1) or: [stopIndex > self size]) ifTrue: [self errorOutOfBounds]. delta _ stopIndex - startIndex + 1]]. newOrderedCollection _ self species new: self size + replacementCollection size - delta. 1 to: startIndex - 1 do: [:index | newOrderedCollection add: (self at: index)]. 1 to: replacementCollection size do: [:index | newOrderedCollection add: (replacementCollection at: index)]. stopIndex + 1 to: self size do: [:index | newOrderedCollection add: (self at: index)]. ^newOrderedCollection!copyWith: newElement "Answer a copy of the receiver that is 1 bigger than the receiver and includes the argument, newElement, at the end." | newCollection | newCollection _ self copy. newCollection add: newElement. ^newCollection!copyWithout: oldElement "Answer a copy of the receiver that does not contain any elements equal to oldElement." | newCollection each | newCollection _ self species new: self size. self do: [:each | oldElement = each ifFalse: [newCollection add: each]]. ^newCollection! !!OrderedCollection methodsFor: 'adding'!add: newObject ^self addLast: newObject!add: newObject after: oldObject "Add the argument, newObject, as an element of the receiver. Put it in the position just succeeding oldObject. Answer newObject." | index | index _ self find: oldObject. self insert: newObject before: index + 1. ^newObject!add: newObject before: oldObject "Add the argument, newObject, as an element of the receiver. Put it in the position just preceding oldObject. Answer newObject." | index | index _ self find: oldObject. self insert: newObject before: index. ^newObject!addAll: anOrderedCollection "Add each element of anOrderedCollection at my end. Answer anOrderedCollection." ^self addAllLast: anOrderedCollection!addAllFirst: anOrderedCollection "Add each element of anOrderedCollection at the beginning of the receiver. Answer anOrderedCollection." anOrderedCollection reverseDo: [:each | self addFirst: each]. ^anOrderedCollection!addAllLast: anOrderedCollection "Add each element of anOrderedCollection at the end of the receiver. Answer anOrderedCollection." anOrderedCollection do: [:each | self addLast: each]. ^anOrderedCollection!addFirst: newObject "Add newObject to the beginning of the receiver. Add newObject." firstIndex = 1 ifTrue: [self makeRoomAtFirst]. firstIndex _ firstIndex - 1. self basicAt: firstIndex put: newObject. ^newObject!addLast: newObject "Add newObject to the end of the receiver. Answer newObject." lastIndex = self basicSize ifTrue: [self makeRoomAtLast]. lastIndex _ lastIndex + 1. self basicAt: lastIndex put: newObject. ^newObject!grow "Become larger. Typically, a subclass has to override this if the subclass adds instance variables" | newSelf | newSelf _ self species new: self size + self growSize. self do: [:each | newSelf addLast: each]. self become: newSelf! !!OrderedCollection methodsFor: 'removing'!remove: oldObject ifAbsent: absentBlock | index | index _ firstIndex. [index <= lastIndex] whileTrue: [oldObject = (self basicAt: index) ifTrue: [self removeIndex: index. ^oldObject] ifFalse: [index _ index + 1]]. ^absentBlock value!removeAllSuchThat: aBlock "Evaluate aBlock for each element of the receiver. Remove each element for which aBlock evaluates to true. A subclass might have to override this message to initialize additional instance variables for newCollection" | index element newCollection | newCollection _ self species new. index _ firstIndex. [index <= lastIndex] whileTrue: [element _ self basicAt: index. (aBlock value: element) ifTrue: [newCollection add: element. self removeIndex: index] ifFalse: [index _ index + 1]]. ^newCollection!removeFirst "Remove the first element of the receiver. If the receiver is empty, create an error message." | firstObject | self emptyCheck. firstObject _ self basicAt: firstIndex. self basicAt: firstIndex put: nil. firstIndex _ firstIndex + 1. ^firstObject!removeLast "Remove the last element of the receiver. If the receiver is empty, create an error message." | lastObject | self emptyCheck. lastObject _ self basicAt: lastIndex. self basicAt: lastIndex put: nil. lastIndex _ lastIndex - 1. ^lastObject! !!OrderedCollection methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of my elements as the argument. Collect the resulting values into a collection that is like me. Answer with the new collection. Override superclass in order to use add:, not at:put:." | newCollection | newCollection _ self species new. self do: [:each | newCollection add: (aBlock value: each)]. ^newCollection!do: aBlock "override the superclass for performance" | index | index _ firstIndex. [index <= lastIndex] whileTrue: [aBlock value: (self basicAt: index). index _ index + 1]!reverse "Answer with a new collection like me with its elements in the opposite order. Override superclass in order to use add:, not at:put:." | newCollection | newCollection _ self species new. self reverseDo: [:each | newCollection add: each]. ^newCollection!reverseDo: aBlock "override the superclass for performance" | index | index _ lastIndex. [index >= firstIndex] whileTrue: [aBlock value: (self basicAt: index). index _ index - 1]!select: aBlock "Evaluate aBlock with each of my elements as the argument. Collect into a new collection like me, only those elements for which aBlock evaluates to true. Override superclass in order to use add:, not at:put:." | newCollection | newCollection _ self copyEmpty. self do: [:each | (aBlock value: each) ifTrue: [newCollection add: each]]. ^newCollection! !!OrderedCollection methodsFor: 'private'!errorFirstObject self error: 'specified object is first object'!errorLastObject self error: 'specified object is last object'!errorNoSuchElement self error: 'attempt to index non-existent element in an ordered collection'!errorNotFound self error: 'element not found'!find: oldObject | index | index _ firstIndex. [index <= lastIndex and: [oldObject ~= (self basicAt: index)]] whileTrue: [index _ index + 1]. index <= lastIndex ifTrue: [^index] ifFalse: [self errorNotFound]!insert: anObject before: spot | index delta spotIndex| spotIndex _ spot. delta _ spotIndex - firstIndex. firstIndex = 1 ifTrue: [self makeRoomAtFirst. spotIndex _ firstIndex + delta]. index _ firstIndex _ firstIndex - 1. [index < (spotIndex - 1)] whileTrue: [self basicAt: index put: (self basicAt: index + 1). index _ index + 1]. self basicAt: index put: anObject. ^anObject!makeRoomAtFirst | delta index | delta _ self basicSize - self size. delta = 0 ifTrue: [self grow. delta _ self basicSize - self size]. lastIndex = self basicSize ifTrue: [^self]. "just in case we got lucky" index _ self basicSize. [index > delta] whileTrue: [self basicAt: index put: (self basicAt: index - delta + firstIndex - 1). self basicAt: index - delta + firstIndex - 1 put: nil. index _ index - 1]. firstIndex _ delta + 1. lastIndex _ self basicSize!makeRoomAtLast | index newLast | newLast _ self size. self basicSize - self size = 0 ifTrue: [self grow]. firstIndex = 1 ifTrue: [^self]. "we might be here under false premises or grow did the job for us" index _ 1. [index <= newLast] whileTrue: [self basicAt: index put: (self basicAt: index + firstIndex - 1). self basicAt: index + firstIndex - 1 put: nil. index _ index + 1]. firstIndex _ 1. lastIndex _ newLast!removeIndex: removedIndex | index | index _ removedIndex. [index < lastIndex] whileTrue: [self basicAt: index put: (self basicAt: index + 1). index _ index + 1]. self basicAt: lastIndex put: nil. lastIndex _ lastIndex - 1!setIndices firstIndex _ self basicSize // 2 max: 1. lastIndex _ firstIndex - 1 max: 0! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!OrderedCollection class instanceVariableNames: ''!!OrderedCollection class methodsFor: 'instance creation'!new ^self new: 10!new: anInteger "If a subclass adds fields, then it is necessary for that subclass to reimplement new: " ^(super new: anInteger) setIndices! ! Change subclass: #OtherChange instanceVariableNames: 'text ' classVariableNames: '' poolDictionaries: '' category: 'System-Changes'!OtherChange comment:'I represent a non-classifiable change, i.e. a doIt. I cache my text to reduce disk accesses.'!!OtherChange methodsFor: 'accessing'!name ^self defaultName: ' doIt '!parameters ^self text!text text == nil ifTrue: [text _ super text]. ^text!text: aString text _ aString. file _ nil! !!OtherChange methodsFor: 'checking'!checkWith: aChecker "Discard comments and 'From ...' messages if from the current system" | myText aStream first | myText _ self text. myText isEmpty ifTrue: [^self]. aStream _ ReadStream on: myText. first _ aStream next. first = $" ifTrue: [aStream skipTo: $"; skipSeparators. aStream atEnd ifTrue: [^self]]. first = $' ifTrue: [first _ 'From ', Smalltalk version, ' on '. myText size > first size ifTrue: [(aStream next: first size) = first ifTrue: [^self]]]. aChecker addDoIt: self! ! DisplayText subclass: #Paragraph instanceVariableNames: 'clippingRectangle compositionRectangle destinationForm rule mask marginTabsLevel firstIndent restIndent rightIndent lines lastLine outputMedium ' classVariableNames: 'DefaultCompositionRectangle ' poolDictionaries: 'TextConstants ' category: 'Graphics-Display Objects'!Paragraph comment:'The font and emphasis changes for text is fundamentally more complex than such graphical entities as a bar chart or pie chart. Hence many of the methods associated with Paragraph tend to be, stylistically, longer and more complex than those in most other system classes.Instance Variables: clippingRectangle<Rectangle> A Rectangle in CurrentDisplay coordinates. Its intersection with the compositionRectangle in turn intersected with the destinationForm is the area in which characters are constrained to display. compositionRectangle<Rectangle> Its offset serves as a relative offset similar to the offset field in Form. The width of the compositionRectangle is the dimension, modified by indents and tabsLevels, against which line wraparound is measured. The height of the compositionRectangle is reset each time recomposition is required. This happens when the stylizedString is initially composed and whenever a replacement (copyReplaceFrom:to:with:) occurs. destinationForm <Form> The Form into which the characters are scanned. Typically CurrentDisplay. rule <Integer> The rule according to which character display behaves. For example, rule may equal over, under, reverse, etc. mask<Form> The form with which each character is combined by the scanner before applying the rule for display. marginTabsLevel<Integer> The margin tabs give the left and right indent values for a specified marginTabsLevel. The marginTabsLevel is sometimes referred to as the nesting level and is an index into the marginTabsArray of the stringStyle. firstIndent<Integer> Amount to inset from the left margin for the first line of a paragraph. Initialized to value in the textStyle. restIndent<Integer> Amount to inset from the left margin for all but the first line of a paragraph. Initialized to value in the textStyle. rightIndent<Integer> Amount to inset from the right margin for all the lines of the paragraph. Initialized to value in the textStyle. lines<Array> This array is built during composition and modified when the stylizedString is modified (copyReplaceFrom:to:with:). Each of its fields from 1 to lastLine contains a TextLineInterval which in turn contains the starting index and stopping index of a given line as well as its internal spaces and padding width, the latter two being used to support the management of padded spaces, tabs and changing margin alignments. lastLine<Integer> The index of the last validly composed line in the lines array. outputMedium<Symbol> Either #Display, #PressPrinter or #DisplayPrinterWidths as of 1/20/80. Needed by CompositionScanner for determining the nature of the font to be used for character widths. For the DisplayScanner there are several places where distinguishing between displaying and printing is required. Also used for some margin and grid computations.'!!Paragraph methodsFor: 'accessing'!baseline "Answer the baseline of my TextStyle." ^textStyle baseline!clippingRectangle "Answer the rectangle, defined in absolute coordinates, whose intersection with the destinationForm is the area in which the characters are constrained to display." ^clippingRectangle!clippingRectangle: aRectangle "Set the rectangle, defined in absolute coordinates, whose intersection with the destinationForm is the area in which the characters are constrained to display." clippingRectangle _ aRectangle.!compositionRectangle "Answer the rectangle whose width is the dimension, modified by indents and tabsLevels, against which line wraparound is measured. The height of the compositionRectangle is reset each time recomposition is required." ^compositionRectangle!compositionRectangle: compRectangle "Set the rectangle whose width is the dimension, modified by indents and tabsLevels, against which line wraparound is measured." compositionRectangle _ compRectangle. self composeAll!destinationForm "Answer the Form into which the characters are scanned." ^destinationForm!destinationForm: aFormOrRectangle "Set the Form or Rectangle into which the characters are scanned. The destinationFrom is a Form when the outputMedium is #Display or #DisplayPrinterWidths, a Rectangle when the outputMedium is a #PressPrinter." destinationForm _ aFormOrRectangle.!form ^form!height "Answer the height of the composition rectangle." ^compositionRectangle height!lineGrid "Answer the lineGrid of my TextStyle." ^textStyle lineGrid!mask "Answer the form with which each character is combined by the scanner before applying the rule for display." ^mask!mask: maskForm "Set the argument, maskForm, to be the form with which each character is combined by the scanner before applying the rule for display." mask _ maskForm.!numberOfLines "Answer the number of lines of text in the receiver." ^lastLine!outputMedium "Answer the outputMedium for the receiver." ^outputMedium!outputMedium: aSymbol "Set the argument to be the outputMedium for the receiver. As of 1/20/80, #Display, #PressPrinter, #DisplayPrinterWidths are the possibilities." outputMedium _ aSymbol. "Changing the outputMedium means that the text must be recomposed." textStyle outputMedium: aSymbol. self composeAll!replaceFrom: start to: stop with: aText displaying: displayBoolean "Replace the receiver's text starting at position start, stopping at stop, by the characters in aText. It is expected that most requirements for modifications to the receiver will call this code. Certainly all cut's or paste's." | compositionScanner obsoleteLines obsoleteLastLine firstLineIndex lastLineIndex startLine stopLine replacementRange visibleRectangle startIndex newLine done newStop obsoleteY newY upOrDown moveRectangle | text "Update the text." replaceFrom: start to: stop with: aText. lastLine = 0 ifTrue: ["if lines have never been set up, measure them and display all the lines falling in the visibleRectangle" self composeAll. displayBoolean ifTrue: [self clearVisibleRectangle. self displayLines: (1 to: lastLine)]. ^self]. "save -- things get pretty mashed as we go along" obsoleteLines _ lines copy. obsoleteLastLine _ lastLine. "find the starting and stopping lines" firstLineIndex _ startLine _ self lineIndexOfCharacterIndex: start. stopLine _ self lineIndexOfCharacterIndex: stop. "how many characters being inserted or deleted -- negative if aText size is < characterInterval size." replacementRange _ aText size - (stop - start + 1). "Give ourselves plenty of elbow room." compositionRectangle height: textStyle lineGrid * 8196. "max Vector length" "build a boundingBox of the actual screen space in question -- we'll need it later" visibleRectangle _ (clippingRectangle intersect: compositionRectangle) intersect: destinationForm boundingBox. "Initialize a scanner." compositionScanner _ CompositionScanner new in: self. "If the starting line is not also the first line, then measuring must commence from line preceding the one in which characterInterval start appears. For example, deleting a line with only a carriage return may move characters following the deleted portion of text into the line preceding the deleted line." startIndex _ (lines at: firstLineIndex) first. startLine > 1 ifTrue: [newLine _ compositionScanner composeLine: startLine - 1 fromCharacterIndex: (lines at: startLine - 1) first inParagraph: self. (lines at: startLine - 1) = newLine ifFalse: ["start in line preceding the one with the starting character" startLine _ startLine - 1. self lineAt: startLine put: newLine. startIndex _ newLine last + 1]]. startIndex > text size ifTrue: ["nil lines after a deletion -- remeasure last line below" self trimLinesTo: (firstLineIndex - 1 max: 0). text size = 0 ifTrue: ["entire text deleted -- clear visibleRectangle and return." destinationForm fill: visibleRectangle rule: rule mask: Form white. self updateCompositionHeight. ^self]]. "Now we really get to it." done _ false. lastLineIndex _ stopLine. [done or: [startIndex > text size]] whileFalse: [self lineAt: firstLineIndex put: (newLine _ compositionScanner composeLine: firstLineIndex fromCharacterIndex: startIndex inParagraph: self). [(lastLineIndex > obsoleteLastLine or: ["no more old lines to compare with?" newLine last < (newStop _ (obsoleteLines at: lastLineIndex) last + replacementRange)]) or: [done]] whileFalse: [newStop = newLine last ifTrue: ["got the match" upOrDown _ replacementRange < 0 ifTrue: [0] ifFalse: [1]. "get source and dest y's for moving the unchanged lines" obsoleteY _ self topAtLineIndex: lastLineIndex + upOrDown. newY _ self topAtLineIndex: firstLineIndex + upOrDown. stopLine _ firstLineIndex. done _ true. "Fill in the new line vector with the old unchanged lines. Update their starting and stopping indices on the way." ((lastLineIndex _ lastLineIndex + 1) to: obsoleteLastLine) do: [:upDatedIndex | self lineAt: (firstLineIndex _ firstLineIndex + 1) put: ((obsoleteLines at: upDatedIndex) slide: replacementRange)]. "trim off obsolete lines, if any" self trimLinesTo: firstLineIndex] ifFalse: [lastLineIndex _ lastLineIndex + 1]]. startIndex _ newLine last + 1. firstLineIndex _ firstLineIndex + 1]. "Now the lines are up to date -- Whew!!. What remains is to move the 'unchanged' lines and display those which have changed." displayBoolean ifTrue: [ startIndex > text size ifTrue: ["If at the end of previous lines simply display lines from the line in which the first character of the replacement occured through the end of the paragraph." self updateCompositionHeight. self displayLines: (startLine to: (stopLine _ firstLineIndex min: lastLine))] ifFalse: ["Otherwise prepare to move the unchanged lines. moveRectangle defines the portion of the visibleRectangle containing the lines which may be moved en masse. Deletion -- moving 'up' the screen or ..." moveRectangle _ visibleRectangle left @ (obsoleteY max: visibleRectangle top) corner: visibleRectangle corner. "Insertion -- moving 'down' the screen. Shorten moveRectangle by height of insertion or ..." obsoleteY <= newY ifTrue: [moveRectangle corner: visibleRectangle corner + (0 @ (obsoleteY - newY))] ifFalse: ["Deletion, and top of moveRectangle will fall above top of visibleRectangle. Increase the origin of moveRectangle by the amount that would fall above (hence outside) the visibleRectangle." newY < visibleRectangle top ifTrue: [moveRectangle origin: visibleRectangle left @ (obsoleteY + visibleRectangle top - newY)]]. "Move'em." destinationForm copyBits: moveRectangle from: destinationForm at: visibleRectangle left @ (newY max: visibleRectangle top) clippingBox: visibleRectangle rule: Form over mask: Form black. "Display the new lines." self displayLines: (startLine to: stopLine). "A deletion may have 'pulled' previously undisplayed lines into the visibleRectangle. If so, display them." (newY < obsoleteY and: [(self topAtLineIndex: obsoleteLastLine + 1) > visibleRectangle bottom]) ifTrue: [self displayLines: ((self lineIndexOfTop: visibleRectangle bottom - (obsoleteY - newY)) to: (stopLine _ self lineIndexOfTop: visibleRectangle bottom))]]. "If we have done a deletion, obsolete material may remain at the bottom of the visibleRectangle. If so, clear it out." obsoleteLastLine >= lastLine ifTrue: [ newY _ self topAtLineIndex: lastLine + 1. newY < visibleRectangle top ifTrue: ["new lastLine is above visibleRectangle, clear entire visibleRectangle" destinationForm fill: visibleRectangle rule: rule mask: Form white] ifFalse: [destinationForm fill: ((visibleRectangle left @ newY extent: visibleRectangle extent) intersect: visibleRectangle) rule: rule mask: Form white]]]. self updateCompositionHeight.!rule "Answer the rule according to which character display behaves. For example, rule may equal over, under, reverse." ^rule!rule: ruleInteger "Set the rule according to which character display behaves." rule _ ruleInteger.!text: aText "Set the argument, aText, to be the text for the receiver." text _ aText. self composeAll! !!Paragraph methodsFor: 'displaying'!displayAt: aPoint "Because Paragraphs cache so much information, computation is avoided and displayAt: 0@0 is not appropriate here" self displayOn: destinationForm at: aPoint clippingBox: clippingRectangle rule: rule mask: mask!displayOn: aDisplayMedium "Display on a new destination medium -- typically a form." self displayOn: aDisplayMedium at: compositionRectangle topLeft clippingBox: clippingRectangle rule: rule mask: mask!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "Default display message when aDisplayPoint is in absolute screen coordinates. " destinationForm _ aDisplayMedium. clippingRectangle _ clipRectangle. rule _ ruleInteger. mask _ aForm. compositionRectangle moveTo: aDisplayPoint. (lastLine == nil or: [lastLine < 1]) ifTrue: [self composeAll]. self displayLines: (1 to: lastLine)!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle align: alignmentPoint with: relativePoint rule: ruleInteger mask: aForm self "Assumes offset has been set!!!!!!!!!!" displayOn: aDisplayMedium at: (offset + (displayTransformation applyTo: relativePoint) - alignmentPoint) rounded clippingBox: clipRectangle rule: ruleInteger mask: aForm.! !!Paragraph methodsFor: 'display box access'!boundingBox ^offset extent: compositionRectangle extent!computeBoundingBox ^offset extent: compositionRectangle extent! !!Paragraph methodsFor: 'composition'!composeAll "Compose a collection of characters into a collection of lines." | startIndex stopIndex lineIndex maximumRightX compositionScanner | lines _ Array new: 32. lastLine _ 0. maximumRightX _ 0. text size = 0 ifTrue: [compositionRectangle height: 0. ^maximumRightX]. startIndex _ lineIndex _ 1. stopIndex _ text size. compositionScanner _ CompositionScanner new in: self. [startIndex > stopIndex] whileFalse: [self lineAt: lineIndex put: (compositionScanner composeLine: lineIndex fromCharacterIndex: startIndex inParagraph: self). maximumRightX _ compositionScanner rightX max: maximumRightX. startIndex _ (lines at: lineIndex) last + 1. lineIndex _ lineIndex + 1]. self updateCompositionHeight. self trimLinesTo: lineIndex - 1. ^maximumRightX!recomposeIn: compositionRect clippingBox: clippingRect "Set the composition rectangle for the receiver so that the lines wrap within the rectangle, compositionRect, and the display of the text is clipped by the rectangle, clippingRect." self compositionRectangle: compositionRect copy text: text style: textStyle offset: offset outputMedium: #Display fitWidth: false. clippingRectangle _ clippingRect copy! !!Paragraph methodsFor: 'character location'!characterBlockAtPoint: aPoint "Answer a CharacterBlock for characters in the text at point aPoint. It is assumed that aPoint has been transformed into coordinates appropriate to the receiver's destinationForm rectangle and the compositionRectangle." ^CharacterBlockScanner new characterBlockAtPoint: aPoint in: self!characterBlockForIndex: targetIndex "Answer a CharacterBlock for character in the text at targetIndex. The coordinates in the CharacterBlock will be appropriate to the intersection of the destinationForm rectangle and the compositionRectangle." ^CharacterBlockScanner new characterBlockForIndex: targetIndex in: self! !!Paragraph methodsFor: 'selecting'!displayCaretAt: aPoint "Display CaretForm located at aPoint with default settings for rule and halftone." CaretForm displayOn: destinationForm at: aPoint clippingBox: clippingRectangle rule: Form reverse mask: Form black!displayCaretForBlock: aCharacterBlock "Show caret at proper place for aCharacterBlock" self displayCaretAt: (aCharacterBlock topLeft + (0@textStyle baseline))!dyForPoint: pt "See if pt is above or below clippingRectangle, return scroll amount" | dy dyLim | ((dy _ pt y - clippingRectangle top) < 0 and: [(dyLim _ compositionRectangle top - clippingRectangle top) < 0]) ifTrue: [^(dy max: dyLim) - textStyle lineGrid]. ((dy _ pt y - clippingRectangle bottom) > 0 and: [(dyLim _ compositionRectangle bottom - clippingRectangle bottom) > 0]) ifTrue: [^(dy min: dyLim) + textStyle lineGrid]. ^0!mouseSelect: previousStartBlock to: previousStopBlock "Answer with an Array of two CharacterBlocks that represent the text selection that the user makes. Allow for scrolling to extend selections." | pivotBlock startBlock stopBlock showingCaret dy pt okToScroll scrollDelay word | startBlock _ stopBlock _ pivotBlock _ self characterBlockAtPoint: Sensor cursorPoint. self displayCaretForBlock: pivotBlock. showingCaret _ true. okToScroll _ true. scrollDelay _ Delay forMilliseconds: 250. "For Dorados" [Sensor redButtonPressed] whileTrue: [ pt _ Sensor cursorPoint. (okToScroll and: [(dy _ self dyForPoint: pt) ~= 0]) ifTrue: [ [okToScroll _ false. scrollDelay wait. okToScroll _ true] forkAt: Processor userInterruptPriority. showingCaret ifTrue: [ self displayCaretForBlock: pivotBlock. showingCaret _ false] ifFalse: [self reverseFrom: startBlock to: pivotBlock]. self scrollBy: dy. pt _ dy < 0 ifTrue: [clippingRectangle topLeft] ifFalse: [clippingRectangle bottomRight]. pivotBlock _ self characterBlockForIndex: pivotBlock stringIndex. startBlock _ pivotBlock ]. stopBlock _ self characterBlockAtPoint: pt. stopBlock = startBlock ifFalse: [ showingCaret ifTrue: [ self displayCaretForBlock: pivotBlock. showingCaret _ false]. self reverseFrom: startBlock to: stopBlock. startBlock _ stopBlock] ]. (showingCaret not and: [pivotBlock = stopBlock]) ifTrue: [self displayCaretForBlock: pivotBlock]. scrollDelay disable. (previousStartBlock = previousStopBlock and: [pivotBlock = stopBlock and: [stopBlock = previousStopBlock]]) ifTrue: "select a word or bracketed range" [word _ self selectWord: pivotBlock stringIndex. word first = word last ifFalse: [self displayCaretForBlock: pivotBlock. pivotBlock _ self characterBlockForIndex: word first. stopBlock _ self characterBlockForIndex: word last. self reverseFrom: pivotBlock to: stopBlock]]. stopBlock < pivotBlock ifTrue: [^Array with: stopBlock with: pivotBlock] ifFalse: [^Array with: pivotBlock with: stopBlock]!reverseFrom: characterBlock1 to: characterBlock2 "Reverse area between the two character blocks given as arguments." | start stop | characterBlock1 = characterBlock2 ifTrue: [^self]. characterBlock1 < characterBlock2 ifTrue: [start _ characterBlock1. stop _ characterBlock2] ifFalse: [start _ characterBlock2. stop _ characterBlock1]. start top = stop top ifTrue: [ ^self reverseRectangle: (start origin corner: stop bottomLeft)]. self reverseRectangle: (start origin corner: compositionRectangle right @ start bottom). self reverseRectangle: (compositionRectangle left@start bottom corner: compositionRectangle right@stop top). self reverseRectangle: (compositionRectangle left@stop top corner: stop bottomLeft).!reverseRectangle: aRectangle "Highlight the part of aRectangle which is visible" | rect | rect _ aRectangle intersect: self visibleRectangle. destinationForm fill: rect rule: Form reverse mask: mask.!selectWord: stringIndex "Select delimited text or word--the result of double-clicking." | openDelimiter closeDelimiter direction match level leftDelimiters rightDelimiters string here hereChar start stop | string _ text string. here _ stringIndex. (here between: 2 and: string size) ifFalse: ["if at beginning or end, select entire string" ^ 1 to: string size + 1]. leftDelimiters _ '([{<''"'. rightDelimiters _ ')]}>''"'. openDelimiter _ string at: here - 1. match _ leftDelimiters indexOf: openDelimiter. match > 0 ifTrue: ["delimiter is on left -- match to the right" start _ here. direction _ 1. here _ here - 1. closeDelimiter _ rightDelimiters at: match] ifFalse: [openDelimiter _ string at: here. match _ rightDelimiters indexOf: openDelimiter. match > 0 ifTrue: ["delimiter is on right -- match to the left" stop _ here - 1. direction _ -1. closeDelimiter _ leftDelimiters at: match] ifFalse: ["no delimiters -- select a token" direction _ -1]]. level _ 1. [level > 0 and: [direction > 0 ifTrue: [here < string size] ifFalse: [here > 1]]] whileTrue: [hereChar _ string at: (here _ here + direction). match = 0 ifTrue: ["token scan goes left, then right" hereChar tokenish ifTrue: [here = 1 ifTrue: [start _ 1. "go right if hit string start" direction _ 1]] ifFalse: [direction < 0 ifTrue: [start _ here + 1. "go right if hit non-token" direction _ 1] ifFalse: [level _ 0]]] ifFalse: ["bracket match just counts nesting level" hereChar = closeDelimiter ifTrue: [level _ level - 1"leaving nest"] ifFalse: [hereChar = openDelimiter ifTrue: [level _ level + 1"entering deeper nest"]]]]. level > 0 ifTrue: ["in case ran off string end" here _ here + direction]. direction > 0 ifTrue: [^ start to: here] ifFalse: [^ here + 1 to: stop + 1]! !!Paragraph methodsFor: 'scrolling'!scrollBy: heightToMove "Change the composition rectangle such that the first line of text corresponds to the line at the current first line plus heightToMove, modulo the grid of the receiver's textstyle." self scrollBy: heightToMove grid: textStyle lineGrid.!scrollBy: height grid: grid "Change the composition rectangle such that the first line of text corresponds to the line at the current first line plus heightToMove, modulo the grid." | initialClippingRectangle heightToMove | "keep from scrolling out of clippingRectangle" heightToMove _ (height max: self compositionRectangleDelta). (heightToMove abs between: 0 and: grid) ifTrue: [heightToMove _ heightToMove sign * grid] ifFalse: [heightToMove _ heightToMove truncateTo: grid]. heightToMove abs >= clippingRectangle height ifTrue: [self clearVisibleRectangle. "adjust compositionRectangle behind clippingRectangle" compositionRectangle moveBy: (0 @ (0 - heightToMove)). "If heightToMove >= clippingRectangle, all lines to be displayed are not currently displayed." self displayLines: (1 to: lastLine). ^self]. "Adjust compositionRectangle behind clippingRectangle" compositionRectangle moveBy: (0 @ (0 - heightToMove)). "Need only to reshow part of clippingRectangle. Some of the lines are already on the display screen." initialClippingRectangle _ clippingRectangle copy. heightToMove < 0 "Box the lines to be moved." ifTrue: ["Moving down." clippingRectangle _ clippingRectangle insetOriginBy: (0 @ 0) cornerBy: (0 @ (0 - heightToMove ))] ifFalse: ["Moving up." clippingRectangle _ clippingRectangle insetOriginBy: (0 @ heightToMove ) cornerBy: (0 @ 0)]. destinationForm copyBits: clippingRectangle from: destinationForm at: clippingRectangle left @ (clippingRectangle top - heightToMove ) clippingBox: initialClippingRectangle rule: Form over mask: Form black. "Make room in clippingRectangle for lines 'pulled' into view." heightToMove < 0 ifTrue: ["On the top." (clippingRectangle bottomRight) y: clippingRectangle top - heightToMove ] ifFalse: ["At the bottom." (clippingRectangle topLeft) y: (((self topAtLineIndex: (self lineIndexOfTop: clippingRectangle bottom - heightToMove))) max: initialClippingRectangle topLeft y)]. "The reduced clippingRectangle informs the displayLines routine of what lines to actually display of those it is requested to display. It only displays those actually falling in the clippingRectangle." self displayLines: (1 to: lastLine). "If we've shortened so that bottom of compositionRectangle is < clippingRectangle, clear out the the potential garbage at the bottom of the clippingRectangle." compositionRectangle bottom < initialClippingRectangle bottom ifTrue: [destinationForm fill: (initialClippingRectangle left @ compositionRectangle bottom corner: initialClippingRectangle bottomRight) mask: Form white]. "And the clippingRectangle needs to be set to its original value." clippingRectangle _ initialClippingRectangle.! !!Paragraph methodsFor: 'alignment'!centered "Set the alignment for the style with which the receiver displays its text so that text is centered in the composition rectangle." textStyle alignment: Centered.!justified "Set the alignment for the style with which the receiver displays its text so that the characters in each of text end on an even border in the composition rectangle." textStyle alignment: Justified.!leftFlush "Set the alignment for the style with which the receiver displays its text so that the characters in each of text begin on an even border in the composition rectangle. This is also known as ragged-right." textStyle alignment: LeftFlush.!rightFlush "Set the alignment for the style with which the receiver displays its text so that the characters in each of text end on an even border in the composition rectangle but the beginning of each line does not (ragged-left)." textStyle alignment: RightFlush!toggleAlignment "Set the alignment for the style with which the receiver displays its text so that it moves from centered to justified to leftFlush to rightFlush and back to centered again." textStyle alignment: textStyle alignment + 1.! !!Paragraph methodsFor: 'tabs and margins'!clearIndents "Reset all the indention settings to be 0." self firstIndent: 0. self restIndent: 0. self rightIndent: 0!deltaMarginTabsLevel: anInteger "Delta the depth of 'nesting' for this paragraph -- an index into the marginTabsArray in the textStyle." self marginTabsLevel: anInteger + marginTabsLevel.!firstIndent "Answer the horizontal indenting of the first line of a paragraph in the style of the receiver." ^firstIndent!firstIndent: anInteger "Set the horizontal indenting of the first line of a paragraph in the style of the receiver to be anInteger." firstIndent _ (anInteger max: 0) min: (compositionRectangle width - DefaultSpace - rightIndent). self composeAll.!marginTabsLevel "Answer the depth of 'nesting' for this paragraph -- an index into the marginTabsArray in the textStyle." ^marginTabsLevel!marginTabsLevel: anInteger "Set the depth of 'nesting' for this paragraph -- an index into the marginTabsArray in the textStyle." marginTabsLevel _ (anInteger max: 0) min: textStyle nestingDepth."Check if we've nested so far that there is no room between the effective margins." [(self leftMarginForCompositionForLine: 1) >= (self rightMarginForComposition) and: [marginTabsLevel > 0]] whileTrue: [marginTabsLevel _ (marginTabsLevel - 1 max: 0)]. [(self leftMarginForCompositionForLine: 2) >= (self rightMarginForComposition) and: [marginTabsLevel > 0]] whileTrue: [marginTabsLevel _ (marginTabsLevel - 1 max: 0)]. self composeAll.!restIndent "Answer the indent for all but the first line of a paragraph in the style of the receiver." ^restIndent!restIndent: anInteger "Set the indent for all but the first line of a paragraph in the style of the receiver to be anInteger." restIndent _ (anInteger max: 0) min: (compositionRectangle width - DefaultSpace - rightIndent). self composeAll.!rightIndent "Answer the right margin indent for the lines of a paragraph in the style of the receiver." ^rightIndent!rightIndent: anInteger "Set the right margin indent for the lines of a paragraph in the style of the receiver to be anInteger." | maxRightIndent | firstIndent > restIndent ifTrue: [maxRightIndent _ (compositionRectangle width- DefaultSpace - firstIndent) max: 1] ifFalse: [maxRightIndent _ (compositionRectangle width- DefaultSpace - restIndent) max: 1]. rightIndent _ anInteger min: maxRightIndent. self composeAll.! !!Paragraph methodsFor: 'indicating'!flash "Complement twice the visible area in which the receiver displays." Display flash: self visibleRectangle!outline "Display a border around the visible area in which the receiver presents its text." clippingRectangle bottom <= compositionRectangle bottom ifTrue: [Display border: (clippingRectangle intersect: compositionRectangle) width: 2] ifFalse: [Display border: (clippingRectangle intersect: destinationForm boundingBox) width: 2].! !!Paragraph methodsFor: 'utilities'!clearVisibleRectangle "Display the area in which the receiver presents its text so that the area is all one tone--in this case, all white." destinationForm fill: self visibleRectangle rule: rule mask: Form white.!fit "Make the bounding rectangle of the receiver contain all the text without changing the width of the receiver's composition rectangle." [(self lineIndexOfTop: clippingRectangle top) = 1] whileFalse: [self scrollBy: (0-1)*textStyle lineGrid]. self updateCompositionHeight. clippingRectangle bottom: compositionRectangle bottom!gridWithLead: leadInteger "Set the line grid of the receiver's style for displaying text to the height of the first font in the receiver's style + the argument, leadInteger." textStyle gridForFont: (text emphasisAt: 1) withLead: leadInteger. "assumes only one font referred to by runs" self updateCompositionHeight.! !!Paragraph methodsFor: 'converting'!asForm "Answer a new Form made up of the bits that represent the receiver's dispayable text." | aForm saveDestinationForm | aForm _ Form new extent: compositionRectangle extent. saveDestinationForm _ destinationForm. self displayOn: aForm at: 0 @ 0 clippingBox: aForm boundingBox rule: Form over mask: Form black. aForm offset: offset. destinationForm _ saveDestinationForm. ^aForm!asString "Answer the string of characters of the receiver's text." ^text string!asText "Answer the receiver's text." ^text! !!Paragraph methodsFor: 'private'!compositionRectangle: compositionRect text: aText style: aTextStyle offset: aPoint outputMedium: aSymbol fitWidth: aBoolean | paddingDelta lineIndex | compositionRectangle _ compositionRect copy. text _ aText. textStyle _ aTextStyle. firstIndent _ textStyle firstIndent. restIndent _ textStyle restIndent. rightIndent _ textStyle rightIndent. marginTabsLevel _ 0. outputMedium _ aSymbol. lines _ Array new: 32. lastLine _ 0. rule _ DefaultRule. mask _ DefaultMask. destinationForm _ Display. clippingRectangle _ destinationForm boundingBox. offset _ aPoint. aBoolean ifTrue: [ "save initial width of compositionRectangle" paddingDelta _ compositionRectangle width. compositionRectangle width: (self composeAll "returns fitted right margin" - compositionRectangle left). paddingDelta _ paddingDelta - compositionRectangle width. "Have to shrink padding widths created when compositionRectangle was large." 1 to: lastLine do: [:i | (lines at: i) paddingWidth: (lines at: i) paddingWidth - paddingDelta]] ifFalse: ["Composition rectangle sent in is the one desired no matter what the maximum right struck by the text." self composeAll].!compositionRectangleDelta "A handy number -- mostly for scrolling" ^compositionRectangle top - clippingRectangle top!copyLines: anInterval ^lines copyFrom: anInterval first to: (anInterval last min: lastLine)!displayLines: linesInterval "This is the first level workhorse in the display portion of the TextForm routines. It checks to see which lines in the interval are actually visible, has the DisplayScanner display only those, clears out the areas in which display will occur, and clears any space remaining in the visibleRectangle following the space occupied by lastLine." | lineGrid visibleRectangle topY firstLineIndex lastLineIndex lastLineIndexBottom | lineGrid _ textStyle lineGrid. "Save some time by only displaying visible lines" visibleRectangle _ (clippingRectangle intersect: compositionRectangle) intersect: destinationForm boundingBox. firstLineIndex _ self lineIndexOfTop: visibleRectangle top. firstLineIndex < linesInterval first ifTrue: [firstLineIndex _ linesInterval first]. lastLineIndex _ self lineIndexOfTop: visibleRectangle bottom - 1. lastLineIndex > linesInterval last ifTrue: [linesInterval last > lastLine ifTrue: [lastLineIndex _ lastLine] ifFalse: [lastLineIndex _ linesInterval last]]. ((Rectangle origin: visibleRectangle left @ (topY _ self topAtLineIndex: firstLineIndex) corner: visibleRectangle right @ (lastLineIndexBottom _ (self topAtLineIndex: lastLineIndex) + lineGrid)) intersects: visibleRectangle) ifFalse: ["None of lines in interval visible." ^self]. "Set boundingBox containing the lines in linesInterval to color for space surrounding the characters." destinationForm fill: ((visibleRectangle left @ topY extent: visibleRectangle width @ (lastLineIndexBottom - topY)) intersect: visibleRectangle) rule: rule mask: Form white. DisplayScanner new displayLines: (firstLineIndex to: lastLineIndex) in: self clippedBy: visibleRectangle. lastLineIndex = lastLine ifTrue: [destinationForm fill: (visibleRectangle left @ lastLineIndexBottom extent: visibleRectangle width @ (visibleRectangle bottom - lastLineIndexBottom)) rule: rule mask: Form white]!leftMarginForCompositionForLine: lineIndex "Build the left margin for composition of a line. Depends upon marginTabsLevel and the indent." | scale | scale _ 1. lineIndex = 1 ifTrue: [^(firstIndent + (textStyle leftMarginTabAt: marginTabsLevel)) * scale] ifFalse: [^(restIndent + (textStyle leftMarginTabAt: marginTabsLevel)) * scale].!leftMarginForDisplayForLine: lineIndex "Build the left margin for display of a line. Depends upon leftMarginForComposition, compositionRectangle left, the outputMedium and the alignment." | pad scale| scale _ 1. (textStyle alignment = LeftFlush or: [textStyle alignment = Justified]) ifTrue: [^((compositionRectangle left * scale) + (self leftMarginForCompositionForLine: lineIndex))]. "When called from character location code and entire string has been cut, there are no valid lines, hence following nil check." ( lineIndex <= lines size and: [(lines at: lineIndex) ~~ nil]) ifTrue: [pad _ (lines at: lineIndex) paddingWidth] ifFalse: [pad _ compositionRectangle width - firstIndent - rightIndent]. textStyle alignment = Centered ifTrue: [^((compositionRectangle left * scale) + (self leftMarginForCompositionForLine: lineIndex)) + (pad // 2)]. textStyle alignment = RightFlush ifTrue: [^((compositionRectangle left * scale) + (self leftMarginForCompositionForLine: lineIndex)) + pad]. self error: ['no such alignment']!lineAt: lineIndex "Return the textLineInterval for the specified line" ^ lines at: lineIndex!lineAt: indexInteger put: aTextLineInterval "store a line, track last, and grow lines if necessary" indexInteger > lastLine ifTrue: [lastLine _ indexInteger]. lastLine > lines size ifTrue: [lines grow]. ^lines at: indexInteger put: aTextLineInterval!lineIndexOfCharacterIndex: characterIndex "line index for a given characterIndex" 1 to: lastLine do: [:lineIndex | (lines at: lineIndex) last >= characterIndex ifTrue: [^lineIndex]]. ^lastLine!lineIndexOfTop: top "line index at a given top y" ^(top - compositionRectangle top // textStyle lineGrid + 1 max: 1) min: lastLine!lines ^lines!lines: anArray "Install a new set of lines in the paragraph, a tricky way to avoid recomposing when a press paragraph overflows a page." lines _ anArray. (lastLine _ (anArray indexOf: nil) - 1) = -1 ifTrue: [^ (lastLine _ anArray size)] ifFalse: [^ lastLine].!removeFirstChars: numberOfChars "Remove a number of characters from the beginning of the receiver, adjusting the composition rectangle so the displayed text moves as little as possible. Special kludge for TextCollectorController." "9/14/82 SBP" | delta scrollDelta | delta _ ((self lineIndexOfCharacterIndex: numberOfChars)-1)*self lineGrid. scrollDelta _ self compositionRectangleDelta negated. delta > scrollDelta ifTrue: [delta _ scrollDelta. "deleting some visible lines" self clearVisibleRectangle]. self replaceFrom: 1 to: numberOfChars with: '' asText displaying: false. compositionRectangle moveBy: 0@delta. delta = scrollDelta ifTrue: [self display]!repositionAt: aPoint clippingBox: clippingBox compositionRectangle moveTo: aPoint. clippingRectangle _ clippingBox.!rightMarginForComposition "Build the right margin for a line. Depends upon compositionRectangle width, marginTabsLevel, and right indent." | scale | scale _ 1. ^(compositionRectangle width - (textStyle rightMarginTabAt: marginTabsLevel) - rightIndent) * scale!rightMarginForDisplay "Build the right margin for a line. Depends upon compositionRectangle rightSide, marginTabsLevel, and right indent." | scale | scale _ 1. ^(compositionRectangle right - rightIndent - (textStyle rightMarginTabAt: marginTabsLevel)) * scale!textAt: lineIndex "Return the text for the specified line (subclasses may override)" ^ text!topAtLineIndex: lineIndex "top y of given line" ^compositionRectangle top + (lineIndex - 1 * textStyle lineGrid)!trimLinesTo: lastLineInteger (lastLineInteger + 1 to: lastLine) do: [:i | lines at: i put: nil]. (lastLine _ lastLineInteger) < (lines size // 2) ifTrue: [lines _ lines copyFrom: 1 to: lines size - (lines size // 2)]!updateCompositionHeight "Mainly used to insure that intersections with compositionRectangle work." compositionRectangle height: textStyle lineGrid * lastLine. (text size ~= 0 and: [(text at: text size) = CR]) ifTrue: [compositionRectangle height: compositionRectangle height + textStyle lineGrid]!visibleRectangle ^ (clippingRectangle intersect: compositionRectangle) intersect: destinationForm boundingBox! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Paragraph class instanceVariableNames: ''!!Paragraph class methodsFor: 'instance creation'!initialize "Paragraph initialize." DefaultCompositionRectangle _ 0@0 corner: 10000@10000.!new "Do not allow an uninitialized view. Create with text that has no characters." ^self withText: '' asText!withText: aText "Answer an instance of me with text set to aText and style set to the system's default text style." ^self withText: aText style: DefaultTextStyle copy!withText: aText style: aTextStyle "Answer an instance of me with text set to aText and style set to aTextStyle." ^super new compositionRectangle: DefaultCompositionRectangle text: aText style: aTextStyle offset: (0@0) outputMedium: #Display fitWidth: true!withText: aText style: aTextStyle compositionRectangle: compRect clippingRectangle: clipRect | para | para _ super new compositionRectangle: compRect text: aText style: aTextStyle offset: (0@0) outputMedium: #Display fitWidth: false. para clippingRectangle: clipRect. ^para! !!Paragraph class methodsFor: 'examples'!example "This simple example illustrates how to display a few lines of text on the screen at the current cursor point." | para point | point _ Sensor waitButton. para _ 'this is the first line of charactersand this is the second line comprising this TextForm.' asParagraph. para displayOn: Display at: point. para displayOn: Display at: point + (0 @ para height) clippingBox: Display boundingBox rule: Form over mask: Form gray "Paragraph example."! !Paragraph initialize! ScrollController subclass: #ParagraphEditor instanceVariableNames: 'paragraph startBlock stopBlock beginTypeInBlock emphasisHere initialText selectionShowing ' classVariableNames: 'CurrentSelection Keyboard TextEditorYellowButtonMenu TextEditorYellowButtonMessages UndoSelection ' poolDictionaries: 'TextConstants ' category: 'Interface-Text'!ParagraphEditor comment:'I contain the main handling of text editing. I ought to be used only on smallish paragraphs.Instance Variables paragraph<Paragraph> A pointer to the textForm being edited. The Paragraph is optimized for managing replacements in it*s stylizedString and for scrolling. startBlock stopBlock<CharacterBlock> These variables contain the string indices, characters, and bounding boxes of the starting and stopping characters in the stylizedString which will be operated upon by the next command. beginTypeInBlock<CharacterBlock> Used to manage typing and to distinguish selection arising from the last characters typed in from selection with the mouse or which is the result of some special keystroke. initialText<Text> A copy of the string held by the Paragraph at the time the text editor was instantiated. It is currently used to manage the editing of Smalltalk code, and is reinstalled in the Paragraph when a *cancel* is executed and is overwritten when an *accept* is executed." selectionState<Integer> 1 = on, 0 = off. Since selection involves raw modification of the bits in the destinationForm of the Paragraph, it must be monitored closely and with care."'!!ParagraphEditor methodsFor: 'initialize-release'!changeParagraph: aParagraph "Install aParagraph as the one to be edited by the receiver." paragraph _ aParagraph. self resetState!initialize super initialize. self initializeYellowButtonMenu!resetState "Establish the initial conditions for editing the paragraph: place caret before first character, set the emphasis to that of the first character, and save the paragraph for purposes of canceling." | insetDisplayBox | insetDisplayBox _ paragraph compositionRectangle. startBlock _ CharacterBlock stringIndex: 1 character: nil boundingRectangle: (insetDisplayBox topLeft extent: 0 @ 0). stopBlock _ startBlock copy. beginTypeInBlock _ startBlock copy. self setEmphasisHere. selectionShowing _ false. initialText _ paragraph text copy! !!ParagraphEditor methodsFor: 'basic control sequence'!controlInitialize super controlInitialize. startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: stopBlock stringIndex. self initializeSelection. beginTypeInBlock _ nil.!controlTerminate super controlTerminate. self closeTypeIn ifTrue: [startBlock _ stopBlock copy]. "so leaving and entering window won't select last type-in"! !!ParagraphEditor methodsFor: 'control defaults'!controlActivity self scrollBarContainsCursor ifTrue: [self scroll] ifFalse: [self processKeyboard. self processMouseButtons].!isControlActive ^super isControlActive & sensor blueButtonPressed not!processKeyset "clever trick to remove this method after it is called for the last time" ParagraphEditor removeSelector: #processKeyset! !!ParagraphEditor methodsFor: 'scrolling'!canScroll ^true!scroll self updateMarker. super scroll!scrollAmount ^sensor cursorPoint y - scrollBar top!scrollBy: heightToMove "Move the paragraph by the amount, heightToMove, and reset the text selection." self deselect. paragraph scrollBy: heightToMove. startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: stopBlock stringIndex. self select!scrollToTop "Scroll so that the paragraph is at the top of the view." self scrollView: (paragraph clippingRectangle top - paragraph compositionRectangle top)!scrollView: anInteger | maximumAmount minimumAmount amount | self deselect. maximumAmount _ paragraph clippingRectangle top - paragraph compositionRectangle top max: 0. minimumAmount _ paragraph clippingRectangle top + paragraph lineGrid - paragraph compositionRectangle bottom min: 0. amount _ (anInteger min: maximumAmount) max: minimumAmount. amount ~= 0 ifTrue: [self scrollBy: amount negated]. self select!viewDelta ^paragraph clippingRectangle top - paragraph compositionRectangle top - ((marker top - scrollBar inside top) asFloat / scrollBar inside height asFloat * self scrollRectangleHeight asFloat) roundTo: paragraph lineGrid! !!ParagraphEditor methodsFor: 'marker adjustment'!computeMarkerRegion paragraph compositionRectangle height = 0 ifTrue: [^0@0 extent: 10 @ scrollBar inside height] ifFalse: [^0@0 extent: 10 @ ((paragraph clippingRectangle height asFloat / self scrollRectangleHeight * scrollBar inside height) rounded min: scrollBar inside height)]!markerDelta ^marker top - scrollBar top - ((paragraph clippingRectangle top - paragraph compositionRectangle top) asFloat / (self scrollRectangleHeight max: 1) asFloat * scrollBar height asFloat) rounded!updateMarker "A variation of moveMarker--only redisplay the marker in the scrollbar if an actual change has occurred in the positioning of the paragraph." | newMarkerRegion | newMarkerRegion _ self computeMarkerRegion. newMarkerRegion extent ~= marker region extent ifTrue: [self markerRegion: newMarkerRegion. self moveMarker]! !!ParagraphEditor methodsFor: 'sensor access'!processBlueButton "The user pressed the blue button on the mouse. Determine what action to take." ^self!processKeyboard "Determine whether the user pressed the keyboard. If so, read the keys." sensor keyboardPressed ifTrue: [self readKeyboard]!processMouseButtons "Determine whether the user pressed any mouse button. For each possible button, determine what actions to take." sensor redButtonPressed ifTrue: [self processRedButton]. sensor yellowButtonPressed ifTrue: [self processYellowButton]. sensor blueButtonPressed ifTrue: [self processBlueButton]!processRedButton "The user pressed a red mouse button, meaning create a new text selection. Highlighting the selection is carried out by the paragraph itself. Double clicking causes a selection of the area between the nearest enclosing delimitors; extension is based on both ends if different." | paragraphOrigin selectionBlocks | self deselect. self closeTypeIn. paragraphOrigin _ paragraph compositionRectangle origin. selectionBlocks _ paragraph mouseSelect: startBlock to: stopBlock. selectionShowing _ true. startBlock _ selectionBlocks at: 1. stopBlock _ selectionBlocks at: 2. self updateMarker. self setEmphasisHere!processYellowButton "User pressed the yellow button on the mouse. Determine what actions to take." self yellowButtonActivity! !!ParagraphEditor methodsFor: 'accessing'!copySelection: aText CurrentSelection _ UndoSelection _ aText!text "Answer the text of the paragraph being edited." ^paragraph text! !!ParagraphEditor methodsFor: 'displaying'!display "Redisplay the paragraph." | selectionState | selectionState _ selectionShowing. self deselect. paragraph displayOn: Display. selectionState ifTrue: [self select]!displayAt: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "Redisplay the paragraph starting at aDisplayPoint, clipped by the rectangle, clipRectangle. The characters are displayed with respect to the rule, ruleInteger, and the mask, aForm." self deselect. paragraph displayOn: Display at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm. self select! !!ParagraphEditor methodsFor: 'menu messages'!accept "Save the current text of the text being edited as the current acceptable version for purposes of canceling." initialText _ paragraph text copy!again "Text subsititution. If the left shift key is down, the substitution is made throughout the entire Paragraph. Otherwise, only the next possible subsitution is made." | many | many _ sensor leftShiftDown. self deselect. self closeTypeIn. self select. many ifTrue: [[self againOnce] whileTrue] ifFalse: [self againOnce ifFalse: [self flash]]. self moveMarker!align "Align text according to the next greater alignment value--cycling among left flush, right flush, center, justified." self deselect. paragraph toggleAlignment. paragraph displayOn: Display. startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: stopBlock stringIndex. self select!cancel "Restore the text of the paragraph to be the text saved since initialization or the last accept." self controlTerminate. UndoSelection _ paragraph text. view clearInside. self changeParagraph: (paragraph text: initialText). paragraph displayOn: Display. self scrollToTop. self controlInitialize!copySelection "Copy the current selection and store it in the shared buffer." CurrentSelection _ UndoSelection _ self selection!cut "Cut out the current selection and redisplay the paragraph if necessary." self deselect. self closeTypeIn. self replaceSelectionWith: Text new. self selectAndScroll. self updateMarker. CurrentSelection _ UndoSelection copy!fit "Make the bounding rectangle of the paragraph contain all the text while not changing the width of the view of the paragraph." self deselect. paragraph clearVisibleRectangle. paragraph fit. paragraph displayOn: Display. paragraph outline. self select. self updateMarker!paste "Paste the text from the shared buffer over the current selection and redisplay if necessary." self deselect. self closeTypeIn. self replaceSelectionWith: CurrentSelection. self selectAndScroll. self updateMarker!undo "Reset the state of the paragraph prior to the previous cut or paste edit." self deselect. self closeTypeIn. self replaceSelectionWith: UndoSelection. self selectAndScroll. self updateMarker! !!ParagraphEditor methodsFor: 'editing'!backspace: characterStream "Backspace over the last character--i.e., cut the previous character." | startIndex | sensor keyboard. "flush character" characterStream isEmpty ifTrue: [startIndex _ 1 max: startBlock stringIndex - 1. startBlock _ paragraph characterBlockForIndex: startIndex. beginTypeInBlock _ paragraph characterBlockForIndex: (beginTypeInBlock stringIndex min: startIndex)] ifFalse: [characterStream skip: -1]. ^false!backWord: characterStream "Backspace over the last word--i.e., cut the last word. Initiated by ctrl w" | startIndex | sensor keyboard. " flush the ctrl-w" characterStream isEmpty ifFalse: [self replaceSelectionWith: (Text string: characterStream contents emphasis: emphasisHere). startBlock _ stopBlock copy. characterStream reset]. startIndex _ 1 max: startBlock stringIndex - 1. [startIndex > 1 and: [(paragraph text at: startIndex - 1) asCharacter tokenish]] whileTrue: [startIndex _ startIndex - 1]. startBlock _ paragraph characterBlockForIndex: startIndex. beginTypeInBlock _ paragraph characterBlockForIndex: (beginTypeInBlock stringIndex min: startIndex). ^false!changeEmphasis: characterStream "Change the emphasis of the current selection or prepare to accept characters with the change in emphasis. Emphasis change amounts to a font change." | oldCode newCode keyboard | oldCode _ paragraph text emphasisAt: startBlock stringIndex. ((newCode _ #(159 144 143 128 127 129 131 180 149 135 223 208) "CTL 1-9, 0, CTLSHIFT 1-2 -- fonts" indexOf: ((keyboard _ sensor keyboard) asciiValue)) = 0) ifTrue: [newCode _ self emphasisDefault: oldCode keyedTo: keyboard]. (((paragraph textStyle isFontUnderlined: oldCode) and: [keyboard ~= CtrlShiftMinus "--unUnderline"]) and: [keyboard ~= Ctrlx "clear emphasis"]) ifTrue: ["If font being replaced was underlined, use underlined version of new font, unless unUnderline has just been struck" newCode _ paragraph textStyle underlinedFontFor: newCode]. startBlock stringIndex = stopBlock stringIndex ifTrue: "only change emphasisHere while typing" [emphasisHere _ newCode. self select. ^true]. self replaceSelectionWith: (Text string: self selection asString emphasis: (newCode max: 1)). self closeTypeIn. self select. ^true!cut: characterStream "Cut out the current text selection." sensor keyboard. "flush character" self cut. ^true!displayDate: characterStream "Replace the current text selection with today's date--initiated by ctrl d." sensor keyboard. "flush character" characterStream nextPutAll: Date today printString. ^false!displayIfFalse: characterStream "Replace the current text selection with the text 'ifFalse:'--initiated by ctrl f." sensor keyboard. "flush character" characterStream nextPutAll: 'ifFalse:'. ^false!displayIfTrue: characterStream "Replace the current text selection with the text 'ifTrue:'--initiated by ctrl t." sensor keyboard. "flush character" characterStream nextPutAll: 'ifTrue:'. ^false!enclose: characterStream "Insert or remove bracket characters around the current selection. If null selection, then make a pair of brackets with cursor inside" | char left right startIndex stopIndex which text oldSelection | char _ Sensor keyboard asciiValue. characterStream reset. self deselect. startIndex _ startBlock stringIndex. stopIndex _ stopBlock stringIndex. which _ #(213 7 218 249 219 15) indexOf: char. left _ '([<{"''' at: which. right _ ')]>}"''' at: which. text _ paragraph text. ((startIndex > 1 and: [stopIndex <= text size]) and: [(text at: startIndex-1) = left and: [(text at: stopIndex) = right]]) ifTrue: ["already enclosed; strip off brackets" oldSelection _ self selection. self selectFrom: startIndex-1 to: stopIndex; deselect. self replaceSelectionWith: oldSelection. self select] ifFalse: ["not enclosed; enclose by matching brackets" self selectAt: startIndex; deselect. self setEmphasisHere. self replaceSelectionWith: (Text string: (String with: left) emphasis: emphasisHere). self selectAt: stopIndex+1; deselect. self setEmphasisHere. self replaceSelectionWith: (Text string: (String with: right) emphasis: emphasisHere). self selectFrom: stopIndex+1 to: stopIndex]. ^ true!leaveBrackets: characterStream "Jump typing cursor over a close-bracket character" | stopIndex nextChar | Sensor keyboard. stopBlock character notNil ifTrue: [stopIndex _ stopBlock stringIndex. nextChar _ paragraph text at: stopIndex. (')]>}"''' includes: nextChar) ifFalse: [^false]. self deselect. startBlock _ stopBlock _ paragraph characterBlockForIndex: stopIndex+1. self select] ifFalse: [self select]. ^ true!normalCharacter: characterStream "A nonspecial character is to be added to the stream of characters." characterStream nextPut: sensor keyboard. ^false!paste: characterStream "Replace the current text selection by the text in the shared buffer." sensor keyboard. "flush character" self paste. ^true!readKeyboard "Key struck on the keyboard. Find out which one and, if special, carry out the associated special action. Otherwise, add the character to the stream of characters. This also includes fast-echo: while the user is typing, it tries to keep up, even if not exactly correctly. When the user pauses, it fixes things up." | typeAhead nextCharacter line font x w delay expired charType firstWasCR | beginTypeInBlock == nil ifTrue: [UndoSelection _ self selection. beginTypeInBlock _ startBlock copy]. self deselect. "Prepare for fast-echo loop" typeAhead _ WriteStream on: (String new: 128). line _ (startBlock expandBy: 9999@0) intersect: paragraph visibleRectangle. startBlock = stopBlock ifTrue: "Only do fast type-in if null selection" [x _ startBlock left. font _ paragraph textStyle fontAt: emphasisHere. firstWasCR _ sensor keyboardPeek = Character cr. "Fast echo loop, accumulates chars in typeAhead stream" [delay _ 100. "wait for small typing pauses:" [sensor keyboardPressed | (delay=0)] whileFalse: [delay _ delay - 1]. sensor keyboardPressed and: [((nextCharacter _ sensor keyboardPeek) = Character cr) == firstWasCR]] whileTrue: [charType _ Keyboard at: nextCharacter asciiValue + 1. (self perform: charType with: typeAhead) ifTrue: [^self]. w _ font widthOf: nextCharacter. (charType = #normalCharacter:) & (x+w <= line right) ifTrue: [Display copy: ((x+w) @ line top corner: line corner) from: x @ line top in: Display rule: Form over. (font characterForm: nextCharacter) displayAt: x @ (line top + paragraph textStyle baseline - font ascent). x _ x+w]]. "end fast echo loop" ] ifFalse: "Do normal behavior if non-null selection" [nextCharacter _ sensor keyboardPeek. charType _ Keyboard at: nextCharacter asciiValue + 1. (self perform: charType with: typeAhead) ifTrue: [^self]]. "Now properly paste and display accumulated characters" self replaceSelectionWith: (Text string: typeAhead contents emphasis: emphasisHere). startBlock _ stopBlock copy. self selectAndScroll!selectCurrentTypeIn: characterStream "The user just finished typing in some text and then typed the esc key. The typed text becomes the current text selection." sensor keyboard. "flush character" characterStream isEmpty ifTrue: [self deselect] ifFalse: [self replaceSelectionWith: (Text string: characterStream contents emphasis: emphasisHere). startBlock _ stopBlock copy]. self closeTypeIn. startBlock = stopBlock ifFalse: [startBlock _ paragraph characterBlockForIndex: stopBlock stringIndex - CurrentSelection size]. self select. ^true! !!ParagraphEditor methodsFor: 'selecting'!deselect "If the text selection is visible on the screen, reverse its highlight." selectionShowing ifTrue: [self reverseSelection]!findAndSelect: aString | index | index _ paragraph text findString: aString startingAt: stopBlock stringIndex. index = 0 ifTrue: [^false]. self selectAndScrollFrom: index to: index + aString size-1. ^true!initializeSelection "Do the initial activity when starting up the receiver. For example, in the ParagraphEditor highlight the current selection." self select!recomputeSelection "eg after changing the composition rectangle of the paragraph" self deselect. startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: stopBlock stringIndex. selectionShowing_ false!reverseSelection "Reverse the valence of the current selection highlighting." selectionShowing _ selectionShowing not. startBlock = stopBlock ifTrue: [paragraph displayCaretAt: startBlock topLeft + (0 @ paragraph textStyle baseline)] ifFalse: [paragraph reverseFrom: startBlock to: stopBlock]!select "If the text selection is visible on the screen, highlight it." selectionShowing ifFalse: [self reverseSelection]!selectAndScroll "Scroll until the selection is in the view and then highlight it." | lineHeight deltaY clippingRectangle | lineHeight _ paragraph textStyle lineGrid. clippingRectangle _ paragraph clippingRectangle. deltaY _ stopBlock top - clippingRectangle top. deltaY >= 0 ifTrue: [deltaY _ stopBlock bottom - clippingRectangle bottom max: 0]. "check if stopIndex below bottom of clippingRectangle" deltaY ~= 0 ifTrue: [self scrollBy: (deltaY abs + lineHeight - 1 truncateTo: lineHeight) * deltaY sign]. self select!selectAndScrollFrom: start to: stop self deselect. startBlock _ paragraph characterBlockForIndex: start. stopBlock _ paragraph characterBlockForIndex: stop + 1. self selectAndScroll!selectAt: characterIndex "Place the character before the character at position characterIndex. Make certain the selection is in the view." self deselect. startBlock _ paragraph characterBlockForIndex: characterIndex. stopBlock _ startBlock copy. self selectAndScroll!selectFrom: start to: stop "The text selection starts at the character at position start and ends at the character at position stop." self deselect. startBlock _ paragraph characterBlockForIndex: start. stopBlock _ paragraph characterBlockForIndex: stop+1. self selectAndScroll!selection "Answer the text in the paragraph that is currently selected." ^paragraph text copyFrom: startBlock stringIndex to: stopBlock stringIndex - 1!selectionAsStream "Answer a ReadStream on the text in the paragraph that is currently selected." ^ReadStream on: paragraph text asString from: startBlock stringIndex to: stopBlock stringIndex - 1! !!ParagraphEditor methodsFor: 'indicating'!flash "Causes the view of he paragraph to complement twice in succession." paragraph flash! !!ParagraphEditor methodsFor: 'copying'!copy | p c | "Return a copy of me, which goes one level deeper into my paragraph" p _ paragraph. paragraph _ paragraph copy. c _ super copy. paragraph _ p. ^ c! !!ParagraphEditor methodsFor: 'private'!againOnce | nextStartIndex | nextStartIndex _ paragraph text findString: UndoSelection startingAt: stopBlock stringIndex. nextStartIndex = 0 ifTrue: [^false]. self deselect. startBlock _ paragraph characterBlockForIndex: nextStartIndex. stopBlock _ paragraph characterBlockForIndex: nextStartIndex + UndoSelection size. CurrentSelection = UndoSelection ifFalse: [self replaceSelectionWith: CurrentSelection]. self selectAndScroll. ^true!closeTypeIn beginTypeInBlock ~~ nil ifTrue: [beginTypeInBlock < startBlock ifTrue: [CurrentSelection _ paragraph text copyFrom: beginTypeInBlock stringIndex to: startBlock stringIndex - 1. startBlock _ beginTypeInBlock copy]. beginTypeInBlock _ nil. ^true] ifFalse: [^false]!emphasisDefault: oldEmphasisCode keyedTo: keyboardCharacter "Some default ways to get common forms of emphasis -- returns a new emphasis code. Subroutine for changeEmphasis. If anyone else uses, please note here." keyboardCharacter = CtrlMinus "underline" ifTrue: [^ paragraph textStyle underlinedFontFor: oldEmphasisCode]. keyboardCharacter = CtrlShiftMinus "unUnderline" ifTrue: [^ paragraph textStyle unUnderlinedFontFor: oldEmphasisCode]. keyboardCharacter = Ctrlb "Bold" ifTrue: [^ paragraph textStyle boldFontFor: oldEmphasisCode]. keyboardCharacter = CtrlB "unBold" ifTrue: [^ paragraph textStyle basalFontFor: oldEmphasisCode]. keyboardCharacter = Ctrli "Italic" ifTrue: [^ paragraph textStyle italicFontFor: oldEmphasisCode]. keyboardCharacter = CtrlI "unItalic" ifTrue: [^ paragraph textStyle basalFontFor: oldEmphasisCode]. keyboardCharacter = Ctrlx "clear emphasis, go to basal font" ifTrue: [^ paragraph textStyle basalFontFor: oldEmphasisCode].!initializeYellowButtonMenu self yellowButtonMenu: TextEditorYellowButtonMenu yellowButtonMessages: TextEditorYellowButtonMessages!replaceSelectionWith: aText beginTypeInBlock == nil ifTrue: [UndoSelection _ self selection]. paragraph replaceFrom: startBlock stringIndex to: stopBlock stringIndex - 1 with: aText displaying: true. startBlock _ paragraph characterBlockForIndex: startBlock stringIndex. stopBlock _ paragraph characterBlockForIndex: startBlock stringIndex + aText size!scrollRectangleHeight ^paragraph compositionRectangle height + paragraph clippingRectangle height - paragraph lineGrid!setEmphasisHere emphasisHere _ paragraph text emphasisAt: startBlock stringIndex! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ParagraphEditor class instanceVariableNames: ''!!ParagraphEditor class methodsFor: 'class initialization'!initialize "Initialize the yellow button menu information, the keyboard map for special control characters, and the shared buffers for copying text across views and managing undo." CurrentSelection _ UndoSelection _ Text new. TextEditorYellowButtonMenu _ PopUpMenu labels: 'againundocopycutpasteacceptcancelalignfit' lines: #(2 5 7). TextEditorYellowButtonMessages _ #(again undo copySelection cut paste accept cancel align fit ). Keyboard _ Array new: 256. Keyboard atAllPut: #normalCharacter:. Keyboard at: Cut asciiValue + 1 put: #cut:. Keyboard at: Paste asciiValue + 1 put: #paste:. Keyboard at: ESC asciiValue + 1 put: #selectCurrentTypeIn:. Keyboard at: BS asciiValue + 1 put: #backspace:. Keyboard at: Ctrlw asciiValue + 1 put: #backWord:. Keyboard at: Ctrlt asciiValue + 1 put: #displayIfTrue:. Keyboard at: Ctrlf asciiValue + 1 put: #displayIfFalse:. Keyboard at: 132 + 1 put: #displayDate:. "ctrl-d" #(159 144 143 128 127 129 131 180 149 135 223 208 "fonts" 137 201 "underline, unUnderline" 166 230 "bold, unbold" 150 214 "italic, unitalic" 151 "clear emphasis") do: ["CTL-1 thru 9, and 0, CTLSHIFT 1-2 CTL-, CTLSHIFT-" :i | Keyboard at: i + 1 put: #changeEmphasis:]. #(213 7 218 249 219 15) do: [:i | "ctl open brackets" Keyboard at: i + 1 put: #enclose:]. Keyboard at: BS2 asciiValue + 1 put: #leaveBrackets:. "ParagraphEditor initialize."! !!ParagraphEditor class methodsFor: 'instance creation'!new "Answer a new instance of me with a null Paragraph to be edited." ^ self newParagraph: '' asParagraph!newParagraph: aParagraph "Answer an instance of me with aParagraph as the text to be edited. " | aParagraphEditor | aParagraphEditor _ super new. aParagraphEditor changeParagraph: aParagraph. ^aParagraphEditor! !ParagraphEditor initialize! Object subclass: #ParseNode instanceVariableNames: 'comment ' classVariableNames: 'Bfp CodeBases CodeLimits Dup EndMethod EndRemote Jmp JmpLimit JmpLong LdFalse LdInstLong LdInstType LdLitIndType LdLitType LdMinus1 LdNil LdSelf LdSuper LdTempType LdThisContext LdTrue NodeFalse NodeNil NodeSelf NodeSuper NodeThisContext NodeTrue Pop Send SendLimit SendLong SendPlus SendType ShortStoP StdLiterals StdSelectors StdVariables Store StorePop ' poolDictionaries: '' category: 'System-Compiler'!ParseNode comment: 'This superclass of most compiler/decompiler classes declares common class variables, default messages, and the code emitters for jumps. Some of the class variables are initialized here; the rest are initialized in class VariableNode, which is the last alphabetically.'!!ParseNode methodsFor: 'accessing'!comment ^comment!comment: newComment "self halt." comment _ newComment! !!ParseNode methodsFor: 'testing'!canBeSpecialArgument "can I be an argument of (e.g.) ifTrue:?" ^false!canCascade ^false!isArg ^false!isReturningIf ^false!isReturnSelf ^false!isVariableReference ^false! !!ParseNode methodsFor: 'code generation'!emitBranch: dist pop: stack on: strm stack pop: 1. dist = 0 ifTrue: [strm nextPut: Pop] ifFalse: [self emitShortOrLong: dist code: Bfp on: strm]!emitForEffect: stack on: strm self emitForValue: stack on: strm. strm nextPut: Pop. stack pop: 1!emitForReturn: stack on: strm self emitForValue: stack on: strm. strm nextPut: EndMethod!emitJump: dist on: strm dist = 0 ifFalse: [self emitShortOrLong: dist code: Jmp on: strm]!emitLong: dist code: longCode on: aStream "force a two-byte jump" | code distance | code _ longCode. distance _ dist. distance < 0 ifTrue: [distance _ distance + 1024] ifFalse: [distance > 1023 ifTrue: [distance _ -1] ifFalse: [code _ code + 4]]. distance < 0 ifTrue: [self error: 'A block compiles more than 1K bytes of code'] ifFalse: [aStream nextPut: distance // 256 + code. aStream nextPut: distance \\ 256]!emitLongJump: dist on: strm "force a two byte jump" self emitLong: dist code: JmpLong on: strm!emitShortOrLong: dist code: shortCode on: strm (1 <= dist and: [dist <= JmpLimit]) ifTrue: [strm nextPut: shortCode + dist - 1] ifFalse: [self emitLong: dist code: shortCode + 16 on: strm]!emitTrueBranch: dist pop: stack on: strm stack pop: 1. "offset for dist>0 adds another 4, so will begin at JmpLong+8" self emitLong: dist code: JmpLong+4 on: strm!sizeBranch: dist dist = 0 ifTrue: [^1]. ^self sizeShortOrLong: dist!sizeForEffect: encoder ^(self sizeForValue: encoder) + 1!sizeForReturn: encoder ^(self sizeForValue: encoder) + 1!sizeJump: dist dist = 0 ifTrue: [^0]. ^self sizeShortOrLong: dist!sizeShortOrLong: dist (1 <= dist and: [dist <= JmpLimit]) ifTrue: [^1]. ^2! !!ParseNode methodsFor: 'encoding'!encodeSelector: selector ^nil! !!ParseNode methodsFor: 'printing'!printCommentOn: aStream indent: indent | thisComment | comment == nil ifTrue: [^self]. 1 to: comment size do: [:index | index > 1 ifTrue: [aStream crtab: indent]. aStream nextPut: $". thisComment _ comment at: index. self printSingleComment: thisComment on: aStream indent: indent. aStream nextPut: $"]. comment _ nil!printOn: aStream aStream nextPutAll: '{'. self printOn: aStream indent: 0. aStream nextPutAll: '}'!printOn: aStream indent: anInteger "If control gets here, avoid recursion loop" super printOn: aStream!printOn: aStream indent: level precedence: p self printOn: aStream indent: level! !!ParseNode methodsFor: 'converting'!asReturnNode ^ReturnNode new expr: self! !!ParseNode methodsFor: 'private'!nextWordFrom: aStream setCharacter: aBlock | outStream char | outStream _ WriteStream on: (String new: 16). [aStream atEnd or: [char _ aStream next. char = Character cr or: [char = Character space]]] whileFalse: [outStream nextPut: char]. aBlock value: char. ^outStream contents!printSingleComment: aString on: aStream indent: indent "Print the comment string, assuming it has been indented indent tabs. Break the string at word breaks, given the widths in the default font, at 450 points." | readStream word position lineBreak lastChar font wordWidth tabWidth spaceWidth | readStream _ ReadStream on: aString. font _ TextStyle default defaultFont. tabWidth _ TextConstants at: #DefaultTab. spaceWidth _ font widthOf: Character space. position _ indent * tabWidth. lineBreak _ 450. [readStream atEnd] whileFalse: [word _ self nextWordFrom: readStream setCharacter: [:lastChar | lastChar]. wordWidth _ 0. word do: [:char | wordWidth _ wordWidth + (font widthOf: char)]. position _ position + wordWidth. position > lineBreak ifTrue: [aStream crtab: indent. position _ indent * tabWidth + wordWidth + spaceWidth. lastChar = Character cr ifTrue: [[readStream peekFor: Character tab] whileTrue]. aStream nextPutAll: word; space] ifFalse: [aStream nextPutAll: word. readStream atEnd ifFalse: [position _ position + spaceWidth. aStream space]. lastChar = Character cr ifTrue: [aStream crtab: indent. position _ indent * tabWidth. [readStream peekFor: Character tab] whileTrue]]]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ParseNode class instanceVariableNames: ''!!ParseNode class methodsFor: 'class initialization'!initialize "ParseNode initialize. VariableNode initialize." LdInstType _ 1. LdTempType _ 2. LdLitType _ 3. LdLitIndType _ 4. SendType _ 5. CodeBases _ #(0 16 32 64 208 ). CodeLimits _ #(16 16 32 32 16 ). LdSelf _ 112. LdTrue _ 113. LdFalse _ 114. LdNil _ 115. LdMinus1 _ 116. LdInstLong _ 128. Store _ 129. StorePop _ 130. ShortStoP _ 96. SendLong _ 131. LdSuper _ 133. Pop _ 135. Dup _ 136. LdThisContext _ 137. EndMethod _ 124. EndRemote _ 125. Jmp _ 144. Bfp _ 152. JmpLimit _ 8. JmpLong _ 160. SendPlus _ 176. Send _ 208. SendLimit _ 16! !ParseNode initialize! Scanner subclass: #Parser instanceVariableNames: 'here hereType hereMark prevToken prevMark encoder requestor parseNode failBlock lastTempMark correctionDelta ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!Parser comment:'I parse Smalltalk syntax and create a parse tree. I look one token ahead.Instance Variables: here <Object> the current token hereType <Symbol> the "type" of the current token (see initialize) hereMark <Integer> position in source stream (mark) where this token began prevToken <Integer> size in chars of the previous token parsed prevMark <Integer> mark of previous token encoder <Encoder> which uses tables to decode tokens requestor object from which parsing was invoked. If not nil, this object will be sent -notify: prior to evaluating the failBlock parseNode <ParseNode> result of current (recursive descent) parse failBlock <BlockContext> to be evaluated in case of parse errors lastTempMark <Integer> mark of last temp; points to vert bar, or last char of pattern if no temps declared correctionDelta <Integer> offset of corrected code relative to source stream owing to interactive corrections so far'!!Parser methodsFor: 'public access'!parse: sourceStream class: class noPattern: noPattern context: ctxt notifying: req ifFail: aBlock "Answer with a parse tree. noPattern is true for doIts (Compiler evaluate)" | meth | self init: sourceStream notifying: req failBlock: [^aBlock value]. encoder _ Encoder new init: class context: ctxt notifying: self. failBlock_ aBlock. meth _ self method: noPattern context: ctxt. encoder _ failBlock _ requestor _ parseNode _ nil. "break cycles & mitigate refct overflow" ^meth!parseArgsAndTemps: aString notifying: req "(for debugger) parse the string and answer with a two-element Array containing Arrays of Strings (the arg and temp names)" aString == nil ifTrue: [^#()]. ^self initPattern: aString notifying: req return: [:pattern | (pattern at: 2) , self temporaries]!parseMethodComment: aString setPattern: aBlock "Answer with the method comment for this string" self initPattern: aString notifying: nil return: aBlock. currentComment == nil ifTrue: [^OrderedCollection new] ifFalse: [^currentComment]!parseSelector: aString "Answer with the selector for this method string" ^self initPattern: aString notifying: nil return: [:pattern | pattern at: 1]! !!Parser methodsFor: 'expression types'!argumentName hereType == #word ifFalse: [^self expected: 'Argument name']. ^self advance!assignment "variable '_' expression => AssignmentNode" | varName var | varName _ self advance. (encoder cantStoreInto: varName) ifTrue: [^self notify: 'Cannot store into']. var _ encoder encodeVariable: varName. self advance. self expression ifFalse: [^self expected: 'Expression']. var isArg ifTrue: [^self notify: 'Cannot store into argument']. parseNode _ AssignmentNode new variable: var value: parseNode from: encoder!blockExpression " [ {:var} ( | statements) ] => BlockNode" | argNodes | argNodes _ OrderedCollection new. [self match: #colon "gather any arguments"] whileTrue: [argNodes addLast: (encoder autoBind: self argumentName)]. (argNodes size > 0 & (hereType ~~ #rightBracket) and: [(self match: #verticalBar) not]) ifTrue: [^self expected: 'Vertical bar']. self statements: argNodes innerBlock: true. (self match: #rightBracket) ifFalse: [^self expected: 'Period or right bracket']!cascade " {; message} => CascadeNode" | rcvr msgs | parseNode canCascade ifFalse: [^self expected: 'Cascading not']. rcvr _ parseNode cascadeReceiver. msgs _ OrderedCollection with: parseNode. [self match: #semicolon] whileTrue: [parseNode _ rcvr. (self messagePart: 3 repeat: false) ifFalse: [^self expected: 'Cascade']. parseNode canCascade ifFalse: [^self expected: '<- No special messages']. parseNode cascadeReceiver. msgs addLast: parseNode]. parseNode _ CascadeNode new receiver: rcvr messages: msgs!expression (hereType == #word and: [tokenType == #leftArrow]) ifTrue: [self assignment. ^true]. self primaryExpression ifFalse: [^false]. (self messagePart: 3 repeat: true) ifTrue: [hereType == #semicolon ifTrue: [self cascade]]. ^true!messagePart: level repeat: repeat | start receiver selector args precedence | [receiver _ parseNode. (hereType == #keyword and: [level >= 3]) ifTrue: [start _ self startOfNextToken. selector _ WriteStream on: (String new: 32). args _ OrderedCollection new. [hereType == #keyword] whileTrue: [selector nextPutAll: self advance. self primaryExpression ifFalse: [^self expected: 'Argument']. self messagePart: 2 repeat: true. args addLast: parseNode]. selector _ self makeNewSymbol: selector contents startingAt: start. precedence _ 3] ifFalse: [((hereType == #binary or: [hereType == #verticalBar]) and: [level >= 2]) ifTrue: [start _ self startOfNextToken. selector _ self advance asSymbol. self primaryExpression ifFalse: [^self expected: 'Argument']. self messagePart: 1 repeat: true. args _ Array with: parseNode. precedence _ 2] ifFalse: [hereType == #word ifTrue: [start _ self startOfNextToken. selector _ self makeNewSymbol: self advance startingAt: start. args _ #(). precedence _ 1] ifFalse: [^args notNil]]]. parseNode _ MessageNode new receiver: receiver selector: selector arguments: args precedence: precedence from: encoder sourceRange: (start to: self endOfLastToken). repeat] whileTrue: []. ^true!method: doit context: ctxt "pattern [ | temporaries ] block => MethodNode" | sap blk prim temps messageComment methodNode | sap _ self pattern: doit inContext: ctxt. "sap={selector, arguments, precedence}" (sap at: 2) do: [:argNode | argNode isArg: true]. temps _ self temporaries. messageComment _ currentComment. currentComment _ nil. prim _ doit ifTrue: [0] ifFalse: [self primitive]. self statements: #() innerBlock: doit. blk _ parseNode. doit ifTrue: [blk returnLast] ifFalse: [blk returnSelfIfNoOther]. hereType == #doIt ifFalse: [^self expected: 'Nothing more']. methodNode _ MethodNode new comment: messageComment. ^methodNode selector: (sap at: 1) arguments: (sap at: 2) precedence: (sap at: 3) temporaries: temps block: blk encoder: encoder primitive: prim!pattern: fromDoit inContext: ctxt "unarySelector | binarySelector arg | keyword arg {keyword arg} => {selector, arguments, precedence}" | args selector | fromDoit ifTrue: [ctxt == nil ifTrue: [^Array with: #DoIt with: #() with: 1] ifFalse: [^Array with: #DoItIn: with: (Array with: (encoder encodeVariable: 'homeContext')) with: 3]]. hereType == #word ifTrue: [^Array with: self advance asSymbol with: #() with: 1]. (hereType == #binary or: [hereType == #verticalBar]) ifTrue: [selector _ self advance asSymbol. args _ Array with: (encoder bindTemp: self argumentName). ^Array with: selector with: args with: 2]. hereType == #keyword ifTrue: [selector _ WriteStream on: (String new: 32). args _ OrderedCollection new. [hereType == #keyword] whileTrue: [selector nextPutAll: self advance. args addLast: (encoder bindTemp: self argumentName)]. ^Array with: selector contents asSymbol with: args with: 3]. ^self expected: 'Message pattern'!primaryExpression hereType == #word ifTrue: [parseNode _ encoder encodeVariable: self advance. ^true]. hereType == #leftBracket ifTrue: [self advance. self blockExpression. ^true]. hereType == #leftParenthesis ifTrue: [self advance. self expression ifFalse: [^self expected: 'expression']. (self match: #rightParenthesis) ifFalse: [^self expected: 'right parenthesis']. ^true]. (hereType == #string or: [hereType == #number or: [hereType == #literal]]) ifTrue: [parseNode _ encoder encodeLiteral: self advance. ^true]. (here == #- and: [tokenType == #number]) ifTrue: [self advance. parseNode _ encoder encodeLiteral: self advance negated. ^true]. ^false!primitive | n | (self matchToken: #<) ifFalse: [^0]. (self matchToken: 'primitive:') ifFalse: [^self expected: 'primitive:']. n _ here. ((self match: #number) and: [n isKindOf: Integer]) ifFalse: [^self expected: 'Integer']. (self matchToken: #>) ifFalse: [^self expected: '>']. ^n!statements: argNodes innerBlock: inner | stmts returns start more blockComment | stmts _ OrderedCollection new. "give initial comment to block, since others trail statements" blockComment _ currentComment. currentComment _ nil. returns _ false. more _ hereType ~~ #rightBracket. [more] whileTrue: [start _ self startOfNextToken. (returns _ self match: #upArrow) ifTrue: [self expression ifFalse: [^self expected: 'Expression to return']. self addComment. stmts addLast: (ReturnNode new expr: parseNode encoder: encoder sourceRange: (start to: self endOfLastToken))] ifFalse: [self expression ifTrue: [self addComment. stmts addLast: parseNode] ifFalse: [self addComment. stmts size = 0 ifTrue: [stmts addLast: (encoder encodeVariable: (inner ifTrue: ['nil'] ifFalse: ['self']))]]]. returns ifTrue: [(hereType == #rightBracket or: [hereType == #doIt]) ifFalse: [^self expected: 'End of block']]. more _ returns not and: [self match: #period]]. parseNode _ BlockNode new arguments: argNodes statements: stmts returns: returns from: encoder sourceEnd: self endOfLastToken+1. parseNode comment: blockComment. ^true!temporaries "[ '|' (variable) ] (variable, ..., variable)* " | vars | (self match: #verticalBar) ifFalse: [lastTempMark _ self bareEndOfLastToken. ^#()]. "no temps" (self match: #verticalBar) ifTrue: [lastTempMark _ self endOfLastToken. ^#()]. "empty temps" vars _ OrderedCollection new. [hereType == #word] whileTrue: [vars addLast: (encoder bindTemp: self advance)]. (self match: #verticalBar) ifTrue: [lastTempMark _ self endOfLastToken. ^vars]. ^self expected: 'Vertical bar'! !!Parser methodsFor: 'comparing'!match: type "Answer with true if next tokens type matches" hereType == type ifTrue: [self advance. ^true]. ^false!matchToken: thing "matches the token, not its type" here = thing ifTrue: [self advance. ^true]. ^false! !!Parser methodsFor: 'scanning'!advance | this | prevMark _ hereMark. prevToken _ "Now means prev size" (hereType == #number) | (hereType == #string) ifTrue: [mark - prevMark] ifFalse: [here size]. this _ here. here _ token. hereType _ tokenType. hereMark _ mark. self scanToken. ^this!bareEndOfLastToken ^ prevMark + prevToken - 1 + correctionDelta!endOfLastToken hereType == #doIt ifTrue: [^ prevMark + prevToken + 1 + correctionDelta]. tokenType == #doIt ifTrue: [^ prevMark + prevToken + correctionDelta]. ^ prevMark + prevToken - 1 + correctionDelta!startOfNextToken "return starting position in source of next token" hereType == #doIt ifTrue: [^source position + 1 + correctionDelta]. ^hereMark + correctionDelta! !!Parser methodsFor: 'temporaries'!bindTemp: name ^name! !!Parser methodsFor: 'error handling'!abort | exitBlock | encoder == nil ifFalse: [encoder release. encoder _ nil]. "break cycle" exitBlock _ failBlock. failBlock _ nil. ^exitBlock value!editor ^ requestor editor!expected: aString "Notify a problem at token 'here'" tokenType == #doIt ifTrue: [hereMark _ hereMark + 1]. hereType == #doIt ifTrue: [hereMark _ hereMark + 1]. ^ self notify: aString , ' expected' at: hereMark!notify: aString "Notify problem at token before 'here'" ^self notify: aString at: prevMark!notify: string at: location requestor == nil ifFalse: [requestor notify: string , ' ->' at: location + correctionDelta]. self abort!offEnd: aString " notify a problem beyond 'here' (in lookAhead token). Don't be offEnded!!" ^ self notify: aString at: mark! !!Parser methodsFor: 'code view interaction'!pasteTemp: name | editor | editor _ self editor. (lastTempMark > 0 and: [(editor text at: lastTempMark) = $|]) ifTrue: "Paste in before vertical bar" [editor selectAt: lastTempMark. self replaceEditSelectionWith: name , ' '. lastTempMark _ lastTempMark + name size + 1] ifFalse: "No temp declarations yet; have to insert whole line" [editor selectAt: lastTempMark+1. self replaceEditSelectionWith: (String with: Character cr) , ' | ' , name , ' | '. lastTempMark _ lastTempMark + name size + 6]!replaceEditSelectionWith: aString | editor | editor _ self editor. correctionDelta _ correctionDelta + aString size - editor selection size. editor deselect; replaceSelectionWith: aString asText!selectVariable: name self editor selectFrom: self bareEndOfLastToken - name size + 1 to: self bareEndOfLastToken! !!Parser methodsFor: 'private'!addComment parseNode ~~ nil ifTrue: [parseNode comment: currentComment. currentComment _ nil]!init: sourceStream notifying: req failBlock: aBlock requestor _ req. failBlock _ aBlock. correctionDelta _ 0. super scan: sourceStream. prevMark _ hereMark _ mark. self advance!initPattern: aString notifying: req return: aBlock | result | self init: (ReadStream on: aString asString) notifying: req failBlock: [^nil]. encoder _ self. result _ aBlock value: (self pattern: false inContext: nil). encoder _ failBlock _ nil. "break cycles" ^result!makeNewSymbol: aString startingAt: start | editor index menu sym oldText newText oldStream oldKey | Symbol hasInterned: aString ifTrue: [:symbol | ^ symbol]. (editor _ self editor) isNil ifTrue: [^ aString asSymbol]. editor selectFrom: start to: self endOfLastToken. Cursor normal show. index _ (menu _ ActionMenu labels: 'proceed as is\correct it\abort' withCRs selectors: #(proceed correct abort)) startUp: #anyButton withHeading: ' ' , (aString contractTo: 20) , ' is a new message '. index = 0 ifTrue: [^ self notify: '']. (menu selectorAt: index) == #proceed ifTrue: [^ aString asSymbol]. (menu selectorAt: index) == #correct ifTrue: [sym _ Symbol correctMessage: aString. sym == false ifTrue: [self notify: 'Couldn''t correct'. self abort]. sym == nil ifTrue: [self abort]. oldText _ editor selection. sym isKeyword ifTrue: [newText _ oldText. oldStream _ ReadStream on: aString. sym keywords do: [:newKey | oldKey _ (oldStream upTo: $:) , ':'. oldKey = newKey ifFalse: [newText _ newText copyReplaceAll: oldKey asText with: newKey asText]]] ifFalse: [newText _ oldText copyReplaceAll: aString asText with: sym asText]. self replaceEditSelectionWith: newText. ^ sym]. self abort! ! Object subclass: #ParseStack instanceVariableNames: 'position length ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!ParseStack comment:'I keep track of the current and high position of the stack that will be needed by code being compiled. I am only used during the code generation pass of the compiler (MethodNode generate:)'!!ParseStack methodsFor: 'initialize-release'!init length _ position _ 0! !!ParseStack methodsFor: 'accessing'!max: otherSize "Set my max length (size) to be the max of mine and otherSize" length _ length max: otherSize!pop: n (position _ position - n) < 0 ifTrue: [self error: 'Parse stack underflow']!push: n (position _ position + n) > length ifTrue: [length _ position]!size ^length! !!ParseStack methodsFor: 'results'!position ^position! ! DisplayObject subclass: #Path instanceVariableNames: 'form collectionOfPoints ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Display Objects'!Path comment: 'This is the basic superclass of the Graphic Spatial Primitives. Spatial Primitives are used to generate "trajactories" or paths like lines and circles. Theinstance variable form is the "brush" used for displaying the Path: the image is accomplished by displaying the form at each point in the Path.'!!Path methodsFor: 'accessing'!at: index "Answer the point on the receiver's path at position index." ^collectionOfPoints at: index!at: index put: aPoint "Store the argument, aPoint, as the point on the receiver's path at position index." ^collectionOfPoints at: index put: aPoint!first "Answer the first point on the receiver's path." ^collectionOfPoints first!firstPoint "Answer the first point on the receiver's path." ^collectionOfPoints first!firstPoint: aPoint "Answer the argument aPoint. Replace the first element of the receiver with the new value aPoint." collectionOfPoints at: 1 put: aPoint. ^aPoint!form "Answer the receiver's form. If form is nil then a 1 x 1 black form (a black dot) is answered." | aForm | form == nil ifTrue: [aForm _ Form new extent: 1 @ 1. aForm black. ^aForm] ifFalse: [^form]!form: aForm "Make the argument, aForm, the receiver's form." form _ aForm!last "Answer the last point on the receiver's path." ^collectionOfPoints last!offset "There are basically two kinds of display objects in the system: those that, when asked to transform themselves, create a new object; and those that side effect themselves by maintaining a record of the transformation request (typically an offset). Path, like Rectangle and Point, is a display object of the first kind." self shouldNotImplement!secondPoint "Answer the second element of the receiver." ^collectionOfPoints at: 2!secondPoint: aPoint "Answer the argument aPoint. Replace the second element of the receiver with the new value aPoint." collectionOfPoints at: 2 put: aPoint. ^aPoint!size "Answer the length of the receiver." ^collectionOfPoints size!thirdPoint "Answer the third element of the receiver." ^collectionOfPoints at: 3!thirdPoint: aPoint "Answer the argument aPoint. Replace the third element of the receiver with the new value aPoint." collectionOfPoints at: 3 put: aPoint. ^aPoint! !!Path methodsFor: 'testing'!isEmpty ^collectionOfPoints isEmpty! !!Path methodsFor: 'displaying'!displayOn: aDisplayMedium at: aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm "Display this Path--offset by aPoint, clipped by clipRect and the form associated with this Path will be displayedr according to one of the sixteen functions of two logical variables (rule). Also the source form will be first anded with aForm as a mask. Does not effect the state of the Path" collectionOfPoints do: [:element | self form displayOn: aDisplayMedium at: element + aDisplayPoint clippingBox: clipRectangle rule: ruleInteger mask: aForm]!displayOn: aDisplayMedium transformation: displayTransformation clippingBox: clipRectangle rule: ruleInteger mask: aForm "Displays this path, translated and scaled by aTransformation." "get the scaled and translated Path." | newPath transformedPath | transformedPath _ displayTransformation applyTo: self. newPath _ Path new. transformedPath do: [:point | newPath add: point]. newPath form: self form. newPath displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRectangle rule: ruleInteger mask: aForm! !!Path methodsFor: 'display box access'!computeBoundingBox | box | box _ Rectangle origin: (self at: 1) extent: 0 @ 0. collectionOfPoints do: [:aPoint | box _ box merge: (Rectangle origin: aPoint extent: 0 @ 0)]. ^box! !!Path methodsFor: 'transforming'!scaleBy: aPoint "Answers with a new Path scaled by aPoint. Does not effect the current data in this Path." | newPath | newPath _ Path new: self size. newPath form: self form. collectionOfPoints do: [:element | newPath add: (aPoint x * element x) truncated @ (aPoint y * element y) truncated]. ^newPath!translateBy: aPoint "Answers with a new instance of Path whose elements are translated by aPoint. Does not effect the elements of this Path." | newPath | newPath _ Path new: self size. newPath form: self form. collectionOfPoints do: [:element | newPath add: (element x + aPoint x) truncated @ (element y + aPoint y) truncated]. ^newPath! !!Path methodsFor: 'adding'!add: aPoint "Include aPoint as one of the receiver's elements." collectionOfPoints add: aPoint! !!Path methodsFor: 'removing'!removeAllSuchThat: aBlock "Evaluate aBlock for each element of the receiver. Remove each element for which aBlock evaluates to true." | newCollection | newCollection _ collectionOfPoints removeAllSuchThat: aBlock. newCollection form: self form. ^newCollection! !!Path methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect the resulting values into a collection that is like the receiver. Answer the new collection." | newCollection | newCollection _ collectionOfPoints collect: aBlock. newCollection form: self form. ^newCollection!select: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect into a new collection like the receiver, only those elements for which aBlock evaluates to true. Answer the new collection." | newCollection | newCollection _ collectionOfPoints select: aBlock. newCollection form: self form. ^newCollection! !!Path methodsFor: 'private'!initializeCollectionOfPoints collectionOfPoints _ OrderedCollection new!initializeCollectionOfPoints: anInteger collectionOfPoints _ OrderedCollection new: anInteger! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Path class instanceVariableNames: ''!!Path class methodsFor: 'instance creation'!new ^self basicNew initializeCollectionOfPoints!new: anInteger ^self basicNew initializeCollectionOfPoints: anInteger! !!Path class methodsFor: 'examples'!example "Creates a Path from mousePoints and displays it several ways on the display screen. Messes up the display. for learning about class Path. just select the code below and execute it to create a path and see it redisplayed in another place on the screen. Each path displays using a different form. A path is indicated by pressing the red mouse button in sequence; press any other mouse button to terminate." | aPath aForm p1 f1 flag | aForm _ Form new extent: 2 @ 40. "creates a form one inch long" aForm black. "turns it black" aPath _ Path new. aPath form: aForm. "use the long black form for display" flag _ true. [flag] whileTrue: [Sensor waitButton. Sensor redButtonPressed ifTrue: [aPath add: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: aPath last] ifFalse: [flag _ false]]. Display white. aPath displayOn: Display. "the original path" p1 _ aPath translateBy: 0 @ 300. f1 _ Form new extent: 40 @ 40. f1 gray. p1 form: f1. p1 displayOn: Display. "the translated path" Sensor waitNoButton "Path example."! ! BitBlt subclass: #Pen instanceVariableNames: 'frame location direction penDown ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Primitives'!Pen comment: 'Pens can scribble on the screen, drawing and printing at any angle.'!!Pen methodsFor: 'initialize-release'!defaultNib: widthInteger "Nib is the tip of a pen. This is an easy way to set up a default pen." self sourceForm: (Form dotOfSize: widthInteger)! !!Pen methodsFor: 'accessing'!direction "Answer the receiver's current direction. 0 is towards the top of the screen." ^direction!frame "Answer with the rectangle in which the receiver can draw." ^frame!frame: aRectangle "Set the rectangle in which the receiver can draw." frame _ aRectangle. self clipRect: aRectangle!location "Answer where the receiver is currently located." ^location!sourceForm: aForm sourceForm _ aForm. width _ aForm width. height _ aForm height.!width: anInteger "Setting width with this message is not allowed." self error: 'Pen widths cannot be reset this way; use defaultNib: or specify a new source form using sourceForm: '! !!Pen methodsFor: 'coloring'!black "Set the receiver's mask to the black form." self mask: Form black!color: ignored "Only meaningful for PressPens"!white "Set the receiver's mask to the white form." self mask: Form white! !!Pen methodsFor: 'moving'!down "Set the state of the receiver's pen to down (drawing)." penDown _ true!fillIn: aBlock "Just draw the outline; PressPens fill it in" ^ aBlock value!go: distance "Move the receiver in its current direction a number of bits equal to the argument, distance. If the pen is down, a line will be drawn using the receiver's form source as the shape of the drawing brush." | dir | dir _ direction degreesToRadians. dir _ dir cos @ dir sin. self goto: dir * distance + location!goto: aPoint "Move the receiver to position aPoint. If the pen is down, a line will be drawn from the current position to the new one using the receiver's form source as the shape of the drawing brush. The receiver's set direction does not change." | old | old _ location. location _ aPoint. penDown ifTrue: [self drawFrom: old to: location]!home "Place the receiver at the center of its frame." location _ frame center!north "Set the receiver's direction to facing toward the top of the display screen." direction _ 270.0!place: aPoint "Set the receiver at position aPoint. No lines are drawn." location _ aPoint!turn: degrees "Change the direction that the receiver faces by an amount equal to the argument, degrees." direction _ (direction + degrees) \\ 360!up "Set the state of the receiver's pen to up (not drawing)." penDown _ false! !!Pen methodsFor: 'geometric designs'!dragon: order "Draws a dragon curve of order order in the center of the screen. Writes directly into the display bitmap." order = 0 ifTrue: [self go: 10] ifFalse: [order > 0 ifTrue: [self dragon: order - 1; turn: 90; dragon: 1 - order] ifFalse: [self dragon: -1 - order; turn: -90; dragon: 1 + order]] " Pen new dragon: 8. "!filberts: n side: s "Two Hilbert curve fragments back to back form a Hilbert tile. Draw four interlocking tiles of order n directly on the display. (Can you fix this algorithm?)" | n2 | Display white. n2 _ 1 bitShift: n - 1. self up; go: 0 - n2 * s; down. 1 to: 4 do: [:i | self color: i - 1 * 40. self fillIn: [self hilbert: n side: s. self go: s. self hilbert: n side: s. self go: s]. self black. self hilbert: n side: s. self go: s. self hilbert: n side: s. self go: s. self up. self go: n2 - 1 * s. self turn: -90. self go: n2 * s. self turn: 180. self down] " Pen new filberts: 3 side: 10. "!hilbert: n side: s "Draws an nth lever Hilbert curve directly into the display bitmap. A Hilbert curve is a space-filling curve." | a m | n = 0 ifTrue: [^self turn: 180]. n > 0 ifTrue: [a _ 90. m _ n - 1] ifFalse: [a _ -90. m _ n + 1]. self turn: a. self hilbert: 0 - m side: s. self turn: a; go: s. self hilbert: m side: s. self turn: 0 - a; go: s; turn: 0 - a. self hilbert: m side: s. self go: s; turn: a. self hilbert: 0 - m side: s. self turn: a " (Pen new) hilbert: 3 side: 8. (Pen new sourceForm: Cursor wait) combinationRule: Form under; hilbert: 3 side: 25. "!hilberts: n "Demonstrates the space-filling nature of Hilbert curves by drawing n levers of nested curves on the screen." | s | self up; go: 128; down. 1 to: n do: [:i | s _ 256 bitShift: 0 - i. self color: n - i * 40. self defaultNib: n - i + 1. self up; go: 0 - s // 2; turn: -90; go: s // 2; turn: 90; down. self hilbert: i side: s. self go: s. self hilbert: i side: s. self go: s] " Display white. Pen new hilberts: 4. "!mandala: npoints diameter: d "On a circle of diameter d, place n points. Draw all possible connecting lines directly on the display." | l points | Display white. l _ (3.14 * d / npoints) rounded. self home; up; turn: -90; go: d // 2; turn: 90; go: 0 - l // 2. points _ Array new: npoints. 1 to: npoints do: [:i | points at: i put: location. self go: l; turn: 360 // npoints]. self down. npoints // 2 to: 1 by: -1 do: [:i | self color: npoints // 2 - i * 20 \\ 250. 1 to: npoints do: [:j | self place: (points at: j). self goto: (points at: j + i - 1 \\ npoints + 1)]] " Pen new mandala: 30 diameter: 400. "!spiral: n angle: a "Draw a double squiral directly on the display." 1 to: n do: [:i | self color: i * 2 \\ 256. self go: i; turn: a] " Display white. Pen new spiral: 200 angle: 89; home; spiral: 200 angle: -89. "! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Pen class instanceVariableNames: ''!!Pen class methodsFor: 'instance creation'!new | quill | quill _ super new. quill destForm: Display. quill frame: Display boundingBox. quill sourceOrigin: 0@0. quill mask: Form black. quill defaultNib: 1. quill combinationRule: Form paint. quill down. quill home. quill north. ^quill! !!Pen class methodsFor: 'examples'!example "Draws a spiral in gray with a pen that is 4 pixels wide." | bic | bic _ Pen new. bic mask: Form gray. bic defaultNib: 4. bic combinationRule: Form under. 1 to: 50 do: [:i | bic go: i*4. bic turn: 89] "Pen example"! ! Object subclass: #Point instanceVariableNames: 'x y ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Primitives'!Point comment: 'I am an x-y pair of numbers usually designating a location on the screen'!!Point methodsFor: 'accessing'!x "Answer the x coordinate." ^x!x: xInteger "Set the x coordinate." x _ xInteger!y "Answer the y coordinate." ^y!y: yInteger "Set the y coordinate." y _ yInteger! !!Point methodsFor: 'comparing'!< aPoint "Answer whether the receiver is 'above and to the left' of aPoint." ^x < aPoint x and: [y < aPoint y]!<= aPoint "Answer whether the receiver is 'neither below nor to the right' of aPoint." ^x <= aPoint x and: [y <= aPoint y]!= aPoint self species = aPoint species ifTrue: [^x = aPoint x and: [y = aPoint y]] ifFalse: [^false]!> aPoint "Answer whether the receiver is 'below and to the right' of aPoint." ^x > aPoint x and: [y > aPoint y]!>= aPoint "Answer whether the receiver is 'neither above nor to the left' of aPoint." ^x >= aPoint x and: [y >= aPoint y]!hash ^(x hash bitShift: 2) bitXor: y hash!hashMappedBy: map "My hash is independent of my oop" ^ self hash!max: aPoint "Answer the lower right corner of the rectangle uniquely defined by the receiver and aPoint." ^Point x: (x max: aPoint x) y: (y max: aPoint y)!min: aPoint "Answer the upper left corner of the rectangle uniquely defined by the receiver and aPoint." ^Point x: (x min: aPoint x) y: (y min: aPoint y)! !!Point methodsFor: 'arithmetic'!* scale "Answer a new Point that is the product of the receiver and scale (which is a Point or Number)." | scalePoint | scalePoint _ scale asPoint. ^x * scalePoint x @ (y * scalePoint y)!+ delta "Answer a new Point that is the sum of the receiver and delta (which is a Point or Number)." | deltaPoint | deltaPoint _ delta asPoint. ^x + deltaPoint x @ (y + deltaPoint y)!- delta "Answer a new Point that is the difference of the receiver and delta (which is a Point or Number)." | deltaPoint | deltaPoint _ delta asPoint. ^x - deltaPoint x @ (y - deltaPoint y)!/ scale "Answer a new Point that is the quotient of the receiver and scale (which is a Point or Number)." | scalePoint | scalePoint _ scale asPoint. ^x / scalePoint x @ (y / scalePoint y)!// scale "Answer a new Point that is the quotient of the receiver and scale (which is a Point or Number)." | scalePoint | scalePoint _ scale asPoint. ^x // scalePoint x @ (y // scalePoint y)!abs "Answer a new Point whose x and y are the absolute values of the receiver's x and y." ^Point x: x abs y: y abs! !!Point methodsFor: 'truncation and round off'!rounded "Answer a new Point that is the receiver's x and y rounded." ^x rounded @ y rounded!truncateTo: grid "Answer a new Point that is the receiver's x and y truncated to grid x and grid y." ^(x truncateTo: grid) @ (y truncateTo: grid)! !!Point methodsFor: 'polar coordinates'!r "Answer the receiver's radius in polar coordinate system." ^(self dotProduct: self) sqrt!theta "Answer the angle the receiver makes with origin in radians. right is 0; down is 90." | tan theta | x = 0 ifTrue: [y >= 0 ifTrue: [^1.5708"90.0 degreesToRadians"] ifFalse: [^4.71239"270.0 degreesToRadians"]] ifFalse: [tan _ y asFloat / x asFloat. theta _ tan arcTan. x >= 0 ifTrue: [y >= 0 ifTrue: [^theta] ifFalse: [^360.0 degreesToRadians + theta]] ifFalse: [^180.0 degreesToRadians + theta]]! !!Point methodsFor: 'point functions'!dist: aPoint "Answer the distance between aPoint and the receiver." ^(aPoint - self) r!dotProduct: aPoint "Answer a Number that is the dot product of the receiver and the argument, aPoint. That is, the two points are multipled and the coordinates of the result summed." | temp | temp _ self * aPoint. ^temp x abs + temp y abs!grid: aPoint "Answer a new Point to the nearest rounded grid modules specified by aPoint." | newX newY | aPoint x = 0 ifTrue: [newX _ 0] ifFalse: [newX _ x roundTo: aPoint x]. aPoint y = 0 ifTrue: [newY _ 0] ifFalse: [newY _ y roundTo: aPoint y]. ^newX @ newY!normal "Answer a new Point representing the unit vector rotated 90 deg toward the y axis." ^(y negated @ x) unitVector!pointNearestLine: point1 to: point2 "Answers the closest integer point to the receiver on the line determined by (point1, point2)." | relPoint delta | delta _ point2 - point1. "normalize coordinates" relPoint _ self - point1. delta x = 0 ifTrue: [^point1 x@y]. delta y = 0 ifTrue: [^x@point1 y]. delta x abs > delta y abs "line more horizontal?" ifTrue: [^x@(point1 y + (x * delta y // delta x))] ifFalse: [^(point1 x + (relPoint y * delta x // delta y))@y] "43@55 pointNearestLine: 10@10 to: 100@200"!transpose "Answer a new Point whose x is the receiver's y and whose y is the receiver's x." ^y @ x!truncatedGrid: aPoint "Answer a new Point to the nearest truncated grid modules specified by aPoint." ^(x truncateTo: aPoint x) @ (y truncateTo: aPoint y)!unitVector "Answer the receiver scaled to unit length." ^self / self r! !!Point methodsFor: 'converting'!asPoint "Answer the receiver itself." ^self!corner: aPoint "Answer a new Rectangle whose origin is the receiver and whose corner is aPoint. This is one of the infix ways of expressing the creation of a rectangle." ^Rectangle origin: self corner: aPoint!extent: aPoint "Answer a new Rectangle whose origin is the receiver and whose extent is aPoint. This is one of the infix ways of expressing the creation of a rectangle." ^Rectangle origin: self extent: aPoint! !!Point methodsFor: 'coercing'!coerce: aNumber ^aNumber@aNumber!generality ^90! !!Point methodsFor: 'transforming'!scaleBy: factor "Answer a new Point scaled by factor (an instance of Point)." ^(factor x * x) @ (factor y * y)!translateBy: delta "Answer a new Point translated by delta (an instance of Point)." ^(delta x + x) @ (delta y + y)! !!Point methodsFor: 'copying'!deepCopy "Implemented here for better performance." ^x deepCopy @ y deepCopy!shallowCopy "Implemented here for better performance." ^x @ y! !!Point methodsFor: 'printing'!printOn: aStream "The receiver prints on aStream in terms of infix notation." x printOn: aStream. aStream nextPut: $@. y printOn: aStream!storeOn: aStream aStream nextPut: $(; nextPutAll: self species name; nextPutAll: ' x: '; store: x; nextPutAll: ' y: '; store: y; nextPut: $).! !!Point methodsFor: 'private'!setX: xPoint setY: yPoint x _ xPoint. y _ yPoint! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Point class instanceVariableNames: ''!!Point class methodsFor: 'instance creation'!x: xInteger y: yInteger "Answer a new instance of me with coordinates xInteger and yInteger." ^self new setX: xInteger setY: yInteger! ! Object subclass: #PopUpMenu instanceVariableNames: 'labelString font lineArray frame form marker selection ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!PopUpMenu comment:'I represent a list of items. My instances are presented on the display screen in a rectangular area. The user points to an item, pressing a mouse button; the item is highlighted. When the button is released, the highlighted item indicates the selection.Instance Variables:labelString <String> of menu itemsfont <StrikeFont> for displaying the characterslineArray <Array> of integers indicating where lines should be drawn in the menuframe <Quadrangle>form <Form> containing the composed paragraphmarker <Rectangle> used to highlight selectionselection <Integer> index into menu items; if 0, no selection'!!PopUpMenu methodsFor: 'basic control sequence'!startUp "Show the receiver and give control to the user to make a selection." ^self startUp: #anyButton! !!PopUpMenu methodsFor: 'accessing'!center "Answer the point at the center of the receiver's rectangular area." ^frame center!height "Answer the width of the receiver's rectangular area." ^frame height!reset marker _ marker align: marker topLeft with: frame topLeft + frame borderWidth. selection _ 0.!topLeft "Answer the point at the topLeft of the receiver's rectangular area." ^frame topLeft!width "Answer the width of the receiver's rectangular area." ^frame width! !!PopUpMenu methodsFor: 'bordering'!borderWidth "Answer the borderWidth of the receiver's rectangular area." ^frame borderWidth! !!PopUpMenu methodsFor: 'displaying'!displayAt: aPoint during: aBlock "Display the receiver centered at aPoint while aBlock is evaluated. If necessary, translate so the view is completely on the screen." | delta savedArea | frame _ frame align: marker center with: aPoint. delta _ frame amountToTranslateWithin: Display boundingBox. frame moveBy: delta. marker _ marker align: marker center with: aPoint + delta. savedArea _ Form fromDisplay: frame. Display black: (frame origin + (1@1) corner: frame corner). Display black: (frame origin corner: frame corner - (1@1)). form displayOn: Display at: frame inside topLeft clippingBox: frame inside. selection ~= 0 ifTrue: [Display reverse: marker]. aBlock value. savedArea displayOn: Display at: frame topLeft!displayAt: aPoint withHeading: aText during: aBlock "Display the receiver centered at aPoint while aBlock is evaluated. If necessary, translate so the view is completely on the screen." | delta savedArea heading headingBox headingSavedArea | frame _ frame align: marker center with: aPoint. heading _ aText asDisplayText. headingBox _ heading boundingBox expandBy: 2. headingBox _ headingBox align: headingBox bottomCenter with: frame topCenter + (0@2). delta _ (frame merge: headingBox) amountToTranslateWithin: Display boundingBox. frame moveBy: delta. headingBox moveBy: delta. marker _ marker align: marker center with: aPoint + delta. savedArea _ Form fromDisplay: frame. headingSavedArea _ Form fromDisplay: headingBox. Display border: (headingBox) width: 2 mask: Form black. heading displayAt: headingBox origin + (2@2). Display black: (frame origin + (1@1) corner: frame corner). Display black: (frame origin corner: frame corner - (1@1)). form displayOn: Display at: frame inside topLeft clippingBox: frame inside. selection ~= 0 ifTrue: [Display reverse: marker]. aBlock value. savedArea displayOn: Display at: frame topLeft. headingSavedArea displayOn: Display at: headingBox topLeft! !!PopUpMenu methodsFor: 'marker adjustment'!manageMarker "If the cursor is inside the receiver's frame, then highlight the marked item. Otherwise no item is to be marked." | aPoint | aPoint _ Sensor cursorPoint. (frame inside containsPoint: aPoint) ifTrue: [self markerOn: aPoint] ifFalse: [self markerOff]!markerOff "No item is selected. Reverse the highlight if any item has been marked as selected." selection ~= 0 ifTrue: [Display reverse: marker. selection _ 0]!markerOn: aPoint "The item whose bounding area contains aPoint should be marked as selected. Highlight its area and set the selection to its index." selection = 0 | (marker containsPoint: aPoint) not ifTrue: [selection = 0 & (marker containsPoint: aPoint) ifTrue: [Display reverse: marker] ifFalse: [selection ~= 0 ifTrue: [Display reverse: marker]. marker _ marker align: marker topLeft with: marker left @ (self markerTop: aPoint). Display reverse: marker]]. selection _ marker top - frame top // marker height + 1!markerTop: aPoint "Answer aPoint, gridded to lines in the receiver." ^(aPoint y - frame inside top truncateTo: font height) + frame inside top! !!PopUpMenu methodsFor: 'selecting'!selection "Answer the current selection." ^selection! !!PopUpMenu methodsFor: 'controlling'!buttonPressed: aSymbol "The argument indicates which button should be tested. Answer whether it is pressed." aSymbol = #redButton ifTrue: [^Sensor redButtonPressed]. aSymbol = #yellowButton ifTrue: [^Sensor yellowButtonPressed]. aSymbol = #blueButton ifTrue: [^Sensor blueButtonPressed]. ^Sensor anyButtonPressed!startUp: aSymbol "Display and make a selection from the receiver as long as the button denoted by the symbol, aSymbol, is pressed. Answer the current selection." self displayAt: Sensor cursorPoint during: [Sensor cursorPoint: marker center. [self buttonPressed: aSymbol] whileFalse: []. [self buttonPressed: aSymbol] whileTrue: [self manageMarker]]. ^selection!startUp: aSymbol withHeading: aText "Display and make a selection from the receiver as long as the button denoted by the symbol, aSymbol, is pressed. Answer the current selection." self displayAt: Sensor cursorPoint withHeading: aText during: [Sensor cursorPoint: marker center. [self buttonPressed: aSymbol] whileFalse: [(frame containsPoint: Sensor cursorPoint) ifFalse: [Display flash: frame]]. [self buttonPressed: aSymbol] whileTrue: [self manageMarker]]. ^selection!startUpAndWaitForSelectionAt: aPoint "Display and make a selection from the receiver as long as the button denoted by the symbol, aSymbol, is pressed. Answer the current selection." | upperLeft | self displayAt: aPoint during: [[(Sensor anyButtonPressed and: [frame inside containsPoint: Sensor cursorPoint])] whileFalse: []. [self buttonPressed: #anyButton] whileTrue: [self manageMarker]]. ^selection!startUpBlueButton "Display and make a selection from the receiver as long as the blue button is pressed." ^self startUp: #blueButton!startUpRedButton "Display and make a selection from the receiver as long as the red button is pressed." ^self startUp: #redButton!startUpYellowButton "Display and make a selection from the receiver as long as the yellow button is pressed." ^self startUp: #yellowButton! !!PopUpMenu methodsFor: 'private'!labels: aString font: aFont lines: anArray | style labelPara | labelString _ aString. font _ aFont. style _ TextStyle fontArray: (Array with: font). style alignment: 2. "centered" style gridForFont: 1 withLead: 0. labelPara _ Paragraph withText: aString asText style: style. lineArray _ anArray. form _ labelPara asForm. frame _ Quadrangle new. frame region: (labelPara compositionRectangle expandBy: 2). frame borderWidth: (1@1 corner: 3@3). lineArray == nil ifFalse: [lineArray do: [:line | form fill: (0 @ (line * font height) extent: (frame width @ 1)) mask: Form black]]. marker _ frame inside topLeft extent: frame inside width @ labelPara lineGrid. selection _ 0!rescan "cause me to be recreated for system changes like fonts" labelString == nil ifFalse: [self labels: labelString font: font lines: lineArray] "PopUpMenu allInstancesDo: [:x | x rescan]."! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!PopUpMenu class instanceVariableNames: ''!!PopUpMenu class methodsFor: 'instance creation'!labels: aString "Answer an instance of me whose items are in aString." ^self labels: aString lines: nil!labels: aString lines: anArray "Answer an instance of me whose items are in aString, with lines drawn after each item indexed by anArray." ^ self new labels: aString font: (TextStyle default fontAt: 1) lines: anArray! ! Stream subclass: #PositionableStream instanceVariableNames: 'collection position readLimit ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Streams'!PositionableStream comment: 'I assume that my contents is an indexable collection and that, in support of accessing the elements of my contents, I can reposition a pointer. I am abstract in that I do not implement the messages next and nextPut: which are inherited from my superclass Stream.'!!PositionableStream methodsFor: 'accessing'!contents "Answer with a copy of my collection from 1 to readLimit." ^collection copyFrom: 1 to: readLimit!next: anInteger "Answer the next anInteger elements of the receiver." | newArray | newArray _ self contents species new: anInteger. 1 to: anInteger do: [:index | newArray at: index put: self next]. ^newArray!peek "Answer what would be returned with a self next, without changing position. If the receiver is at the end, answer nil." | nextObject | self atEnd ifTrue: [^nil]. nextObject _ self next. position _ position - 1. ^nextObject!peekFor: anObject "Answer false and do not move the position if self next ~= anObject or if the receiver is at the end. Answer true and increment position if self next = anObject." | nextObject | self atEnd ifTrue: [^false]. nextObject _ self next. "peek for matching element" anObject = nextObject ifTrue: [^true]. "gobble it if found" position _ position - 1. ^false!through: anObject "Answer a subcollection from position to the occurrence (if any, not inclusive) of anObject. If not there, answer everything." | newStream element | newStream _ WriteStream on: (collection species new: 64). [(self atEnd or: [(element _ self next) = anObject]) or: [newStream size > 64000]] whileFalse: [newStream nextPut: element]. self atEnd ifFalse: [newStream nextPut: element]. ^newStream contents!upTo: anObject "Answer a subcollection from position to the occurrence (if any, not inclusive) of anObject. If not there, answer everything." | newStream element | newStream _ WriteStream on: (collection species new: 64). [self atEnd or: [(element _ self next) = anObject]] whileFalse: [newStream nextPut: element]. ^newStream contents! !!PositionableStream methodsFor: 'testing'!atEnd "Answer true if the position is greater than or equal to the limit, otherwise answer false. Fail if position or readLimit is not a SmallInteger. Optional. See Object documentation whatIsAPrimitive." <primitive: 67> ^position >= readLimit!isEmpty "Answer whether the receiver has no elements." ^position = 0! !!PositionableStream methodsFor: 'positioning'!position "Answer the current position of accessing the stream." ^position!position: anInteger "Set position to anInteger as long as anInteger is within the bounds of the receiver's contents. If it is not, cause an error." anInteger >= 0 & (anInteger <= readLimit) ifTrue: [position _ anInteger] ifFalse: [self positionError]!reset "Set the receiver's position to 0." position _ 0!setToEnd "Set the position of the receiver to the end of its stream of elements." position _ readLimit!skip: anInteger "Set position to position+anInteger. A subclass might choose to be more helpful and select the minimum of self size and position+anInteger or maximum of 1 and position+anInteger for the repositioning." self position: position + anInteger!skipTo: anObject "Position the receiver past the next occurrance of anObject. Answer true if anObject is found, false otherwise." [self atEnd] whileFalse: [self next = anObject ifTrue: [^true]]. ^false! !!PositionableStream methodsFor: 'fileIn/Out'!nextChunk "Answer the contents of the receiver, up to the next terminator character, with double terminators ignored." | aStream char terminator | terminator _ $!!. aStream _ WriteStream on: (String new: 200). self skipSeparators. [(char _ self next)==nil] whileFalse: [char == terminator ifTrue: [(self peekFor: terminator) ifTrue: ["doubled terminator" aStream nextPut: char] ifFalse: [^aStream contents]] ifFalse: [aStream nextPut: char]]. ^aStream contents!skipSeparators "Move the receiver's position past any separators." [self atEnd == false and: [self peek isSeparator]] whileTrue: [self next]! !!PositionableStream methodsFor: 'private'!on: aCollection collection _ aCollection. readLimit _ aCollection size. position _ 0. self reset!positionError "Since I am not necessarily writable, it is up to my subclasses to override position: if expanding the collection is preferrable to giving this error." self error: 'Attempt to set the position of a PositionableStream out of bounds'! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!PositionableStream class instanceVariableNames: ''!!PositionableStream class methodsFor: 'instance creation'!on: aCollection "Answer a new instance of me, streaming over aCollection." ^self basicNew on: aCollection!on: aCollection from: firstIndex to: lastIndex "Answer a new instance of me, streaming over a copy of aCollection from firstIndex to lastIndex." ^self basicNew on: (aCollection copyFrom: firstIndex to: lastIndex)! ! Link subclass: #Process instanceVariableNames: 'suspendedContext priority myList ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Processes'!Process comment: 'Instance Variables: suspendedContext <Context> activeContext at time of process suspension priority <Integer> partial indication of relative scheduling myList <LinkedList> on which I am suspendedI represent an independent path of control in the system. This path of control may be stopped (by sending me the message suspend) in such a way that it can later be restarted (by sending me the message restore). When any one of several paths of control can be advanced, the single instance of ProcessorScheduler named Processor determines which one will actually be advanced partly using my priority.'!!Process methodsFor: 'changing process state'!resume "Allow the process that the receiver represents to continue. Put the receiver in line to become the activeProcess. Fail if the receiver is already waiting in a queue (in a Semaphore or ProcessScheduler). Essential. See Object documentation whatIsAPrimitive." <primitive: 87> self primitiveFailed!suspend "Stop the process that the receiver represents in such a way that it can be restarted at a later time (by sending the receiver the message resume). If the receiver represents the activeProcess, suspend it. Otherwise fail and the code below will remove the receiver from the list of waiting processes. Essential. See Object documentation whatIsAPrimitive." <primitive: 88> Processor activeProcess == self ifTrue: [self primitiveFailed] ifFalse: [Processor remove: self ifAbsent: [self error: 'This process was not active']. myList _ nil]!terminate "Perhaps this method should be primitive. If the a process might run at any moment (like a Delay), and another process is trying to terminate it, there is a race condition in this method. The remove:ifAbsent: may get confused. One way to avoid this is to let Delays terminate themselves. See MessageTally spyEvery:on: for an example. " | context | Processor activeProcess == self ifTrue: [thisContext sender == nil ifFalse: [thisContext sender release]. thisContext removeSelf suspend] ifFalse: ["remove me first, then destroy me" myList == nil ifFalse: [myList remove: self ifAbsent: []. myList _ nil]. context _ suspendedContext. suspendedContext _ nil. (context ~~ nil and: [context sender ~~ nil]) ifTrue: [context sender release]]! !!Process methodsFor: 'changing suspended state'!install: aContext "Replace the suspendedContext with aContext." self == Processor activeProcess ifTrue: [^self error: 'The active process cannot install contexts']. suspendedContext _ aContext!popTo: aContext "Replace the suspendedContext with aContext, releasing all contexts between the currently suspendedContext and it." self == Processor activeProcess ifTrue: [^self error: 'The active process cannot pop contexts']. suspendedContext releaseTo: aContext. suspendedContext _ aContext! !!Process methodsFor: 'accessing'!offList "Inform the receiver that it has been taken off a list that it was suspended on. This is to break a backpointer." myList _ nil!priority "Answer the priority of the receiver." ^priority!priority: anInteger "Set the receiver's priority to anInteger." anInteger<=Processor highestPriority ifTrue: [priority _ anInteger] ifFalse: [self error: 'priority too high']!suspendedContext "Answer the context the receiver has suspended." ^suspendedContext!suspendingList "Answer the list on which the receiver has been suspended." ^myList! !!Process methodsFor: 'printing'!printOn: aStream super printOn: aStream. aStream nextPutAll: ' in '. suspendedContext printOn: aStream! !!Process methodsFor: 'private'!suspendedContext: aContext suspendedContext _ aContext! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Process class instanceVariableNames: ''!!Process class methodsFor: 'instance creation'!forContext: aContext priority: anInteger "Answer an instance of me that has suspended aContext at priority anInteger." | newProcess | newProcess _ self new. newProcess suspendedContext: aContext. newProcess priority: anInteger. ^newProcess! ! Object subclass: #ProcessHandle instanceVariableNames: 'process controller interrupted resumeContext proceedValue ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Debugger'!ProcessHandle comment:'A ProcessHandle holds the state of an interrupted process. It is capable of cutting backthe process''s stack, terminating the process, or causing it to resume again.'!!ProcessHandle methodsFor: 'initialize-release'!process: aProcess controller: aController interrupted: aBoolean resumeContext: aContext process _ aProcess. controller _ aController. interrupted _ aBoolean. resumeContext _ aContext. proceedValue _ nil!release process _ nil. "break all cycles" controller _ nil. resumeContext _ nil. proceedValue _ nil! !!ProcessHandle methodsFor: 'access'!interrupted ^ interrupted!interrupted: aBoolean "whoever uses this should be a method in this class" interrupted _ aBoolean!proceedValue ^ proceedValue!proceedValue: value proceedValue _ value!topContext ^ resumeContext!topContext: aContext resumeContext _ aContext! !!ProcessHandle methodsFor: 'menu messages'!proceed interrupted ifTrue: [resumeContext push: proceedValue]. self resumeProcess! !!ProcessHandle methodsFor: 'control'!resumeProcess | aScheduledController | aScheduledController _ ScheduledControllers activeController. aScheduledController view erase. process suspendedContext method == (Process compiledMethodAt: #terminate) ifFalse: [resumeContext == process suspendedContext ifFalse: [process popTo: resumeContext]. ScheduledControllers activeControllerNoTerminate: controller "NoTerminate" andProcess: process]. "if old process was terminated, just terminate current one" self release. "must precede close because it tries to terminate" aScheduledController closeAndUnscheduleNoErase. Processor terminateActive!terminate process == nil ifFalse: [process terminate]. self release! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ProcessHandle class instanceVariableNames: ''!!ProcessHandle class methodsFor: 'instance creation'!on: aProcess at: aContext interrupted: aBoolean ^ self new process: aProcess controller: (ScheduledControllers activeControllerProcess == aProcess ifTrue: [ScheduledControllers activeController] ifFalse: [nil]) interrupted: aBoolean resumeContext: aContext! ! Object subclass: #ProcessorScheduler instanceVariableNames: 'quiescentProcessLists activeProcess ' classVariableNames: 'BackgroundProcess HighIOPriority LowIOPriority SystemBackgroundPriority SystemRockBottomPriority TimingPriority UserBackgroundPriority UserInterruptPriority UserSchedulingPriority ' poolDictionaries: '' category: 'Kernel-Processes'!ProcessorScheduler comment: 'Instance Variables: quiescentProcessLists <Array of LinkedLists> on which to suspend processes activeProcess <Process> currently executing processMy single instance, named Processor, coordinates the use of the physical processor by all Processes requiring service'!!ProcessorScheduler methodsFor: 'accessing'!activePriority "Answer the priority level of the currently running Process." ^activeProcess priority!activeProcess "Answer the currently running Process." ^activeProcess!highestPriority "Answer the number of priority levels currently available for use." ^quiescentProcessLists size!highestPriority: newHighestPriority "Change the number of priority levels currently available for use." | continue newProcessLists | (quiescentProcessLists size > newHighestPriority and: [self anyProcessesAbove: newHighestPriority]) ifTrue: [self error: 'There are processes with priority higher than ' ,newHighestPriority printString]. newProcessLists _ Array new: newHighestPriority. 1 to: ((quiescentProcessLists size) min: (newProcessLists size)) do: [:priority | newProcessLists at: priority put: (quiescentProcessLists at: priority)]. quiescentProcessLists size to: newProcessLists size do: [:priority | newProcessLists at: priority put: LinkedList new]. quiescentProcessLists become: newProcessLists! !!ProcessorScheduler methodsFor: 'removing'!remove: aProcess ifAbsent: aBlock "Remove aProcess from the list on which it is waiting for the processor. If it is not waiting, evaluate aBlock." (quiescentProcessLists at: aProcess priority) remove: aProcess ifAbsent: aBlock. ^aProcess! !!ProcessorScheduler methodsFor: 'process state change'!suspendFirstAt: aPriority "Suspend the first Process that is waiting to run with priority aPriority." ^self suspendFirstAt: aPriority ifNone: [self error: 'No Process to suspend']!suspendFirstAt: aPriority ifNone: noneBlock "Suspend the first Process that is waiting to run with priority aPriority. If no Process is waiting, evaluate noneBlock" | aList | aList _ quiescentProcessLists at: aPriority. aList isEmpty ifTrue: [^noneBlock value] ifFalse: [^aList first suspend]!terminateActive "Terminate the process that is currently running." activeProcess terminate!yield "Give other Processes at the current priority a chance to run" | semaphore | semaphore _ Semaphore new. [semaphore signal] fork. semaphore wait! !!ProcessorScheduler methodsFor: 'timing'!signal: aSemaphore atTime: timeInterval "Signal aSemaphore when the system's millisecond clock reaches timeInterval (an Integer)" | milliseconds | (timeInterval digitLength > 4 or: [timeInterval negative]) ifTrue: [self error: 'Can''t convert time to double word']. milliseconds _ ByteArray new: 4. milliseconds at: 1 put: (timeInterval digitAt: 1). milliseconds at: 2 put: (timeInterval digitAt: 2). milliseconds at: 3 put: (timeInterval digitAt: 3). milliseconds at: 4 put: (timeInterval digitAt: 4). ^self signal: aSemaphore atMilliseconds: milliseconds! !!ProcessorScheduler methodsFor: 'priority names'!highIOPriority "Answer the priority at which the most time critical input/output processes should run. An example is the process handling input from a network." ^HighIOPriority!lowIOPriority "Answer the priority at which most input/output processes should run. Examples are the process handling input from the user (keyboard, pointing device, etc.) and the process distributing input from a network." ^LowIOPriority!systemBackgroundPriority "Answer the priority at which system background processes should run. Examples are an incremental garbage collector or status checker." ^SystemBackgroundPriority!timingPriority "Answer the priority at which the system processes keeping track of real time should run." ^TimingPriority!userBackgroundPriority "Answer the priority at which user background processes should run." ^UserBackgroundPriority!userInterruptPriority "Answer the priority at which user processes desiring immediate service should run. Processes run at this level will preempt the window scheduler and should, therefore, not consume the processor forever." ^UserInterruptPriority!userSchedulingPriority "Answer the priority at which the window scheduler should run." ^UserSchedulingPriority! !!ProcessorScheduler methodsFor: 'private'!anyProcessesAbove: highestPriority "Do any instances of Process exist with higher priorities?" ^(Process allInstances select: [:aProcess | aProcess priority > highestPriority]) isEmpty!signal: aSemaphore atMilliseconds: milliseconds "Signal the semaphore when the millisecond clock reaches the value of the second argument. The second argument is a byte indexable object at least four bytes long (a 32-bit unsigned number with the low order 8-bits stored in the byte with the lowest index). Fail if the first argument is neither a Semaphore nor nil. Essential. See Object documentation whatIsAPrimitive." <primitive: 100> self primitiveFailed! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ProcessorScheduler class instanceVariableNames: ''!!ProcessorScheduler class methodsFor: 'class initialization'!initialize SystemRockBottomPriority _ 1. SystemBackgroundPriority _ 2. UserBackgroundPriority _ 3. UserSchedulingPriority _ 4. UserInterruptPriority _ 5. LowIOPriority _ 6. HighIOPriority _ 7. TimingPriority _ 8 "ProcessorScheduler initialize."! !!ProcessorScheduler class methodsFor: 'instance creation'!new "New instances of ProcessorScheduler should not be created." self error:'New ProcessSchedulers should not be created sincethe integrity of the system depends on a unique scheduler'! !!ProcessorScheduler class methodsFor: 'background process'!background: aBlock "Replace the background process with a process running the code in aBlock." BackgroundProcess == nil ifFalse: [BackgroundProcess terminate]. BackgroundProcess _ aBlock newProcess. BackgroundProcess priority: SystemRockBottomPriority. BackgroundProcess resume!hiddenBackgroundProcess "Install a default background process which is invisible." self background: [[true] whileTrue: []]!sweepHandBackgroundProcess "Install the default background process which shows a sweeping circle of Xor-ed bits on the screen." | sweepHand | sweepHand _ Pen new. sweepHand defaultNib: 2. sweepHand combinationRule: 6. self background: [[true] whileTrue: [2 timesRepeat: [sweepHand north. 36 timesRepeat: [sweepHand place: Display boundingBox topRight + (-25@25). sweepHand go: 20. sweepHand turn: 10]]]]! !ProcessorScheduler initialize! StringHolder subclass: #Project instanceVariableNames: 'projectWindows projectChangeSet projectTranscript projectHolder ' classVariableNames: 'CurrentProject ' poolDictionaries: '' category: 'Interface-Projects'!Project comment: 'Each screen is a manifestation of a project. Each project manages the windows (views) in it. While the user is working in the project, the changes made to classes are collected. Thus a system-wide set of changes is the collection of all project changes.'!!Project methodsFor: 'initialize-release'!release projectWindows isNil ifFalse: [projectWindows release]. ^super release! !!Project methodsFor: 'controlling'!enter "The user has chosen to change the context of the workspace to be that of the receiver. Change the ChangeSet, Transcript, and collection of scheduled views accordingly." Smalltalk newChanges: projectChangeSet. CurrentProject _ self. TextCollector newTranscript: projectTranscript. ControlManager newScheduler: projectWindows!exit "Leave the current project and enter the project in which the receiver's view is scheduled." projectHolder enter! !!Project methodsFor: 'dependents access'!removeDependent: aDependent super removeDependent: aDependent. self dependents isEmpty ifTrue: [self release]! !!Project methodsFor: 'change management'!noChanges "Reset the receiver's ChangeSet so that it is empty." projectChangeSet _ ChangeSet new. Smalltalk newChanges: projectChangeSet! !!Project methodsFor: 'lock access'!isLocked ^super isLocked | projectChangeSet isEmpty not | (projectWindows scheduledControllers size > 1)!isUnlocked ^ self isLocked not! !!Project methodsFor: 'private'!initialProject projectWindows _ ScheduledControllers. projectChangeSet _ Smalltalk changes. projectHolder _ self!setProjectHolder: aProject projectWindows _ ControlManager new. projectChangeSet _ ChangeSet new. projectTranscript _ TextCollector new. projectHolder _ aProject! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Project class instanceVariableNames: ''!!Project class methodsFor: 'class initialization'!initialize "This is the Top Project." CurrentProject _ super new initialProject "Project initialize."! !!Project class methodsFor: 'instance creation'!new ^super new setProjectHolder: CurrentProject! !!Project class methodsFor: 'constants'!current "Answer the project that is currently being used." ^CurrentProject! !Project initialize! StringHolderController subclass: #ProjectController instanceVariableNames: '' classVariableNames: 'ProjectYellowButtonMenu ProjectYellowButtonMessages ' poolDictionaries: '' category: 'Interface-Projects'!ProjectController comment:'I am a kind of StringHolderController (a ParagraphEditor that adds the doIt, printIt, accept, and cancel commands). The commands doIt and printIt are omitted. I provide one additional menu command enter -- replace the current project by the model, thereby "entering" the door to a new office or work area'!!ProjectController methodsFor: 'menu messages'!enter "Exchange projects so that the receiver's model is the context in which the user works." view topView deEmphasize. model enter! !!ProjectController methodsFor: 'private'!initializeYellowButtonMenu self yellowButtonMenu: ProjectYellowButtonMenu yellowButtonMessages: ProjectYellowButtonMessages.! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ProjectController class instanceVariableNames: ''!!ProjectController class methodsFor: 'class initialization'!initialize "Initialize the menu for the yellow mouse button." ProjectYellowButtonMenu _ PopUpMenu labels: 'againundocopycutpasteacceptcancelenter' lines: #(2 5 7 ). ProjectYellowButtonMessages _ #(again undo copySelection cut paste accept cancel enter ) "ProjectViewController initialize"! !ProjectController initialize! StringHolderView subclass: #ProjectView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Projects'!ProjectView comment:'I am a StringHolderView of the description of a Project. ProjectController is my default controller.'!!ProjectView methodsFor: 'initialize-release'!release model release. super release! !!ProjectView methodsFor: 'controller access'!defaultControllerClass ^ProjectController! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ProjectView class instanceVariableNames: ''!!ProjectView class methodsFor: 'instance creation'!open "Answer an instance of me for a new Project. It is created on the display screen." ^self open: Project new "ProjectView open"!open: aProject "Answer an instance of me for the argument, aProject. It is created on the display screen." | aProjectView topView | aProjectView _ super new. aProjectView model: aProject. aProjectView borderWidth: 1. topView _ StandardSystemView new. topView model: aProject. topView borderWidth: 1. topView addSubView: aProjectView. topView label: 'Project'. topView minimumSize: 100 @ 50. topView controller open! ! Rectangle subclass: #Quadrangle instanceVariableNames: 'borderWidth borderColor insideColor ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Primitives'!Quadrangle comment:'I represent a particular kind of Rectangle that has a border and inside color.Instance Variables: borderWidth <Rectangle> the left, right, top, bottom border widths borderColor <Form> insideColor <Form>'!!Quadrangle methodsFor: 'initialize-release'!initialize "Initialize the region to a null Rectangle, the borderWidth to 1, the borderColor to black, and the insideColor to white." origin _ 0 @ 0. corner _ 0 @ 0. borderWidth _ 1. borderColor _ Form black. insideColor _ Form white! !!Quadrangle methodsFor: 'bordering'!borderColor "Answer the borderColor of the receiver." ^borderColor!borderColor: aColor "Set the borderColor of the receiver to aColor." borderColor _ aColor!borderWidth "Answer the borderWidth of the receiver." ^borderWidth!borderWidth: anInteger "Set the borderWidth of the receiver to anInteger." borderWidth _ anInteger!borderWidthLeft: anInteger1 right: anInteger2 top: anInteger3 bottom: anInteger4 "Set the border width of the receiver to a Rectangle that represents the left, right, top, and bottom border widths." borderWidth _ anInteger1 @ anInteger3 corner: anInteger2 @ anInteger4!inside "Answer a Rectangle that is the receiver inset by the borderWidth." ^self insetBy: borderWidth!insideColor "Answer the insideColor of the receiver." ^insideColor!insideColor: aColor "Set the insideColor of the receiver to aColor." insideColor _ aColor!region "Answer a Rectangle that defines the area of the receiver." ^origin corner: corner!region: aRectangle "Set the rectangular area of the receiver to aRectangle." origin _ aRectangle origin. corner _ aRectangle corner! !!Quadrangle methodsFor: 'displaying'!displayAlign: aPoint1 with: aPoint2 clippingBox: aRectangle "Display the border and region of the reciever so that its position at aPoint1 is aligned with position aPoint2. The displayed information should be clipped so that only information with the area determined by aRectangle is displayed." | savedRegion | savedRegion _ self region. self region: ((savedRegion align: aPoint1 with: aPoint2) intersect: aRectangle). self displayOn: Display. self region: savedRegion! !!Quadrangle methodsFor: 'rectangle functions'!intersect: aRectangle "Answer a new Quadrangle whose region is the intersection of the receiver's area and aRectangle." ^ Quadrangle region: (super intersect: aRectangle) borderWidth: borderWidth borderColor: borderColor insideColor: insideColor! !!Quadrangle methodsFor: 'transforming'!align: aPoint1 with: aPoint2 "Answer a new Quadrangle translated by aPoint2 - aPoint1." ^ Quadrangle region: (super translateBy: aPoint2 - aPoint1) borderWidth: borderWidth borderColor: borderColor insideColor: insideColor!scaleBy: aPoint "Answer a new Quadrangle scaled by aPoint." ^ Quadrangle region: (super scaleBy: aPoint) borderWidth: borderWidth borderColor: borderColor insideColor: insideColor!translateBy: aPoint "Answer a new Quadrangle translated by aPoint." ^ Quadrangle region: (super translateBy: aPoint) borderWidth: borderWidth borderColor: borderColor insideColor: insideColor! !!Quadrangle methodsFor: 'displaying-generic'!displayOn: aDisplayMedium "Display the border and insideRegion of the receiver." insideColor ~~ nil ifTrue: [aDisplayMedium fill: self inside mask: insideColor]. borderWidth ~~ 0 & (insideColor ~~ nil) ifTrue: [aDisplayMedium fill: self region mask: borderColor. aDisplayMedium fill: self inside mask: insideColor]!displayOn: aDisplayMedium align: aPoint1 with: aPoint2 clippingBox: aRectangle "Display the border and region of the reciever so that its position at aPoint1 is aligned with position aPoint2. The displayed information should be clipped so that only information with the area determined by aRectangle is displayed." | savedRegion | savedRegion _ self region. self region: ((savedRegion align: aPoint1 with: aPoint2) intersect: aRectangle). self displayOn: aDisplayMedium. self region: savedRegion!displayOn: aDisplayMedium transformation: aWindowingTransformation clippingBox: aRectangle "Display the border and region of the reciever so that it is scaled and translated with respect to aWindowingTransformation. The displayed information should be clipped so that only information with the area determined by aRectangle is displayed." | screenRectangle | screenRectangle _ (aWindowingTransformation applyTo: self) intersect: aRectangle. borderWidth ~~ 0 & (insideColor ~~ nil) ifTrue: [aDisplayMedium fill: screenRectangle mask: borderColor. aDisplayMedium fill: (screenRectangle insetBy: borderWidth) mask: insideColor]! !!Quadrangle methodsFor: 'displaying-Display'!display self displayOn: Display! !!Quadrangle methodsFor: 'private'!region: aRectangle borderWidth: anInteger borderColor: aMask1 insideColor: aMask2 origin _ aRectangle origin. corner _ aRectangle corner. borderWidth _ anInteger. borderColor _ aMask1. insideColor _ aMask2.! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Quadrangle class instanceVariableNames: ''!!Quadrangle class methodsFor: 'instance creation'!new "Answer an instance of me, initialized to a null Rectangle, with borderWidth of 1, borderColor of black, and insideColor of white." ^super new initialize!region: aRectangle borderWidth: anInteger borderColor: aMask1 insideColor: aMask2 "Answer an instance of me with rectangle, border width and color, and inside color determined by the arguments." ^super new region: aRectangle borderWidth: anInteger borderColor: aMask1 insideColor: aMask2! ! Stream subclass: #Random instanceVariableNames: 'seed ' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Numbers'!Random comment:'A simple random number generator.'!!Random methodsFor: 'accessing'!contents ^self shouldNotImplement!next "Answer with the next random number." | temp | [seed _ 13849 + (27181 * seed) bitAnd: 65535. 0 = (temp _ seed / 65536.0)] whileTrue. ^temp!nextPut: anObject ^self shouldNotImplement! !!Random methodsFor: 'testing'!atEnd ^false! !!Random methodsFor: 'private'!setSeed seed _ Time millisecondClockValue bitAnd: 65535 "Time millisecondClockValue gives a large integer; I only want the lower 16 bits."! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Random class instanceVariableNames: ''!!Random class methodsFor: 'instance creation'!new "Answer a new random number generator." ^self basicNew setSeed! ! PositionableStream subclass: #ReadStream instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Streams'!ReadStream comment: 'I am a reader of an indexable collection. I only define the message next.'!!ReadStream methodsFor: 'accessing'!next "Answer with the next object in the Stream represented by the receiver. Fail if the collection of this stream is not an Array or a String. Fail if the stream is positioned at its end, or if the position is out of bounds in the collection. Optional. See Object documentation whatIsAPrimitive." <primitive: 65> position >= readLimit ifTrue: [^nil] ifFalse: [^collection at: (position _ position + 1)]!nextPut: anObject self shouldNotImplement! !!ReadStream methodsFor: 'private'!on: aCollection from: firstIndex to: lastIndex | len | collection _ aCollection. readLimit _ lastIndex > (len _ collection size) ifTrue: [len] ifFalse: [lastIndex]. position _ firstIndex <= 1 ifTrue: [0] ifFalse: [firstIndex - 1]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ReadStream class instanceVariableNames: ''!!ReadStream class methodsFor: 'instance creation'!on: aCollection from: firstIndex to: lastIndex "Answer with a new instance streaming over a copy of aCollection from firstIndex to lastIndex." ^self basicNew on: aCollection from: firstIndex to: lastIndex! ! WriteStream subclass: #ReadWriteStream instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Streams'!ReadWriteStream comment: 'I am a positionable stream into which we can both read and write.'!!ReadWriteStream methodsFor: 'accessing'!contents "Answer with a copy of my collection from 1 to readLimit." readLimit _ readLimit max: position. ^collection copyFrom: 1 to: readLimit!next "Return the next object in the Stream represented by the receiver. Fail if the collection of this stream is not an Array or a String. Fail if the stream is positioned at its end, or if the position is out of bounds in the collection. Optional. See Object documentation whatIsAPrimitive." <primitive: 65> "treat me as a FIFO" position >= readLimit ifTrue: [^nil] ifFalse: [^collection at: (position _ position + 1)]! !!ReadWriteStream methodsFor: 'file status'!close "Prsumably sets the status of the stream to be closed. This message does nothing at this level, but is included for FileStream compatibility." ^self! !!ReadWriteStream methodsFor: 'fileIn/Out'!fileIn "This is special for reading expressions from text that has been formatted with exclamation delimitors. The expressions are read and passed to the Compiler. Answer the result of compilation." | val | Cursor read showWhile: [[self atEnd] whileFalse: [self skipSeparators. val _ (self peekFor: $!!) ifTrue: [(Compiler evaluate: self nextChunk logged: false) scanFrom: self] ifFalse: [Compiler evaluate: self nextChunk logged: true]]. self close]. ^val!fileOutChanges "Append to the receiver a description of all system changes." Cursor write showWhile: [self timeStamp. Smalltalk changes fileOutOn: self. self close]!fileOutChangesFor: class "Append to the receiver a description of the changes to the argument, class." Cursor write showWhile: [self timeStamp. Smalltalk changes fileOutChangesFor: class on: self. self close]!timeStamp "Append the current time to the receiver as a chunk." | aStream | aStream _ WriteStream on: (String new: 16). Smalltalk timeStamp: aStream. self nextChunkPut: aStream contents printString. "double quotes and !!s" self cr; cr! ! Object subclass: #Rectangle instanceVariableNames: 'origin corner ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Primitives'!Rectangle comment:'I usually represent a rectangular area on the screen. Arithmetic functions take points as arguments and carry out scaling and translating operations to create new Rectangles. Rectangle functions create new Rectangles by determining intersections of rectangles with rectangles. '!!Rectangle methodsFor: 'accessing'!area "Answer the receiver's area, the product of width and height." ^self width * self height!bottom "Answer the position of the receiver's bottom horizontal line." ^corner y!bottom: anInteger "Set the position of the bottom horizontal line of the receiver." corner y: anInteger!bottomCenter "Answer the point at the center of the bottom horizontal line of the receiver." ^self center x @ self bottom!bottomLeft "Answer the point at the left edge of the bottom horizontal line of the receiver." ^origin x @ corner y!bottomRight "Answer the point at the right edge of the bottom horizontal line of the receiver." ^corner!bottomRight: bottomRightPoint "Set the position of the right corner of the bottom horizontal line of the receiver." corner _ bottomRightPoint!center "Answer the point at the center of the receiver." ^self topLeft + self bottomRight // 2!corner "Answer the point at the bottom right corner of the receiver." ^corner!corner: cornerPoint "Set the point at the bottom right corner of the receiver." corner _ cornerPoint!extent "Answer with a rectangle with origin 0@0 and corner the receiver's width @ the receiver's height." ^corner - origin!extent: extentPoint "Set the extent (width and height) of the receiver to be extentPoint." corner _ origin + extentPoint!height "Answer the height of the receiver." ^corner y - origin y!height: heightInteger "Change the receiver's bottom y to make its height heightInteger." corner y: origin y + heightInteger!left "Answer the position of the receiver's left vertical line." ^origin x!left: anInteger "Set the position of the receiver's left vertical line." origin x: anInteger!leftCenter "Answer the point at the center of the receiver's left vertical line." ^self left @ self center y!origin "Answer the point at the top left corner of the receiver." ^origin!origin: originPoint "Set the point at the top left corner of the receiver." origin _ originPoint!origin: originPoint corner: cornerPoint "Set the points at the top left corner and the bottom right corner of the receiver." origin _ originPoint. corner _ cornerPoint!origin: originPoint extent: extentPoint "Set the point at the top left corner of the receiver to be originPoint and set the width and height of the receiver to be extentPoint." origin _ originPoint. corner _ origin + extentPoint!right "Answer the position of the receiver's right vertical line." ^corner x!right: anInteger "Set the position of the receiver's right vertical line." corner x: anInteger!rightCenter "Answer the point at the center of the receiver's right vertical line." ^self right @ self center y!top "Answer the position of the receiver's top horizontal line." ^origin y!top: anInteger "Set the position of the receiver's top horizontal line." origin y: anInteger!topCenter "Answer the point at the center of the receiver's top horizontal line." ^self center x @ self top!topLeft "Answer the point at the top left corner of the receiver's top horizontal line." ^origin!topLeft: topLeftPoint "Set the point at the top left corner of the receiver's top horizontal line." origin _ topLeftPoint!topRight "Answer the point at the top right corner of the receiver's top horizontal line." ^corner x @ origin y!width "Answer the width of the receiver." ^corner x - origin x!width: widthInteger "Change the receiver's right vertical line to make its width widthInteger." corner x: origin x + widthInteger! !!Rectangle methodsFor: 'comparing'!= aRectangle "Answer true if the receiver's species, origin and corner match aRectangle's." self species = aRectangle species ifTrue: [^origin = aRectangle origin and: [corner = aRectangle corner]] ifFalse: [^false]!hash ^origin hash bitXor: corner hash!hashMappedBy: map "My hash is independent of my oop" ^ self hash! !!Rectangle methodsFor: 'rectangle functions'!amountToTranslateWithin: aRectangle "Answer a Point, delta, such that self + delta is forced within aRectangle." | delta | delta _ 0@0. self left < aRectangle left ifTrue: [delta x: aRectangle left - self left]. self top < aRectangle top ifTrue: [delta y: aRectangle top - self top]. self right > aRectangle right ifTrue: [delta x: aRectangle right - self right]. self bottom > aRectangle bottom ifTrue: [delta y: aRectangle bottom - self bottom]. ^delta!areasOutside: aRectangle "Answer with a Collection of Rectangles comprising the parts of me which do not lie within aRectangle." | areas yOrigin yCorner | "Make sure the intersection is non-empty" (origin <= aRectangle corner and: [aRectangle origin <= corner]) ifFalse: [^Array with: self]. areas _ OrderedCollection new. aRectangle origin y > origin y ifTrue: [areas add: (origin corner: corner x @ (yOrigin _ aRectangle origin y))] ifFalse: [yOrigin _ origin y]. aRectangle corner y < corner y ifTrue: [areas add: (origin x @ (yCorner _ aRectangle corner y) corner: corner)] ifFalse: [yCorner _ corner y]. aRectangle origin x > origin x ifTrue: [areas add: (origin x @ yOrigin corner: aRectangle origin x @ yCorner)]. aRectangle corner x < corner x ifTrue: [areas add: (aRectangle corner x @ yOrigin corner: corner x @ yCorner)]. ^areas!expandBy: delta "Answer a Rectangle that is outset from the receiver by delta. delta is a Rectangle, Point, or scalar." (delta isKindOf: Rectangle) ifTrue: [^Rectangle origin: origin - delta origin corner: corner + delta corner] ifFalse: [^Rectangle origin: origin - delta corner: corner + delta]!insetBy: delta "Answer a Rectangle that is inset from the receiver by delta. delta is a Rectangle, Point, or scalar." (delta isKindOf: Rectangle) ifTrue: [^Rectangle origin: origin + delta origin corner: corner - delta corner] ifFalse: [^Rectangle origin: origin + delta corner: corner - delta]!insetOriginBy: originDeltaPoint cornerBy: cornerDeltaPoint "Answer a Rectangle that is inset from the receiver by a given amount in the origin and corner." ^Rectangle origin: origin + originDeltaPoint corner: corner - cornerDeltaPoint!intersect: aRectangle "Answer a Rectangle that is the area in which the receiver overlaps with aRectangle. " ^Rectangle origin: (origin max: aRectangle origin) corner: (corner min: aRectangle corner)!merge: aRectangle "Answer a Rectangle that contains both the receiver and aRectangle." ^Rectangle origin: (origin min: aRectangle origin) corner: (corner max: aRectangle corner)! !!Rectangle methodsFor: 'testing'!contains: aRectangle "Answer whether the receiver is equal to aRectangle or whether aRectangle is contained within the receiver." ^aRectangle origin >= origin and: [aRectangle corner <= corner]!containsPoint: aPoint "Answer whether aPoint is within the receiver." ^origin <= aPoint and: [aPoint < corner]!intersects: aRectangle "Answer whether aRectangle intersects the receiver anywhere." ^(origin max: aRectangle origin) < (corner min: aRectangle corner)! !!Rectangle methodsFor: 'truncation and round off'!rounded "Answer a Rectangle whose origin and corner are rounded." ^Rectangle origin: origin rounded corner: corner rounded! !!Rectangle methodsFor: 'transforming'!align: aPoint1 with: aPoint2 "Answer a new Rectangle that is a translated by aPoint2 - aPoint1." ^self translateBy: aPoint2 - aPoint1!moveBy: aPoint "Change the corner positions of the receiver so that its area translates by the amount defined by the argument, aPoint." origin _ origin + aPoint. corner _ corner + aPoint!moveTo: aPoint "Change the corners of the receiver so that its top left position is aPoint." corner _ corner + aPoint - origin. origin _ aPoint!scaleBy: scale "Answer a new Rectangle scaled by scale, a Point or a scalar." ^Rectangle origin: origin * scale corner: corner * scale!translateBy: factor "Answer a new Rectangle translated by factor, a Point or a scalar." ^Rectangle origin: origin + factor corner: corner + factor! !!Rectangle methodsFor: 'copying'!copy ^self deepCopy! !!Rectangle methodsFor: 'printing'!printOn: aStream origin printOn: aStream. aStream nextPutAll: ' corner: '. corner printOn: aStream!storeOn: aStream aStream nextPut: $(; nextPutAll: self species name; nextPutAll: ' origin: '; store: origin; nextPutAll: ' corner: '; store: corner; nextPut: $).! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Rectangle class instanceVariableNames: ''!!Rectangle class methodsFor: 'instance creation'!fromUser "Answer an instance of me that is determined by having the user designate the top left and bottom right corners. The gridding for user selection is 1@1." ^self fromUser: 1 @ 1!fromUser: gridPoint "Answer an instance of me that is determined by having the user designate the top left and bottom right corners. The gridding for user selection is gridPoint." | originPoint newSelf minCorner oldCursor| oldCursor _ Sensor currentCursor. Cursor cursorLink: false. originPoint _ Sensor cursorPoint grid: gridPoint. [Sensor redButtonPressed] whileFalse: [Processor yield. Cursor origin showGridded: gridPoint. originPoint _ Sensor cursorPoint grid: gridPoint]. newSelf _ self new origin: originPoint. minCorner _ originPoint + gridPoint. Sensor cursorPoint: minCorner. [Sensor redButtonPressed] whileTrue: [Processor yield. Cursor corner showGridded: gridPoint. newSelf corner: ((Sensor cursorPoint grid: gridPoint) max: minCorner). Display flash: newSelf]. Cursor cursorLink: true. oldCursor show. ^newSelf "Rectangle fromUser: 100@100."!fromUserAspectRatio: aspectPoint "Answer an instance of Rectangle that is determined by having the user designate the top left and bottom right corners, constrained so the aspect ratio is determined by aspectPoint." | rectangle extent ratio | Cursor origin showWhile: [rectangle _ Sensor waitButton extent: 1@1]. ratio _ aspectPoint y/aspectPoint x. Cursor corner showWhile: [Sensor cursorPoint: rectangle corner. [Sensor anyButtonPressed] whileTrue: [extent _ Sensor cursorPoint-rectangle origin max: 1@1. (extent y*aspectPoint x) > (aspectPoint y*extent x) ifTrue: [extent x: (extent y/ratio) rounded] "contrain width" ifFalse: [extent y: (extent x*ratio) rounded]. "constrain height" rectangle extent: extent. Display flash: rectangle]]. ^rectangle "Rectangle fromUserAspectRatio: Sensor waitButton"!left: leftNumber right: rightNumber top: topNumber bottom: bottomNumber "Answer an instance of me whose left, right, top, and bottom coordinates are determined by the arguments." ^self origin: leftNumber @ topNumber corner: rightNumber @ bottomNumber!origin: originPoint corner: cornerPoint "Answer an instance of me whose corners (top left and bottom right) are determined by the arguments." ^self new origin: originPoint corner: cornerPoint!origin: originPoint extent: extentPoint "Answer an instance of me whose top left corner is originPoint and width by height is extentPoint." ^self new origin: originPoint extent: extentPoint!originFromUser: extentPoint "Answer an instance of me that is determined by having the user designate the top left corner. The width and height are determined by extentPoint. The gridding for user selection is 1@1." ^self originFromUser: extentPoint grid: 1 @ 1!originFromUser: extentPoint grid: scaleFactor "Answer an instance of me that is determined by having the user designate the top left corner. The width and height are determined by extentPoint. The gridding for user selection is scaleFactor. Assumes that the sender has determined an extent that is a proper multiple of scaleFactor." | tempRect | tempRect _ (Sensor cursorPoint grid: scaleFactor) extent: extentPoint. [Sensor redButtonPressed] whileFalse: [Display reverse: tempRect. Display reverse: tempRect. tempRect _ (Sensor cursorPoint grid: scaleFactor) extent: extentPoint]. ^tempRect! ! Object subclass: #RemoteString instanceVariableNames: 'sourceFileNumber filePositionHi filePositionLo ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Support'!RemoteString comment: 'Instance Variables: sourceFileNumber <Integer> index into SourceFiles filePositionHi <Integer> filePositionLo <Integer>I hold the file reference to the class comment (or any other piece of executable text).'!!RemoteString methodsFor: 'accessing'!position "Answer the location of the string on a file." ^(filePositionHi bitShift: 8) + filePositionLo!sourceFileNumber "Answer the index of the file on which the string is stored." ^sourceFileNumber!string "Answer the receiver's string if remote files are enabled." | theFile | (SourceFiles == nil or: [sourceFileNumber == nil]) ifTrue: [^''] ifFalse: [theFile _ SourceFiles at: sourceFileNumber. theFile position: (filePositionHi bitShift: 8) + filePositionLo. ^theFile nextChunk]! !!RemoteString methodsFor: 'private'!fileNumber: sourceIndex position: anInteger sourceFileNumber _ sourceIndex. filePositionHi _ anInteger bitShift: -8. filePositionLo _ anInteger bitAnd: 255!string: aString onFileNumber: anInteger "Store this as my string if source files exist" | theFile | SourceFiles == nil ifFalse: [theFile _ SourceFiles at: anInteger. theFile setToEnd; readWriteShorten; cr. self string: aString onFileNumber: anInteger toFile: theFile. theFile readOnly]!string: aString onFileNumber: anInteger toFile: aFileStream "Store this as the receiver's string if source files exist." | position | sourceFileNumber _ anInteger. filePositionHi _ (position _ aFileStream position) bitShift: -8. filePositionLo _ position bitAnd: 255. aFileStream nextChunkPut: aString! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!RemoteString class instanceVariableNames: ''!!RemoteString class methodsFor: 'instance creation'!newFileNumber: sourceIndex position: anInteger "Answer a new instance of RemoteString for file indexed by sourceIndex, at the position anInteger. Assumes that the string is already stored on the file and the instance will be used to access it." ^self new fileNumber: sourceIndex position: anInteger!newString: aString onFileNumber: sourceIndex "Answer a new instance of RemoteString for string, aString, on file indexed by sourceIndex. Puts the string on the file and creates the remote reference." ^self new string: aString onFileNumber: sourceIndex!newString: aString onFileNumber: sourceIndex toFile: aFileStream "Answer a new instance of RemoteString for string, aString, on file indexed by sourceIndex. Puts the string on the file, aFileStream, and creates the remote reference. Assumes that the index corresponds properly to aFileStream." ^self new string: aString onFileNumber: sourceIndex toFile: aFileStream! ! ParseNode subclass: #ReturnNode instanceVariableNames: 'expr pc ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!ReturnNode comment: 'I represent an expression of the form ^expr'!!ReturnNode methodsFor: 'initialize-release'!expr: e expr _ e!expr: e encoder: encoder sourceRange: range expr _ e. encoder noteSourceRange: range forNode: self! !!ReturnNode methodsFor: 'converting'!asReturnNode! !!ReturnNode methodsFor: 'testing'!isReturnSelf ^expr == NodeSelf!isVariableReference ^expr isVariableReference! !!ReturnNode methodsFor: 'code generation'!code ^expr code!emitForReturn: stack on: strm expr emitForReturn: stack on: strm. pc _ strm position!emitForValue: stack on: strm expr emitForReturn: stack on: strm. pc _ strm position!pc "used by encoder source mapping" pc == nil ifTrue: [^3]. "quick returns never generate, so pc=nil" ^pc!sizeForReturn: encoder ^expr sizeForReturn: encoder!sizeForValue: encoder ^expr sizeForReturn: encoder! !!ReturnNode methodsFor: 'printing'!printOn: aStream indent: level aStream nextPut: $^. expr printOn: aStream indent: level. expr printCommentOn: aStream indent: level! ! ArrayedCollection subclass: #RunArray instanceVariableNames: 'runs values ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed'!RunArray comment: 'RunArrays provide space-efficient storage of data which tends to be constant over long runs of the possible indices. runs is an array of Integers, and each indicates the number of indices over which the corresponding value (in values) is constant.'!!RunArray methodsFor: 'accessing'!at: index | run offset value | self at: index setRunOffsetAndValue: [:run :offset :value | ^value]!runLengthAt: index "Answer the length remaining in run beginning at index." | run offset value | self at: index setRunOffsetAndValue: [:run :offset :value | ^(runs at: run) - offset]!size | size | size _ 0. runs do: [:run | size _ size + run]. ^size!values "Answer the values in the receiver." ^values! !!RunArray methodsFor: 'adding'!addFirst: value "Add value as the first element of the receiver." (runs size=0 or: [values first ~= value]) ifTrue: [runs_ (Array with: 1) , runs. values_ (Array with: value) , values] ifFalse: [runs at: 1 put: runs first+1]!addLast: value "Add value as the last element of the receiver." (runs size=0 or: [values last ~= value]) ifTrue: [runs_ runs copyWith: 1. values_ values copyWith: value] ifFalse: [runs at: runs size put: runs last+1]! !!RunArray methodsFor: 'copying'!, aRunArray "Answer a new RunArray that is a concatenation of the receiver and aRunArray." | new newRuns | (aRunArray isMemberOf: RunArray) ifFalse: [new _ self copy. "attempt to be sociable" aRunArray do: [:each | new addLast: each]. ^new]. runs size = 0 ifTrue: [^aRunArray copy]. aRunArray runs size = 0 ifTrue: [^self copy]. values last ~= aRunArray first ifTrue: [^RunArray runs: runs , aRunArray runs values: values , aRunArray values]. newRuns _ runs copyReplaceFrom: runs size to: runs size with: aRunArray runs. newRuns at: runs size put: runs last + aRunArray runs first. ^RunArray runs: newRuns values: (values copyReplaceFrom: values size to: values size with: aRunArray values)!copyFrom: start to: stop | run1 offset1 value1 run2 offset2 value2 newRuns | stop < start ifTrue: [^RunArray new]. self at: start setRunOffsetAndValue: [:run1 :offset1 :value1 | value1]. self at: stop setRunOffsetAndValue: [:run2 :offset2 :value2 | value2]. run1 = run2 ifTrue: [newRuns _ Array with: offset2 - offset1 + 1] ifFalse: [newRuns _ runs copyFrom: run1 to: run2. newRuns at: 1 put: (newRuns at: 1) - offset1. newRuns at: newRuns size put: offset2 + 1]. ^RunArray runs: newRuns values: (values copyFrom: run1 to: run2)!copyReplaceFrom: start to: stop with: replacement ^(self copyFrom: 1 to: start - 1) , replacement , (self copyFrom: stop + 1 to: self size)! !!RunArray methodsFor: 'printing'!storeOn: aStream aStream nextPut: $(. aStream nextPutAll: self class name. aStream nextPutAll: ' runs: '. runs storeOn: aStream. aStream nextPutAll: ' values: '. values storeOn: aStream. aStream nextPut: $)! !!RunArray methodsFor: 'fileIn/Out'!writeOn: aStream aStream nextWordPut: runs size. 1 to: runs size do: [:x | aStream nextWordPut: (runs at: x). aStream nextWordPut: (values at: x)]! !!RunArray methodsFor: 'private'!at: index setRunOffsetAndValue: aBlock "Supply all run information to aBlock." | run limit position | " Tolerates index=0 and index=size+1 for copyReplace:" run _ 1. limit _ runs size. position _ index. [run <= limit and: [position > (runs at: run)]] whileTrue: [position _ position - (runs at: run). run _ run + 1]. run > limit ifTrue: ["adjustment for size+1" run _ run - 1. position _ position + (runs at: run)]. ^aBlock value: run "an index into runs and values" value: position - 1 "zero-based offset from beginning of this run" value: (values at: run) "value for this run"!runs ^runs!setRuns: newRuns setValues: newValues runs _ newRuns. values _ newValues! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!RunArray class instanceVariableNames: ''!!RunArray class methodsFor: 'instance creation'!new ^self runs: Array new values: Array new!new: size withAll: value "Answer a new instance of me, whose every element is equal to the argument, value." size = 0 ifTrue: [^self new]. ^self runs: (Array with: size) values: (Array with: value)!readFrom: aStream "Answer a new instance of RunArray as described on the stream, aStream" | size runs values | size _ aStream nextWord. runs _ Array new: size. values _ Array new: size. 1 to: size do: [:x | runs at: x put: aStream nextWord. values at: x put: aStream nextWord]. ^ self runs: runs values: values!runs: newRuns values: newValues "Answer a new instance of RunArray with runs and values specified by the arguments." | instance | instance _ self basicNew. instance setRuns: newRuns setValues: newValues. ^instance! ! Object subclass: #Scanner instanceVariableNames: 'source mark hereChar aheadChar token tokenType currentComment buffer typeTable ' classVariableNames: 'EndChar TypeTable ' poolDictionaries: '' category: 'System-Compiler'!Scanner comment: 'I scan a stream picking out Smalltalk syntactic tokens. I look one character ahead. I put each token found into token and its type (a Symbol) into tokenType. At the end of stream or a doit symbol, I pretend to see an endless sequence of doits.'!!Scanner methodsFor: 'initialize-release'!initScanner buffer _ WriteStream on: (String new: 40). typeTable _ TypeTable!on: inputStream "Bind the input stream, fill the character buffers" source _ inputStream. self step. self step!scan: inputStream "Bind the input stream, fill the character buffers and first token buffer" self on: inputStream. self scanToken! !!Scanner methodsFor: 'public access'!scanFieldNames: stringOrArray "Answer with an Array of strings which are the identifiers in the input string. If passed an Array, just answer with that Array (it has already been scanned)." | strm | (stringOrArray isMemberOf: Array) ifTrue: [^stringOrArray]. self scan: (ReadStream on: stringOrArray asString). strm _ WriteStream on: (Array new: 10). [tokenType = #doIt] whileFalse: [tokenType = #word ifTrue: [strm nextPut: token]. self scanToken]. ^strm contents "Scanner new scanFieldNames: 'abc def ghi' ('abc' 'def' 'ghi' )"!scanTokens: textOrString "Answer with an Array which has been tokenized as though the input text had appeared between #( and ) in a Smalltalk literal expression." self scan: (ReadStream on: textOrString asString). self scanLitVec. ^token "Scanner new scanTokens: 'identifier keyword: 8r31 ''string'' embedded.period key:word: . ' "! !!Scanner methodsFor: 'expression types'!scanLitVec | s | s _ WriteStream on: (Array new: 16). [tokenType = #rightParenthesis or: [tokenType = #doIt]] whileFalse: [tokenType = #leftParenthesis ifTrue: [self scanToken; scanLitVec] ifFalse: [tokenType = #word | (tokenType = #keyword) ifTrue: [self scanLitWord] ifFalse: [(token == #- and: [(typeTable at: hereChar asciiValue) = #xDigit]) ifTrue: [self scanToken. token _ token negated]]]. s nextPut: token. self scanToken]. token _ s contents!scanLitWord "accumulate keywords and asSymbol the result" | t | [(typeTable at: hereChar asciiValue) = #xLetter] whileTrue: [t _ token. self xLetter. token _ t , token]. token _ token asSymbol!scanToken [(tokenType _ typeTable at: hereChar asciiValue) == #xDelimiter] whileTrue: [self step]. "Skip delimiters fast, there almost always is one." mark _ source position - 1. (tokenType at: 1) = $x "x as first letter" ifTrue: [self perform: tokenType "means perform to compute token & type"] ifFalse: [token _ self step asSymbol "else just unique the first char"]. ^token!step | c | c _ hereChar. hereChar _ aheadChar. (aheadChar _ source next) == nil ifTrue: [aheadChar _ EndChar "doit"]. ^c! !!Scanner methodsFor: 'multi-character scans'!xBinary tokenType _ #binary. token _ Symbol internCharacter: self step. ((typeTable at: hereChar asciiValue) = #xBinary and: [hereChar ~= $-]) ifTrue: [token _ (token , (String with: self step)) asSymbol]!xDelimiter "ignore blanks etc." self scanToken!xDigit "form a number" tokenType _ #number. (aheadChar = EndChar and: [source atEnd and: [source skip: -1. source next ~= EndChar]]) ifTrue: [source skip: -1 "Read off the end last time"] ifFalse: [source skip: -2]. token _ Number readFrom: source. self step; step!xDollar "form a Character literal" self step. "pass over $" token _ self step. tokenType _ #number "really should be Char, but rest of compiler doesn't know"!xDoubleQuote "collect comment" | aStream | aStream _ WriteStream on: (String new: 32). self step. [aStream nextPut: self step. hereChar == $"] whileFalse: [(hereChar = EndChar and: [source atEnd]) ifTrue: [^self offEnd: 'Unmatched comment quote']]. self step. currentComment == nil ifTrue: [currentComment _ OrderedCollection with: aStream contents] ifFalse: [currentComment add: aStream contents]. self scanToken!xLetter "form a word or keyword" | type prefix | buffer reset. [type _ typeTable at: hereChar asciiValue. type == #xLetter or: [type == #xDigit]] whileTrue: ["open code step for speed" buffer nextPut: hereChar. hereChar _ aheadChar. source atEnd ifTrue: [aheadChar _ EndChar "doit"] ifFalse: [aheadChar _ source next]]. (type == #period and: [tokenType _ typeTable at: aheadChar asciiValue. (tokenType == #xLetter) | (tokenType == #xBinary)]) ifTrue: "Allow embedded period in selectors" [buffer nextPut: self step. prefix _ buffer contents. self perform: tokenType. token _ prefix , token. tokenType == #binary ifTrue: [token _ token asSymbol]. ^self]. type == #colon ifTrue: [buffer nextPut: self step. tokenType _ #keyword] ifFalse: [tokenType _ #word]. token _ buffer contents!xLitQuote "UniqueStrings and Vectors" " #(1 (4 5) 2 3) #ifTrue:ifFalse:" | start | self step. "litQuote" self scanToken. tokenType = #leftParenthesis ifTrue: [start _ mark. self scanToken; scanLitVec. tokenType == #doIt ifTrue: [mark _ start. self offEnd: 'Unmatched parenthesis']] ifFalse: [(#(word keyword colon) includes: tokenType) ifTrue: [self scanLitWord]]. tokenType _ #literal!xSingleQuote "string" self step. buffer reset. [hereChar == $' and: [aheadChar == $' ifTrue: [self step. false] ifFalse: [true]]] whileFalse: [buffer nextPut: self step. (hereChar == EndChar and: [source atEnd]) ifTrue: [^self offEnd: 'Unmatched string quote']]. self step. token _ buffer contents. tokenType _ #string! !!Scanner methodsFor: 'error handling'!notify: string self error: string!offEnd: aString "Parser overrides this" ^self notify: aString! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Scanner class instanceVariableNames: ''!!Scanner class methodsFor: 'class initialization'!initialize "Scanner initialize." | newTable | newTable _ Array new: 256 withAll: #xBinary. "default" newTable atAll: #(9 10 12 13 32 ) put: #xDelimiter. "tab lf ff cr space" newTable atAll: ($0 asciiValue to: $9 asciiValue) put: #xDigit. newTable atAll: ($A asciiValue to: $Z asciiValue) put: #xLetter. newTable atAll: ($a asciiValue to: $z asciiValue) put: #xLetter. newTable at: 30 put: #doIt. newTable at: $" asciiValue put: #xDoubleQuote. newTable at: $# asciiValue put: #xLitQuote. newTable at: $$ asciiValue put: #xDollar. newTable at: $' asciiValue put: #xSingleQuote. newTable at: $( asciiValue put: #leftParenthesis. newTable at: $) asciiValue put: #rightParenthesis. newTable at: $. asciiValue put: #period. newTable at: $: asciiValue put: #colon. newTable at: $; asciiValue put: #semicolon. newTable at: $[ asciiValue put: #leftBracket. newTable at: $] asciiValue put: #rightBracket. newTable at: $^ asciiValue put: #upArrow. newTable at: $_ asciiValue put: #leftArrow. newTable at: $| asciiValue put: #verticalBar. EndChar _ 30 asCharacter. TypeTable _ newTable "bon voyage!!"! !!Scanner class methodsFor: 'instance creation'!new ^super new initScanner! !!Scanner class methodsFor: 'testing'!isLiteralSymbol: aSymbol "Test whether a symbol can be stored as # followed by its characters. Symbols created internally with asSymbol may not have this property, e.g. '3' asSymbol." | i ascii type | i _ aSymbol size. i = 0 ifTrue: [^false]. ascii _ (aSymbol at: 1) asciiValue. "TypeTable should have been origined at 0 rather than 1 ..." ascii = 0 ifTrue: [^false]. type _ TypeTable at: ascii. (type == #colon or: [type == #verticalBar]) ifTrue: [^i = 1]. type == #xBinary ifTrue: [[i > 1] whileTrue: [ascii _ (aSymbol at: i) asciiValue. ascii = 0 ifTrue: [^false]. (TypeTable at: ascii) == #xBinary ifFalse: [^false]. i _ i - 1]. ^true]. type == #xLetter ifTrue: [[i > 1] whileTrue: [ascii _ (aSymbol at: i) asciiValue. ascii = 0 ifTrue: [^false]. type _ TypeTable at: ascii. (type == #xLetter or: [type == #xDigit or: [type == #colon]]) ifFalse: [^false]. i _ i - 1]. ^true]. ^false! !Scanner initialize! MouseMenuController subclass: #ScreenController instanceVariableNames: '' classVariableNames: 'ScreenYellowButtonMenu ScreenYellowButtonMessages ' poolDictionaries: '' category: 'Interface-Support'!ScreenController comment:'I am the controller for the parts of the display screen that have no window on them. I only provide a standard yellow button menu. I view (a FormView of) an infinite gray form.'!!ScreenController methodsFor: 'initialize-release'!initialize super initialize. self initializeYellowButtonMenu! !!ScreenController methodsFor: 'control defaults'!isControlActive ^super isControlActive and: [sensor yellowButtonPressed]!isControlWanted ^super isControlWanted and: [sensor yellowButtonPressed]!openFileList "Create and schedule a FileList view for specifying files to access." FileList open! !!ScreenController methodsFor: 'menu messages'!exitProject Project current exit!openBrowser BrowserView openOn: SystemOrganization!openProject ProjectView open!openSystemWorkspace StringHolderView openSystemWorkspace.!openTranscript TextCollectorView open: Transcript label: 'System Transcript'!openWorkspace StringHolderView open!quit | menu index imagePrefix | menu _ PopUpMenu labels: ' Save, then quit Quit, without saving Continue ' lines: #(1 2). index _ menu startUp. index = 1 ifTrue: [imagePrefix _ Smalltalk getImagePrefix. imagePrefix isEmpty ifTrue: [^self]. Smalltalk saveAs: imagePrefix thenQuit: true]. index = 2 ifTrue: [Smalltalk quit]!restoreDisplay ScheduledControllers restore!save | prefix | prefix _ Smalltalk getImagePrefix. prefix isEmpty ifTrue: [^self]. Smalltalk saveAs: prefix thenQuit: false! !!ScreenController methodsFor: 'cursor'!centerCursorInView "Override so this doesn't happen when taking control"! !!ScreenController methodsFor: 'private'!initializeYellowButtonMenu self yellowButtonMenu: ScreenYellowButtonMenu yellowButtonMessages: ScreenYellowButtonMessages! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!ScreenController class instanceVariableNames: ''!!ScreenController class methodsFor: 'class initialization'!initialize "Initialize the System Menu." ScreenYellowButtonMenu _ PopUpMenu labels: 'restore displayexit projectprojectfile listbrowserworkspacesystem transcriptsystem workspacesavequit' lines: #(2 8 ). ScreenYellowButtonMessages _ #(restoreDisplay exitProject openProject openFileList openBrowser openWorkspace openTranscript openSystemWorkspace save quit). "ScreenController initialize. ScreenController allInstancesDo: [:c | c initializeYellowButtonMenu]"! !ScreenController initialize! MouseMenuController subclass: #ScrollController instanceVariableNames: 'scrollBar marker savedArea ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Support'!ScrollController comment:'I represent control for scrolling using a scrollBar. I am a MouseMenuController that creates a scrollBar, rather than menus. My subclasses add the button menus. I keep control as long as the cursor is inside the view or the scrollBar area.A scrollBar is a rectangular area representing the length of the information being viewed. It contains an inner rectangle whose top y-coordinate represents the relative position of the information visible on the screen with respect to all of the information, and whose size represents the relative amount of that information visible on the screen. The user controls which part of the information is visible by pressing the red button. If the cursor is to the right of the inner rectangle, the window onto the visible information moves upward, if the cursor is to the left, the window moves downward, and if the cursor is inside, the inner rectangle is grabbed and moved to a desired position. Instance Variables: scrollBar <Quadrangle> inside white, the outer rectangle marker <Quadrangle> inside gray, the inner rectangle savedArea <Form> the area the scrollBar overlaps, restored whenever the scrollBar is hidden '!!ScrollController methodsFor: 'initialize-release'!initialize super initialize. scrollBar _ Quadrangle new. scrollBar borderWidthLeft: 2 right: 0 top: 2 bottom: 2. marker _ Quadrangle new. marker insideColor: Form gray! !!ScrollController methodsFor: 'basic control sequence'!controlInitialize "The scrollbar has a two-pixel border, and for alignment it assumes that this sub-view has a one-pixel border and shares another one-pixel border from its neighbor/super view" super controlInitialize. scrollBar region: (0 @ 0 extent: 32 @ (view displayBox height + 2)). marker region: self computeMarkerRegion. scrollBar _ scrollBar align: scrollBar topRight with: view displayBox topLeft - (0@1). marker _ marker align: marker topCenter with: scrollBar inside topCenter. savedArea _ Form fromDisplay: scrollBar. scrollBar displayOn: Display. self moveMarker!controlTerminate super controlTerminate. savedArea notNil ifTrue: [savedArea displayOn: Display at: scrollBar topLeft. savedArea_ nil]! !!ScrollController methodsFor: 'control defaults'!controlActivity self scrollBarContainsCursor ifTrue: [self scroll] ifFalse: [super controlActivity]!isControlActive ^self viewHasCursor | self scrollBarContainsCursor!isControlWanted ^self viewHasCursor! !!ScrollController methodsFor: 'scrolling'!canScroll "Answer whether there is information that is not visible and can be seen by scrolling." ^marker region height < scrollBar inside height!scroll "Check to see whether the user wishes to jump, scroll up, or scroll down." | savedCursor regionPercent | savedCursor _ sensor currentCursor. [self scrollBarContainsCursor] whileTrue: [Processor yield. regionPercent _ 100 * (sensor cursorPoint x - scrollBar left) // scrollBar width. regionPercent <= 40 ifTrue: [self scrollDown] ifFalse: [regionPercent >= 60 ifTrue: [self scrollUp] ifFalse: [self scrollAbsolute]]]. savedCursor show!scrollAmount "Answer the number of bits of y-coordinate should be scrolled. This is a default determination based on the view's preset display transformation." ^((view inverseDisplayTransform: sensor cursorPoint) - (view inverseDisplayTransform: scrollBar inside topCenter)) y!scrollView "The scroll bar jump method was used so that the view should be updated to correspond to the location of the scroll bar gray area." self scrollView: self viewDelta!scrollView: anInteger "If anInteger is not zero, tell the reciever's view to scroll by anInteger amount." anInteger ~= 0 ifTrue: [view scrollBy: 0 @ ((anInteger min: view window top - view boundingBox top) max: view window top - view boundingBox bottom). view clearInside. view display]!scrollViewDown "Scroll the receiver's view down the default amount." self scrollView: self scrollAmount!scrollViewUp "Scroll the receiver's view up the default amount." self scrollView: self scrollAmount negated!viewDelta "Answer an integer that indicates how much the view should be scrolled. The scroll bar has been moved and now the view must be so the amount to scroll is computed as a ratio of the current scroll bar position." ^view window top - view boundingBox top - ((marker top - scrollBar inside top) asFloat / scrollBar inside height asFloat * view boundingBox height asFloat) rounded! !!ScrollController methodsFor: 'cursor'!changeCursor: aCursor "The current cursor should be set to be aCursor." sensor currentCursor ~~ aCursor ifTrue: [aCursor show]!markerContainsCursor "Answer whether the gray area inside the scroll bar area contains the cursor." ^marker inside containsPoint: sensor cursorPoint!scrollBarContainsCursor "Answer whether the cursor is anywhere within the scroll bar area." ^scrollBar containsPoint: sensor cursorPoint! !!ScrollController methodsFor: 'marker adjustment'!computeMarkerRegion "Answer the rectangular area in which the gray area of the scroll bar should be displayed." ^0@0 extent: 10 @ ((view window height asFloat / view boundingBox height * scrollBar inside height) rounded min: scrollBar inside height)!markerDelta ^marker top - scrollBar inside top - ((view window top - view boundingBox top) asFloat / view boundingBox height asFloat * scrollBar inside height asFloat) rounded!markerRegion: aRectangle "Set the area defined by aRectangle as the marker. Fill it with gray tone." Display fill: marker mask: scrollBar insideColor. marker region: aRectangle. marker _ marker align: marker topCenter with: scrollBar inside topCenter!moveMarker "The view window has changed. Update the marker." self moveMarker: self markerDelta negated!moveMarker: anInteger "Update the marker so that is is translated by an amount corresponding to a distance of anInteger, constrained within the boundaries of the scroll bar." Display fill: marker mask: scrollBar insideColor. marker _ marker translateBy: 0 @ ((anInteger min: scrollBar inside bottom - marker bottom) max: scrollBar inside top - marker top). marker displayOn: Display! !!ScrollController methodsFor: 'private'!scrollAbsolute | oldMarker | self changeCursor: Cursor marker. self canScroll & sensor anyButtonPressed ifTrue: [[sensor anyButtonPressed] whileTrue: [oldMarker _ marker. marker _ marker translateBy: 0@((sensor cursorPoint y - marker center y min: scrollBar inside bottom - marker bottom) max: scrollBar inside top - marker top). (oldMarker areasOutside: marker), (marker areasOutside: oldMarker) do: [:region | Display fill: region rule: Form reverse mask: Form gray]]. self scrollView. scrollBar display. self moveMarker]!scrollDown self changeCursor: Cursor down. sensor anyButtonPressed ifTrue: [self canScroll ifTrue: [self scrollViewDown. self moveMarker]]. sensor waitNoButton!scrollUp self changeCursor: Cursor up. sensor anyButtonPressed ifTrue: [self canScroll ifTrue: [self scrollViewUp. self moveMarker]]. sensor waitNoButton! ! ListController subclass: #SelectionInListController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Lists'!SelectionInListController comment:'This controllers is designed to support the pluggable SelectionInListViews (q.v.).As its operation is parameterized in the view, it must ask its view for currentselection and for menu options. The tighter controller/view relationship appropriate topluggable viewing has not yet fully matured. Note that control is not acceptedif the view is empty.'!!SelectionInListController methodsFor: 'menu messages'!redButtonActivity | selectionMovement oldSelection trialSelection nextSelection | selectionMovement _ false. oldSelection _ view selection. [sensor redButtonPressed] whileTrue: [trialSelection _ view findSelection: sensor cursorPoint. trialSelection ~~ nil ifTrue: [nextSelection _ trialSelection. view moveSelectionBox: nextSelection. nextSelection ~= oldSelection ifTrue: [selectionMovement _ true]]]. nextSelection == nil ifTrue: [^self]. nextSelection = oldSelection ifTrue: [selectionMovement ifTrue: [^self]. nextSelection _ 0. view moveSelectionBox: nextSelection]. model changeRequest ifFalse: [view moveSelectionBox: oldSelection. ^ view flash]. view changeModelSelection: nextSelection!yellowButtonActivity | index menu | menu _ view yellowButtonMenu. menu == nil ifTrue: [view flash. super controlActivity] ifFalse: [index _ menu startUpYellowButton. index ~= 0 ifTrue: [self controlTerminate. model perform: (menu selectorAt: index). self controlInitialize]]! !!SelectionInListController methodsFor: 'control defaults'!isControlWanted view isEmpty ifTrue: [^ false]. ^super isControlWanted! ! ListView subclass: #SelectionInListView instanceVariableNames: 'itemList printItems oneItem partMsg initialSelectionMsg changeMsg listMsg menuMsg ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Lists'!SelectionInListView comment:'SelectionInListView is a "pluggable" ListView. The notion of pluggable views is anexperiment in user interface design. The idea is to provide a view which can be pluggedonto any object, rather than having to define a new subclass specific to every kind ofobject which needs to be viewed.The chief mechanism is a set of selectors, which can be thought of as an adaptor toconvert the generic listView operations (such as changeSelection) into model-specificoperations (such as fileName:).An added feature of this listView is that it tries to preserve its selection throughchanges in the choice list. This effect, and also the choice of an intial selection aretransmitted to the model just as a user-requested selection would be.See the protocol ''adaptor'' for use of the pluggable selectors.See the creation messages in my class for an explication of the various parameters.Browse senders of the creation messages in my class for examples in the system.'!!SelectionInListView methodsFor: 'initialization'!on: anObject printItems: flag1 oneItem: flag2 aspect: m1 change: m3 list: m4 menu: m5 initialSelection: m6 self model: anObject. printItems _ flag1. oneItem _ flag2. partMsg _ m1. changeMsg _ m3. listMsg _ m4. menuMsg _ m5. initialSelectionMsg _ m6. oneItem ifTrue: [self noTopDelimiter noBottomDelimiter. initialSelectionMsg == nil ifTrue: [self error: 'initialSelection must be specified for oneItem mode']]. self list: self getList! !!SelectionInListView methodsFor: 'list access'!list: anArray | item | itemList _ anArray. anArray == nil ifTrue: [isEmpty _ true. selection _ 0. ^self changeModelSelection: 0]. printItems ifTrue: [super list: (anArray collect: [:each | each printString copyUpTo: Character cr])] ifFalse: [super list: anArray]. item _ self initialSelection. selection _ item == nil ifTrue: [0] ifFalse: [itemList findFirst: [:x | x = item]]. selection > 0 ifTrue: [self positionList]. self changeModelSelection: selection! !!SelectionInListView methodsFor: 'adaptor'!changeModelSelection: anInteger changeMsg ~~ nil ifTrue: [model perform: changeMsg with: (anInteger = 0 ifTrue: [nil] ifFalse: [itemList at: anInteger])]!getList | item | oneItem ifTrue: [item _ self initialSelection. item == nil ifTrue: [^ nil]. ^ Array with: item]. listMsg == nil ifTrue: [^nil]. ^ model perform: listMsg!initialSelection initialSelectionMsg == nil ifTrue: [^ nil]. ^ model perform: initialSelectionMsg!yellowButtonMenu menuMsg == nil ifTrue: [^ nil]. ^ model perform: menuMsg! !!SelectionInListView methodsFor: 'controller access'!defaultControllerClass ^ SelectionInListController! !!SelectionInListView methodsFor: 'updating'!update: aSymbol aSymbol == partMsg ifTrue: [self list: self getList; displayView]! !!SelectionInListView methodsFor: 'displaying'!displayView isEmpty ifTrue: [self clearInside] ifFalse: [super displayView]! !!SelectionInListView methodsFor: 'testing'!isEmpty ^ isEmpty! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SelectionInListView class instanceVariableNames: ''!!SelectionInListView class methodsFor: 'instance creation'!on: anObject aspect: aspectMsg change: changeMsg list: listMsg menu: menuMsg initialSelection: sel "Create a 'pluggable' (see class comment) listView viewing anObject. aspectMsg is sent to read the value of the current selection. It is also used as the changed: parameter for this view. changeMsg is sent to inform anObject of a new selection. listMsg is sent to read the current list which should be displayed. menuMsg is sent to read the yellowButton menu for this view. initialSelection is sent to read a selection to be selected initailly as a default." ^ self new on: anObject printItems: false oneItem: false aspect: aspectMsg change: changeMsg list: listMsg menu: menuMsg initialSelection: sel!on: anObject printItems: flag1 oneItem: flag2 aspect: aspectMsg change: changeMsg list: listMsg menu: menuMsg initialSelection: sel "Create a listView with these parameters - see comment in on:aspect:change: . . . Moreover, if printItems is true, then the view will show the printStrings of the items in the list, rather than assuming they are already text-like objects. And if oneItem is true the list works as a read-only list of one item. this is mainly used for the root list of various sub-browsers spawned from the browser." ^ self new on: anObject printItems: flag1 oneItem: flag2 aspect: aspectMsg change: changeMsg list: listMsg menu: menuMsg initialSelection: sel! ! LeafNode subclass: #SelectorNode instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!SelectorNode comment: 'I am a parse tree leaf representing a selector'!!SelectorNode methodsFor: 'code generation'!emit: stack args: nArgs on: strm self emit: stack args: nArgs on: strm super: false!emit: stack args: nArgs on: aStream super: supered | index | stack pop: nArgs. (supered not and: [code - Send < SendLimit and: [nArgs < 3]]) ifTrue: ["short send" aStream nextPut: (code < Send ifTrue: [code] ifFalse: ["special" nArgs * 16 + code])] ifFalse: [index _ code < 256 ifTrue: [code - Send] ifFalse: [code \\ 256]. (index < 32 and: [nArgs <= 7]) ifTrue: ["medium send" aStream nextPut: SendLong + (supered ifTrue: [2] ifFalse: [0]). aStream nextPut: nArgs * 32 + index] ifFalse: ["long send" aStream nextPut: SendLong + 1 + (supered ifTrue: [2] ifFalse: [0]). aStream nextPut: nArgs. aStream nextPut: index]]!size: encoder args: nArgs super: supered | index | self reserve: encoder. (supered not and: [code - Send < SendLimit and: [nArgs < 3]]) ifTrue: [^1]. "short send" (supered and: [code < Send]) ifTrue: ["super special:" code _ self code: (encoder litIndex: key) type: 5]. index _ code < 256 ifTrue: [code - Send] ifFalse: [code \\ 256]. (index < 32 and: [nArgs <= 7]) ifTrue: [^2]. "medium send" ^3 "long send"! !!SelectorNode methodsFor: 'printing'!printOn: aStream indent: level aStream nextPutAll: key! ! LinkedList subclass: #Semaphore instanceVariableNames: 'excessSignals ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Processes'!Semaphore comment: 'I provide synchronized communication of a single bit of information (a "signal") between Processes. A signal is sent by sending me the message signal and received by sending me the message wait. If no signal has been sent when a wait message is sent, the sending Process will be suspended until a signal is sent.'!!Semaphore methodsFor: 'initialize-release'!initSignals "Consume any excess signals the receiver may have accumulated." excessSignals _ 0!terminateProcess self isEmpty ifFalse: [self removeFirst terminate]! !!Semaphore methodsFor: 'communication'!signal "Send a signal through the receiver. If one or more processes have been suspended trying to receive a signal, allow the first one to proceed. If no process is waiting, remember the excess signal. Essential. See Object documentation whatIsAPrimitive. " <primitive: 85> self primitiveFailed "self isEmpty ifTrue: [excessSignals _ excessSignals+1] ifFalse: [Processor resume: self removeFirstLink]"!wait "The active Process must receive a signal through the receiver before proceeding. If no signal has been sent, the active Process will be suspended until one is sent. Essential. See Object whatIsAPrimitive." <primitive: 86> self primitiveFailed "excessSignals>0 ifTrue: [excessSignals _ excessSignals-1] ifFalse: [self addLastLink: Processor activeProcess suspend]"! !!Semaphore methodsFor: 'mutual exclusion'!critical: mutuallyExcludedBlock "Evaluate mutuallyExcludedBlock only if the receiver is not currently in the process of running the critical: message. If the receiver is, evaluate mutuallyExcludedBlock after the other critical: message is finished." | blockValue | self wait. blockValue _ mutuallyExcludedBlock value. self signal. ^blockValue! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Semaphore class instanceVariableNames: ''!!Semaphore class methodsFor: 'instance creation'!forMutualExclusion "Answer a new instance of me that contains a single signal. This new instance can now be used for mutual exclusion (see the critical: message to Semaphore)." ^self new signal!new "Answer a new instance of Semaphore that contains no signals." ^self basicNew initSignals! ! Collection subclass: #SequenceableCollection instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Abstract'!SequenceableCollection comment: 'Abstract superclass for collections that have a well-defined order associated with their elements'!!SequenceableCollection methodsFor: 'comparing'!= otherCollection "Answer whether the species of the receiver is the same as otherCollection's species, and the receiver's size is the same as otherCollection's size, and each of the receiver's elements equal the corresponding element of otherCollection" | size index | (size _ self size) = otherCollection size ifFalse: [^false]. self species == otherCollection species ifFalse: [^false]. index _ 0. [(index _ index + 1) <= size] whileTrue: [(self at: index) = (otherCollection at: index) ifFalse: [^false]]. ^true! !!SequenceableCollection methodsFor: 'accessing'!atAll: anInterval put: anObject "Put anObject at every index specified by the integer elements of anInterval." anInterval do: [:index | self at: index put: anObject]!atAllPut: anObject "Put anObject at every one of the receiver's indices." | index size | index _ 0. size _ self size. [(index _ index + 1) <= size] whileTrue: [self at: index put: anObject]!first "Answer the first element of the receiver. Create an error if the receiver contains no elements." self emptyCheck. ^self at: 1!indexOf: anElement "Answer the index of anElement within the receiver. If the receiver does not contain anElement, answer 0." ^self indexOf: anElement ifAbsent: [0]!indexOf: anElement ifAbsent: exceptionBlock "Answer the index of anElement within the receiver. If the receiver does not contain anElement, answer the result of evaluating the exceptionBlock." (1 to: self size) do: [:i | (self at: i) = anElement ifTrue: [^i]]. ^exceptionBlock value!indexOfSubCollection: aSubCollection startingAt: anIndex "Answer the index of the receiver's first element, such that that element equals the first element of aSubCollection, and the next elements equal the rest of the elements of aSubCollection. Begin the search at element anIndex of the receiver. If no such match is found, answer 0." ^self indexOfSubCollection: aSubCollection startingAt: anIndex ifAbsent: [0]!indexOfSubCollection: aSubCollection startingAt: anIndex ifAbsent: exceptionBlock "Answer the index of the receiver's first element, such that that element equals the first element of aSubCollection, and the next elements equal the rest of the elements of aSubCollection. Begin the search at element anIndex of the receiver. If no such match is found, answer the result of evaluating exceptionBlock." | firstElement eq | aSubCollection size = 0 ifTrue: [^exceptionBlock value]. firstElement _ aSubCollection at: 1. anIndex to: self size - aSubCollection size + 1 do: [:i | eq _ true. (self at: i) = firstElement ifTrue: [1 to: aSubCollection size do: [:index | (self at: i + index - 1) = (aSubCollection at: index) ifFalse: [eq _ false]]. eq ifTrue: [^i]]]. ^exceptionBlock value!last "Answer the last element of the receiver. Create an error if the receiver contains no elements." self emptyCheck. ^self at: self size!replaceFrom: start to: stop with: replacement "This destructively replaces elements from start to stop in the receiver. Answer the receiver itself. Use copyReplaceFrom:to:with: for insertion/deletion which may alter the size of the result." replacement size = (stop - start + 1) ifFalse: [self error: 'Size of replacement doesnt match']. ^self replaceFrom: start to: stop with: replacement startingAt: 1!replaceFrom: start to: stop with: replacement startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the collection, replacement. Answer the receiver. No range checks are performed - this may be primitively implemented." | index repOff | repOff _ repStart - start. index _ start - 1. [(index _ index + 1) <= stop] whileTrue: [self at: index put: (replacement at: repOff + index)]!size self subclassResponsibility! !!SequenceableCollection methodsFor: 'adding'!grow "The receiver becomes bigger--this is not a copy of the receiver, so all shared references survive." | newArray | newArray _ self species new: self size + self growSize. newArray replaceFrom: 1 to: self size with: self. ^self become: newArray! !!SequenceableCollection methodsFor: 'removing'!remove: oldObject ifAbsent: anExceptionBlock "SequencableCollections cannot implement removing." self shouldNotImplement! !!SequenceableCollection methodsFor: 'copying'!, aSequenceableCollection "Answer with a copy of the receiver concatenated with the argument, a SequencableCollection." ^self copyReplaceFrom: self size + 1 to: self size with: aSequenceableCollection!copyFrom: start to: stop "Answer a copy of a subset of the receiver, starting from element at index start until element at index stop." | newSize | newSize _ stop - start + 1. ^(self species new: newSize) replaceFrom: 1 to: newSize with: self startingAt: start!copyReplaceAll: oldSubstring with: newSubstring "Answer a copy of the receiver in which all occurrances of oldSubstring have been replaced by newSubstring." | aString startSearch currentIndex | aString _ self. startSearch _ 1. [(currentIndex _ aString indexOfSubCollection: oldSubstring startingAt: startSearch) > 0] whileTrue: [aString _ aString copyReplaceFrom: currentIndex to: currentIndex + oldSubstring size - 1 with: newSubstring. startSearch _ currentIndex + newSubstring size]. ^aString "'How noww brown cowow?' copyReplaceAll: 'ow' with: 'ello'"!copyReplaceFrom: start to: stop with: replacementCollection "Answer a copy of the receiver satisfying the following conditions: If stop is less than start, then this is an insertion; stop should be exactly start-1, start = 1 means insert before the first character, start = size+1 means append after last character. Otherwise, this is a replacement; start and stop have to be within the receiver's bounds." | newSequenceableCollection newSize endReplacement | newSize _ self size - (stop - start + 1) + replacementCollection size. endReplacement _ start - 1 + replacementCollection size. newSequenceableCollection _ self species new: newSize. newSequenceableCollection replaceFrom: 1 to: start - 1 with: self startingAt: 1. newSequenceableCollection replaceFrom: start to: endReplacement with: replacementCollection startingAt: 1. newSequenceableCollection replaceFrom: endReplacement + 1 to: newSize with: self startingAt: stop + 1. ^newSequenceableCollection!copyWith: newElement "Answer a copy of the receiver that is 1 bigger than the receiver and has newElement at the last element." | newIC | newIC _ self species new: self size + 1. newIC replaceFrom: 1 to: self size with: self startingAt: 1. newIC at: newIC size put: newElement. ^newIC!copyWithout: oldElement "Answer a copy of the receiver in which all occurrences of oldElement have been left out." | aStream | aStream _ WriteStream on: (self species new: self size). self do: [:each | oldElement = each ifFalse: [aStream nextPut: each]]. ^aStream contents!shallowCopy ^self copyFrom: 1 to: self size! !!SequenceableCollection methodsFor: 'enumerating'!collect: aBlock | aStream index length | aStream _ WriteStream on: (self species new: self size). index _ 0. length _ self size. [(index _ index + 1) <= length] whileTrue: [aStream nextPut: (aBlock value: (self at: index))]. ^aStream contents!do: aBlock | index length | index _ 0. length _ self size. [(index _ index + 1) <= length] whileTrue: [aBlock value: (self at: index)]!findFirst: aBlock "Return the index of my first element for which aBlock evaluates as true." | index | index _ 0. [(index _ index + 1) <= self size] whileTrue: [(aBlock value: (self at: index)) ifTrue: [^index]]. ^ 0!findLast: aBlock "Return the index of my last element for which aBlock evaluates as true." | index | index _ self size + 1. [(index _ index - 1) >= 1] whileTrue: [(aBlock value: (self at: index)) ifTrue: [^index]]. ^ 0!reverse "Answer with a new collection like me with its elements in the opposite order." | aStream index length | aStream _ WriteStream on: (self species new: self size). index _ self size + 1. [(index _ index - 1) > 0] whileTrue: [aStream nextPut: (self at: index)]. ^aStream contents!reverseDo: aBlock "Evaluate aBlock with each of the receiver's elements as the argument, starting with the last element and taking each in sequence up to the first. For SequenceableCollections, this is the reverse of the enumeration in do:." self size to: 1 by: -1 do: [:index | aBlock value: (self at: index)]!select: aBlock | aStream index length | aStream _ WriteStream on: (self species new: self size). index _ 0. length _ self size. [(index _ index + 1) <= length] whileTrue: [(aBlock value: (self at: index)) ifTrue: [aStream nextPut: (self at: index)]]. ^aStream contents!with: aSequenceableCollection do: aBlock "Evaluate aBlock with each of the receiver's elements along with the corresponding element from aSequencableCollection." | otherCollection | self size ~= aSequenceableCollection size ifTrue: [^self errorNoMatch]. otherCollection _ ReadStream on: aSequenceableCollection. self do: [:each | aBlock value: each value: otherCollection next]! !!SequenceableCollection methodsFor: 'converting'!asArray "Answer a new instance of Array whose elements are the elements of the receiver, in the same order." | newArray | newArray _ Array new: self size. 1 to: self size do: [:index | newArray at: index put: (self at: index)]. ^newArray!mappedBy: aSequenceableCollection "Answer a new instance of MappedCollection whose contents is the receiver and whose map is the argument, aSequencableCollection." ^(MappedCollection collection: self map: aSequenceableCollection) contents! !!SequenceableCollection methodsFor: 'private'!errorOutOfBounds self error: 'indices are out of bounds'!swap: oneIndex with: anotherIndex "Move the element at oneIndex to anotherIndex, and vice-versa." | element | element _ self at: oneIndex. self at: oneIndex put: (self at: anotherIndex). self at: anotherIndex put: element! ! Collection variableSubclass: #Set instanceVariableNames: 'tally ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Unordered'!Set comment: 'I am an unordered collection of elements that are not duplicated in me.'!!Set methodsFor: 'accessing'!at: index self errorNotKeyed!at: index put: anObject self errorNotKeyed!size ^tally! !!Set methodsFor: 'testing'!includes: anObject ^(self basicAt: (self findElementOrNil: anObject)) ~~ nil!occurrencesOf: anObject (self includes: anObject) ifTrue: [^1] ifFalse: [^0]! !!Set methodsFor: 'adding'!add: newObject | index | newObject == nil ifTrue: [^newObject]. index _ self findElementOrNil: newObject. (self basicAt: index) == nil ifTrue: [self atNewIndex: index put: newObject]. ^newObject!grow "The receiver becomes twice as big--this is not a copy of the receiver, so all shared references survive." | newSelf | newSelf _ self species new: self basicSize + self growSize. self do: [:each | newSelf noCheckAdd: each]. self become: newSelf! !!Set methodsFor: 'removing'!remove: oldObject ifAbsent: aBlock | index | index _ self find: oldObject ifAbsent: [^aBlock value]. self basicAt: index put: nil. tally _ tally - 1. self fixCollisionsFrom: index. ^oldObject! !!Set methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Collect the resulting values into another Set. Answer the new Set. We override the general method, so that we make a big enough set and avoid growing. " | newSet size index element | tally = 0 ifTrue: [^Set new: 2]. newSet _ Set new: (size _ self basicSize). index _ 0. [(index _ index + 1) <= size] whileTrue: [(element _ self basicAt: index) == nil ifFalse: [newSet add: (aBlock value: element)]]. ^newSet!do: aBlock tally = 0 ifTrue: [^self]. 1 to: self basicSize do: [:index | (self basicAt: index) == nil ifFalse: [aBlock value: (self basicAt: index)]]! !!Set methodsFor: 'private'!atNewIndex: index put: anObject self basicAt: index put: anObject. tally _ tally + 1. self fullCheck!find: anObject ifAbsent: aBlock | index | index _ self findElementOrNil: anObject. (self basicAt: index) == nil ifTrue: [^aBlock value] ifFalse: [^index]!findElementOrNil: anObject | index length probe pass | length _ self basicSize. pass _ 1. index _ anObject hash \\ length + 1. [(probe _ self basicAt: index) == nil or: [probe = anObject]] whileFalse: [(index _ index + 1) > length ifTrue: [index _ 1. pass _ pass + 1. pass > 2 ifTrue: [^self grow findElementOrNil: anObject]]]. ^index!fixCollisionsFrom: index | myLength oldIndex nextIndex nextObject | oldIndex _ index. myLength _ self basicSize. [oldIndex _ oldIndex \\ myLength + 1. nextObject _ self basicAt: oldIndex. nextObject == nil] whileFalse: [nextIndex _ self findElementOrNil: nextObject. nextIndex = oldIndex ifFalse: [self basicAt: nextIndex put: nextObject. self basicAt: oldIndex put: nil]]!fullCheck self basicSize - self size <= (self basicSize // 4) ifTrue: [self grow]!noCheckAdd: anObject self basicAt: (self findElementOrNil: anObject) put: anObject. tally _ tally + 1!rehash | newSelf | newSelf _ self species new: self basicSize. self do: [:each | newSelf noCheckAdd: each]. self become: newSelf!setTally tally _ 0!swap: oneElement with: otherElement | save | save _ self basicAt: oneElement. self basicAt: oneElement put: (self basicAt: otherElement). self basicAt: otherElement put: save! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Set class instanceVariableNames: ''!!Set class methodsFor: 'instance creation'!new ^self new: 2!new: anInteger ^(super new: (anInteger max: 1)) setTally! ! Object subclass: #SharedQueue instanceVariableNames: 'contentsArray readPosition writePosition accessProtect readSynch ' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Processes'!SharedQueue comment: 'I provide synchronized communication of arbitrary objects between Processes. An object is sent by sending me the message nextPut: and received by sending me the message next. If no object has been sent when a next message is sent, the Process requesting the object will be suspended until one is sent.'!!SharedQueue methodsFor: 'initialize-release'!release contentsArray _ nil! !!SharedQueue methodsFor: 'accessing'!next "Answer the object that was sent through the receiver first and has not yet been received by anyone. If no object has been sent, suspend the requesting process until one is." | value | readSynch wait. accessProtect critical: [readPosition = writePosition ifTrue: [self error: 'Error in SharedQueue synchronization'. value _ nil] ifFalse: [value _ contentsArray at: readPosition. contentsArray at: readPosition put: nil. readPosition _ readPosition + 1]]. ^value!nextPut: value "Send value through the receiver. If a Process has been suspended waiting to receive a value through the receiver, allow it to proceed." accessProtect critical: [writePosition > contentsArray size ifTrue: [self makeRoomAtEnd]. contentsArray at: writePosition put: value. writePosition _ writePosition + 1]. readSynch signal. ^value!peek "Answer the object that was sent through the receiver first and has not yet been received by anyone but do not remove it from the receiver. If no object has been sent, suspend the requesting process until one is." | value | accessProtect critical: [readPosition >= writePosition ifTrue: [readPosition _ 1. writePosition _ 1. value _ nil] ifFalse: [value _ contentsArray at: readPosition]]. ^value!size "Answer the number of objects that have been sent through the receiver and not yet received by anyone." ^writePosition - readPosition! !!SharedQueue methodsFor: 'testing'!isEmpty "Answer whether any objects have been sent through the receiver and not yet received by anyone." ^readPosition = writePosition! !!SharedQueue methodsFor: 'private'!init: size contentsArray _ Array new: size. readPosition _ 1. writePosition _ 1. accessProtect _ Semaphore forMutualExclusion. readSynch _ Semaphore new!makeRoomAtEnd | contentsSize | readPosition = 1 ifTrue: [contentsArray grow] ifFalse: [contentsSize _ writePosition - readPosition. 1 to: contentsSize do: [:index | contentsArray at: index put: (contentsArray at: index + readPosition - 1)]. readPosition _ 1. writePosition _ contentsSize + 1]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SharedQueue class instanceVariableNames: ''!!SharedQueue class methodsFor: 'instance creation'!new "Answer a new instance of SharedQueue that has 10 elements." ^self new: 10!new: anInteger ^super new init: anInteger! ! Integer subclass: #SmallInteger instanceVariableNames: '' classVariableNames: 'Digitbuffer ' poolDictionaries: '' category: 'Numeric-Numbers'!SmallInteger comment:'SmallIntegers are optimized for the interpreter, stored in two-s complement form. The allowable range is from minVal to maxVal.'!!SmallInteger methodsFor: 'arithmetic'!* aNumber "Multiply the receiver by the argument and answer with the result if it is a SmallInterger. Fail if the argument or the result is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 9> self = 0 ifTrue: [^0]. "This eliminates the need for a self=0 check in LargeInteger *" ^super * aNumber!+ aNumber "Add the receiver to the argument and answer with the result if it is a SmallInterger. Fail if the argument or the result is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 1> ^super + aNumber!- aNumber "Subtract the argument from the receiver and answer with the result if it is a SmallInterger. Fail if the argument or the result is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 2> ^super - aNumber!/ aNumber "This primitive (for /) divides the receiver by the argument and returns the result if the division is exact. Fail if the result is not a whole integer. Fail if the argument is 0 or is not a SmallInteger. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 10> aNumber = 0 ifTrue: [^self error: 'division by 0']. (aNumber isMemberOf: SmallInteger) ifTrue: [^(Fraction numerator: self denominator: aNumber) reduced] ifFalse: [^super / aNumber]!// aNumber "Divide the receiver by the argument and answer with the result. Round the result down towards negative infinity to make it a whole integer. Fail if the argument is 0 or is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 12> ^super // aNumber"Do with quo: if primitive fails"!quo: aNumber "Divide the receiver by the argument and answer with the result. Round the result down towards zero to make it a whole integer. Fail if the argument is 0 or is not a SmallInteger. Optional. See Object documentation whatIsAPrimitive." <primitive: 13> aNumber = 0 ifTrue: [^self error: 'Attempt to divide by zero']. (aNumber isMemberOf: SmallInteger) ifTrue: [self primitiveFailed] ifFalse: [^super quo: aNumber]!\\ aNumber "Take the receiver modulo the argument. The result is the remainder rounded towards negative infinity, of the receiver divided by the argument. Fail if the argument is 0 or is not a SmallInteger. Optional. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 11> ^super \\ aNumber"Do with // if primitive fails"! !!SmallInteger methodsFor: 'bit manipulation'!bitAnd: arg "Logical AND the twos-complement representation of the receiver with the argument and answer with the result. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 14> ^arg bitAnd: self!bitOr: arg "Logical OR the twos-complement representation of the receiver with the argument and answer with the result. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 15> ^arg bitOr: self!bitShift: arg "Answers with a SmallInteger whose value (in twos-complement representation) is the receiver's value (in twos-complement representation) shifted left by the number of bits indicated by the argument. Negative arguments shift right. Zeros are shifted in from the right in left shifts. The sign bit is extended in right shifts. Fail if the result cannot be represented as a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 17> ^super bitShift: arg!bitXor: arg "Exclusive OR the twos-complement representation of the receiver with the argument and answer with the result. Fail if the argument is not a SmallInteger. Essential. See Object documentation whatIsAPrimitive." <primitive: 16> ^arg bitXor: self!highBit | i bit | self < 0 ifTrue: [^self error: 'highBit is not defined for negative numbers']. self = 0 ifTrue: [^0]. i _ 1. bit _ 1. [self > bit] whileTrue: [i _ i + 1. bit _ bit + bit + 1]. ^i! !!SmallInteger methodsFor: 'testing'!even ^(self bitAnd: 1) = 0!odd ^(self bitAnd: 1) = 1! !!SmallInteger methodsFor: 'comparing'!< aNumber "Compare the receiver with the argument and answer with true if the receiver is less than the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 3> ^super < aNumber!<= aNumber "Compare the receiver with the argument and answer true if the receiver is less than or equal to the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Optional. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 5> ^super <= aNumber!= aNumber "Compare the receiver with the argument and answer true if the receiver is equal to the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 7> ^super = aNumber!> aNumber "Compare the receiver with the argument and answer true if the receiver is greater than the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 4> ^super > aNumber!>= aNumber "Compare the receiver with the argument and answer true if the receiver is greater than or equal to the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Optional. No Lookup. See Object documentation whatIsAPrimitive." <primitive: 6> ^super >= aNumber!hash ^self!hashMappedBy: map "My hash is independent of my oop" ^ self hash!~= aNumber "Compare the receiver with the argument and answer true if the receiver is not equal to the argument. Otherwise answer false. Fail if the argument is not a SmallInteger. Essential. No Lookup. See Object documentation whatIsAPrimitive. " <primitive: 8> ^super ~= aNumber! !!SmallInteger methodsFor: 'copying'!deepCopy!shallowCopy! !!SmallInteger methodsFor: 'coercing'!coerce: n ^n truncated!generality ^20! !!SmallInteger methodsFor: 'converting'!asFloat "Create and answer an instance of Float whose value is the value of the receiver. Essential. See Object documentation whatIsAPrimitive." <primitive: 40> self primitiveFailed! !!SmallInteger methodsFor: 'printing'!printOn: aStream base: b | i x | (x _ self) < 0 ifTrue: [aStream nextPut: $-. x _ self negated]. i _ 0. [x >= b] whileTrue: [Digitbuffer at: (i _ i + 1) put: x \\ b. x _ x // b]. Digitbuffer at: (i _ i + 1) put: x. [i > 0] whileTrue: [aStream nextPut: (Character digitValue: (Digitbuffer at: i)). i _ i - 1]! !!SmallInteger methodsFor: 'system primitives'!asObject "This is the inverse of Object.asOop; look there for details. See also Object documentation whatIsAPrimitive." <primitive: 76> ^self primitiveFailed!asOop "Answer an integer which is unique to me, consistent with Object.asOop. See Object.asOop for detailed documentation" self >= 0 ifTrue: [^ 32768 + self] "0...16K-1 --> 32K...48K-1" ifFalse: [^ 65536 + self] "-16k...-1 --> 48K...64K-1"!digitAt: n "Answer the value of an apparent indexable field. This is provided for compatibility with LargeInteger." n = 1 ifTrue: ["Negate carefully in case I am SmallInteger minVal" self < 0 ifTrue: [^-256 - self bitAnd: 255]. ^self bitAnd: 255] ifFalse: [self < 0 ifTrue: [^(-256 - self bitShift: -8) + 1 digitAt: n - 1]. ^(self bitShift: 8 - (n bitShift: 3)) bitAnd: 255]!digitAt: n put: value "Fails. The digits of a small integer can not be modified." self error: 'You cant store in a SmallInteger'!digitLength "Answer with the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Included so that a SmallInteger can behave like a LargeInteger." | maxSize minValue size | (self < 16r100 and: [self > -16r100]) ifTrue: [^1]. maxSize _ SmallInteger maxBytes. maxSize = 2 ifTrue: [^2]. "Make things go fast for 16-bit systems" minValue _ -16r100. size _ 2. [size < maxSize] whileTrue: [minValue _ minValue bitShift: 8. (self <= (-1 - minValue) and: [self > minValue]) ifTrue: [^size]. size _ size + 1]. ^maxSize!instVarAt: i "small integer has to be specially handled" i = 1 ifTrue: [^self]. self error: 'argument too big for small integer instVarAt:'! !!SmallInteger methodsFor: 'private'!fromString: str radix: radix | maxdigit c val | maxdigit _ radix + (radix > 10 ifTrue: [55 - 1] ifFalse: [48 - 1]). val _ 0. 1 to: str size do: [:i | c _ str at: i. (c < 48 ifFalse: [c > maxdigit]) ifTrue: [^false]. val _ val * radix + (c <= 57 ifTrue: [c - 48] ifFalse: [c < 65 ifTrue: [^false]. c - 55])]. ^val!subtractOrFail: aNumber "This is a private copy of the subtraction primitive, used by SmallInteger class initialize to discover the correct value of SmallInteger minVal." <primitive: 2> ^nil! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SmallInteger class instanceVariableNames: 'minVal maxVal maxBits maxBytes '!!SmallInteger class methodsFor: 'class initialization'!initialize "Initialize the digit buffer, and discover the range of SmallIntegers on this system." | val bits | Digitbuffer _ Array new: 32. "Big enough for 32-bit systems" "Discover minVal and maxVal dynamically. Assume that minVal is -2^N and maxVal is (2^N)-1." val _ -1. bits _ 0. [(val subtractOrFail: 1) notNil] whileTrue: [val _ val + val. bits _ bits + 1]. minVal _ val. maxVal _ (val + 1) negated. maxBits _ bits. maxBytes _ bits + 7 // 8. "SmallInteger initialize."! !!SmallInteger class methodsFor: 'constants'!maxBits "Answer N such that maxVal is (2^N)-1." ^maxBits!maxBytes "Answer N such that maxVal < 256^N." ^maxBytes!maxVal "Answer the maximum value for a SmallInteger" ^maxVal!minVal "Answer the minimum value for a Small Integer" ^minVal! !!SmallInteger class methodsFor: 'documentation'!guideToDivision "Handy guide to the kinds of Integer division: / exact division, returns a fraction if result is not a whole integer. // returns an Integer, rounded towards negative infinity. \\ is modulo rounded towards negative infinity. quo: truncated division, rounded towards zero."! !!SmallInteger class methodsFor: 'instance creation'!new self error: 'SmallIntegers can only be created by performing arithmetic'! !SmallInteger initialize! OrderedCollection variableSubclass: #SortedCollection instanceVariableNames: 'sortBlock ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Sequenceable'!SortedCollection comment: 'I am an ordered collection of elements, sorted via the function sortBlock.'!!SortedCollection methodsFor: 'comparing'!= aSortedCollection "Answer true if my and aSortedCollection's species are the same, and if our blocks are the same, and if our elements are the same." self species = aSortedCollection species ifFalse: [^false]. sortBlock = aSortedCollection sortBlock ifTrue: [^super = aSortedCollection] ifFalse: [^false]! !!SortedCollection methodsFor: 'accessing'!at: anInteger put: anObject "Storing into a SortedCollection with at:put: is not allowed." self error: 'to add to a sorted collection, you must use add:'!sortBlock "Answer the blockContext which is the criterion for sorting elements of the receiver." ^sortBlock!sortBlock: aBlock "Make the argument, aBlock, be the criterion for ordering elements of the receiver." sortBlock _ aBlock fixTemps. "The sortBlock must copy its home context, so as to avoid circularities!!" "Therefore sortBlocks with side effects may not work right" self size > 0 ifTrue: [self reSort]! !!SortedCollection methodsFor: 'copying'!copy | newCollection | newCollection _ self species sortBlock: sortBlock. newCollection addAll: self. ^newCollection!copyEmpty "Answer a copy of the receiver without any of the receiver's elements." ^SortedCollection sortBlock: sortBlock! !!SortedCollection methodsFor: 'adding'!add: newObject | nextIndex | self isEmpty ifTrue: [^super addLast: newObject]. nextIndex _ self indexForInserting: newObject. self insert: newObject before: nextIndex. ^newObject!addAll: aCollection aCollection size > (self size // 3) ifTrue: ["Faster to add the new elements and resort" aCollection do: [:each | super addLast: each]. self reSort] ifFalse: ["Faster to add the elements individually in their proper places" aCollection do: [:each | self add: each]]!grow "We must duplicate this message from OrderedCollection so the addLast: won't cause an error." | newSelf | newSelf _ self species new: self size + self growSize. newSelf sortBlock: sortBlock. newSelf addAll: self. self become: newSelf! !!SortedCollection methodsFor: 'enumerating'!collect: aBlock "Evaluate aBlock with each of my elements as the argument. Collect the resulting values into an OrderedCollection Answer with the new collection. Override superclass in order to produce OrderedCollection instead of SortedCollection. " | newCollection | newCollection _ OrderedCollection new. self do: [:each | newCollection add: (aBlock value: each)]. ^newCollection! !!SortedCollection methodsFor: 'private'!indexForInserting: newObject | index low high | low _ firstIndex. high _ lastIndex. [index _ high + low // 2. low > high] whileFalse: [(sortBlock value: (self basicAt: index) value: newObject) ifTrue: [low _ index + 1] ifFalse: [high _ index - 1]]. ^low!reSort self sort: firstIndex to: lastIndex!sort: i to: j "Sort elements i through j of self to be nondescending according to sortBlock." | di dij dj tt ij k l n | "The prefix d means the data at that index." (n _ j + 1 - i) <= 1 ifTrue: [^self]. "Nothing to sort." "Sort di,dj." di _ self basicAt: i. dj _ self basicAt: j. (sortBlock value: di value: dj) "i.e., should di precede dj?" ifFalse: [self swap: i with: j. tt _ di. di _ dj. dj _ tt]. n > 2 ifTrue: "More than two elements." [ij _ (i + j) // 2. "ij is the midpoint of i and j." dij _ self basicAt: ij. "Sort di,dij,dj. Make dij be their median." (sortBlock value: di value: dij) "i.e. should di precede dij?" ifTrue: [(sortBlock value: dij value: dj) "i.e., should dij precede dj?" ifFalse: [self swap: j with: ij. dij _ dj]] ifFalse: "i.e. di should come after dij" [self swap: i with: ij. dij _ di]. n > 3 ifTrue: "More than three elements." ["Find k>i and l<j such that dk,dij,dl are in reverse order. Swap k and l. Repeat this procedure until k and l pass each other." k _ i. l _ j. [[l _ l - 1. k <= l and: [sortBlock value: dij value: (self basicAt: l)]] whileTrue. "i.e. while dl succeeds dij" [k _ k + 1. k <= l and: [sortBlock value: (self basicAt: k) value: dij]] whileTrue. "i.e. while dij succeeds dk" k <= l] whileTrue: [self swap: k with: l]. "Now l<k (either 1 or 2 less), and di through dl are all less than or equal to dk through dj. Sort those two segments." self sort: i to: l. self sort: k to: j]]!swap: i with: j | t | t _ self basicAt: i. self basicAt: i put: (self basicAt: j). self basicAt: j put: t! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SortedCollection class instanceVariableNames: ''!!SortedCollection class methodsFor: 'instance creation'!new: anInteger "The default sorting function is a <= comparison on elements." ^(super new: anInteger) sortBlock: [:x :y | x <= y]!sortBlock: aBlock "Answer a new instance of me such that its elements are sorted according to the criterion specified in aBlock." ^(super new: 10) sortBlock: aBlock! ! Path subclass: #Spline instanceVariableNames: 'derivatives ' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Paths'!Spline comment: 'This is a subclass of Path. Basically, a collection of Points through which a cubic spline curve is fitted.'!!Spline methodsFor: 'accessing'!derivativePointsAt: knot ^Array with: ((derivatives at: 1) at: knot) with: ((derivatives at: 2) at: knot) with: ((derivatives at: 3) at: knot)!isCyclic ^self size > 3 and: [self first = self last]! !!Spline methodsFor: 'displaying'!displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm "Method for display of a Spline curve approximated by straight line segments." | segment steps a b c d t | segment _ Line new. segment form: self form. segment beginPoint: self first. 1 to: self size-1 do: "for each knot" [:k | "taylor series coefficients" d _ self at: k. c _ (derivatives at: 1) at: k. b _ ((derivatives at: 2) at: k) / 2.0. a _ ((derivatives at: 3) at: k) / 6.0. "guess stepping parameter" steps _ ((derivatives at: 2) at: k) abs + ((derivatives at: 2) at: k+1) abs. steps _ 5 max: (steps x + steps y) // 100. 1 to: steps - 1 do: [:j | t _ j asFloat / steps. segment endPoint: a * t + b * t + c * t + d. segment displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm. segment beginPoint: segment endPoint]. segment endPoint: (self at: k+1). segment displayOn: aDisplayMedium at: aPoint clippingBox: clipRect rule: anInteger mask: aForm]!displayOn: aDisplayMedium transformation: aTransformation clippingBox: clipRect rule: anInteger mask: aForm "get the scaled and translated path of newKnots." | newKnots newSpline | newKnots _ aTransformation applyTo: self. newSpline _ Spline new. newKnots do: [:knot | newSpline add: knot]. newSpline form: self form. newSpline displayOn: aDisplayMedium at: 0 @ 0 clippingBox: clipRect rule: anInteger mask: aForm! !!Spline methodsFor: 'private'!computeCurve "Compute an array for the derivatives at each knot." | size extras values | size _ self size. self isCyclic ifTrue: "for cyclic curves" [extras _ 2. "add 2 extra points to each end." values _ Array new: 2*extras + size. 1 to: extras do: [:i | values at: i put: (self at: size-extras+i-1). values at: size+extras+i put: (self at: i+1)]. values replaceFrom: extras+1 to: extras+size with: collectionOfPoints] ifFalse: [extras _ 0. values _ collectionOfPoints]. derivatives _ Array new: 3. 1 to: 3 do: [:i | derivatives at: i put: (Array new: values size)]. self derivs: values first: (derivatives at: 1) second: (derivatives at: 2) third: (derivatives at: 3). extras > 0 ifTrue: "remove extra points" [1 to: 3 do: [:i | derivatives at: i put: ((derivatives at: i) copyFrom: extras+1 to: extras+size)]]!derivs: values first: first second: second third: third "Computes the first, second and third derivitives at each point in the array values." | size v b | size _ values size. size > 2 ifTrue: [v _ Array new: size. v at: 1 put: 4.0. b _ Array new: size. b at: 1 put: 6.0*(values first-((values at: 2)*2.0)+(values at: 3)). 2 to: size-2 do: [:i | v at: i put: 4.0-(1.0/(v at: i-1)). b at: i put: 6.0*((values at: i)-((values at: i+1)*2.0) +(values at: i+2))-((b at: i-1)/(v at: i-1))]. second at: size-1 put: (b at: size-2)/(v at: size-2). size-2 to: 2 by: -1 do: [:i | second at: i put: (b at: i-1)-(second at: i+1)/(v at: i-1)]]. second at: 1 put: 0.0 asPoint. second at: size put: 0.0 asPoint. 1 to: size-1 do: [:i | first at: i put: (values at: i+1)-(values at: i)-((second at: i)*2.0 +(second at: i+1)/6.0). third at: i put: (second at: i+1)-(second at: i)].! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Spline class instanceVariableNames: ''!!Spline class methodsFor: 'examples'!example "Designate points on the Path by clicking the red button. Terminate by pressing any other button. A curve will be displayed, through the selected points, using a square black form." | splineCurve aForm flag| aForm _ Form new extent: 8@8. aForm black. splineCurve _ Spline new. splineCurve form: aForm. flag _ true. [flag] whileTrue: [Sensor waitButton. Sensor redButtonPressed ifTrue: [splineCurve add: Sensor waitButton. Sensor waitNoButton. aForm displayOn: Display at: splineCurve last] ifFalse: [flag_false]]. splineCurve computeCurve. splineCurve isEmpty ifFalse: [splineCurve displayOn: Display. Sensor waitNoButton]. ^splineCurve "Spline example."! ! MouseMenuController subclass: #StandardSystemController instanceVariableNames: 'status ' classVariableNames: 'ScheduledBlueButtonMenu ScheduledBlueButtonMessages ' poolDictionaries: '' category: 'Interface-Support'!StandardSystemController comment:'I am a controller for StandardSystemViews, that is, those views that are at the top level of a project in the system user interface. I am a kind of MouseMenuController that creates a blue button menu for moving, framing, collapsing, and closing StandardSystemViews, and for selecting views under the view of my instance.Instance Variables: status <Symbol> condition, either #active--keep control as long as the cursor is inside the view if a button is pressed #inactive -- no longer in control, deEmphasize any highlighting #open -- visible on the screen #closed -- unschedule the instance from the project '!!StandardSystemController methodsFor: 'initialize-release'!initialize super initialize. status _ #inactive. self initializeBlueButtonMenu!initializeBlueButtonMenu "Initialize the blue button pop-up menu and corresponding array of messages for the receiver." self blueButtonMenu: ScheduledBlueButtonMenu blueButtonMessages: ScheduledBlueButtonMessages! !!StandardSystemController methodsFor: 'control defaults'!isControlActive ^status == #active and: [sensor anyButtonPressed ifTrue: [view containsPoint: sensor cursorPoint] ifFalse: [true]]! !!StandardSystemController methodsFor: 'basic control sequence'!controlInitialize view displayEmphasized. status _ #active!controlTerminate status == #closed ifTrue: [view ~~ nil ifTrue: [view release]. ScheduledControllers unschedule: self. ^self]. status == #inactive ifTrue: [view deEmphasize. ScheduledControllers pullBottomToTop. ^self]. view deEmphasize! !!StandardSystemController methodsFor: 'menu messages'!close "The receiver's view should be removed from the screen and from the collection of scheduled views." model changeRequest "check for changes in progress" ifFalse: [^self]. status _ #closed. view erase!collapse "Get the receiver's view to change to a collapsed view on the screen." view erase; collapse; display. self move.!expand "The receiver's view was collapsed; open it again and ask the user to designate its rectangular area." view erase. view expand. view resize. view displayEmphasized!menuMessageReceiver "Answer the object that should receive the message corresponding to a menu selection." ^ self!move "Ask the user to designate a new origan position for the recevier's view." | form | Sensor cursorPoint: view labelDisplayBox origin. view deEmphasize. form _ Form fromDisplay: (view labelDisplayBox). view erase. Cursor origin showWhile: [form follow: [Sensor cursorPoint] while: [Sensor noButtonPressed]]. view align: view labelDisplayBox origin with: sensor cursorPoint. view displayEmphasized.!under "Deactive the receiver's scheduled view and pass control to any view that might be positioned directly underneath it and the cursor." status _ #inactive! !!StandardSystemController methodsFor: 'scheduling'!closeAndUnschedule "Erase the receiver's view and remove it from the collection of scheduled controllers." status _ #closed. view erase. view release. ScheduledControllers unschedule: self!closeAndUnscheduleNoErase "Remove the scheduled view from the collection of scheduled controllers. Set its status to closed but do not erase." status _ #closed. view release. ScheduledControllers unschedule: self!open "Create an area on the screen in which the receiver's scheduled controller can be displayed. Make it the active controller." view resize. status _ #open. ScheduledControllers scheduleActive: self!openDisplayAt: aPoint "Create an area with origin aPoint in which the receiver's scheduled view can be displayed. If necessary, translate so the view is completely on the screen. Make it the active view." view align: view viewport center with: aPoint. view translateBy: (view displayBox amountToTranslateWithin: Display boundingBox). status _ #open. ScheduledControllers scheduleActive: self!openNoTerminate "Create an area in which the receiver's scheduled view can be displayed. Make it the active view. Do not terminate the currently active process." view resize. status _ #open. ScheduledControllers scheduleActiveNoTerminate: self!openNoTerminateDisplayAt: aPoint "Create an area with origin aPoint in which the receiver's scheduled view can be displayed. Make it the active view. Do not terminate the currently active process." view resizeMinimumCenteredAt: aPoint. status _ #open. ScheduledControllers scheduleActiveNoTerminate: self! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!StandardSystemController class instanceVariableNames: ''!!StandardSystemController class methodsFor: 'class initialization'!initialize "StandardSystemController initialize." ScheduledBlueButtonMenu _ PopUpMenu labels: 'undermoveframecollapseclose' lines: #(4 ). ScheduledBlueButtonMessages _ #(under move expand collapse close )! !!StandardSystemController class methodsFor: 'access'!ScheduledBlueButtonMenu ^ ScheduledBlueButtonMenu!ScheduledBlueButtonMessages ^ ScheduledBlueButtonMessages! !StandardSystemController initialize! View subclass: #StandardSystemView instanceVariableNames: 'labelFrame labelText isLabelComplemented savedSubViews minimumSize maximumSize ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Support'!StandardSystemView comment:'I represent a view that has a label above its top left corner. The text in the label identifies the kind of view. In addition to a label, I add control over the maximum and minimum size of the display box of my instance. My default controller is StandardSystemController. The elements of ScheduledControllers, the sole instance of ControlManager, usually contain controllers for instances of me.Instance Variables: labelFrame <Quadrangle> labelText <Paragraph> isLabelComplemented <Boolean> true if the label is complemented savedSubViews <Array> of Views minimumSize <Point> representing minimum width and height maximumSize <Point> representing maximum width and height '!!StandardSystemView methodsFor: 'initialize-release'!initialize super initialize. self insideColor: Form lightGray. labelFrame _ Quadrangle new. labelFrame region: (Rectangle origin: 0 @ 0 extent: 50 @ 20). labelFrame insideColor: Form white. labelFrame borderWidthLeft: 2 right: 2 top: 2 bottom: 0. self label: nil. isLabelComplemented _ false. minimumSize _ 50 @ 50. maximumSize _ Display extent!release self expand. super release! !!StandardSystemView methodsFor: 'testing'!containsPoint: aPoint ^(super containsPoint: aPoint) | (self labelDisplayBox containsPoint: aPoint)!isCollapsed "Answer whether the scheduled view is collapsed (true) or expanded (false)." ^savedSubViews ~~ nil! !!StandardSystemView methodsFor: 'label access'!deEmphasizeLabel "If the label is highlighted, reverse it." isLabelComplemented ifTrue: [self reverseLabel. isLabelComplemented _ false]!emphasizeLabel "Highlight the label." isLabelComplemented ifFalse: [self reverseLabel. isLabelComplemented _ true]!label "Answer the string that appears in the receiver's label." ^labelText isNil ifTrue: [^''] ifFalse: [labelText asString]!label: aString "Set aString to be the receiver's label." aString == nil ifTrue: [labelText _ nil. labelFrame region: (0 @ 0 extent: 0 @ 0)] ifFalse: [labelText _ aString asParagraph. labelFrame region: (0 @ 0 extent: labelText boundingBox width + 8 @ 20)]!labelDisplayBox "Answer the rectangle that borders the visible parts of the receiver's label on the display screen." ^labelFrame align: (self isCollapsed ifTrue: [labelFrame topLeft] ifFalse: [labelFrame bottomLeft]) with: self displayBox topLeft!labelFrame "Answer the bounding box for the label." ^labelFrame!labelFrame: aQuadrangle "Set the bounding box for the label to be aQuadrangle." labelFrame _ aQuadrangle! !!StandardSystemView methodsFor: 'size'!maximumSize "Answer a point representing the maximum width and height of the receiver." ^maximumSize!maximumSize: aPoint "Set the argument, aPoint, to be the maximum width and height of the receiver." maximumSize _ aPoint!minimumSize "Answer a point representing the minimum width and height of the receiver." ^minimumSize!minimumSize: aPoint "Set the argument, aPoint, to be the minimum width and height of the receiver." minimumSize _ aPoint! !!StandardSystemView methodsFor: 'framing'!collapse "If the receiver is not already collapsed, change its view to be that of its label only." self isCollapsed ifFalse: [savedSubViews _ subViews. self resetSubViews. labelText isNil ifTrue: [self label: 'No Label']. self window: (self inverseDisplayTransform: self labelDisplayBox region). labelFrame borderWidthLeft: 2 right: 2 top: 2 bottom: 2]!erase "Clear the display box of the receiver to be gray, as in the screen background." self clear: Form gray. Display fill: self labelDisplayBox region mask: Form gray. isLabelComplemented _ false!expand "If the receiver is collapsed, change its view to be that of all of its subviews, not its label alone." self isCollapsed ifTrue: [subViews _ savedSubViews. self window: self defaultWindow. labelFrame borderWidthLeft: 2 right: 2 top: 2 bottom: 0. savedSubViews _ nil]!getFrame "Ask the user to designate a rectangular area in which the receiver should be displayed." | origin minimumCorner maximumCorner frame corner | Sensor waitNoButton. Cursor origin showWhile: [origin _ Sensor cursorPoint. [Sensor redButtonPressed] whileFalse: [Processor yield. origin _ Sensor cursorPoint]]. minimumCorner _ origin + self minimumSize. maximumCorner _ origin + self maximumSize. frame _ origin corner: minimumCorner. Display fill: frame rule: Form reverse mask: Form gray. Display fill: frame rule: Form reverse mask: Form gray. minimumCorner = maximumCorner ifFalse: [Sensor cursorPoint: minimumCorner. Cursor corner showWhile: [corner _ Sensor cursorPoint. [Sensor redButtonPressed] whileTrue: [Processor yield. frame _ origin corner: ((corner max: minimumCorner) min: maximumCorner). Display fill: frame rule: Form reverse mask: Form gray. Display fill: frame rule: Form reverse mask: Form gray. corner _ Sensor cursorPoint]]]. ^frame!resize "Determine the rectangular area for the receiver, adjusted to the minimum and maximum sizes." | aRectangle | aRectangle _ self getFrame. aRectangle _ aRectangle origin extent: ((aRectangle extent max: minimumSize) min: maximumSize). self window: self window viewport: aRectangle.!resizeMinimumCenteredAt: aPoint "Determine the rectangular area for the receiver, adjusted so that it is centered a position, aPoint." | aRectangle | aRectangle _ 0 @ 0 extent: self minimumSize. aRectangle _ aRectangle align: aRectangle center with: aPoint. self window: self window viewport: aRectangle! !!StandardSystemView methodsFor: 'controller access'!defaultControllerClass ^StandardSystemController! !!StandardSystemView methodsFor: 'displaying'!displayEmphasized "Display the receiver with the label highlighted to indicate that it is active." self display. self emphasize. self emphasizeLabel!displayView | clippingBox labelDisplayBox | clippingBox _ self clippingBox. labelDisplayBox _ self labelDisplayBox. (labelDisplayBox intersect: clippingBox) displayOn: Display. labelText isNil ifFalse: [labelText displayOn: Display at: (labelDisplayBox center - (labelText boundingBox center - labelText boundingBox topLeft)) clippingBox: clippingBox]! !!StandardSystemView methodsFor: 'deEmphasizing'!deEmphasizeView self deEmphasizeLabel! !!StandardSystemView methodsFor: 'clipping box access'!clippingBox "Answer the rectangular area in which the receiver can show its label." ^self isTopView ifTrue: [self labelDisplayBox] ifFalse: [super insetDisplayBox]! !!StandardSystemView methodsFor: 'private'!reverseLabel labelText isNil ifFalse: [Display reverse: self labelDisplayBox inside]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!StandardSystemView class instanceVariableNames: ''!!StandardSystemView class methodsFor: 'instance creation'!model: aModel label: labelText minimumSize: minimumSize | view | view _ self new. view model: aModel. view label: labelText. view minimumSize: minimumSize. view borderWidth: 1. ^view! ! Object subclass: #Stream instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Streams'!Stream comment: 'I am an abstract class representing objects that stream over a self typing data structure.'!!Stream methodsFor: 'accessing'!contents "Answer the contents of the receiver." self subclassResponsibility!next "Answer the next object in the receiver." self subclassResponsibility!next: anInteger "Answer an OrderedCollection of the next anInteger number of random numbers." | aCollection | aCollection _ OrderedCollection new. anInteger timesRepeat: [aCollection addLast: self next]. ^aCollection!next: anInteger put: anObject "Put anObject into the next anInteger elements of the receiver." anInteger timesRepeat: [self nextPut: anObject]. ^anObject!nextMatchFor: anObject "Gobble the next element and answer whether it is equal to anObject." ^anObject = self next!nextPut: anObject "Insert the argument, anObject, at the next position in the receiver. Answer anObject." self subclassResponsibility!nextPutAll: aCollection "Append the elements of aCollection onto the receiver. Answer aCollection." aCollection do: [:v | self nextPut: v]. ^aCollection! !!Stream methodsFor: 'testing'!atEnd "Answer whether the position is greater than or equal to the limit." self subclassResponsibility! !!Stream methodsFor: 'enumerating'!do: aBlock "Evaluate aBlock for each of the elements of the receiver." [self atEnd] whileFalse: [aBlock value: self next]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Stream class instanceVariableNames: ''!!Stream class methodsFor: 'instance creation'!new self error: 'Streams are created with on: and with:'! ! Object subclass: #StrikeFont instanceVariableNames: 'xTable glyphs name stopConditions type minAscii maxAscii maxWidth strikeLength ascent descent xOffset raster subscript superscript emphasis ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!StrikeFont comment:'Instance Variables: xTable <Array> Of left x-coordinate of character in glyphs. glyphs <Form> Containing bits representing the characters. name <String> Name of this font. stopConditions <Array> Of selectors to be performed in scanning text. type <Integer> Code for strike fonts files. minAscii, maxAscii <Integer> Giving range supported by this font. maxWidth <Integer> Width of widest char. Not presently used, but may be for font modification. strikeLength <Integer> Not used. ascent, descent <Integer> Max extent of chars above and below the baseline xOffset <Integer> For kerning (not presently used) raster <Integer> Specifies layout of the glyphs form subscript, superscript <Integer> Further vertical offset relative to baseline emphasis <Integer> code for synthetic bold, italic, underline, strike-outStrikeFonts are a compact encoding of a set of Forms corresponding to characters in the ASCII character set. All the forms are placed side by side in a large form whose height is the font height, and whose width is the sum of all the character widths. The xTable gives the left-x coordinates of the subForms corresponding to the characters.'!!StrikeFont methodsFor: 'accessing'!ascent "Answer the font's maximum extent of characters above the baseline." ^ascent!characterForm: character "Answer a Form copied out of the glyphs for this character." | characterForm ascii | ascii _ character asciiValue. ascii > maxAscii ifTrue: [ascii _maxAscii]. characterForm _ Form new extent: (self widthOf: character) @ self height. characterForm copyBits: (Rectangle origin: (xTable at: ascii + 1) @ 0 extent: (self widthOf: character) @ self height) from: glyphs at: 0 @ 0 clippingBox: characterForm boundingBox rule: Form over mask: Form black. ^characterForm!descent "Answer the font's maximum extent of characters below the baseline." ^descent!familySizeFace "Return an array with familyName <String> pointSize <Integer> faceCode <Integer>" | fontName firstDigit lastDigit | fontName_ name asUppercase. firstDigit _ fontName findFirst: [:char | char isDigit]. lastDigit _ fontName findLast: [:char | char isDigit]. ^Array with: (fontName copyFrom: 1 to: firstDigit-1) with: (Integer readFromString: (fontName copyFrom: firstDigit to: lastDigit)) with: (#('B' 'I' 'BI') indexOf: (fontName copyFrom: lastDigit+1 to: fontName size))" (1 to: 12) collect: [:x | (TextStyle default fontAt: x) familySizeFace] "!glyphs "Answer a Form containing the bits representing the characters of the receiver." ^glyphs!height "Answer the height of the font, total of maximum extents of characters above and below the baseline." ^self ascent + self descent!maxAscii "Answer the integer that is the last Ascii character value of the receiver." ^maxAscii!maxWidth "Answer the integer that is the width of the receiver's widest character." ^maxWidth!minAscii "Answer the integer that is the first Ascii character value of the receiver." ^minAscii!name "Answer the receiver's name." ^name!name: aString "Set the receiver's name." name _ aString.!raster "Answer an integer that specifies the layout of the glyphs' form." ^raster!stopConditions "Answer the array of selectors to be performed in scanning text made up of the receiver's characters." ^stopConditions!subscript "Answer an integer that is the further vertical offset relative to the baseline for positioning characters as subscripts." ^subscript!subscript: anInteger "Answer an integer that is the further vertical offset relative to the baseline for positioning characters as subscripts." subscript _ anInteger.!superscript "Answer an integer that is the further vertical offset relative to the baseline for positioning characters as superscripts." ^superscript!superscript: anInteger "Answer an integer that is the further vertical offset relative to the baseline for positioning characters as superscripts." superscript _ anInteger.!widthOf: aCharacter "Answer the width of the argument as a character in the receiver." | ascii | ascii _ (aCharacter asciiValue min: maxAscii + 1) max: minAscii. ^(xTable at: ascii + 2) - (xTable at: ascii + 1)!xTable "Answer an array of the left x-coordinate of characters in glyphs." ^xTable! !!StrikeFont methodsFor: 'testing'!checkCharacter: character "Answer a character that is within the ascii range of the receiver--either character or the last character in the receiver." | ascii | ascii _ character asciiValue. ((ascii < minAscii) or: [ascii > maxAscii]) ifTrue: [^maxAscii asCharacter] ifFalse: [^character]! !!StrikeFont methodsFor: 'displaying'!characters: anInterval in: sourceString displayAt: aPoint clippedBy: clippingRectangle rule: ruleInteger mask: aForm "Simple, slow, primitive method for displaying a line of characters. No wrap-around is handled." | ascii character characterForm | anInterval do: [:i | ascii _ (character _ sourceString at: i) asciiValue. (ascii < minAscii or: [ascii > maxAscii]) ifTrue: [character _ (ascii _ maxAscii) asCharacter]. characterForm _ self characterForm: character. characterForm displayOn: Display at: aPoint clippingBox: clippingRectangle rule: ruleInteger mask: aForm. aPoint x: aPoint x + (self widthOf: character)]. ^aPoint x!composeWord: aTextLineInterval in: sourceString beginningAt: xInteger "Non-primitive composition of a word -- add up widths of characters, add sum to beginning x and answer the resulting x. Similar to performance of scanning primitive, but without stop conditions." | character resultX | resultX _ xInteger. aTextLineInterval do: [:i | character _ sourceString at: i. resultX _ resultX + (self widthOf: character)]. ^resultX!displayLine: aString at: aPoint "Display the characters in aString, starting at position aPoint." self characters: (1 to: aString size) in: aString displayAt: aPoint clippedBy: Display boundingBox rule: Form over mask: Form black! !!StrikeFont methodsFor: 'emphasis'!emphasis "Answer the integer code for synthetic bold, itallic, underline, and strike-out." ^emphasis!emphasis: code "Set the integer code for synthetic bold, itallic, underline, and strike-out, where bold=1, itallic=2, underlined=4, struck out=8, subscript=16, superscript=32." emphasis _ code!emphasized: code "Answer a copy of the receiver with emphasis set to code." ^self copy emphasis: code + emphasis "TextStyle default fontAt: 9 put: ((TextStyle default fontAt: 1) emphasized: 4)"!emphasized: code named: aString "Answer a copy of the receiver with emphasis set to code." | copy | copy _ self copy emphasis: (code + emphasis). copy name: aString. ^copy "TextStyle default fontAt: 9 put: ((TextStyle default fontAt: 1) emphasized: 4 named: 'TimesRoman10i')"! !!StrikeFont methodsFor: 'printing'!printOn: aStream aStream nextPutAll: self class name, ' name ', name, ' emphasis '; print: emphasis; nextPut: Character cr.! !!StrikeFont methodsFor: 'private'!ascent: anInteger "Set the font's maximum extent of characters above the baseline." ascent _ anInteger.!glyphs: aForm "Set the Form containing the bits representing the characters of the receiver." glyphs _ aForm.! ! ArrayedCollection variableByteSubclass: #String instanceVariableNames: '' classVariableNames: 'StringBlter ' poolDictionaries: '' category: 'Collections-Text'!String comment: 'I am an indexed collection of Characters. I really store 8-bit bytes, but my access protocol translates between these and real Character instances.'!!String methodsFor: 'comparing'!< aString "Answer true if and only if the receiver collates before aString. The collation sequence is ascii with case differences ignored." ^(self compare: aString) = 1!<= aString "Answer true if and only if the receiver collates before aString or is the same as aString. The collation sequence is ascii with case differences ignored." ^(self compare: aString) <= 2!> aString "Answer true if and only if the receiver collates after aString. The collation sequence is ascii with case differences ignored." ^(self compare: aString) = 3!>= aString "Answer true if and only if the receiver collates after aString or is the same as aString. The collation sequence is ascii with case differences ignored." ^(self compare: aString) >= 2!hash | l m | (l _ m _ self size) <= 2 ifTrue: [l = 2 ifTrue: [m _ 3] ifFalse: [l = 1 ifTrue: [^((self at: 1) asciiValue bitAnd: 127) * 106]. ^21845]]. ^(self at: 1) asciiValue * 48 + ((self at: (m - 1)) asciiValue + l)!hashMappedBy: map "My hash is independent of my oop" ^ self hash!match: text "Answer whether text matches the pattern in the receiver. Matching ignores upper/lower case differences. Where the receiver contains #, text may contain any single character. Where the receiver contains *, text may contain any sequence of characters." | pattern scanning p t back textStream startScan | pattern _ ReadStream on: self. textStream _ ReadStream on: text. scanning _ false. [pattern atEnd] whileFalse: [p _ pattern next. p = $* ifTrue: [pattern atEnd ifTrue: [^true]. scanning _ true. startScan _ pattern position] ifFalse: [textStream atEnd ifTrue: [^false]. t _ textStream next. (t asUppercase = p asUppercase or: [p = $#]) ifFalse: [scanning ifFalse: [^false]. back _ startScan - pattern position. pattern skip: back. textStream skip: back + 1]]. (scanning and: [pattern atEnd and: [textStream atEnd not]]) ifTrue: [back _ startScan - pattern position. pattern skip: back. textStream skip: back + 1] ]. ^textStream atEnd " Examples: 'xyz' match: 'Xyz' true 'x#z' match: 'x@z' true 'x*z' match: 'x whyNot? z' true '*x' match: 'xx' true "!sameAs: aString "Answer whether the receiver collates precisely with aString. The collation sequence is ascii with case differences ignored." ^(self compare: aString) = 2!spellAgainst: aString "Answer an integer between 0 and 100 indicating how similar the argument is to the receiver. No case conversion is done." | i1 i2 size1 size2 score maxLen | size1 _ self size. size2 _ aString size. maxLen _ size1 max: size2. score _ 0. i1 _ i2 _ 1. [i1 <= size1 and: [i2 <= size2]] whileTrue: [(self at: i1) = (aString at: i2) ifTrue: [score _ score+1. "match" i1 _ i1+1. "advance both" i2 _ i2+1] ifFalse: [(i2 < size2 and: [(self at: i1) = (aString at: i2+1)]) ifTrue: [i2 _ i2+1] "skip in other" ifFalse: [(i1 < size1 and: [(self at: i1+1) = (aString at: i2)]) ifTrue: [i1 _ i1+1] "skip in self" ifFalse: [i1 _ i1+1. "miss - advance both" i2 _ i2+1] ] ] ]. score = maxLen ifTrue: [^100] ifFalse: [^100*score//maxLen] " 'Smalltalk' spellAgainst: 'Smalltlak' "! !!String methodsFor: 'accessing'!at: index "Answer the Character stored in the field of the receiver indexed by the argument. Fail if the index argument is not an Integer or is out of bounds. Essential. See Object documentation whatIsAPrimitive." <primitive: 63> ^Character value: (super at: index)!at: index put: aCharacter "Store the Character in the field of the receiver indicated by the index. Fail if the index is not an Integer or is out of bounds, or if the argument is not a Character. Essential. See Object documentation whatIsAPrimitive." <primitive: 64> (aCharacter isKindOf: Character) ifTrue: [self errorNonIntegerIndex] ifFalse: [self error: 'Strings only store Characters']!basicAt: index "Answer the Character stored in the field of the receiver indexed by the argument. Fail if the index argument is not an Integer or is out of bounds. Essential. See Object documentation whatIsAPrimitive." <primitive: 63> ^Character value: (super at: index)!basicAt: index put: aCharacter "Store the Character in the field of the receiver indicated by the index. Fail if the index is not an Integer or is out of bounds, or if the argument is not a Character. Essential. See Object documentation whatIsAPrimitive." <primitive: 64> (aCharacter isKindOf: Character) ifTrue: [self errorNonIntegerIndex] ifFalse: [self error: 'Strings only store Characters']!findString: subString startingAt: start "Answer the index of subString within the receiver, starting at start. If the receiver does not contain subString, answer 0." | aCharacter index | subString isEmpty ifTrue: [^0]. aCharacter _ subString first. start to: self size - subString size + 1 do: [:startIndex | (self at: startIndex) = aCharacter ifTrue: [index _ 1. [(self at: startIndex+index-1) = (subString at: index)] whileTrue: [index = subString size ifTrue: [^startIndex]. index _ index+1]]]. ^0!replaceFrom: start to: stop with: replacement startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the collection, replacement. Answer the receiver." (replacement isKindOf: String) ifTrue: [self primReplaceFrom: start to: stop with: replacement startingAt: repStart] ifFalse: [super replaceFrom: start to: stop with: replacement startingAt: repStart]!replaceFrom: start to: stop withByteArray: aByteArray startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the byte array, aByteArray. Answer the receiver." | index repOff characterTable | <primitive: 105> repOff _ repStart - start. characterTable _ Character characterTable. "in-line asCharacter for speed" index _ start - 1. [(index _ index + 1) <= stop] whileTrue: [self at: index put: (characterTable at: (aByteArray at: repOff + index)+1)]!size "Answer the number of indexable fields in the receiver. This value is the same as the largest legal subscript. Essential. See Object documentation whatIsAPrimitive." <primitive: 62> ^self basicSize!string "Answer the receiver itself. This is for compatibility with other text classes." ^self! !!String methodsFor: 'copying'!copyUpTo: aCharacter "Answer a copy of the receiver from index 1 to the first occurrence of aCharacter, non-inclusive." | index | index _ self indexOf: aCharacter ifAbsent: [^self]. ^self copyFrom: 1 to: index-1!deepCopy "DeepCopy would otherwise mean make a copy of the character; since characters are unique, just return a shallowCopy." ^self shallowCopy! !!String methodsFor: 'printing'!isLiteral ^true!printOn: aStream "Print inside string quotes, doubling inbedded quotes." ^self storeOn: aStream!storeOn: aStream "Print inside string quotes, doubling inbedded quotes." | i length x | aStream nextPut: $'. i _ 0. length _ self size. [(i _ i + 1) <= length] whileTrue: [aStream nextPut: (x _ self at: i). x == $' ifTrue: [aStream nextPut: x]]. "embedded quotes get doubled" aStream nextPut: $'! !!String methodsFor: 'converting'!asDisplayText "Answer a DisplayText whose text string is the receiver." ^DisplayText text: self asText!asFileName "Answer a string made up from the receiver that is an acceptable file name." ^Disk checkName: self fixErrors: true!asLowercase "Answer a string made up from the receiver whose characters are all lowercase." | aStream | aStream _ WriteStream on: (String new: self size). self do: [:aCharacter | aStream nextPut: aCharacter asLowercase]. ^aStream contents!asNumber "Answer the number created by interpreting the receiver as the string representation of a number." ^Number readFromString: self!asParagraph "Answer a Paragraph whose text string is the receiver." ^Paragraph withText: self asText!asString "Answer the receiver itself." ^self!asSymbol "Answer the unique symbol whose characters are the characters of the string." ^Symbol intern: self!asText "Answer a Text whose string is the receiver." ^Text fromString: self!asUppercase "Answer a string made up from the receiver whose characters are all uppercase." | aStream | aStream _ WriteStream on: (String new: self size). self do: [:aCharacter | aStream nextPut: aCharacter asUppercase]. ^aStream contents!contractTo: charCount "Shorten by ellipsis if too long" | half | self size > charCount ifTrue: [half _ charCount // 2. ^ self copyReplaceFrom: half to: self size - (charCount-half) + 2 with: '...'] " 'antidisestablishmentarianism' contractTo: 10 'anti...ism' "!oldRunDecodeOn: decodedStream "Decodes strings encoded by the message oldRunEncoded. Output is written onto decodedStream" | index size byte count bitsValue | index _ 0. size _ self size. [index>=size] whileFalse: [byte _ (self at: (index _ index+1)). byte asInteger == 0 ifTrue: [count _ (self at: (index _ index+1)) asInteger. count = 0 ifTrue: "<0> <0> means one zero byte" [decodedStream nextPut: byte] ifFalse: "<0> <count> <bitsValue> means count bytes = bitsValue" [bitsValue _ (self at: (index _ index+1)). [(count _ count-1)>=0] whileTrue: [decodedStream nextPut: bitsValue]]] ifFalse: "<nonZero> means one nonZero byte" [decodedStream nextPut: byte]]. ^ decodedStream contents!oldRunEncoded "Returns a string with equal consecutive bytes encoded as <0> <count> <val> Single zeroes are encoded as <0> <0> " | stream count previousByte byte | stream _ WriteStream on: (String new: self size). count _ 0. previousByte _ self at: 1. 2 to: self size do: [:i | byte _ self at: i. (byte = previousByte and: [count < 255]) ifTrue: [count _ count + 1] ifFalse: [count > 0 ifTrue: [stream nextPut: (Character value: 0); nextPut: (Character value: count+1); nextPut: previousByte. count _ 0] ifFalse: [stream nextPut: previousByte. previousByte asInteger = 0 ifTrue: [stream nextPut: previousByte]]. previousByte _ byte]]. count > 0 ifTrue: [stream nextPut: (Character value: 0); nextPut: (Character value: count+1); nextPut: previousByte] ifFalse: [stream nextPut: previousByte. previousByte asInteger = 0 ifTrue: [stream nextPut: previousByte]]. ^stream contents!withCRs "substitute CRs for backslashes" ^ self collect: [:char | char = $\ ifTrue: [Character cr] ifFalse: [char]]! !!String methodsFor: 'displaying'!displayAt: aPoint "Show a representation of the receiver as a DisplayText at location aPoint on the display screen." self asDisplayText displayAt: aPoint!displayOn: aDisplayMedium at: aPoint "Show a representation of the receiver as a DisplayText at location aPoint on aDisplayMedium." self asDisplayText displayOn: aDisplayMedium at: aPoint! !!String methodsFor: 'private'!compare: s | i len endResult u1 u2 mylen | mylen _ self size. len _ s size. mylen < len ifTrue: [len _ mylen. endResult _ 1] ifFalse: [endResult _ mylen = len ifTrue: [2] ifFalse: [3]]. i _ 0. [(i _ i + 1) <= len] whileTrue: [u1 _ self at: i. u2 _ s at: i. u1 = u2 ifFalse: [u1 _ u1 asUppercase. u2 _ u2 asUppercase. u1 = u2 ifFalse: [^u1 < u2 ifTrue: [1] ifFalse: [3]]]]. ^endResult!primReplaceFrom: start to: stop with: replacement startingAt: repStart "This destructively replaces elements from start to stop in the receiver starting at index, repStart, in the collection, replacement. Answer the receiver. No range checks are performed - this may be primitively implemented." <primitive: 105> super replaceFrom: start to: stop with: replacement startingAt: repStart!stringhash ^self hash! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!String class instanceVariableNames: ''!!String class methodsFor: 'instance creation'!fromString: aString "Answer a new String that is a copy of the argument, aString." | newString | newString _ self new: aString size. aString size do: [:i | newString at: i put: (aString at: i)]. ^newString!readFrom: inStream "Answer a new String that is determined by reading the stream, inStream. Embedded double quotes become the quote Character." | outStream char done | outStream _ WriteStream on: (String new: 16). "go to first quote" inStream skipTo: $'. done _ false. [done or: [inStream atEnd]] whileFalse: [char _ inStream next. char = $' ifTrue: [char _ inStream next. char = $' ifTrue: [outStream nextPut: char] ifFalse: [done _ true]] ifFalse: [outStream nextPut: char]]. ^outStream contents! !!String class methodsFor: 'examples'!example "To see the string displayed at the cursor point, execute this expression and select a point by pressing a mouse button." 'this is some text' displayOn: Display at: Sensor waitButton "String example"! ! Object subclass: #StringHolder instanceVariableNames: 'contents isLocked ' classVariableNames: 'Workspace ' poolDictionaries: '' category: 'Interface-Text'!StringHolder comment:'A model for providing a layer of structure in order to view an aspect of structured information that is a string.Instance variables contents <String> isLocked <Boolean> whether or not the contents has been changed but not stored '!!StringHolder methodsFor: 'initialize-release'!initialize "Initialize the state of the receiver to be unlocked with default contents." isLocked _ false. contents _ self defaultContents! !!StringHolder methodsFor: 'accessing'!contents "Answer the contents that the receiver is holding--presumably a string." ^contents!contents: aString "Set aString to be the contents of the receiver." contents _ aString! !!StringHolder methodsFor: 'doIt/accept/explain'!doItContext "Answer the context in which a text selection can be evaluated." ^nil!doItReceiver "Answer the object that should be informed of the result of evaluating a text selection." ^nil! !!StringHolder methodsFor: 'lock access'!isLocked "Answer whether the receiver is locked, that is, has the contents of the receiver been modified since the last time it was unlocked." ^isLocked!isUnlocked "Answer whether the receiver is unlocked." ^isLocked not!lock "Note that the receiver has been modified." isLocked _ true!unlock "Unlock the receiver. Any modification has presumably been saved." isLocked _ false! !!StringHolder methodsFor: 'private'!defaultContents ^ ''! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!StringHolder class instanceVariableNames: ''!!StringHolder class methodsFor: 'class initialization'!initialize "The class variables were initialized once, and subsequently filled with information. Re-executing this method is therefore dangerous. workSpace _ StringHolder new. StringHolder initialize"! !!StringHolder class methodsFor: 'instance creation'!new ^super new initialize! !!StringHolder class methodsFor: 'workspace constants'!workspace "Answer the model for the system workspace." ^Workspace! !StringHolder initialize! ParagraphEditor subclass: #StringHolderController instanceVariableNames: 'isLockingOn ' classVariableNames: 'CodeYellowButtonMenu CodeYellowButtonMessages ' poolDictionaries: '' category: 'Interface-Text'!StringHolderController comment:'I represent a ParagraphEditor for a single paragraph of text, omitting alignment commands. I provide items in the yellow button menu so that the text selection can be evaluated and so that the contents of the model can be stored or restored. doIt -- evaluate the text selection as an expression printIt -- same as doIt but insert a description of the result after the selection accept -- store the contents of the StringHolder into the model cancel -- store the contents of the model into the StringHolderInstance Variables: isLockingOn <Boolean> true if the view has been editted so that it should not be closed without warning the user. '!!StringHolderController methodsFor: 'initialize-release'!initialize super initialize. isLockingOn _ true! !!StringHolderController methodsFor: 'lock access'!isLockingOff "Answer whether no unsaved modifications have been carried out using the receiver." ^isLockingOn not!isLockingOn "Answer whether unsaved modifications have been carried out using the receiver." ^isLockingOn!lockModel "If the receiver is lock, do so to the receiver's model." isLockingOn ifTrue: [model lock]!turnLockingOff "Turn off the receiver's indication that it is locked." isLockingOn _ false!turnLockingOn "Turn on the receiver's indication that it is locked." isLockingOn _ true!unlockModel "If the receiver is locked, then the model probably is, but should not be, so unlock the model." isLockingOn ifTrue: [model unlock]! !!StringHolderController methodsFor: 'menu messages'!accept super accept. model contents: paragraph string. self unlockModel!cancel super cancel. self unlockModel!doIt "Treat the current text selection as an expression; evaluate it" | result | self controlTerminate. result _ model doItReceiver class evaluatorClass new evaluate: self selectionAsStream in: model doItContext to: model doItReceiver notifying: self ifFail: [self controlInitialize. ^#failedDoit]. Smalltalk logChange: self selection string. self controlInitialize. ^result!printIt "Treat the current text selection as an expression; evaluate it. Insert the description of the result of evaluation after the selection and then make this description the new text selection." | result | result _ self doIt. result ~~ #failedDoit ifTrue: [self afterSelectionInsertAndSelect: result printString]! !!StringHolderController methodsFor: 'model access'!model: aModel super model: aModel. view displayContents == nil ifFalse: [self changeParagraph: view displayContents]! !!StringHolderController methodsFor: 'editing'!insertAndSelect: aString at: anInteger self selectAt: anInteger. self deselect. self replaceSelectionWith: (' ' , aString) asText. self selectAndScroll! !!StringHolderController methodsFor: 'private'!afterSelectionInsertAndSelect: aString self insertAndSelect: aString at: stopBlock stringIndex!initializeYellowButtonMenu self yellowButtonMenu: CodeYellowButtonMenu yellowButtonMessages: CodeYellowButtonMessages!replaceSelectionWith: aText super replaceSelectionWith: aText. self lockModel! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!StringHolderController class instanceVariableNames: ''!!StringHolderController class methodsFor: 'class initialization'!initialize "Initialize the yellow button pop-up menu and corresponding messages." CodeYellowButtonMenu _ PopUpMenu labels: 'againundocopycutpastedo itprint itacceptcancel' lines: #(2 5 7). CodeYellowButtonMessages _ #(again undo copySelection cut paste doIt printIt accept cancel) "StringHolderController initialize"! !StringHolderController initialize! View subclass: #StringHolderView instanceVariableNames: 'displayContents ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!StringHolderView comment:'I am a View of a String that is an aspect of a more structured object. This String should not be changed by any editing unless the user issues the accept command. Thus my instances provide a working copy of the String. This copy is edited. When the user issues the accept command, the String is copied from the working version; or if the user issues the cancel command, the working version is restored from the String. StringHolderController is my default controller. It is initialized specially by passing the string viewed which is then converted to a Paragraph for editing.Instance Variables: displayContents <String> the working copy'!!StringHolderView methodsFor: 'initialize-release'!initialize super initialize. displayContents _ '' asParagraph. self insideColor: Form white! !!StringHolderView methodsFor: 'updating'!update: aSymbol self updateDisplayContents!updateDisplayContents "Make the text that is displayed be the contents of the receiver's model." | contents | contents _ self getContents. displayContents string ~= contents ifTrue: [self editString: contents. self displayView]!updateRequest ^ model isUnlocked or: [(self confirm: 'Contents have not been saved. Are youcertain that you want to close?') ifTrue: [model unlock. ^true] ifFalse: [^false]]! !!StringHolderView methodsFor: 'controller access'!defaultController ^self defaultControllerClass newParagraph: displayContents!defaultControllerClass ^StringHolderController!displayContents ^displayContents! !!StringHolderView methodsFor: 'displaying'!display self isUnlocked ifTrue: [self positionDisplayContents. (self controller isKindOf: ParagraphEditor) ifTrue: [controller recomputeSelection]]. super display!displayView self clearInside. (self controller isKindOf: ParagraphEditor) ifTrue: [controller display] ifFalse: [displayContents display]!positionDisplayContents "Presumably the text being displayed changed so that the wrapping box and clipping box should be reset." displayContents recomposeIn: (self insetDisplayBox insetBy: self paragraphInset) clippingBox: self insetDisplayBox! !!StringHolderView methodsFor: 'model access'!editString: aString "The paragraph to be displayed is created from the characters in aString." displayContents _ Paragraph withText: aString asText style: TextStyle default copy compositionRectangle: (self insetDisplayBox insetBy: self paragraphInset) clippingRectangle: self insetDisplayBox. (self controller isKindOf: ParagraphEditor) ifTrue: [controller changeParagraph: displayContents]!model: aLockedModel super model: aLockedModel. self editString: self getContents! !!StringHolderView methodsFor: 'deEmphasizing'!deEmphasizeView (self controller isKindOf: ParagraphEditor) ifTrue: [controller deselect]! !!StringHolderView methodsFor: 'private'!getContents ^model contents!paragraphInset "Answer the amount to inset the paragraph from the border" ^6@0! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!StringHolderView class instanceVariableNames: ''!!StringHolderView class methodsFor: 'instance creation'!container "Answer an instance of me with a new instance of StringHolder as the model." ^self container: StringHolder new!container: aContainer "Answer an instance of me whose model is aContainer. Give it a 2-dot border." | aCodeView | aCodeView _ self new model: aContainer. aCodeView borderWidth: 1. ^aCodeView!open "Create a scheduled view of a workspace on the screen." self open: StringHolder new label: 'Workspace'!open: aStringHolder "Create a scheduled view of the argument, aStringHolder, as viewed by an instance of me. The view has label 'StringHolder'." self open: aStringHolder label: 'StringHolder'!open: aStringHolder label: aString "Create a StandardSystemView of the model, aStringHolder, as viewed by an instance of me. The label of the view is aString." | aStringHolderView topView | aStringHolderView _ self container: aStringHolder. topView _ StandardSystemView new. topView borderWidth: 1. topView model: aStringHolderView model. topView addSubView: aStringHolderView. topView label: aString. topView minimumSize: 200 @ 150. topView controller open! !!StringHolderView class methodsFor: 'workspace constants'!openSystemWorkspace "StringHolderView openSystemWorkspace." "Schedule a view of the system workspace." self open: StringHolder workspace label: 'System Workspace'! ! Object subclass: #Switch instanceVariableNames: 'on onAction offAction ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!Switch comment:'I represent a selection setting and actions to take depending on a change in the setting. An instance of me has three attributes: state, which is either on or off; on action; and off action. The on and off actions are blocks of code that execute whenever the instance changes state. I am typically used as a menu item in conjunction with a SwitchView and a SwitchController.Instance Variables: on <Boolean> true if the Switch is on onAction <BlockContext> or nil offAction <BlockContext> or nil'!!Switch methodsFor: 'initialize-release'!release "Set the on and off actions of the receiver to nil ('no action') in order to break possible pointer cycles. It is sent by Switch|deleteDependent: when the last dependent has been deleted from the Switch's list of dependents." super release. onAction _ nil. offAction _ nil! !!Switch methodsFor: 'dependents access'!removeDependent: aDependent "If aDependent is the only dependent in the list, the receiver sends Switch|release to try to break up possible pointer cycles." super removeDependent: aDependent. self dependents isEmpty ifTrue: [self release]! !!Switch methodsFor: 'clearing'!clear "Set the state of the receiver to 'off'. If the state of the receiver was previously 'on', then 'self change' is sent. The receiver's off action is NOT executed." self isOn ifTrue: [on _ false. self changed]! !!Switch methodsFor: 'state'!isOff "Answer whether the receiver is set off or not." ^on not!isOn "Answer whether the receiver is set on or not." ^on!set "Set the state of the receiver to 'on'. If the state of the receiver was previously 'off', then 'self change' is sent. The receiver's on action is NOT executed." self isOff ifTrue: [on _ true. self changed]!switch "Change the state of the receiver from 'on' to 'off' or from 'off' to 'on' (see Switch|turnOn, Switch|turnOff)." self isOn ifTrue: [self turnOff] ifFalse: [self turnOn]!turnOff "Set the state of the receiver to 'off'. If the state of the receiver was previously 'on', then 'self change' is sent and the receiver's off action is executed." self isOn ifTrue: [on _ false. self changed. self doAction: offAction]!turnOn "Set the state of the receiver to 'on'. If the state of the receiver was previously 'off', then 'self change' is sent and the receiver's on action is executed." self isOff ifTrue: [on _ true. self changed. self doAction: onAction]! !!Switch methodsFor: 'action'!doAction: anAction "Execute anAction if it is non-nil." anAction == nil ifFalse: [anAction value]!offAction: anAction "Set the off action of the receiver to anAction." offAction _ anAction fixTemps!onAction: anAction "Set the on action of the receiver to anAction." onAction _ anAction fixTemps! !!Switch methodsFor: 'private'!initializeOff on _ false. onAction _ nil. offAction _ nil!initializeOn on _ true. onAction _ nil. offAction _ nil! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Switch class instanceVariableNames: ''!!Switch class methodsFor: 'instance creation'!new "Answer an instance of me such that the on and off actions are set to nil ('no action'), and the state is set to 'off'." ^self newOff!newOff "Answer an instance of me such that the on and off actions are set to nil ('no action'), and the state is set to 'off'." ^super new initializeOff!newOn "Answer an instance of me such that the on and off actions are set to nil ('no action'), and the state is set to 'on'." ^super new initializeOn! ! Controller subclass: #SwitchController instanceVariableNames: 'selector arguments cursor ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!SwitchController comment:'I coordinate the interaction of a Switch, a SwitchView, and input events (user actions, see class Sensor). My instances own a message in the form of a selector and an array of arguments. Whenever the Switch is selected, this message is sent to the Switch.Instance Variables: selector <Symbol> arguments <Array>'!!SwitchController methodsFor: 'initialize-release'!initialize super initialize. selector _ #switch. arguments _ Array new: 0! !!SwitchController methodsFor: 'accessing'!addArgument: aValue "Add the argument, aValue, as one of the arguments of the message the receiver sends to its model." arguments _ arguments copyWith: aValue!arguments "Answer the arguments the receiver sends in a message to its receiver." ^arguments!arguments: anArray "The argument, anArray, consists of the arguments of the message the receiver sends to its model." arguments _ anArray!cursor: aCursor cursor _ aCursor!selector "Answer the selector the receiver sends in a message to its receiver." ^selector!selector: aSymbol "Set aSymbol to be the selector the receiver sends in a message to its model." selector _ aSymbol! !!SwitchController methodsFor: 'basic control sequence'!controlInitialize view indicatorReverse!controlTerminate view indicatorReverse. self viewHasCursor ifTrue: [self sendMessage]!sendMessage "The receiver consists of a selector and possibly of arguments that should be used to create a message to send to the receiver's model." arguments size = 0 ifTrue: [model perform: selector] ifFalse: [model perform: selector withArguments: arguments]! !!SwitchController methodsFor: 'control defaults'!controlActivity ^ self!isControlActive ^sensor anyButtonPressed & self viewHasCursor!isControlWanted self viewHasCursor ifTrue: [cursor == nil ifFalse: [cursor show]]. ^self viewHasCursor & sensor redButtonPressed! ! View subclass: #SwitchView instanceVariableNames: 'complemented label selector keyCharacter highlightForm arguments ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Menus'!SwitchView comment:'I am a view of a Switch. My instances have labels and display modes (set to "normal" or "complemented"). When one of my instances is displayed in complemented mode, its inside color is reversed. The value of the display mode corresponds to the value of the model so that, for example, when a Switch is off, its SwitchView is displayed with black text (for the label) on a white background, and when the Switch is off, its SwitchView is displayed with white text on a black background. My instances have a key character that can be used for switching on or off. Highlighting can be done specially using a stored form, rather than simply changing all black bits to white and vice versa. My default controller is SwitchController.Instance Variables: complemented <Boolean> true if the model is on label <DisplayObject>, for example, a DisplayText or a Form selector <Symbol> keyCharacter <Character> highlightForm <Form> arguments <Array>'!!SwitchView methodsFor: 'initialize-release'!initialize super initialize. insideColor _ Form white. complemented _ false. label _ nil. selector _ #isOn. arguments _ #()!release super release. label release! !!SwitchView methodsFor: 'accessing'!arguments "Answer the arguments the receiver sends in a message to its receiver." ^arguments!arguments: anArray "The argument, anArray, consists of the arguments of the message the receiver sends to its model." arguments _ anArray!highlightForm: aForm "The argument is the form to be used to highlight the receiver." highlightForm _ aForm!key: aCharacter "Set the receiver to be selected by the argument, aCharacter." keyCharacter _ aCharacter! !!SwitchView methodsFor: 'testing'!containsKey: aCharacter "Answer whether the receiver can be selected by the argument, aCharacter." ^keyCharacter = aCharacter! !!SwitchView methodsFor: 'controller access'!defaultControllerClass ^SwitchController! !!SwitchView methodsFor: 'window access'!defaultWindow "Returns the frame of the SwitchView's label's frame (slightly enlarged) if the label exists, and returns the standard View default window (see View|defaultWindow), otherwise." label == nil ifTrue: [^super defaultWindow] ifFalse: [^label boundingBox expandBy: 6]!window: aWindow super window: aWindow. self centerLabel! !!SwitchView methodsFor: 'displaying'!display "Sets the SwitchView mode to 'normal', displays the border, displays the inside and, if its model is 'on', complements the inside." self displayBorder. complemented _ self interrogateModel. highlightForm == nil ifTrue: [self displayView. complemented ifTrue: [self highlight]] ifFalse: [self displaySpecial]!displayComplemented "Complement the receiver if its mode is 'normal'." complemented ifFalse: [complemented _ true. self highlight]!displayNormal "Complement the receiver if its mode is 'complemented'." complemented ifTrue: [complemented _ false. self highlight]!displaySpecial complemented ifTrue: [self displaySpecialComplemented]. label == nil ifFalse: [label displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox align: label boundingBox center with: label boundingBox center rule: Form under mask: Form black]!displaySpecialComplemented highlightForm displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox fixedPoint: label boundingBox center!displayView "Does the standard View actions and, in addition, displays the receiver's label based on the current display transformation and inset display box." self clearInside. label == nil ifFalse: [label displayOn: Display transformation: self displayTransformation clippingBox: self insetDisplayBox fixedPoint: label boundingBox center]! !!SwitchView methodsFor: 'updating'!update: aParameter highlightForm == nil ifTrue: [self interrogateModel ifTrue: [self displayComplemented] ifFalse: [self displayNormal]] ifFalse: [self display]! !!SwitchView methodsFor: 'label access'!centerLabel "Align the center of the frame of the label with the center of the receiver's window." label == nil ifFalse: [label align: label boundingBox center with: self getWindow center]!label "Answer the label, a display object, that is the receiver's screen image." ^label!label: aDisplayObject "Set aDisplayObject to be the label that is the receiver's screen image." label release. label _ aDisplayObject. self centerLabel! !!SwitchView methodsFor: 'indicating'!indicatorOnDuring: aBlockContext "Indicate the receiver during the execution of aBlockContext by complementing the label (or a portion of the display box if no label is defined). " self indicatorReverse. self highlight. aBlockContext value. self highlight. self indicatorReverse!indicatorReverse "Complement the label (or a portion of the displayBox if no label is defined)." Display reverse: self insetDisplayBox mask: Form gray. Display reverse: (self insetDisplayBox insetBy: 2) mask: Form gray! !!SwitchView methodsFor: 'selector'!interrogateModel "Answer the result of sending the receiver's model the message created from the receiver's selector and arguments." arguments size = 0 ifTrue: [^model perform: selector] ifFalse: [^model perform: selector withArguments: arguments]!selector "Answer the selector the receiver sends in a message to its receiver." ^selector!selector: aSymbol "Set aSymbol to be the selector the receiver sends in a message to its model." selector _ aSymbol! !!SwitchView methodsFor: 'deEmphasizing'!deEmphasizeView | newForm | complemented ifTrue: [self highlight. newForm _ Form fromDisplay: self insetDisplayBox. newForm displayOn: Display at: (self insetDisplayBox topLeft + (1@0)) clippingBox: self insetDisplayBox rule: Form under mask: Form black. Display fill: self insetDisplayBox rule: Form under mask: Form lightGray]! ! String variableByteSubclass: #Symbol instanceVariableNames: '' classVariableNames: 'SingleCharSymbols USTable ' poolDictionaries: '' category: 'Collections-Text'!Symbol comment:'Symbols are Strings which are created uniquely. Thus, someString asSymbol == someString asSymbol.'!!Symbol methodsFor: 'accessing'!at: anInteger put: anObject "you can not modify the receiver." self errorNoModification!replaceFrom: start to: stop with: replacement startingAt: repStart self errorNoModification! !!Symbol methodsFor: 'comparing'!= anObject ^self == anObject!hash "Answer with a SmallInteger whose value is half of the receiver's object pointer (interpreting object pointers as 16-bit signed quantities). Essential. See Object documentation whatIsAPrimitive." <primitive: 75> ^self!hashMappedBy: map "Answer what my hash would be if oops changed according to map" ^ map newHashFor: self hash! !!Symbol methodsFor: 'copying'!copy "Answer with me, because Symbols are unique."!shallowCopy "Answer with me, because Symbols are unique."! !!Symbol methodsFor: 'printing'!isLiteral ^Scanner isLiteralSymbol: self!printOn: aStream aStream nextPutAll: self!storeOn: aStream self isLiteral ifTrue: [aStream nextPut: $#. aStream nextPutAll: self] ifFalse: [super storeOn: aStream. aStream nextPutAll: ' asSymbol']! !!Symbol methodsFor: 'converting'!asString | newString | newString _ String new: self size. 1 to: self size do: [:index | newString at: index put: (self at: index)]. ^newString!asSymbol! !!Symbol methodsFor: 'private'!errorNoModification self error: 'symbols can not be modified.'!species ^String!string: aString 1 to: aString size do: [:j | super at: j put: (aString at: j)]. ^self!stringhash ^super hash! !!Symbol methodsFor: 'system primitives'!classPart "I must be a compound selector. Return my class name" | i | i _ self indexOf: $. ifAbsent: [self error: 'class part not found']. ^(self copyFrom: 1 to: i-1) asSymbol!isCompound "return true if the receiver is of the form Class.foo " ^self includes: $.!isInfix "Answer whether the receiver is an infix message selector." ^(self at: 1) isLetter not!isKeyword "Answer whether the receiver is a message keyword, i.e., ends with colon." self size <= 1 ifTrue: [^false]. ^(self at: self size) = $:!keywords "Answer an array of the keywords that compose the receiver." | result aStream i l char | result _ WriteStream on: (Array new: 10). aStream _ WriteStream on: (String new: 16). i _ 1. l _ self size. [i <= l] whileTrue: [char _ self at: i. aStream nextPut: char. (char = $: or: [i = l]) ifTrue: [result nextPut: aStream contents. aStream reset]. i _ i + 1]. ^result contents!numArgs "Answer the number of arguments that the receiver requires if it is interpreted as a message selector." | len n i | len _ self size. n _ (self at: 1) isLetter ifTrue: [0] ifFalse: [1]. i _ 1. [(i _ i + 1) <= len] whileTrue: "count colons" [(self at: i) = $: ifTrue: [n _ n + 1]]. ^n!selectorPart "return just my part after the class name if the receiver is a compound selector (otherwise the whole thing)" ^(self copyFrom: (self indexOf: $.) + 1 to: self size) asSymbol! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Symbol class instanceVariableNames: ''!!Symbol class methodsFor: 'class initialization'!initialize | a v | "make up table of 1-char atoms" v _ Array new: 128. a _ String new: 1. 1 to: 128 do: [:i | a at: 1 put: i - 1. v at: i put: a asSymbol]. SingleCharSymbols _ v "Symbol initialize."! !!Symbol class methodsFor: 'instance creation'!correctMessage: unknown "Attempt to correct the spelling of an unknown message symbol." | lc candidates score bestScore guess hasColon nArgs smaller larger | lc _ unknown first asLowercase. hasColon _ unknown last = $:. unknown first isLetter ifFalse: [^ nil]. nArgs _ (unknown select: [:char | char = $:]) size. candidates _ OrderedCollection new. smaller _ unknown size-4. larger _ unknown size+4. Symbol allInstancesDo: "fast tests first" [:each | (((each at: 1) = lc and: [each size between: smaller and: larger]) and: [(each last = $:) = hasColon and: [each numArgs = nArgs]]) ifTrue: [candidates add: each]]. bestScore _ 0. candidates do: [:each | (score _ each spellAgainst: unknown) > bestScore ifTrue: [bestScore _ score. guess _ each]]. bestScore > 50 ifFalse: [^false]. (self confirm: 'Confirm correction to ' , guess) ifTrue: [^ guess asSymbol] ifFalse: [^ nil]!intern: aString "Answer a unique Symbol whose characters are those of aString." | sym index | self hasInterned: aString ifTrue: [:sym | ^sym]. "check if already exists" sym _ (aString isMemberOf: Symbol) ifTrue: [aString] "putting old symbol in new table" ifFalse: [(Symbol new: aString size) string: aString]. "create a new one" index _ aString stringhash \\ USTable size + 1. USTable at: index put: ((USTable at: index) copyWith: sym). ^sym!internCharacter: aCharacter "Answer with, and create if necessary, a unique Symbol whose characters are just this character." | ascii | (ascii _ aCharacter asciiValue) < 128 ifTrue: [^SingleCharSymbols at: ascii + 1]. ^self intern: (String with: aCharacter)! !!Symbol class methodsFor: 'private'!hasInterned: aString ifTrue: symBlock "Answer with false if aString hasnt been interned (into a Symbol), otherwise supply the symbol to symBlock and return true" | v i ascii | aString size = 1 ifTrue: [(ascii _ (aString at: 1) asciiValue) < 128 ifTrue: [symBlock value: (SingleCharSymbols at: ascii + 1). ^true]]. v _ USTable at: aString stringhash \\ USTable size + 1. 1 to: v size do: [:i | (v at: i) == nil ifFalse: [aString size = (v at: i) size ifTrue: [aString = (v at: i) ifTrue: [symBlock value: (v at: i). ^true]]]]. ^false!rehash "Rebuild the hash table that holds all the unique Symbols." | sym | USTable _ USTable collect: [:sym | Array new: 0]. Symbol allInstancesDo: [:sym | self intern: sym] "Symbol rehash"!table "Access for SystemTracer" ^USTable!table: newArray "Access for SystemTracer" ^USTable _ newArray! !Symbol initialize! Object subclass: #SyntaxError instanceVariableNames: 'class badText processHandle ' classVariableNames: 'TextMenu ' poolDictionaries: '' category: 'Interface-Debugger'!SyntaxError comment:'I represent a report of a syntax error when reading class descriptions from a noninteractive source such as an external file. As a StringHolder, the string to be viewed is the code or expression containing the error.'!!SyntaxError methodsFor: 'text'!proceed "Continue the file in, ignoring this section of code, regardless of whether or not the syntax error was corrected." self changeRequest ifTrue: [processHandle proceed]!text ^ badText!textMenu "SyntaxError flushMenus" TextMenu == nil ifTrue: [TextMenu _ ActionMenu labels: 'again\undo\copy\cut\paste\do it\print it\accept\cancel\proceed' withCRs lines: #(2 5 7 9) selectors: #(again undo copySelection cut paste doIt printIt accept cancel proceed)]. ^ TextMenu! !!SyntaxError methodsFor: 'doIt/accept/explain'!acceptText: aString from: aController "Compile the code in aString and notify aController of any errors. Proceed if successful." (class compile: aString classified: ClassOrganizer defaultProtocol notifying: aController) == nil ifTrue: [^false] ifFalse: [^true]!doItContext ^ nil!doItReceiver ^ nil!doItValue: ignored! !!SyntaxError methodsFor: 'dependents access'!removeDependent: aDependent super removeDependent: aDependent. self dependents isEmpty "detect when closing" ifTrue: [processHandle release]! !!SyntaxError methodsFor: 'private'!setClass: aClass code: aString processHandle: aProcessHandle class _ aClass. processHandle _ aProcessHandle. badText _ aString asText! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SyntaxError class instanceVariableNames: ''!!SyntaxError class methodsFor: 'instance creation'!errorInClass: aClass withCode: aString errorString: errorString "Answer a StandardSystemView whose model is an instance of me. The syntax error occurred in trying to add code, aString, to class, aClass." | aSyntaxError topView aListView aCodeView | Cursor normal show. aSyntaxError _ self new setClass: aClass code: aString processHandle: (ProcessHandle on: Processor activeProcess at: thisContext interrupted: false). topView _ StandardSystemView model: aSyntaxError label: 'Syntax Error' minimumSize: 300 @ 180. topView addSubView: (CodeView on: aSyntaxError aspect: #text change: #acceptText:from: menu: #textMenu initialSelection: errorString) in: (0@0 extent: 1@1) borderWidth: 1. topView controller openNoTerminateDisplayAt: Display extent // 2. Processor activeProcess suspend! !!SyntaxError class methodsFor: 'initialization'!flushMenus TextMenu _ nil! ! Dictionary variableSubclass: #SystemDictionary instanceVariableNames: '' classVariableNames: 'CachedClassNames Frills LowSpaceProcess LowSpaceSemaphore OopsLeftLimit SpecialSelectors SystemChanges WordsLeftLimit ' poolDictionaries: '' category: 'System-Support'!SystemDictionary comment: 'I am a special dictionary that supports protocol for asking questions about the structure of the system. My only instance is Smalltalk.'!!SystemDictionary methodsFor: 'initialize-release'!install "Get connected back up to the hardware after a snapshot or quit." "Call the initialization code that depends on system parameters, in case we are coming up on a system different from the one that we quit or snapshot on." CompiledMethod initialize. SmallInteger initialize. LargePositiveInteger initialize. LargeNegativeInteger initialize. DisplayScreen currentDisplay: Display. Cursor currentCursor: Cursor currentCursor. InputSensor install. LowSpaceProcess == nil ifFalse: [LowSpaceProcess terminate]. LowSpaceSemaphore _ Semaphore new. LowSpaceProcess _ [self lowSpaceNotificationLoop] newProcess. LowSpaceProcess priority: Processor lowIOPriority. LowSpaceProcess resume. self resetSpaceLimits.! !!SystemDictionary methodsFor: 'accessing'!at: aKey put: anObject "Override from Dictionary so that can check Undeclared and fix up references of undeclared variables." | index element | index _ self findKeyOrNil: aKey. element _ self basicAt: index. element == nil ifTrue: [self valueAtNewKey: aKey put: anObject atIndex: index declareFrom: Undeclared] ifFalse: [element value: anObject]. ^anObject!valueAtNewKey: aKey put: anObject atIndex: index declareFrom: aDictionary "Handle overriding atKey:put: from Dictionary so that adding something new to a system dictionary such as Smalltalk checks Undeclared and fixes up all references to the undeclared variable" (aDictionary includesKey: aKey) ifTrue: [self atNewIndex: index put: ((aDictionary associationAt: aKey) value: anObject). aDictionary removeKey: aKey] ifFalse: [self atNewIndex: index put: (Association key: aKey value: anObject)]. self flushClassNameCache! !!SystemDictionary methodsFor: 'enumerating'!allBehaviorsDo: aBlock "Evaluate the argument, aBlock, for each kind of Behavior in the system (that is, Object and its subclasses)." aBlock value: Object. Object allSubclassesDo: aBlock!allClassesDo: aBlock "Evaluate the argument, aBlock, for each class in the system." (self classNames collect: [:name | Smalltalk at: name]) do: aBlock!pointersTo: anObject do: aBlock "Evaluate the argument aBlock for each pointer to anObject in the system." | me class obj method i fixedSize | me _ thisContext. Smalltalk allBehaviorsDo: [:class | class isBits ifTrue: ["Might be CompiledMethod" class == CompiledMethod ifTrue: [class allInstancesDo: [:method | 1 to: method numLiterals + 1 do: [:i | (method objectAt: i) == anObject ifTrue: [aBlock value: method]]]]] ifFalse: [fixedSize _ class instSize. class allInstancesDo: [:obj | 1 to: (fixedSize + obj basicSize) do: [:i | ((obj instVarAt: i) == anObject and: [obj ~~ me]) ifTrue: [aBlock value: obj]]]]]. me _ nil "Break cycle"! !!SystemDictionary methodsFor: 'browsing'!browseAllCallsOn: aSymbol "Create and schedule a message browser on each method that calls on aSymbol. For example, Smalltalk browseAllCallsOn: #open:label:. " | label key | (aSymbol isMemberOf: Association) ifTrue: [key _ aSymbol key. label _ 'Users of ' , key] ifFalse: [key _ aSymbol. label _ 'Senders of ', key]. ^ BrowserView openListBrowserOn: (self allCallsOn: aSymbol) label: label initialSelection: key asSymbol keywords first!browseAllCallsOn: literal1 and: literal2 "Create and schedule a message browser on each method that calls on the two Symbols, literal1 and literal2. For example, Smalltalk browseAllCallsOn: #at: and: #at:pt:. " BrowserView openListBrowserOn: (self allCallsOn: literal1 and: literal2) label: literal1 printString , literal2 printString!browseAllImplementorsOf: selector "Create and schedule a message browser on each method that implements the message whose selector is the argument, selector. For example, Smalltalk browseAllImplementorsOf: #at:put:. " BrowserView openListBrowserOn: (self allImplementorsOf: selector) label: 'Implementors of ' , selector!browseAllSelect: aBlock "Create and schedule a message browser on each method that, when used as the block argument to aBlock gives a true result. For example, Smalltalk browseAllSelect: [:method | method numLiterals > 10] " BrowserView openListBrowserOn: (self allSelect: aBlock) label: 'selected messages'!browseChangedMessages "Smalltalk browseChangedMessages" BrowserView openListBrowserOn: SystemChanges changedMessageList label: 'Changed Messages'!showMenuThenBrowse: selectorCollection "Show a menu of the given selectors, abbreviated to 20 characters. Create and schedule a message set browser of all implementors of the message chosen. Do nothing if no message is chosen." | aStream menu index | selectorCollection isEmpty ifTrue: [^Transcript cr; show: 'No messages sent.']. aStream _ WriteStream on: (String new: 200). selectorCollection do: [:sel | aStream nextPutAll: (sel contractTo: 20); cr]. aStream skip: -1. index _ (PopUpMenu labels: aStream contents) startUp. index > 0 ifTrue: [Smalltalk browseAllImplementorsOf: (selectorCollection at: index)]! !!SystemDictionary methodsFor: 'retrieving'!allCallsOn: aLiteral "Answer a SortedCollection of all the methods that call on aLiteral." | aSortedCollection special | aSortedCollection _ SortedCollection new. special _ self hasSpecialSelector: aLiteral ifTrueSetByte: [:byte ]. Cursor execute showWhile: [self allBehaviorsDo: [:class | (class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [aSortedCollection add: class name , ' ' , sel]]]]. ^aSortedCollection!allCallsOn: firstLiteral and: secondLiteral "Answer a SortedCollection of all the methods that call on both aLiteral and secondLiteral." | aCollection secondArray firstSpecial secondSpecial | aCollection _ SortedCollection new. firstSpecial _ self hasSpecialSelector: firstLiteral ifTrueSetByte: [:firstByte]. secondSpecial _ self hasSpecialSelector: secondLiteral ifTrueSetByte: [:secondByte]. Cursor execute showWhile: [self allBehaviorsDo: [:class | secondArray _ class whichSelectorsReferTo: secondLiteral special: secondSpecial byte: secondByte. ((class whichSelectorsReferTo: firstLiteral special: firstSpecial byte: firstByte) select: [:aSel | (secondArray includes: aSel)]) do: [:sel | aCollection add: class name , ' ' , sel]]]. ^aCollection!allClassesImplementing: aSelector "Answer an Array of all classes that implement the message aSelector." | aCollection | aCollection _ ReadWriteStream on: Array new. self allBehaviorsDo: [:class | (class includesSelector: aSelector) ifTrue: [aCollection nextPut: class]]. ^ aCollection contents!allImplementedMessages "Answer a Set of all the messages that are sent by a method in the system but are not implemented." | aSet | aSet _ Set new: (Symbol instanceCount * 1.5) truncated. Cursor execute showWhile: [self allBehaviorsDo: [:cl | cl selectors do: [:aSelector | aSet add: aSelector]]]. ^aSet!allImplementorsOf: aSelector "Answer a SortedCollection of all the methods that implement the message aSelector." | aCollection | aCollection _ SortedCollection new. Cursor execute showWhile: [self allBehaviorsDo: [:class | (class includesSelector: aSelector) ifTrue: [aCollection add: class name, ' ', aSelector]]]. ^aCollection!allSelect: aBlock "Answer a SortedCollection of each method that, when used as the block argument to aBlock, gives a true result." | aCollection | aCollection _ SortedCollection new. Cursor execute showWhile: [self allBehaviorsDo: [:class | class selectors do: [:sel | (aBlock value: (class compiledMethodAt: sel)) ifTrue: [aCollection add: class name , ' ' , sel]]]]. ^aCollection!collectPointersTo: anObject "Answer an Array of all occurrences in the system of pointers to the argument anObject." | some me | some _ OrderedCollection new. me _ thisContext. self pointersTo: anObject do: [:obj | (obj ~~ me) & (obj ~~ some) ifTrue: [some add: obj]]. me _ nil. "to avoid circularity" ^some asArray "(Smalltalk collectPointersTo: Browser) inspect."! !!SystemDictionary methodsFor: 'class names'!classNames "Answer a SortedCollection of all class names. Use cached copy if available." CachedClassNames == nil ifTrue: [^self newClassNames]. ^CachedClassNames!flushClassNameCache "Invalidate cached copy of classnames (see classNames)" CachedClassNames _ nil!newClassNames "Compute a sorted collection of class names and cache it for efficiency." | names | names _ OrderedCollection new: self size. self do: [:cl | (cl isKindOf: Class) ifTrue: [names add: cl name]]. ^CachedClassNames _ names asSortedCollection! !!SystemDictionary methodsFor: 'compiling'!recompileAllFrom: firstName "Recompile all classes, starting with given name." | class | Smalltalk forgetDoIts. self allClassesDo: [:class | class name >= firstName ifTrue: [Transcript show: class name; cr. class compileAll]] "Smalltalk recompileAllFrom: 'Aardvark'."!recompileCallsOn: aLiteral "Recompile every message in the system that refers to aLiteral." | special | special _ self hasSpecialSelector: aLiteral ifTrueSetByte: [:byte ]. Cursor execute showWhile: [self allBehaviorsDo: [:class | (class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [class recompile: sel]]]]!recompileMethodsForWhich: aBlock "Recompile all methods in the system for which aBlock evaluates to true. For example, Smalltalk recompileMethodsForWhich: [:meth | meth size=6]" Cursor execute showWhile: [self allBehaviorsDo: [:class | class selectors do: [:sel | (aBlock value: (class compiledMethodAt: sel)) ifTrue: [Transcript show: class name , ' ' , sel; cr. class recompile: sel]]]]! !!SystemDictionary methodsFor: 'change management'!changes "Answer the current system ChangeSet." ^SystemChanges!logChange: aStringOrText "Write the argument, a String or Text, onto the changes file." | aFileStream aString | SourceFiles == nil ifTrue: [^self]. (aString isMemberOf: Text) ifTrue: [aString _ aStringOrText string] ifFalse: [aString _ aStringOrText]. (aString isMemberOf: String) ifFalse: [self error: 'cant log this change']. (aString findFirst: [:char | char isSeparator not]) = 0 ifTrue: [^self]. "null doits confuse replay" aFileStream _ SourceFiles at: 2. aFileStream setToEnd; readWrite. aFileStream cr; cr; nextChunkPut: aString. aFileStream readOnly!newChanges: aChangeSet "Set the system ChangeSet to be aChangeSet." SystemChanges _ aChangeSet!noChanges "Initialize the system ChangeSet." SystemChanges initialize!recover: nCharacters "Schedule an editable text view on the last n characters of changes." | changes | changes _ SourceFiles at: 2. changes setToEnd; skip: nCharacters negated. (Disk file: 'st80.recent') nextPutAll: changes; close; edit!removeClassNamed: className "Remove the class with the name className, and all of its subclasses, from the system, and note the removal in the system ChangeSet." | class | class _ self at: className asSymbol ifAbsent: [^self]. class subclasses do: [:subclass | self removeClassNamed: subclass name]. "remove subclasses first" SystemChanges removeClass: class. SystemOrganization removeElement: className. self removeKey: className asSymbol. self flushClassNameCache. class obsolete.!renameClass: aClass as: newName "Rename the class, aClass, to have the title newName." | oldref | SystemOrganization classify: newName under: aClass category. SystemOrganization removeElement: aClass name. SystemChanges renameClass: aClass as: newName. oldref _ self removeKey: aClass name. oldref key: newName. (Undeclared includesKey: newName) ifTrue: [self at: newName put: aClass] ifFalse: [self add: oldref "Preserve old reference"]. self flushClassNameCache! !!SystemDictionary methodsFor: 'memory space'!core "Answer an Array containing the number of objects in the system and the number of words they occupy. Smalltalk core" | n nobjects nwords isBytes name | nobjects _ nwords _ 0. Smalltalk allBehaviorsDo: [:class | class isVariable ifTrue: [n _ 0. isBytes _ class isBytes. class allInstancesDo: [:inst | n _ n + 1. nwords _ nwords + (isBytes ifTrue: [inst basicSize + 1 // 2] ifFalse: [inst basicSize])]] ifFalse: [n _ class isMeta ifTrue: ["quicker" 1] ifFalse: [class instanceCount]]. nobjects _ nobjects + n. nwords _ nwords + (class instSize + 2 * n) "+2 for header"]. ^Array with: nobjects with: nwords!coreLeft "Answer the number of unallocated words in the object space. Essential. See Object documentation whatIsAPrimitive." <primitive: 112> self primitiveFailed!coreLeftLimit "Answer the threashold at which the user is to be notified that the system is low in core space." ^WordsLeftLimit!coreLeftLimit: newLimit "Set newLimit to be the threashold at which the user is to be notified that the system is low in core space." WordsLeftLimit _ newLimit. self resetLowSpaceSignal. ^newLimit!frills "Answer whether the current Smalltalk is willing to work harder - on slow machines, you may want to set Smalltalk frills: false" ^Frills!frills: aBoolean "Set to true for more functionality on fast machines - but on slow machines, you may want to set Smalltalk frills: false." ^Frills _ aBoolean!oopsLeft "Answer the number of unallocated object pointers in the object table. Equal to the net number of objects which can be created before the object table is full. Essential. See Object documentation whatIsAPrimitive." <primitive: 115> self primitiveFailed!oopsLeftLimit "Answer the threashold at which the user is to be notified that the system is low in number of oops." ^OopsLeftLimit!oopsLeftLimit: newLimit "Set newLimit to be the threashold at which the user is to be notified that the system is low in nubmer of oops." OopsLeftLimit _ newLimit. self resetLowSpaceSignal. ^newLimit!resetLowSpaceSignal "The threasholds for notifying the user the space is low have changed so update the system." self signal: LowSpaceSemaphore atOopsLeft: OopsLeftLimit wordsLeft: WordsLeftLimit!resetSpaceLimits "Reset the threashold on the number of oops and the core space at which point the user should be notified." OopsLeftLimit _ self oopsLeft // 4. WordsLeftLimit _ self coreLeft // 4. self resetLowSpaceSignal!signal: aSemaphore atOopsLeft: numOops wordsLeft: numWords "Tell the object memory to signal the Semaphore when either the number of object pointers remaining drops below numOops, or the number of words in the object space remaining drops below numWords. Fail if the frist argument is neither a Semaphore nor nil. Fail if numOops is not a 16-bit Integer, or if numWords is not a 32-bit LargePositiveInteger. Essential. See Object documentation whatIsAPrimitive." <primitive: 116> self primitiveFailed! !!SystemDictionary methodsFor: 'special selectors'!hasSpecialSelector: aLiteral ifTrueSetByte: aBlock 1 to: self specialSelectorSize do: [:index | (self specialSelectorAt: index) == aLiteral ifTrue: [aBlock value: index + 16rAF. ^true]]. ^false!specialNargsAt: anInteger "Answer the number of arguments for the special selector at: anInteger" ^SpecialSelectors at: anInteger * 2!specialSelectorAt: anInteger "Answer the special message selector stored at location anInteger in the system dictionary." ^SpecialSelectors at: anInteger * 2 - 1!specialSelectorSize "Answer the number of special selectors in the system." ^SpecialSelectors size // 2! !!SystemDictionary methodsFor: 'system backup/out'!copyChangesTo: newFileName "If the file name supplied is different than the current changes file name, copy the changes file and install the new copy as the changes file." | oldName newFile | SourceFiles == nil ifTrue: [^self]. oldName _ (SourceFiles at: 2) name. oldName last = $. ifTrue: [oldName _ oldName copyFrom: 1 to: oldName size-1]. (newFileName sameAs: oldName) ifFalse: [Transcript cr; show: 'Copying ', oldName, ' to ', newFileName, '...'. (SourceFiles at: 2) close; readOnly; reset. newFile _ FileStream fileNamed: newFileName. Cursor write showWhile: [newFile nextPutAll: (SourceFiles at: 2)]. newFile readOnly. SourceFiles at: 2 put: newFile. Transcript show: ' done'; cr]!getImagePrefix "Prompt the user for a snapshot file name. Persist until a legal name is supplied." | default newPrefix prompt | SourceFiles == nil ifTrue: [^'snapshot']. prompt _'Enter name for image file:'. default _ 'snapshot'. newPrefix _ ''. FillInTheBlank request: prompt displayAt: Sensor cursorPoint centered: true action: [:newPrefix | ] initialAnswer: default. [newPrefix isEmpty or: [(Disk isLegalFileName: newPrefix, '.changes') not]] whileTrue: [newPrefix isEmpty ifTrue: [^newPrefix]. FillInTheBlank request: prompt displayAt: Sensor cursorPoint centered: true action: [:newPrefix | ] initialAnswer: default. (newPrefix size > 2 and: [(newPrefix copyFrom: newPrefix size-2 to: newPrefix size) sameAs: '.im']) ifTrue: [newPrefix _ newPrefix copyFrom: 1 to: newPrefix size-3]. prompt _'Illegal file name: ', newPrefix, 'Enter name for image file:'. default _ Disk checkName: newPrefix, '.changes' fixErrors: true. default _ default copyFrom: 1 to: default size - 8]. ^newPrefix!quit "Close open files then exit to another operating system on the host machine, if one exists. All state changes in the object space since the last snapshot are lost." self releaseExternalViews. self quitPrimitive!saveAs: imagePrefix thenQuit: quitIfTrue "Copy the changes file to the new name if necessary, then create a matching image file. Answer true if the image file was just created." Disk == nil ifFalse: [(imagePrefix sameAs: 'snapshot') ifFalse: [self copyChangesTo: imagePrefix, '.changes']]. ^self snapshotAs: imagePrefix thenQuit: quitIfTrue!shutdown "Shut off the low space signal so that the Vmem writer can be sure the system is stable while it is tracing." self coreLeftLimit: 0. self oopsLeftLimit: 0!snapshot "Write the OT and Data of this Smalltalk out on the external file snapshot.im." self snapshotAs: 'snapshot' thenQuit: false!snapshotAs: imageFilePrefix thenQuit: quitIfTrue "Write the OT and Data of this Smalltalk out on an external file. Answer true if the snapshot was just created." | height justSnapped | Cursor execute show. self logChange: '''----SNAPSHOT----'''. Disk == nil ifFalse: "install as snapshot file and update creation time" [(FileStream fileNamed: imageFilePrefix, '.im') beSnapshotFile; readWrite; close]. self releaseExternalViews. Transcript cr; show: 'Snapshot at: ', Time dateAndTimeNow printString. height _ Display height. DisplayScreen displayHeight: (height min: 100). "Minimize display space on snapshot" Delay preSnapshot. Cursor wait show. justSnapped _ self snapshotPrimitive isNil. justSnapped & quitIfTrue ifTrue: [self quitPrimitive] ifFalse: [Delay postSnapshot. DisplayScreen displayHeight: height. self install]. Cursor normal show. ^justSnapped! !!SystemDictionary methodsFor: 'time/versions'!copyright "The Smalltalk copyright. Copyright (c) 1983 Xerox Corp. All rights reserved. " ^'Copyright (c) 1983 Xerox Corp. All rights reserved.'!timeStamp: aStream "Writes system version and current time on stream aStream." | dateTime | dateTime _ Time dateAndTimeNow. aStream nextPutAll: 'From ', Smalltalk version, ' on ', (dateTime at: 1) printString, ' at ', (dateTime at: 2) printString!version "Answer the version of this Smalltalk release." ^'Smalltalk-80, version 2, of April 1, 1983'!versionName "Answer the version identification, e.g. Smalltalk-80" ^'Smalltalk-80'! !!SystemDictionary methodsFor: 'system compression'!condenseChanges "Move all the changes onto a compacted sources file. Smalltalk condenseChanges." | f fileName | f _ Disk file: 'ST80.temp'. f timeStamp. Smalltalk allBehaviorsDo: [:class | class moveChangesTo: f]. f close. f readOnly. fileName _ (SourceFiles at: 2) name. (SourceFiles at: 2) close. SourceFiles at: 2 put: f. Disk removeKey: fileName. f file rename: fileName!forgetDoIts "get rid of old DoIt methods" Smalltalk allBehaviorsDo: [:class | class removeSelectorSimply: #DoIt; removeSelectorSimply: #DoItIn:] "Smalltalk forgetDoIts"!newSourceFile: vers without: setOfClasses "Make a new source file omitting references to any classes in the set, setOfClasses. Smalltalk newSourceFile: Smalltalk versionName without: (Array new). Make sure versionName is updated. Then rename the image similarly, and delete the old sources and changes." | oldFile newFile class | oldFile _ SourceFiles at: 1. newFile _ Disk file: vers , '.sources'. newFile timeStamp. Smalltalk classNames do: [:className | class _ Smalltalk at: className. (setOfClasses includes: class) ifFalse: [class fileOutOn: newFile moveSource: true toFile: 1. newFile nextPut: 12 asCharacter]]. newFile shorten; readOnly. SourceFiles at: 1 put: newFile. SourceFiles at: 2 put: (Disk file: vers , '.changes'). (SourceFiles at: 2) shorten; readOnly!renameSystemFiles: newVersion "Rename the sources and changes and image files. Smalltalk renameSystemFiles: Smalltalk versionName. Then rename the relevant .run and .syms files manually." | oldFile oldName oldVersion file | oldFile _ SourceFiles at: 1. oldName _ oldFile name. oldVersion _ oldName copyFrom: 1 to: (oldName indexOf: $.) - 1. (SourceFiles at: 1) close. SourceFiles at: 1 put: nil. (SourceFiles at: 2) close. SourceFiles at: 2 put: nil. #('.sources' '.changes' '.im' ) do: [:ext | (Disk file: oldVersion , ext) file rename: newVersion , ext]. 1 to: 2 do: [:i | file _ Disk file: newVersion , (#('.sources' '.changes' ) at: i). file readOnly. SourceFiles at: i put: file]! !!SystemDictionary methodsFor: 'printing'!printOn: aStream "Intercepted to avoid infinite recursion when #Smalltalk is reached." | tooMany | tooMany _ aStream position + self maxPrint. aStream nextPutAll: self class name, ' keys ('. self keysDo: [:key | aStream position > tooMany ifTrue: [aStream nextPutAll: '...etc...)'. ^self]. key printOn: aStream. aStream space]. aStream nextPut: $)! !!SystemDictionary methodsFor: 'private'!exitToDebugger "Enter the machine language debugger, if one exists. Essential. See Object documentation whatIsAPrimitive. " <primitive: 114> self primitiveFailed!lowSpaceNotificationLoop [true] whileTrue: [LowSpaceSemaphore wait. ScheduledControllers interruptName: 'Space is Low'. self resetSpaceLimits]!quitPrimitive "Exit to another operating system on the host machine, if one exists. All state changes in the object space since the last snapshot are lost. Essential. See Object documentation whatIsAPrimitive." <primitive: 113> self primitiveFailed!releaseExternalViews SourceFiles==nil ifFalse: [SourceFiles do: [:t | t==nil ifFalse: [t close]]]. Disk==nil ifFalse: [Disk close]. FileDirectory releaseExternalReferences!snapshotPrimitive "Write the current state of the object memory on a file in the same format as the Smalltalk-80 release. The file can later be resumed, returning you to this exact state. Return normally after writing the file. Essential. See Object documentation whatIsAPrimitive." <primitive: 97> self primitiveFailed!specialSelectors "Used by SystemTracer only" ^SpecialSelectors! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SystemDictionary class instanceVariableNames: ''!!SystemDictionary class methodsFor: 'class initialization'!initialize Project current noChanges "SystemDictionary initialize"! !SystemDictionary initialize! ClassOrganizer subclass: #SystemOrganizer instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Support'!SystemOrganizer comment: 'Provides an organization for the classes in the system just as ClassOrganizer organizes the messages within a class. The only difference is the filout/printing messages.'!!SystemOrganizer methodsFor: 'fileIn/Out'!fileOutCategory: category | aFileStream | aFileStream _ Disk file: (category , '.st.') asFileName. self fileOutCategory: category on: aFileStream. aFileStream shorten; close!fileOutCategory: category on: aFileStream | class first | first _ true. (self superclassOrder: category) do: [:class | first ifTrue: [first _ false] ifFalse: [aFileStream cr; nextPut: Character newPage; cr]. class fileOutOn: aFileStream moveSource: false toFile: 0. class removeFromChanges]!printOutCategory: category "Create a file with readable version of the classes in this category. Default to fileOut." self fileOutCategory: category!superclassOrder: category "Answer an ordered collection containing the classes in category (a string). The classes are ordered with superclasses first so they can be filed in." | list | list _ (self listAtCategoryNamed: category asSymbol) collect: [:title | Smalltalk at: title]. ^ ChangeSet superclassOrder: list! !!SystemOrganizer methodsFor: 'accessing'!changeFromString: aString "Intercept to notify the system change set of the system reorganization." | file | SourceFiles == nil ifFalse: [file _ SourceFiles at: 2. file setToEnd; readWriteShorten. file cr; nextChunkPut: 'SystemOrganization changeFromString: ', SystemOrganization printString storeString. file cr; readOnly]. Smalltalk changes reorganizeSystem. super changeFromString: aString.! ! Object subclass: #SystemTracer instanceVariableNames: 'map refcts file holder writeDict maxOop specialObjects initialProcess ot bank addr ' classVariableNames: 'Clamped MT NewNil NoRefs ODD OVref PTRS ' poolDictionaries: '' category: 'System-Releasing'!SystemTracer comment:'Instance Variables: map <Array> of new oops indexed by old oops refcts <ByteArray> encoding refcts and clamping file <FileStream> for writing vmem image holder <Stream> of objects created just for the new image writeDict <Dictionary> of writing selectors for each class maxOop <Integer> number of objects written in clone specialObjects <Array> of objects to get first N oops in clone initialProcess <Process> to resume at startup ot <FileStream> for writing OT bank <Integer> high bits of object offest in image addr <Integer> low bitsThe system Tracer is the secret weapon of Smalltalk developers. Some people think it is an overnight garbage collector. It is; in fact on a decent machine (heh, heh), it is a coffee-break garbage collector. But the real value of the tracer is that it allows fundamental changes to be made to the system from within.Basically, the tracer runs through the system tracing every accessible object, and writing a copy of each object onto a disk image. It does this carefully enough that the resulting clone can be started up and run, just like a snapshot. Some care is taken so that objects appear in the same order in the data space as they do in the object table.The tracer has built-in support for clamping unwanted (or unneeded) classes out of the system. Use the message writeCloneWithout: for this. A considerably more powerful clamping mechanism is the message winnowing feature. It will cull out all unreferenced messages, and then based on THOSE deletions, cull out more and so on. See the comment in winnow.Examples of things we have done with the SystemTracer include changing the instruction set of Smalltalk. For this we define a subclass called Junta which defines a special method for writing CompiledMethods out in the new format. Then we change the virtual machine and fire up the clone. Another example is changing the format of FloatingPoint numbers'!!SystemTracer methodsFor: 'initialize-release'!doitWithout: classSet | time1 time2 ctxt n | ctxt _ thisContext sender. ctxt push: nil. self init: ctxt. self initClampedClasses: classSet. FileDirectory initializeExternalReferences. Smalltalk shutdown. "Make sure the system is stable underneath us." Transcript show: 'Tracing . . . '. time1 _ Time now asSeconds. n _ self writeImage: (Array with: Smalltalk). time2 _ Time now asSeconds. Transcript print: n; show: ' objects, words, '; print: time2 - time1; show: ' sec.'; cr. Smalltalk install. "Allow things to change again." ctxt pop "So we can resume"!init: aContext initialProcess _ Process forContext: aContext priority: Processor activePriority. refcts _ ByteArray new: 49152. map _ WordArray new: 49152. file _ Disk file: 'clone.im'. file binary. ot _ Disk file: 'ot.scratch'. ot binary. holder _ ReadWriteStream on: (Array new: 100). maxOop _ 0. self clamp: self. self initDict!initClampedClasses: classSet | x | classSet isEmpty ifTrue: [^self]. classSet do: [:class | self clamp: class]. Smalltalk allBehaviorsDo: [:class | class superclass == nil & ((writeDict at: class) ~= #writeClamped:) ifTrue: [class == Object ifFalse: [self error: class name , 'superclass is clamped!!!!!!!!']]]. SystemOrganization removeEmptyCategories. Smalltalk newClassNames; noChanges. Browser allInstancesDo: [:x | x updateCategories]. Smalltalk newSourceFile: 'Smalltalk80' without: classSet!initDict writeDict _ Dictionary new: 256. Smalltalk allBehaviorsDo: [:class | writeDict at: class put: #writePointers:. class isBits ifTrue: [writeDict at: class put: (class isBytes ifTrue: [#writeBytes:] ifFalse: [#writeWords:])] ifFalse: [(class inheritsFrom: Set) | (class == Set) ifTrue: [writeDict at: class put: #writeSet:]. (class inheritsFrom: IdentityDictionary) | (class == IdentityDictionary) ifTrue: [writeDict at: class put: #writeIdentityDictionary:]]]. writeDict at: SmallInteger put: #writeClamped:. writeDict at: CompiledMethod put: #writeMethod:. writeDict at: Process put: #writeProcess:!new: obj class: class length: length trace: traceBlock write: writeBlock | oop objpos endpos | oop_ self oopOf: obj. (refcts at: oop)=NoRefs ifTrue: "create a new ot entry" [map at: oop put: (maxOop_ maxOop+1). refcts at: oop put: 1. ot nextWordPut: oop. "save oop; fill in refct in pass2" ot nextPut: bank + (class isBits ifTrue: [(class isBytes and: [obj size even == false]) ifTrue: [ODD] ifFalse: [0]] ifFalse: [PTRS]). ot nextWordPut: addr. addr _ addr + length+2. addr >= 65536 ifTrue: [addr _ (addr - 65536) truncated. bank _ bank + 1]] ifFalse: [(map at: oop)>specialObjects size ifTrue: [self error: 'double write!!']]. objpos_ file position. file skip: length+2*2. traceBlock notNil ifTrue: [self trace: class. traceBlock value]. endpos_ file position. file position: objpos. self writeBitField: length+2. self writePointerField: class. writeBlock value. file position: endpos!preserve: refs "This message should puts into the set 'refs' all the messages considered as roots in the system to be winnowed. Those given below are a minimal set. See the comment in winnow:" 1 to: Smalltalk specialSelectorSize do: "these at least" [:i | refs add: (Smalltalk specialSelectorAt: i)]. refs addAll: #(doesNotUnderstand: cannotReturn: monitor: unusedOop51). refs addAll: #() "Lots more here for a real trace"!winnow: nPasses "This method will clamp message out of the cloning process. First it calls preserve: to establish a root set of messages which must not be deleted. Then it makes a pass through the system figuring out which messages are not called from anywhere except in classes which have already been clamped. Then it makes another pass, picking up those which are now unreferenced due to the preceding deletions. And so on; usually 6 iterations gets most everything. It is advisable to run just the winnow phase of the trace (2 passes, say) ExportTracer new init: thisContext; winnow: 2 and then read the file chaff.st to see what got zapped, before doing a full trace. Chances are, you will have forgotten to include several messages in preserve: (qv)." | f refs class sel lit method first | f _ Disk file: 'chaff.st'. " 6 iterations gets most everything" 1 to: nPasses do: [:i | Transcript show: 'Winnow pass ' , i printString; cr; endEntry. refs _ Set new: 4096. self preserve: refs. Smalltalk allBehaviorsDo: [:class | "collect all refs" (self hasClamped: class) ifFalse: [class selectors do: [:sel | method _ class compiledMethodAt: sel. (self hasClamped: method) ifFalse: [method literals do: [:lit | (lit isMemberOf: Symbol) ifTrue: [refs add: lit]]]]]]. Smalltalk allBehaviorsDo: [:class | "collect all unrefs" (self hasClamped: class) ifFalse: [first _ true. class selectors do: [:sel | (refs includes: sel) ifFalse: [method _ class compiledMethodAt: sel. (self hasClamped: method) ifFalse: [first ifTrue: [first _ false. f cr; cr; nextPutAll: class name; space]. self clamp: (class compiledMethodAt: sel). class organization removeElement: sel. f nextPutAll: sel; space]]]]]. f cr; nextPutAll: '------------'; cr]. f close! !!SystemTracer methodsFor: 'image'!writeImage: roots | datalen otlen root oop i | ot readWrite. file readWrite. file position: 512. "Skip header page" ot position: 0. addr _ bank _ 0. self writeSpecial1. roots do: [:root | self trace: root]. self writeSpecial2. datalen _ file position - 512 // 2. ot shorten. otlen _ ot position // 5 + 1 * 2. file padTo: 512 put: 0. ot position: 0. file nextWordPut: MT. file nextWordPut: 0. "oop zero" 1 to: maxOop do: [:i | "append the OT, rectifying reference counts" oop _ ot nextWord. file nextPut: (refcts at: oop). file nextPut: ot next. file nextPut: ot next. file nextPut: ot next]. file shorten. "info in header page" file position: 0. file nextWordPut: datalen // 65536. file nextWordPut: datalen \\ 65536. file nextWordPut: otlen // 65536. file nextWordPut: otlen \\ 65536. file nextWordPut: 0. file padTo: 512 put: 0. "Pad header page" ot close. file close. ^Array with: otlen // 2 with: datalen!writeSpecial1 | obj | specialObjects _ "1:" (Array with: nil with: false with: true with: (Smalltalk associationAt: #Processor)) , "5:" (Array with: Symbol table with: SmallInteger with: String with: Array) , "9:" (Array with: (Smalltalk associationAt: #Smalltalk) with: Float with: MethodContext with: BlockContext) , "13:" (Array with: Point with: LargePositiveInteger with: DisplayBitmap with: Message) , "17:" (Array with: CompiledMethod with: #unusedOop18 with: Semaphore with: Character) , "21:" (Array with: #doesNotUnderstand: with: #cannotReturn: with: #monitor: with: Smalltalk specialSelectors) , "25:" (Array with: Character characterTable with: #mustBeBoolean). specialObjects size = 26 ifFalse: [self error: 'try again!!']. specialObjects do: "create OT entries" [:obj | self new: obj class: obj class length: (self sizeInWordsOf: obj) trace: nil write: []. refcts at: (self oopOf: obj) put: OVref "jam refcts of special objects"]. self trace: #Smalltalk; trace: #Processor "need to get mapped now"!writeSpecial2 | obj pos max oldTable | specialObjects do: [:obj | "make sure parts are written (will cause extra ref)" self trace: obj class. obj == Symbol table | obj class isBits ifFalse: [1 to: (self sizeInWordsOf: obj) do: [:i | self trace: (obj instVarAt: i)]]]. oldTable _ Symbol table copy. "trim Symbol table to only those UStrings used" 1 to: Symbol table size do: [:i | Symbol table at: i put: ((Symbol table at: i) select: [:obj | (refcts at: (self oopOf: obj)) > NoRefs])]. 1 to: (self sizeInWordsOf: Symbol table) do: [:i | self trace: (Symbol table instVarAt: i)]. pos _ file position. file position: 512. max _ maxOop. specialObjects do: [:obj | "go back and write data after tracing" self perform: (writeDict at: obj class) with: obj]. max ~= maxOop ifTrue: [self error: 'bug in tracer']. file position: pos. specialObjects do: [:obj | "undo the extra refs due to specialObjects" self unref: obj class. obj class isBits ifFalse: [1 to: (self sizeInWordsOf: obj) do: [:i | self unref: (obj instVarAt: i)]]]. Symbol table: oldTable. self unref: #Smalltalk; unref: #Processor! !!SystemTracer methodsFor: 'tracing and writing'!trace: obj | oop refct | (obj isMemberOf: SmallInteger) ifTrue: [^self]. oop _ self oopOf: obj. refct _ refcts at: oop. refct >= OVref ifTrue: [^self]. refct > NoRefs ifTrue: [refcts at: oop put: refct + 1. ^self]. self perform: (writeDict at: obj class) with: obj!writeBitField: bits bits class == SmallInteger ifTrue: [file nextPut: (bits bitShift: -8). file nextPut: (bits bitAnd: 255)] ifFalse: [file nextPut: (bits at: 2). file nextPut: (bits at: 1)]!writeBytes: obj self new: obj class: obj class length: (self sizeInWordsOf: obj) trace: [] write: [1 to: obj size do: [:i | file nextPut: (obj at: i) asInteger]. file padToNextWordPut: 0]!writeClamped: obj "Take no action"!writeIdentityDictionary: obj "Elements of an IdentityDict need to be reOrdered owing to new oops" "Here we also support removal of entries for clamped values" | i perm fixPart length objCopy | objCopy _ obj copy. objCopy keys do: [:key | (self hasClamped: (objCopy at: key)) ifTrue: [objCopy removeKey: key]]. holder nextPut: objCopy. fixPart _ objCopy class instSize. self new: obj class: objCopy class length: (length _ self sizeInWordsOf: objCopy) trace: ["map the keys first" 3 to: length do: [:i | self trace: (objCopy instVarAt: i)]. perm _ self permutation: [:key | "IdentityDicts hash by asOop, not hash" key class == SmallInteger ifTrue: [self newSmallIntegerHash: key] ifFalse: [self newHashFor: key asOop]] for: objCopy. self permute: (objCopy instVarAt: 2) by: perm. "and permute the new value vector" 1 to: 2 do: [:i | self trace: (objCopy instVarAt: i)]] write: [1 to: fixPart do: [:i | self writePointerField: (objCopy instVarAt: i)]. 1 to: objCopy basicSize do: [:i | self writePointerField: ((perm at: i) == nil ifFalse: [objCopy instVarAt: (perm at: i) + fixPart])]]!writeMethod: obj | nptrs | nptrs _ obj numLiterals + 1. self new: obj class: obj class length: (self sizeInWordsOf: obj) trace: [1 to: nptrs do: [:i | self trace: (obj objectAt: i)]] write: [1 to: nptrs do: [:i | self writePointerField: (obj objectAt: i)]. nptrs * 2 + 1 to: obj size do: [:i | file nextPut: (obj at: i)]. file padToNextWordPut: 0]!writePointerField: obj | oop | (obj isMemberOf: SmallInteger) ifTrue: [file nextPut: ((obj bitShift: -7) bitAnd: 255). file nextPut: (obj bitAnd: 127) * 2 + 1] ifFalse: [oop _ map at: (self oopOf: obj). oop = 0 ifTrue: [oop _ NewNil]. file nextPut: ((oop bitShift: -7) bitAnd: 255). file nextPut: (oop bitAnd: 127) * 2 + 0]!writePointers: obj | length | self new: obj class: obj class length: (length _ self sizeInWordsOf: obj) trace: [1 to: length do: [:i | self trace: (obj instVarAt: i)]] write: [1 to: length do: [:i | self writePointerField: (obj instVarAt: i)]]!writeProcess: obj "Substitute new initialProcess for current" | length newObj | newObj _ obj == Processor activeProcess ifTrue: [initialProcess] ifFalse: [obj]. self new: obj class: newObj class length: (length _ self sizeInWordsOf: newObj) trace: [1 to: length do: [:i | self trace: (newObj instVarAt: i)]] write: [1 to: length do: [:i | self writePointerField: (newObj instVarAt: i)]]!writeSet: obj "Elements of a Set need to be reOrdered owing to new oops" | perm length assoc | self new: obj class: obj class length: (length _ self sizeInWordsOf: obj) trace: [1 to: length do: [:i | self trace: (obj instVarAt: i)]. "map the elements first" perm _ self permutation: [:key | key hashMappedBy: self] for: obj] write: [1 to: obj class instSize do: [:i | self writePointerField: (obj instVarAt: i)]. 1 to: obj basicSize do: [:i | self writePointerField: ((perm at: i) == nil ifFalse: [obj basicAt: (perm at: i)])]]!writeWords: obj | length | self new: obj class: obj class length: (length _ self sizeInWordsOf: obj) trace: [] write: [1 to: length do: [:i | self writeBitField: (obj instVarAt: i)]]! !!SystemTracer methodsFor: 'static checks'!allCallsOn: aLiteral clampedBy: nameSet "Specialized version of the SystemDictionary allCallsOn:, which doesnt include calls from clamped classes." | aSortedCollection classNames class name special | aSortedCollection _ SortedCollection new. special _ Smalltalk hasSpecialSelector: aLiteral ifTrueSetByte: [:byte ]. classNames _ Smalltalk classNames. nameSet do: [:name | classNames remove: name ifAbsent: []]. Cursor execute showWhile: [classNames do: [:name | class _ Smalltalk at: name. (class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [aSortedCollection add: class name , ' ' , sel]]. class _ class class. (class whichSelectorsReferTo: aLiteral special: special byte: byte) do: [:sel | sel ~~ #DoIt ifTrue: [aSortedCollection add: class name , ' ' , sel]]]]. ^aSortedCollection!printDanglingRefs "SystemTracer new printDanglingRefs." "Use this method to locate calls on classes and other global objects which are to be clamped from the system" | class x clamped f dangling | clamped _ Set new. "clamp entire categories of classes: " (SystemOrganization categories select: [:x | 'ClampThis*' match: x]) do: [:str | (SystemOrganization superclassOrder: str) do: [:class | clamped add: class name]]. "clamp individual classes and other Globals: " (Array with: #AltoFile with: #AltoFileDirectory with: #AltoFilePage) do: [:x | clamped add: x]. Smalltalk allBehaviorsDo: [:class | (class organization categories select: [:name | ('clampme*' match: name)]) do: [:name | Transcript print: class; space; nextPutAll: name; cr; endEntry. class removeCategory: name]. ]. f_ Disk file: 'dangling.st'. clamped do: [:name | dangling _ self allCallsOn: (Smalltalk associationAt: name) clampedBy: clamped. dangling isEmpty ifFalse: [f cr; nextPutAll: name; cr. dangling do: [:x | f tab; nextPutAll: x; cr]]]. f close! !!SystemTracer methodsFor: 'private'!asOopFromIndex: oop "Convert from OT index to values returned by asOop" oop <= 16383 ifTrue: [^ oop] ifFalse: [^ oop - 32768]!asOopToIndex: oop "Unscramble asOop values to return OT index in range 1 to 32767." oop < 0 ifTrue: [^ oop + 32768] ifFalse: [^ oop]!clamp: obj refcts at: (self oopOf: obj) put: Clamped. (obj isKindOf: Behavior) ifTrue: [writeDict at: obj put: #writeClamped:. Smalltalk removeKey: obj name. SystemOrganization removeElement: obj name]!hasClamped: obj obj class == SmallInteger ifTrue: [^false]. ^(refcts at: (self oopOf: obj)) = Clamped!newHashFor: asOop "This is what asOop will return in the cloned system. asOop is what asOop returns in the current system" ^ self asOopFromIndex: (map at: (self asOopToIndex: asOop))!newSmallIntegerHash: anInteger ^ anInteger asOop!oopOf: obj "Returns an OT index, also suitable for indexing map and refcts. obj must not be a SmallInteger." ^ self asOopToIndex: obj asOop!permutation: permutationBlock for: array | len perm key hash | "Return an inverse permutation for an array to permute it according to the mapped oop values. The keys in array MUST have been mapped." len _ array basicSize. perm _ Array new: len. 1 to: len do: [:i | key _ array basicAt: i. (key == nil or: [self hasClamped: key]) ifFalse: [hash _ permutationBlock value: key. hash _ hash \\ len + 1. [(perm at: hash) == nil] whileFalse: [hash _ (hash = len ifTrue: [1] ifFalse: [hash + 1])]. perm at: hash put: i]]. ^perm!permute: vec by: perm | copy j len inverse | (perm isMemberOf: Interval) ifTrue: [^perm"no-op for 1~n identity"]. len _ vec size. copy _ Array new: len. inverse _ Array new: len. 1 to: len do: [:i | (j _ perm at: i) == nil ifFalse: [copy at: i put: (vec at: j). inverse at: j put: i]]. 1 to: len do: [:i | vec at: i put: (copy at: i)]. ^inverse!refctOf: obj (obj isMemberOf: SmallInteger) ifTrue: [^0]. ^refcts at: (self oopOf: obj)!sizeInWordsOf: anObject | class | class_ anObject class. class isBytes ifTrue: [^anObject size+1//2]. class isVariable ifTrue: [^class instSize+anObject basicSize]. ^class instSize!unref: obj | oop refct | (obj isMemberOf: SmallInteger) ifTrue: [^self]. oop _ self oopOf: obj. (refct _ refcts at: oop) = OVref ifTrue: [^self]. refct = 1 ifTrue: [self error: 'deleting last ref']. refcts at: oop put: refct - 1! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!SystemTracer class instanceVariableNames: ''!!SystemTracer class methodsFor: 'class initialization'!initialize "SystemTracer initialize." ODD _ 128. PTRS _ 64. MT _ 32. NoRefs _ 0. OVref _ 128. Clamped _ 255. NewNil _ 1! !!SystemTracer class methodsFor: 'cloning'!writeClone "This message creates and runs a SystemTracer: SystemTracer writeClone. If all goes well, it will produce a file called clone.im which is a valid image file" self writeCloneWithout: Set new!writeCloneWithout: aSet "This message creates and runs a SystemTracer without the sets named: SystemTracer writeCloneWithout: (Set with: AltoFilePage with: AltoFile with: AltoFileDirectory). If all goes well, it will produce a file called clone.im which is a valid image file" | tracer | tracer_ self new. tracer doitWithout: aSet. tracer == nil ifTrue: [Smalltalk install. ScheduledControllers restore. Disk == nil ifFalse: [Disk release]] " Below are checks for things which might cause the Tracer to run amock: Checker rehashBadSets Smalltalk obsoleteClasses do: [:class | class obsolete] BrowserView openListBrowserOn: Smalltalk obsoleteClassReferences label: 'References to Obsolete Classes' Smalltalk classNames select: [:x | (Smalltalk at: x) superclass class ~~ (Smalltalk at: x) class superclass] "! !SystemTracer initialize! ArrayedCollection subclass: #Text instanceVariableNames: 'string runs ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Collections-Text'!Text comment: 'Instance Variables: string: A String of Characters runs: A RunArray of emphasis codes The emphasis codes indicate abstract changes in character appearance. Actual display is performed in the presence of a TextStyle which indicates, for each abstract code, an actual font to be used'!!Text methodsFor: 'comparing'!= anotherText ^string = anotherText string! !!Text methodsFor: 'accessing'!at: index ^string at: index!at: index put: character ^string at: index put: character!findString: aString startingAt: start "Answer the index of subString within the receiver, starting at position start. If the receiver does not contain subString, answer 0." ^string findString: aString asString startingAt: start!replaceFrom: start to: stop with: aText string _ string copyReplaceFrom: start to: stop with: aText string. runs _ runs copyReplaceFrom: start to: stop with: aText runs!size ^string size!string "Answer the string representation of the receiver." ^string! !!Text methodsFor: 'copying'!copy ^self deepCopy!copyFrom: start to: stop "Answer with a copied subrange of this text" | realStart realStop | stop > self size ifTrue: [realStop _ self size] "handle selection at end of string" ifFalse: [realStop _ stop]. start < 1 ifTrue: [realStart _ 1] "handle selection before start of string" ifFalse: [realStart _ start]. ^Text string: (string copyFrom: realStart to: realStop) runs: (runs copyFrom: realStart to: realStop)!copyReplaceFrom: start to: stop with: aText ^self shallowCopy replaceFrom: start to: stop with: aText! !!Text methodsFor: 'converting'!asDisplayText "Answer a DisplayText whose text is the receiver." ^DisplayText text: self!asLowercase string _ string asLowercase!asNumber "Answer the number created by interpreting the receiver as the textual representation of a number." ^string asNumber!asParagraph "Answer a Paragraph whose text is the receiver." ^Paragraph withText: self!asString "Answer a String representation of the textual receiver." ^string!asText "Answer the receiver itself." ^self!asUppercase string _ string asUppercase! !!Text methodsFor: 'emphasis'!allBold self emphasizeFrom: 1 to: self size with: 2!emphasisAt: characterIndex "Answer the code for characters in the run beginning at characterIndex." self size = 0 ifTrue: [^1]. "null text tolerates access" ^runs at: characterIndex!emphasizeFrom: start to: stop with: emphasis "Set the emphasis for characters in the interval start-stop." runs _ runs copyReplaceFrom: start to: stop with: (RunArray new: stop - start + 1 withAll: emphasis)!makeSelectorBoldIn: aClass "For formatting Smalltalk source code, set the emphasis of that portion of the receiver's string that parses as a message selector to be bold." | parser | string size = 0 ifTrue: [^self]. (parser _ aClass parserClass new) parseSelector: string. self emphasizeFrom: 1 to: (parser endOfLastToken min: string size) with: 2!runLengthFor: characterIndex "Answer the count of characters remaining in run beginning with characterIndex." ^runs runLengthAt: characterIndex! !!Text methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'Text for '. string printOn: aStream!storeOn: aStream aStream nextPutAll: '(Text string: '; store: string; nextPutAll: ' runs: '; store: runs; nextPut: $)! !!Text methodsFor: 'private'!runs ^runs!setString: aString setRuns: anArray string _ aString. runs _ anArray! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Text class instanceVariableNames: ''!!Text class methodsFor: 'class initialization'!initialize "Initialize constants shared by classes associated with text display. Text initialize." (Smalltalk includes: TextConstants) ifFalse: [Smalltalk at: #TextConstants put: (Dictionary new: 32)]. TextConstants at: #CaretForm put: (Cursor extent: 16@16 fromArray: #( 2r110000000 2r110000000 2r1111000000 2r11111100000 2r11001100000 2r0 2r0 2r0 2r0 2r0 2r0 2r0 2r0 2r0 2r0 2r0) offset: 8@0). self initTextConstants!initTextConstants "Text initTextConstants." "Initialize constants shared by classes associated with text display, e.g., space, tab, cr, bs, esc." | tempArray | TextConstants at: #Space put: (32 asCharacter). TextConstants at: #Tab put: (9 asCharacter). TextConstants at: #CR put: (13 asCharacter). TextConstants at: #BS put: (8 asCharacter). TextConstants at: #BS2 put: (158 asCharacter). TextConstants at: #Ctrlw put: (145 asCharacter). TextConstants at: #ESC put: (160 asCharacter). TextConstants at: #Cut put: (173 asCharacter). TextConstants at: #Paste put: (30 asCharacter). TextConstants at: #Ctrlt put: (11 asCharacter). TextConstants at: #Ctrlf put: (12 asCharacter). TextConstants at: #Ctrlz put: (26 asCharacter). "in case font doesn't have a width for space character" "some plausible numbers-- are there right ones?" TextConstants at: #DefaultSpace put: 4. TextConstants at: #DefaultTab put: 24. TextConstants at: #DefaultLineGrid put: 16. TextConstants at: #DefaultBaseline put: 12. TextConstants at: #DefaultRule put: Form over. TextConstants at: #DefaultMask put: Form black. TextConstants at: #CtrlMinus put: (137 asCharacter). TextConstants at: #CtrlShiftMinus put: (201 asCharacter). TextConstants at: #Ctrlb put: (166 asCharacter). TextConstants at: #CtrlB put: (230 asCharacter). TextConstants at: #Ctrli put: (150 asCharacter). TextConstants at: #CtrlI put: (214 asCharacter). TextConstants at: #Ctrlx put: (151 asCharacter). tempArray _ Array new: Display width // DefaultTab. 1 to: tempArray size do: [:i | tempArray at: i put: DefaultTab * i]. TextConstants at: #DefaultTabsArray put: tempArray. tempArray _ Array new: (Display width // DefaultTab) // 2. 1 to: tempArray size do: [:i | tempArray at: i put: (Array with: (DefaultTab*i) with: (DefaultTab*i))]. TextConstants at: #DefaultMarginTabsArray put: tempArray. self initTextConstants2.!initTextConstants2 "Text initTextConstants." "Initialize constants shared by classes associated with text display, e.g., space, tab, cr, bs, esc." TextConstants at: #Ctrlh put: (179 asCharacter). TextConstants at: #CtrlH put: (243 asCharacter). TextConstants at: #Ctrls put: (19 asCharacter). TextConstants at: #CtrlS put: (211 asCharacter). TextConstants at: #Ctrln put: (14 asCharacter). TextConstants at: #CtrlN put: (245 asCharacter). TextConstants at: #Ctrlp put: (138 asCharacter). TextConstants at: #CtrlTopBlank put: (222 asCharacter). TextConstants at: #CtrlMiddleBlank put: (229 asCharacter). TextConstants at: #CtrlBottomBlank put: (225 asCharacter). "location of non-character stop conditions" TextConstants at: #EndOfRun put: 257. TextConstants at: #CrossedX put: 258. "values for alignment" TextConstants at: #LeftFlush put: 0. TextConstants at: #RightFlush put: 1. TextConstants at: #Centered put: 2. TextConstants at: #Justified put: 3. "subscripts for a marginTabsArray tuple" TextConstants at: #LeftMarginTab put: 1. TextConstants at: #RightMarginTab put: 2. "font faces" TextConstants at: #Basal put: 0. TextConstants at: #Bold put: 1. TextConstants at: #Italic put: 2. TextConstants at: #BoldItalic put: 3. TextConstants at: #Underlined put: 4. TextConstants at: #OverStruck put: 8. TextConstants at: #Subscripted put: 16. TextConstants at: #Superscripted put: 32. TextConstants at: #SubscriptedUnderlined put: 20. TextConstants at: #SuperscriptedUnderlined put: 36. TextConstants at: #UnderlinedBit put: 3. TextConstants at: #OverStruckBit put: 4. TextConstants at: #SubscriptedBit put: 5. TextConstants at: #SuperscriptedBit put: 6. TextConstants at: #SubSuperscriptMask put: 48. TextConstants at: #NonFaceEmphasisMask put: 52. "overstrike not supported" TextConstants at: #FamilyName put: 1. TextConstants at: #PointSize put: 2. TextConstants at: #Face put: 3.! !!Text class methodsFor: 'instance creation'!fromString: aString "Answer an instance of me whose characters are those of the argument, aString." ^self string: aString emphasis: 1!fromUser "Answer an instance of me obtained by requesting the user to type some characters into a View." | result | FillInTheBlank request: 'Type text followed by carriage return' displayAt: (50@ Display boundingBox height//2) centered: false action: [:result] initialAnswer: ''. ^self fromString: result!new: stringSize ^self fromString: (String new: stringSize)!string: aString emphasis: code "Answer an instance of me whose characters are those of the argument, aString. Use the font whose index into the default TextStyle font array is code." ^self string: aString runs: (RunArray new: aString size withAll: code)! !!Text class methodsFor: 'private'!string: aString runs: anArray ^self basicNew setString: aString setRuns: anArray! !Text initialize! StringHolder subclass: #TextCollector instanceVariableNames: 'entryStream ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Transcript'!TextCollector comment:'I represent a StringHolder into which text can also be gathered by sending messages using Stream protocol.Instance Variables entryStream <WriteStream>'!!TextCollector methodsFor: 'initialize-release'!initialize super initialize. self beginEntry! !!TextCollector methodsFor: 'accessing'!next: anInteger put: aCharacter "Insert the character, aCharacter, at position anInteger in the text." ^entryStream next: anInteger put: aCharacter!nextPut: aCharacter "Append aCharacter to the text." ^entryStream nextPut: aCharacter!nextPutAll: aCollection "Append all the characters in aCollection to the text." ^entryStream nextPutAll: aCollection!show: aString "Append all the characters in aCollection to the text and display the text." self nextPutAll: aString. self endEntry! !!TextCollector methodsFor: 'clearing'!clear "Re-initialize the text to contain no characters." contents _ Text new. self beginEntry. self changed: #update "Transcript clear"!refresh "Bring window to front on screen" self changed: #refresh "Transcript refresh"! !!TextCollector methodsFor: 'entry control'!appendEntry "Append the text contents of the receiver's WriteStream to its text." contents _ contents , self nextEntry asText. contents size > self characterLimit ifTrue: [contents _ contents copyFrom: contents size - (self characterLimit // 2) to: contents size]. self beginEntry!beginEntry "To speed up appending information to the receiver, a WriteStream is maintained. Initialize it." entryStream _ WriteStream on: (String new: 200)!endEntry "If the receiver's WriteStream is not empty, then reinitialize it. Send all depends a message that the streaming has changed." entryStream isEmpty ifFalse: [self changed: #appendEntry. self beginEntry]!nextEntry "Answer the text contents of the receiver's WriteStream." ^entryStream contents! !!TextCollector methodsFor: 'character writing'!cr "Append a carriage return to the text." ^entryStream cr!crtab "Append a carriage return and a tab to the text." ^entryStream crtab!crtab: anInteger "Append a carriage return and anInteger number of tabs to the text." ^entryStream crtab: anInteger!space "Append a space to the text." ^entryStream space!tab "Append a tab to the text." ^entryStream tab! !!TextCollector methodsFor: 'printing'!print: anObject "Append a description of the object, anObject, to the text." ^entryStream print: anObject!store: anObject "Have anObject print on me for rereading." anObject storeOn: self! !!TextCollector methodsFor: 'private'!characterLimit ^2000! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextCollector class instanceVariableNames: ''!!TextCollector class methodsFor: 'system'!newTranscript: aTextCollector "Store aTextCollector as the value of the system global Transcript." Smalltalk at: #Transcript put: aTextCollector. ^aTextCollector! !!TextCollector class methodsFor: 'examples'!example "TextCollectors support WriteStream protocol for appending characters to the System Transcript." Transcript show: (3+4) printString; cr. Transcript nextPutAll: '3+4 ='; space; print: 3+4; cr; endEntry "TextCollector example"! ! StringHolderController subclass: #TextCollectorController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Transcript'!TextCollectorController comment:'I am a kind of StringHolderController (a ParagraphEditor) that adds the doIt, printIt, accept, and cancel commands. I do not change the yellow button menu. I do add methods for accepting text that was generated from Stream-like messages to the model, a TextCollector'!!TextCollectorController methodsFor: 'entry control'!appendEntry "Append the text in the model's writeStream to the editable text." "revised 9/14/82 SBP" view topView isCollapsed ifTrue: [paragraph text replaceFrom: 1 to: paragraph text size with: model contents] ifFalse: [self deselect. paragraph text size > model characterLimit ifTrue: [paragraph removeFirstChars: paragraph text size - (model characterLimit//2)]. self selectWithoutComp: paragraph text size + 1. self replaceSelectionWith: model nextEntry asText. self selectWithoutComp: paragraph text size + 1. self selectAndScroll. self deselect. model contents: paragraph text]!changeText: aText "The paragraph to be edited is changed to aText." paragraph text: aText. self resetState. self selectWithoutComp: paragraph text size + 1. self selectAndScroll. paragraph displayOn: Display. self deselect!viewToTop "Bring the view to top in z of screen." view topView isCollapsed ifFalse: [view display].! !!TextCollectorController methodsFor: 'private'!selectWithoutComp: characterIndex startBlock _ paragraph characterBlockForIndex: characterIndex. stopBlock _ startBlock copy! ! StringHolderView subclass: #TextCollectorView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Transcript'!TextCollectorView comment:'I am a StringHolderView of the description of the contents of a TextCollector or Transcript. TextCollectorController is my default controller.'!!TextCollectorView methodsFor: 'updating'!update: aParameter self topView isCollapsed ifTrue: [model appendEntry]. (self controller isKindOf: TextCollectorController) ifTrue: [aParameter == #appendEntry ifTrue: [^controller appendEntry]. aParameter == #update ifTrue: [^controller changeText: model contents asText]. aParameter == #refresh ifTrue: [^controller viewToTop]]! !!TextCollectorView methodsFor: 'controller access'!defaultControllerClass | t | t _ 0. ^TextCollectorController! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextCollectorView class instanceVariableNames: ''!!TextCollectorView class methodsFor: 'instance creation'!open "Answer an instance of me on a new TextCollector. Schedule it." ^self open: TextCollector new label: 'TextCollector'!open: aTextCollector label: aString "Answer an instance of me on the argument, aTextCollector. The label of the StandardSystemView should be aString." | topView aView | topView _ StandardSystemView new. topView model: aTextCollector. topView label: aString. topView minimumSize: 160 @ 120. aView _ self new model: aTextCollector. aView insideColor: Form white. aView borderWidth: 1. topView borderWidth: 1. topView addSubView: aView. topView controller open! ! ParagraphEditor subclass: #TextController instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!TextController comment:'This subclass of the paragraphEditor uses actionMenus for model control protocol.It also makes a stab (localMenuItem:) at the problem of distinguishing user controldirected at the model from that directed at the view/controller.This controller is more tightly connected to its view (for example it asks it for itsyellowButtonMenu), because the view is the current site for "pluggable" parameterization.'!!TextController methodsFor: 'menu messages'!accept (self textHasChanged and: [model changeRequestFrom: view]) ifFalse: [^view flash]. self controlTerminate. (view accept: self text from: self) ifTrue: [super accept] ifFalse: [view flash]. self controlInitialize!localMenuItem: selector ^ #(cut paste copySelection again undo cancel accept) includes: selector! !!TextController methodsFor: 'editing'!insertAndSelect: aString at: anInteger self selectAt: anInteger. self deselect. self replaceSelectionWith: (' ' , aString) asText. self selectAndScroll! !!TextController methodsFor: 'accessing'!paragraph ^ paragraph!textHasChanged ^ self text ~= initialText! !!TextController methodsFor: 'control activity'!yellowButtonActivity | index menu selector | menu _ view yellowButtonMenu. menu == nil ifTrue: [view flash. super controlActivity] ifFalse: [index _ menu startUpYellowButton. index ~= 0 ifTrue: [selector _ menu selectorAt: index. "editing to self, rest to model" (self localMenuItem: selector) ifTrue: [self perform: selector] ifFalse: [self controlTerminate. selector numArgs = 2 ifTrue: [model perform: selector with: self text with: self] ifFalse: [model perform: selector]. self controlInitialize]]]! !!TextController methodsFor: 'composition'!wrappingBox: wrapRectangle clippingBox: clipRectangle paragraph recomposeIn: wrapRectangle clippingBox: clipRectangle. self selectFrom: startBlock stringIndex to: stopBlock stringIndex-1! ! Interval subclass: #TextLineInterval instanceVariableNames: 'internalSpaces paddingWidth ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!TextLineInterval comment: 'A TextLineInterval specifies the starting and stopping points in a String of a composed line. The step is always 1. The internalSpaces is the number of spaces in the line, and the paddingWidth is the amount to be added to the font'!!TextLineInterval methodsFor: 'accessing'!internalSpaces "Answer the number of spaces in the line." ^internalSpaces!internalSpaces: spacesInteger "Set the number of spaces in the line to be spacesInteger." internalSpaces _ spacesInteger!paddingWidth "Answer the amount of space to be added to the font." ^paddingWidth!paddingWidth: padWidthInteger "Set the amount of space to be added to the font to be padWidthInteger." paddingWidth _ padWidthInteger!stop: stopInteger "Set the stopping point in the string of the line to be stopInteger." stop _ stopInteger! !!TextLineInterval methodsFor: 'comparing'!= line self species = line species ifTrue: [^((start = line first and: [stop = line last]) and: [internalSpaces = line internalSpaces]) and: [paddingWidth = line paddingWidth]] ifFalse: [^false]! !!TextLineInterval methodsFor: 'scanning'!justifiedPadFor: spaceIndex "Compute the width of pad for a given space in a line of justified text." | pad | internalSpaces = 0 ifTrue: [^0]. pad _ paddingWidth // internalSpaces. spaceIndex <= (paddingWidth \\ internalSpaces) ifTrue: [^pad + 1] ifFalse: [^pad]!justifiedTabDeltaFor: spaceIndex "Compute the delta for a tab in a line of justified text. So tab falls somewhere plausible when line is justified." | pad extraPad | internalSpaces = 0 ifTrue: [^0]. pad _ paddingWidth // internalSpaces. extraPad _ paddingWidth \\ internalSpaces. spaceIndex <= extraPad ifTrue: [^spaceIndex * (pad + 1)] ifFalse: [^extraPad * (pad + 1) + (spaceIndex - extraPad * pad)]! !!TextLineInterval methodsFor: 'updating'!slide: delta "Change the starting and stopping points of the line by delta." start _ start + delta. stop _ stop + delta! !!TextLineInterval methodsFor: 'copying'!deepCopy ^TextLineInterval start: start stop: stop internalSpaces: internalSpaces paddingWidth: paddingWidth! !!TextLineInterval methodsFor: 'private'!internalSpaces: spacesInteger paddingWidth: padWidthInteger internalSpaces _ spacesInteger. paddingWidth _ padWidthInteger! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextLineInterval class instanceVariableNames: ''!!TextLineInterval class methodsFor: 'instance creation'!start: startInteger stop: stopInteger internalSpaces: spacesInteger paddingWidth: padWidthInteger "Answer an instance of me with the arguments as the start, stop points, number of spaces in the line, and width of the padding." | newSelf | newSelf _ super from: startInteger to: stopInteger by: 1. ^newSelf internalSpaces: spacesInteger paddingWidth: padWidthInteger! ! Paragraph subclass: #TextList instanceVariableNames: 'list ' classVariableNames: 'ListStyle ' poolDictionaries: '' category: 'Interface-Lists'!TextList comment:'TextList is a subclass of Paragraph which is a more efficient representation of lists.Since it displays a list of items, it does not try to produce a single string with CRs,but instead simply makes up TextLineIntervals on the fly as needed by the view.The major savings come from not needing to make up a new string for the whole listand not having to measure the lines, since it is assumed that if they are too long,they will simply be clipped rather than wrapping to the next line.'!!TextList methodsFor: 'initialization'!compositionRectangle: compositionRect list: aList style: aTextStyle offset: aPoint outputMedium: aSymbol compositionRectangle _ compositionRect copy. list _ aList. text _ Text new. textStyle _ aTextStyle. firstIndent _ textStyle firstIndent. restIndent _ textStyle restIndent. rightIndent _ textStyle rightIndent. marginTabsLevel _ 0. outputMedium _ aSymbol. rule _ DefaultRule. mask _ DefaultMask. destinationForm _ Display. clippingRectangle _ destinationForm boundingBox. offset _ aPoint. lastLine _ list size. compositionRectangle height: textStyle lineGrid * lastLine! !!TextList methodsFor: 'line access'!lineAt: lineIndex ^ TextLineInterval start: 1 stop: (list at: lineIndex) size internalSpaces: 1 paddingWidth: 0!textAt: lineIndex ^ (list at: lineIndex) asText! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextList class instanceVariableNames: ''!!TextList class methodsFor: 'instance creation'!onList: aList ^self basicNew compositionRectangle: DefaultCompositionRectangle list: aList style: ListStyle offset: 0@0 outputMedium: #Display! !!TextList class methodsFor: 'class initialization'!initialize "TextList initialize." ListStyle _ DefaultTextStyle copy. ListStyle gridForFont: 1 withLead: 0! !TextList initialize! Object subclass: #TextStyle instanceVariableNames: 'fontArray lineGrid baseline alignment firstIndent restIndent rightIndent tabsArray marginTabsArray outputMedium ' classVariableNames: '' poolDictionaries: 'TextConstants ' category: 'Graphics-Support'!TextStyle comment:'TextStyle is the repository of information which may be shared by a number of paragraphs. What values it contains are still the subject of some experimentation and experience. It presently is used for both display and printing operations.Instance Variables: fontArray<Array> A collection of fonts available to the paragraph. These may be either StrikeFonts or PressFonts. The emphasis portion of a Text returns a value for indexing the font. lineGrid <Integer> The amount to be added to the top of a line to find the top of the next line. Will frequently be the greatest height in the fonts in fontArray. baseline <Integer> The amount to be added to the top of a line to find the baseline of the line. The baseline is the point from which the ascent of a font should rise. alignment<Integer> Indicates the mode for first level placement from the margins -- 0=left flush, 1=centered, 2=right flush, 3=justified. firstIndent<Integer> Amount to inset from the left margin for the first line of a paragraph. Initial value for paragraph associated with this TextStyle. restIndent<Integer> Amount to inset from the left margin for all but the first line of a paragraph. Initial value for paragraph associated with this TextStyle. rightIndent<Integer> Amount to inset from the right margin for all the lines of the paragraph. Initial value for paragraph associated with this TextStyle. tabsArray<Array> Tab stops. Values are relative to the left margin of the paragraph. marginTabsArray<Array> Each value in the array is a tuple indicating an inset from the left and right margin of this paragraph. Allows for inset paragraphs. outputMedium<Symbol> Currently only #Display. Allows for use of TextStyle in both display and printing mode.'!!TextStyle methodsFor: 'accessing'!alignment "Answer the code for the current setting of the alignment." ^alignment!alignment: anInteger "Set the current setting of the alignment to be anInteger-- 0=left flush, 1=centered, 2=right flush, 3=justified." alignment _ anInteger \\ (Justified + 1)!baseline "Answer the distance from the top of the line to the bottom of most of the characters (by convention, bottom of A)." ^baseline!baseline: anInteger "Set the distance from the top of the line to the bottom of most of the characters." baseline _ anInteger!defaultFont "Answer the first font in the font family." ^self fontAt: 1!descent "Answer the distance from the bottom of the line to the bottom of most of the characters (by convention, bottom of A)." ^ self lineGrid - self baseline!firstIndent "Answer the horizontal indenting of the first line of a paragraph in the style of the receiver." ^firstIndent!firstIndent: anInteger "Set the horizontal indenting of the first line of a paragraph in the style of the receiver to be anInteger." firstIndent _ anInteger!fontAt: index "This is private because no object outside TextStyle should depend on the representation of the font family in fontArray" | fontIndex | fontIndex _ index. fontIndex > fontArray size ifTrue: [fontIndex _ fontArray size]. fontIndex < 0 ifTrue: [fontIndex _ 1]. ((fontArray at: fontIndex) isMemberOf: StrikeFont) ifTrue: [^fontArray at: fontIndex]. ((fontArray at: 1) isMemberOf: StrikeFont) ifTrue: [^fontArray at: 1]. self error: 'No valid fonts in font array'.!fontAt: index put: font fontArray at: index put: font!lineGrid "Answer the relative space between lines of a paragraph in the style of the receiver." ^lineGrid!lineGrid: anInteger "Set the relative space between lines of a paragraph in the style of the receiver to be anInteger." lineGrid _ anInteger!nestingDepth "Number of entries in the marginTabsArray" ^ marginTabsArray size!outputMedium "Answer the outputMedium for this style" ^outputMedium!outputMedium: aSymbol "Set the outputMedium for this style -- currently only Display" outputMedium _ aSymbol. outputMedium = #Display ifTrue: [lineGrid _ DefaultLineGrid. baseline _ DefaultBaseline] ifFalse: [self outputMedium: #Display].!restIndent "Answer the indent for all but the first line of a paragraph in the style of the receiver." ^restIndent!restIndent: anInteger "Set the indent for all but the first line of a paragraph in the style of the receiver to be anInteger." restIndent _ anInteger!rightIndent "Answer the right margin indent for the lines of a paragraph in the style of the receiver." ^rightIndent!rightIndent: anInteger "Answer the right margin indent for the lines of a paragraph in the style of the receiver to be anInteger." rightIndent _ anInteger! !!TextStyle methodsFor: 'tabs and margins'!clearIndents "Reset all the margin (index) settings to be 0." self firstIndent: 0. self restIndent: 0. self rightIndent: 0!leftMarginTabAt: marginIndex "Set the 'nesting' level of left margin indents of the paragraph in the style of the receiver to be marginIndex." ^ self marginTabAt: marginIndex side: 1 "1= leftSide, 2 = rightSide" "The marginTabsArray is an Array of tuples. The Array is indexed according to the marginIndex, the 'nesting' level of the requestor."!nextTabXFrom: anX leftMargin: leftMargin rightMargin: rightMargin "Tab stops are distances from the leftMargin. Set the distance into anX normalized for the paragraph's left margin. Scale makes the routine usable for printing. On the display the scale is 1." | normalizedX tabX scale | scale _ 1. normalizedX _ anX - leftMargin. 1 to: tabsArray size do: [:i | (tabX _ ((tabsArray at: i) * scale) asInteger) > normalizedX ifTrue: [^leftMargin + tabX min: rightMargin]]. ^rightMargin!rightMarginTabAt: marginIndex "Set the 'nesting' level of right margin indents of the paragraph in the style of the receiver to be marginIndex." ^ self marginTabAt: marginIndex side: 2 "1= leftSide, 2 = rightSide" "The marginTabsArray is an Array of tuples. The Array is indexed according to the marginIndex, the 'nesting' level of the requestor."!tabWidth "Answer the width of standard tab." ^ DefaultTab! !!TextStyle methodsFor: 'fonts and font indexes'!flushFonts "Clean out the fonts, an aid when snapshotting claims too many are holding onto Display." BinaryChoice message: 'This is very dangerous and should only be used if you know whatyou are doing and understand the system integrity issue.' displayAt: Display boundingBox center ifTrue: [1 to: fontArray size do: [:index | fontArray at: index put: nil]] ifFalse: [Transcript cr; show: 'flushFonts cancelled'] "TextStyle default flushFonts."! !!TextStyle methodsFor: 'private'!basalFontFor: fontIndex ^self fontFor: fontIndex face: Basal!boldFontFor: fontIndex ^self fontFor: fontIndex face: Bold!boldItalicFontFor: fontIndex ^self fontFor: fontIndex face: BoldItalic!fontArray ^fontArray!fontFor: fontIndex face: face | currentFont currentFamilySizeFace family size emphasis newFamilySizeFace | currentFamilySizeFace _ (currentFont _ fontArray at: fontIndex) familySizeFace. family _ currentFamilySizeFace at: FamilyName. size _ currentFamilySizeFace at: PointSize. emphasis _ currentFont emphasis. (1 to: fontArray size) do: [:faceFontIndex | newFamilySizeFace _ (currentFont _ fontArray at: faceFontIndex) familySizeFace. ((((family = (newFamilySizeFace at: FamilyName)) and: [size = (newFamilySizeFace at: PointSize)]) and: [face = (newFamilySizeFace at: Face)]) and: [(emphasis bitAnd: NonFaceEmphasisMask) = (currentFont emphasis bitAnd: NonFaceEmphasisMask)]) ifTrue: [^faceFontIndex]]. ^ fontIndex!fontNamed: aString (1 to: fontArray size) do: [:faceFontIndex | aString = (fontArray at: faceFontIndex) name ifTrue: [^faceFontIndex]]. ^ self basalFontFor: 1!gridForFont: fontIndex withLead: leadInteger "Force whole style to suit one of its fonts. Assumes only one font referred to by runs. " | font | font _ self fontAt: fontIndex. self lineGrid: font height + leadInteger. self baseline: font ascent!isFontBold: fontIndex ^ ((fontArray at: fontIndex) familySizeFace at: Face) = Bold!isFontBoldItalic: fontIndex ^ ((fontArray at: fontIndex) familySizeFace at: Face) = BoldItalic!isFontItalic: fontIndex ^ ((fontArray at: fontIndex) familySizeFace at: Face) = Italic!isFontSubscripted: fontIndex ^ (((self fontAt: fontIndex) emphasis) bitAt: SubscriptedBit) = 1!isFontSuperscripted: fontIndex ^ (((self fontAt: fontIndex) emphasis) bitAt: SuperscriptedBit) = 1!isFontUnderlined: fontIndex ^ (((self fontAt: fontIndex) emphasis) bitAt: UnderlinedBit) = 1!italicFontFor: fontIndex ^self fontFor: fontIndex face: Italic!marginTabAt: marginIndex side: sideIndex "The marginTabsArray is an Array of tuples. The Array is indexed according to the marginIndex, the 'nesting' level of the requestor. sideIndex is 1 for left, 2 for right" | scale | scale _ 1. (marginIndex > 0 and: [marginIndex < marginTabsArray size]) ifTrue: [^((marginTabsArray at: marginIndex) at: sideIndex) * scale] ifFalse: [^0]!newFontArray: anArray fontArray _ anArray. lineGrid _ DefaultLineGrid. baseline _ DefaultBaseline. alignment _ 0. firstIndent _ 0. restIndent _ 0. rightIndent _ 0. outputMedium _ #Display. tabsArray _ DefaultTabsArray. marginTabsArray _ DefaultMarginTabsArray "Currently there is no supporting protocol for changing these arrays. If an editor wishes to implement margin setting, then a copy of the default should be stored as these instance variables."!subscriptedFontFor: fontIndex | name thisFont subscriptedFontIndex subscriptedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:subscriptedFontIndex | (subscriptedFont _ fontArray at: subscriptedFontIndex) name = name ifTrue: [(((subscriptedFont emphasis bitAt: SubscriptedBit) = 1) and: [(thisFont emphasis bitAt: Underlined) = (subscriptedFont emphasis bitAt: Underlined)]) ifTrue: [^subscriptedFontIndex]]]. ^ fontIndex!superscriptedFontFor: fontIndex | name thisFont superscriptedFontIndex superscriptedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:superscriptedFontIndex | (superscriptedFont _ fontArray at: superscriptedFontIndex) name = name ifTrue: [(((superscriptedFont emphasis bitAt: SuperscriptedBit) = 1) and: [(thisFont emphasis bitAt: Underlined) = (superscriptedFont emphasis bitAt: Underlined)]) ifTrue: [^superscriptedFontIndex]]]. ^ fontIndex!underlinedFontFor: fontIndex | name thisFont underlinedFontIndex underlinedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:underlinedFontIndex | (underlinedFont _ fontArray at: underlinedFontIndex) name = name ifTrue: [(((underlinedFont emphasis bitAt: UnderlinedBit) = 1) and: [(thisFont emphasis bitAnd: SubSuperscriptMask) = (underlinedFont emphasis bitAnd: SubSuperscriptMask)]) ifTrue: [^underlinedFontIndex]]]. ^ fontIndex!unSubscriptedFontFor: fontIndex | name thisFont unSubscriptedFontIndex unSubscriptedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:unSubscriptedFontIndex | (unSubscriptedFont _ fontArray at: unSubscriptedFontIndex) name = name ifTrue: [(((unSubscriptedFont emphasis bitAt: SubscriptedBit) = 0) and: [(thisFont emphasis bitAt: Underlined) = (unSubscriptedFont emphasis bitAt: Underlined)]) ifTrue: [^unSubscriptedFontIndex]]]. ^ fontIndex!unSuperscriptedFontFor: fontIndex | name thisFont unSuperscriptedFontIndex unSuperscriptedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:unSuperscriptedFontIndex | (unSuperscriptedFont _ fontArray at: unSuperscriptedFontIndex) name = name ifTrue: [(((unSuperscriptedFont emphasis bitAt: SuperscriptedBit) = 0) and: [(thisFont emphasis bitAt: Underlined) = (unSuperscriptedFont emphasis bitAt: Underlined)]) ifTrue: [^unSuperscriptedFontIndex]]]. ^ fontIndex!unUnderlinedFontFor: fontIndex | name thisFont unUnderlinedFontIndex unUnderlinedFont | name _ (thisFont _ fontArray at: fontIndex) name. (1 to: fontArray size) do: [:unUnderlinedFontIndex | (unUnderlinedFont _ fontArray at: unUnderlinedFontIndex) name = name ifTrue: [(((unUnderlinedFont emphasis bitAt: UnderlinedBit) = 0) and: [(thisFont emphasis bitAnd: SubSuperscriptMask) = (unUnderlinedFont emphasis bitAnd: SubSuperscriptMask)]) ifTrue: [^unUnderlinedFontIndex]]]. ^ fontIndex! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextStyle class instanceVariableNames: ''!!TextStyle class methodsFor: 'instance creation'!fontArray: anArray "Answer an instance of me with fonts those in anArray." ^self new newFontArray: anArray! !!TextStyle class methodsFor: 'constants'!default "Answer the system default text style." ^DefaultTextStyle copy! ! View subclass: #TextView instanceVariableNames: 'partMsg acceptMsg menuMsg ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Text'!TextView comment:'TextView is a "pluggable" view of text. The notion of pluggable views is anexperiment in user interface design. The idea is to provide a view which can be pluggedonto any object, rather than having to define a new subclass specific to every kind ofobject which needs to be viewed.The chief mechanism is a set of selectors, which can be thought of as an adaptor toconvert the generic textView operations (such as yellowButtonMenu) into model-specificoperations (such as textMenu).See the protocol ''adaptor'' for use of the pluggable selectors.See the creation messages in my class for an explication of the various parameters.Browse senders of the creation messages in my class for examples in the system.'!!TextView methodsFor: 'initialize-release'!initialize super initialize. self insideColor: Form white!newText: aText aText == nil ifTrue: [^ self newText: Text new]. self controller paragraph text: aText. self controller scrollToTop; resetState! !!TextView methodsFor: 'controller access'!defaultControllerClass ^ TextController! !!TextView methodsFor: 'displaying'!display self isUnlocked ifTrue: [self controller wrappingBox: (self insetDisplayBox insetBy: 6 @ 0) clippingBox: self insetDisplayBox. "ugly initialization hack: " (controller text isEmpty and: [controller textHasChanged not]) ifTrue: [self newText: self getText]]. super display!displayView self clearInside. self controller display! !!TextView methodsFor: 'updating'!update: aSymbol | text | aSymbol == partMsg ifTrue: [text _ self getText. self controller text ~= text ifTrue: [self newText: text. self displayView]]!updateRequest | cancel | self controller textHasChanged ifFalse: [^true]. self superView isCollapsed ifFalse: [Display reverse: insetDisplayBox mask: Form gray. Display reverse: (insetDisplayBox insetBy: 4) mask: Form gray]. cancel _ self confirm: 'The text showing has been altered.Do you wish to discard those changes?'. self superView isCollapsed ifFalse: [Display reverse: insetDisplayBox mask: Form gray. Display reverse: (insetDisplayBox insetBy: 4) mask: Form gray]. ^ cancel! !!TextView methodsFor: 'deEmphasizing'!deEmphasizeView self controller deselect! !!TextView methodsFor: 'emphasizing'!emphasizeView self controller select! !!TextView methodsFor: 'adaptor'!accept: aText from: aController acceptMsg == nil ifTrue: [self flash. ^ false]. ^ acceptMsg numArgs = 1 ifTrue: "one arg selectors get text only" [model perform: acceptMsg with: aText] ifFalse: "two arg selectors get text and controller as well" [model perform: acceptMsg with: aText with: aController]!getText | text | partMsg == nil ifTrue: [^ Text new]. text _ model perform: partMsg. text == nil ifTrue: [^ Text new]. ^ text!yellowButtonMenu menuMsg == nil ifTrue: [^ nil]. ^ model perform: menuMsg! !!TextView methodsFor: 'private'!on: anObject aspect: m1 change: m3 menu: m4 self model: anObject. partMsg _ m1. acceptMsg _ m3. menuMsg _ m4. self initialize! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!TextView class instanceVariableNames: ''!!TextView class methodsFor: 'instance creation'!on: anObject aspect: aspectMsg change: changeMsg menu: menuMsg "Create a 'pluggable' (see class comment) textView viewing anObject. aspectMsg is sent to read the current text value in the model. It is also used as the changed: parameter for this view. changeMsg is sent to inform anObject of new text for the model. menuMsg is sent to read the yellowButton menu for this view." ^ self new on: anObject aspect: aspectMsg change: changeMsg menu: menuMsg! ! Magnitude subclass: #Time instanceVariableNames: 'hours minutes seconds ' classVariableNames: '' poolDictionaries: '' category: 'Numeric-Magnitudes'!Time comment: 'Implements times of day.'!!Time methodsFor: 'comparing'!< aTime "Answer whether aTime is earlier than the receiver." hours ~= aTime hours ifTrue: [^hours < aTime hours]. minutes ~= aTime minutes ifTrue: [^minutes < aTime minutes]. ^seconds < aTime seconds!= aTime "Answer whether aTime represents the same second as the receiver." self species = aTime species ifTrue: [^hours = aTime hours & (minutes = aTime minutes) & (seconds = aTime seconds)] ifFalse: [^false]!hash "Hash must be redefined since = was redefined." ^((hours hash bitShift: 3) bitXor: minutes) bitXor: seconds! !!Time methodsFor: 'accessing'!hours "Answer the number of hours the receiver represents." ^hours!minutes "Answer the number of minutes the receiver represents." ^minutes!seconds "Answer the number of seconds the receiver represents." ^seconds! !!Time methodsFor: 'arithmetic'!addTime: timeAmount "Answer a new Time that is timeAmount after the receiver. timeAmount is an instance of Date or Time." ^Time fromSeconds: self asSeconds + timeAmount asSeconds!subtractTime: timeAmount "Answer a new Time that is timeAmount before the receiver. timeAmount is an instance of Date or Time." ^Time fromSeconds: self asSeconds - timeAmount asSeconds! !!Time methodsFor: 'printing'!printOn: aStream "Format is h:mm:ss am/pm" hours > 12 ifTrue: [hours - 12 printOn: aStream] ifFalse: [hours < 1 ifTrue: [12 printOn: aStream] ifFalse: [hours printOn: aStream]]. aStream nextPutAll: (minutes < 10 ifTrue: [':0'] ifFalse: [':']). minutes printOn: aStream. aStream nextPutAll: (seconds < 10 ifTrue: [':0'] ifFalse: [':']). seconds printOn: aStream. aStream nextPutAll: (hours < 12 ifTrue: [' am'] ifFalse: [' pm'])!storeOn: aStream aStream nextPutAll: '(', self class name, ' readFromString: '; print: self printString; nextPut: $)! !!Time methodsFor: 'converting'!asSeconds "Answer the number of seconds since midnight of the receiver." ^3600 * hours + (60 * minutes + seconds)! !!Time methodsFor: 'private'!hours: anInteger hours _ anInteger!hours: hourInteger minutes: minInteger seconds: secInteger hours _ hourInteger. minutes _ minInteger. seconds _ secInteger! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!Time class instanceVariableNames: ''!!Time class methodsFor: 'instance creation'!fromSeconds: secondCount "Answer with a Time that is secondCount seconds since midnight." | secondsInHour hours | hours _ secondCount truncated // 3600. secondsInHour _ secondCount truncated \\ 3600. ^self new hours: hours minutes: secondsInHour // 60 seconds: secondsInHour \\ 60!now "Answer with a Time representing the time right now--this is a 24 hour clock." ^self dateAndTimeNow at: 2!readFrom: aStream "Read a Time from the stream in the form: <hour>:<minute>:<second> <am/pm> <minute>, <second> or <am/pm> may be omitted. e.g. 1:59:30 pm; 8AM; 15:30" | hour minute second | hour _ Integer readFrom: aStream. minute _ 0. second _ 0. (aStream peekFor: $:) ifTrue: [minute _ Integer readFrom: aStream. (aStream peekFor: $:) ifTrue: [second _ Integer readFrom: aStream]]. aStream skipSeparators. (aStream atEnd not and: [aStream peek isLetter]) ifTrue: [aStream next asLowercase = $p ifTrue: [hour _ hour + 12]. (aStream peekFor: $m) ifFalse: [aStream peekFor: $M]]. ^self fromSeconds: 60*(60*hour+minute)+second "Time readFrom: (ReadStream on: '2:23:09 pm')"! !!Time class methodsFor: 'general inquiries'!dateAndTimeNow "Answer an array of (Date today, Time now)." ^self currentTime: #dateAndTime!millisecondClockValue "Answer with the number of milliseconds since the millisecond clock was last reset or rolled over." | milliseconds | milliseconds _ LargePositiveInteger new: 4. self millisecondClockInto: milliseconds. ^milliseconds truncated!millisecondsToRun: timedBlock "Answer with the number of milliseconds timedBlock takes to return its value." | initialMilliseconds | initialMilliseconds _ self millisecondClockValue. timedBlock value. ^self millisecondClockValue - initialMilliseconds!timeWords "Answer with the seconds (in GMT) since Jan 1 1901: as a four element ByteArray. The high-order 8-bits of the answer are stored in the byte indexed by 1 and the low-order 8-bits in the byte indexed 4. Note: this order is not consistent with the primitives or the other time messages, but it is what the Alto file system uses (see AltoFile updateLeader:)." | seconds bytes | seconds _ ByteArray new: 4. self secondClockInto: seconds. bytes _ ByteArray new: 4. "Reverse the bytes" 1 to: 4 do: [:i | bytes at: i put: (seconds at: 5 - i)]. ^bytes!totalSeconds "Answer with the total seconds from Jan 1 1901 corrected for time zone and daylight savings time." ^self currentTime: #seconds! !!Time class methodsFor: 'private'!currentTime: formatted "If formatted is #seconds, answer with the total seconds from Jan 1 1901 corrected for time zone and daylight savings time. Otherwise, answer an array of (Date today, Time now). m570 and m571 are time zone specific parameters, set for California." | secondCount d dd t dfirst dlast m570 m571 | secondCount _ LargePositiveInteger new: 4. self secondClockInto: secondCount. secondCount _ secondCount truncated. m570 _ 16505. m571 _ 305. "adjust for time zone" secondCount _ secondCount + ((m570 >= 0 ifTrue: [-1] "west" ifFalse: [1] "east") * (3600 * ((m570 bitAnd: 30720) bitShift: -11) + (60 * ((m571 bitAnd: 32256) bitShift: -9)))). "Guess the number of days since Jan 1 1901." d _ Date fromDays: secondCount // 86400. "The formatted test makes it possible to skip some work if all you want is to correct the total number of seconds. secondCount \\ 86400 is the number of seconds that were left over from the estimate of days" formatted==#seconds ifFalse: [t _ Time fromSeconds: secondCount \\ 86400]. "check for daylight savings time (DST). correct DST parameters for nonleap years and round to previous Sunday if necessary" "day of the year on or before which DST takes effect" dfirst _ m570 bitAnd: 511. (dfirst = 366 ifTrue: [false"DST not in effect"] ifFalse: [(dd _ d day) >= (dfirst _ dfirst + d leap - 1) ifTrue: ["day of the year on or before which DST ends" dlast _ (m571 bitAnd: 511) + d leap - 1. dd < dlast and: [dd < ((Date newDay: dlast year: d year) previous: #Sunday) day]] ifFalse: ["possibly earlier than or at beginning of range" dd >= ((Date newDay: dfirst year: d year) previous: #Sunday) day]]) ifTrue: [formatted==#seconds ifTrue: ["daylight savings time in effect. add an hour" secondCount _ secondCount + 3600] ifFalse: [t hours = 23 ifTrue: [d _ d addDays: 1. t hours: 0] ifFalse: [t hours: t hours + 1]]]. formatted==#seconds ifTrue: [^secondCount] ifFalse: [^Array with: d with: t]!millisecondClockInto: aByteArray "The argument is a byte indexable object of length at least four (a LargePositiveInteger). Store into the first four bytes of the argument the number of milliseconds since the millisecond clock was last reset or rolled over (a 32-bit unsigned number). The low-order 8-bits are stored in the byte indexed by 1 and the high-order 8-bits in the byte indexed 4. Essential. See Object documentation whatIsAPrimitive." <primitive: 99> self primitiveFailed!secondClockInto: aByteArray "The argument is a byte indexable object of length at least four. Store into the first four bytes of the argument the number of seconds since 00:00 in the morning of January 1, 1901 (a 32-bit unsigned number). The low-order 8-bits are stored in the byte indexed by 1 and the high- order 8-bits in the byte indexed 4. Essential. See Object documentation whatIsAPrimitive. " <primitive: 98> self primitiveFailed! ! Boolean subclass: #True instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Objects'!True comment: 'I describe the behavior of my sole instance, true'!!True methodsFor: 'logical operations'!& alternativeObject "Evaluating conjunction -- answer alternativeObject since receiver is true." ^alternativeObject!not "Negation--answer false since the receiver is true." ^false!| aBoolean "Evaluating disjunction (OR) -- answer true since the receiver is true." ^self! !!True methodsFor: 'controlling'!and: alternativeBlock "Nonevaluating conjunction -- answer the value of alternativeBlock since the receiver is true." ^alternativeBlock value!ifFalse: alternativeBlock "Since the condition is true, the value is the true alternative, which is nil. Execution does not actually reach here because the expression is compiled in-line." ^nil!ifFalse: falseAlternativeBlock ifTrue: trueAlternativeBlock "Answer the value of trueAlternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^trueAlternativeBlock value!ifTrue: alternativeBlock "Answer the value of alternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^alternativeBlock value!ifTrue: trueAlternativeBlock ifFalse: falseAlternativeBlock "Answer with the value of trueAlternativeBlock. Execution does not actually reach here because the expression is compiled in-line." ^trueAlternativeBlock value!or: alternativeBlock "Nonevaluating disjunction -- answer true since the receiver is true." ^self! !!True methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'true'! ! Object subclass: #UndefinedObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Objects'!UndefinedObject comment: 'I describe the behavior of my sole instance, nil. nil represents a prior value for variables that have not been initialized, or for results which are meaningless.'!!UndefinedObject methodsFor: 'initialize-release'!release "Nil release is a no-op"! !!UndefinedObject methodsFor: 'copying'!deepCopy "Only one instance of UndefinedObject should ever be made, so answer with self."!shallowCopy "Only one instance of UndefinedObject should ever be made, so answer with self."! !!UndefinedObject methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'nil'!storeOn: aStream aStream nextPutAll: 'nil'! !!UndefinedObject methodsFor: 'testing'!isNil ^true!notNil ^false! !!UndefinedObject methodsFor: 'dependents access'!addDependent: ignored self error: 'Nil should not have dependents'! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!UndefinedObject class instanceVariableNames: ''!!UndefinedObject class methodsFor: 'instance creation'!new self error: 'You may not create any more undefined objects--use nil'! ! LeafNode subclass: #VariableNode instanceVariableNames: 'name isArg ' classVariableNames: '' poolDictionaries: '' category: 'System-Compiler'!VariableNode comment: 'I am a parse tree leaf representing a variable. Note that my name and key are different for pool variables -- the key is the Object Reference.'!!VariableNode methodsFor: 'initialize-release'!isArg: aBoolean isArg _ aBoolean!name: varName index: i type: type self name: varName key: varName index: i type: type!name: string key: object code: byte name _ string. key _ object. code _ byte!name: varName key: objRef index: i type: type name _ varName. self key: objRef index: i type: type! !!VariableNode methodsFor: 'code generation'!emitForReturn: stack on: strm (code >= LdSelf and: [code <= LdNil]) ifTrue: ["short returns" strm nextPut: EndMethod - 4 + (code - LdSelf). stack push: 1 "doesnt seem right"] ifFalse: [super emitForReturn: stack on: strm]!emitForValue: stack on: strm code < 256 ifTrue: [strm nextPut: (code = LdSuper ifTrue: [LdSelf] ifFalse: [code]). stack push: 1] ifFalse: [self emitLong: LdInstLong on: strm. stack push: 1]!emitStore: stack on: strm self emitLong: Store on: strm!emitStorePop: stack on: strm (code between: 0 and: 7) ifTrue: [strm nextPut: ShortStoP + code "short stopop inst"] ifFalse: [(code between: 16 and: 23) ifTrue: [strm nextPut: ShortStoP + 8 + code - 16 "short stopop temp"] ifFalse: [self emitLong: StorePop on: strm]]. stack pop: 1!sizeForReturn: encoder (code >= LdSelf and: [code <= LdNil]) ifTrue: ["short returns" ^1]. ^super sizeForReturn: encoder!sizeForStore: encoder self reserve: encoder. ^2!sizeForStorePop: encoder self reserve: encoder. (code < 24 and: [code noMask: 8]) ifTrue: [^1]. ^2! !!VariableNode methodsFor: 'printing'!printOn: aStream indent: level aStream nextPutAll: name! !!VariableNode methodsFor: 'testing'!canBeSpecialArgument "can I be an argument of (e.g.) ifTrue:?" ^code < LdNil!isArg ^self isTemp and: [isArg==true]!isTemp "Answer true if this describes a temporary variable" code < 0 ifTrue: [^code = LdTempType negated]. code > 255 ifTrue: [^code between: LdTempType * 256 and: LdTempType * 256 + 255]. ^code between: (CodeBases at: 2) and: (CodeBases at: 2) + (CodeLimits at: 2) - 1!isVariableReference ^true! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!VariableNode class instanceVariableNames: ''!!VariableNode class methodsFor: 'class initialization'!initialize "VariableNode initialize. Decompiler initialize." | encoder | encoder _ Encoder new. StdVariables _ Dictionary new: 16. encoder fillDict: StdVariables with: VariableNode mapping: #('self' 'thisContext' 'super' 'nil' 'false' 'true' ) to: (Array with: LdSelf with: LdThisContext with: LdSuper) , (Array with: LdNil with: LdFalse with: LdTrue). StdSelectors _ Dictionary new: 64. encoder fillDict: StdSelectors with: SelectorNode mapping: ((1 to: Smalltalk specialSelectorSize) collect: [:i | Smalltalk specialSelectorAt: i]) to: (SendPlus to: SendPlus + 31). StdLiterals _ LiteralDictionary new: 16. encoder fillDict: StdLiterals with: LiteralNode mapping: #(-1 0 1 2 ) to: (LdMinus1 to: LdMinus1 + 3). encoder initScopeAndLiteralTables. self initialize2: encoder!initialize2: encoder "VariableNode initialize." NodeNil _ encoder encodeVariable: 'nil'. NodeTrue _ encoder encodeVariable: 'true'. NodeFalse _ encoder encodeVariable: 'false'. NodeSelf _ encoder encodeVariable: 'self'. NodeThisContext _ encoder encodeVariable: 'thisContext'. NodeSuper _ encoder encodeVariable: 'super'! !VariableNode initialize! Object subclass: #View instanceVariableNames: 'model controller superView subViews transformation viewport window displayTransformation insetDisplayBox borderWidth borderColor insideColor boundingBox ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Framework'!View comment:'My instances are intended to be components in a structured picture. Each View in the structured picture can contain other Views as sub-components. These sub-components are called subViews. A View can be a subView of only one View. This View is called its superView. The set of Views in a structured picture forms a hierarchy. The one View in the hierarchy that has no superView is called the topView of the structured picture. A View in a structured picture with no subViews is called a bottom View. A View and all of its subViews, and all of their subViews and so on, are treated as a unit in many operations on the View. For example, if a View is displayed, all of its subViews are displayed as well. There are several catagories of operations that can be performed on a View. Among these are the following. 1. Adding subViews to a View. 2. Positioning subViews within a View. 3. Deleting subViews from a View. 4. Transforming a View. 5. Displaying a View. Each View has its own coordinate system. In order to change from one coordinate system to another, each View has two transformations associated with it. The local transformation is a WindowingTransformation that maps objects in the coordinate system of the View to objects in the coordinate system of the superView of the View. The displayTransformation is a WindowingTransformation that maps objects in the coordinate system of the View to objects in the display screen coordinate system.The part of the space that is to be made visible is represented by the window of the View. The window of a View is a Rectangle expressed in the coordinate system of the View. The area occupied by a View in the coordinate system of its superView is called its viewport. The viewport of a View is its window transformed by its local transformation. The region of the display screen occupied by a View is called its displayBox. The display box of a View can include a border. The width of the border expressed in display screen coordinates is called the border width of the View. The color of the border is called the border color. The region of the display box of a View excluding the border is called the inset display box. The color of the inset display box is called the inside color of the View.model - any objectcontroller - <Controller>, #NoControllerAllowed, or nilsuperView - <View>, or nilsubViews - <OrderedCollection> of Viewstransformation - <WindowingTransformation>viewport - <Rectangle> (in superView coordinates), or nil.window - <Rectangle> (in View coordinates), or nil.displayTransformation - <WindowingTransformation>, or nil.insetDisplayBox - <Rectangle> (in display screen coordinates), or nil.borderWidth - <Rectangle> (display screen unit) or 0 (meaning no border).borderColor - <Form>insideColor - <Form>, or nil (meaning transparent)boundingBox - <Rectangle> (in View coordinates), or nil'!!View methodsFor: 'initialize-release'!initialize "Initialize the state of the receiver. Subclasses should include 'super initialize' when redefining this message to insure proper initialization." self resetSubViews. transformation _ WindowingTransformation identity. self borderWidth: 0. self borderColor: Form black!release "Remove the receiver from its model's list of dependents (if the model exists), and release all of its subViews. It is used to break possible cycles in the receiver and should be sent when the receiver is no longer needed. Subclasses should include 'super release.' when redefining release." super release. model removeDependent: self. model _ nil. controller release. controller _ nil. subViews ~~ nil ifTrue: [subViews do: [:aView | aView release]]. subViews _ nil. superView _ nil.! !!View methodsFor: 'testing'!containsPoint: aPoint "Answer true if aPoint is within the receiver's display box, and answer false, otherwise. It is sent to a View's subViews by View|subViewAt: in order to determine which subView contains the cursor point (so that, for example, control can be pass down to that subView's controller)." ^self displayBox containsPoint: aPoint! !!View methodsFor: 'model access'!model "Answer the receiver's model." ^model!model: aModel "Set the receiver's model to aModel. The model of the receiver's controller is also set to aModel." self model: aModel controller: controller! !!View methodsFor: 'superView access'!isTopView "Answer true if the receiver is a top view, that is, if it has no superView." ^superView == nil!resetSubViews "Set the list of subviews to an empty collection." subViews _ OrderedCollection new!superView "Answer the superView of the receiver." ^superView!topView "Answer the root of the tree of Views in which the receiver is a node. The root of the tree is found by going up the superView path until reaching a View whose superView is nil." superView == nil ifTrue: [^self] ifFalse: [^superView topView]! !!View methodsFor: 'subView access'!firstSubView "Answer the first subView in the receiver's list of subViews if it is not empty, else nil." subViews isEmpty ifTrue: [^nil] ifFalse: [^subViews first]!lastSubView "Answer the last subView in the receiver's list of subViews if it is not empty, else nil." subViews isEmpty ifTrue: [^nil] ifFalse: [^subViews last]!subViewContaining: aPoint "Answer the first subView that contains aPoint within its window and answer nil, otherwise. It is typically sent from a Controller in order to determine where to pass control (usually to the Controller of the View returned by View|subViewContaining:). " subViews reverseDo: [:aSubView | (aSubView displayBox containsPoint: aPoint) ifTrue: [^aSubView]]. ^nil!subViews "Answer the receiver's collection of subViews." ^subViews! !!View methodsFor: 'controller access'!controller "If the receiver's controller is nil (the default case), an initialized instance of the receiver's default controller is returned." controller == nil ifTrue: [self controller: self defaultController]. ^controller!controller: aController "Set the receiver's controller to aController. An instance of NoController can be specified to indicate that the receiver will not have a controller. The model of aController is set to the receiver's model." self model: model controller: aController!defaultController "Answer an initialized instance of the receiver's default controller. Subclasses should redefine this message only if the default controller instances need to be initialized in a nonstandard way." ^self defaultControllerClass new!defaultControllerClass "Answer the class of the default controller for the receiver. Subclasses should redefine View|defaultControllerClass if the class of the default controller is not Controller." ^Controller!model: aModel controller: aController "Set the receiver's model to aModel, add the receiver to aModel's list of dependents, and set the receiver's controller to aController. Subsequent changes to aModel (see Model|change) will result in View|update: messages being sent to the receiver. nil for the value of aController indicates that the default controller is to be used when needed. If aController is not nil, its view is set to the receiver and its model is set to aModel." model ~~ nil & (model ~~ aModel) ifTrue: [model removeDependent: self]. aModel ~~ nil & (aModel ~~ model) ifTrue: [aModel addDependent: self]. model _ aModel. aController ~~ nil ifTrue: [aController view: self. aController model: aModel]. controller _ aController! !!View methodsFor: 'basic control sequence'!subViewWantingControl "Answer the first subView that has a controller that now wants control." subViews reverseDo: [:aSubView | aSubView controller isControlWanted ifTrue: [^aSubView]]. ^nil! !!View methodsFor: 'window access'!defaultWindow "Build the minimum Rectangle that encloses all the windows of the receiver's subViews. The answer is a Rectangle obtained by expanding this minimal Rectangle by the borderWidth of the receiver. If the receiver has no subViews, then a Rectangle enclosing the entire display screen is answered. It is used internally by View methods if no window has been specified for the View. Specialized subclasses of View should redefine View|defaultWindow to handle the default case for instances that have no subViews. " | aRectangle | subViews isEmpty ifTrue: [^DisplayScreen boundingBox]. aRectangle _ self firstSubView viewport. subViews do: [:aView | aRectangle _ aRectangle merge: aView viewport]. ^aRectangle expandBy: borderWidth!insetWindow "Answer a Rectangle that is obtained by insetting the receiver's window rectangle by the border width." ^self getWindow insetBy: borderWidth!window "Answer a copy of the receiver's window." ^self getWindow copy!window: aWindow "Set the receiver's window to a copy of aWindow." self setWindow: aWindow copy! !!View methodsFor: 'viewport access'!viewport "Answer a copy of the receiver's viewport." ^self getViewport copy! !!View methodsFor: 'display box access'!boundingBox "Answer the bounding box which for the default case is the rectangular area surrounding the bounding boxes of all the subViews." boundingBox ~~ nil ifTrue: [^boundingBox] ifFalse: [^self computeBoundingBox]!computeBoundingBox "Answer the minimum Rectangle that encloses the bounding boxes of the receiver's subViews. If the receiver has no subViews, then the bounding box is the receiver's window. Subclasses should redefine View|boundingBox if a more suitable default for the case of no subViews is available." | aRectangle | subViews isEmpty ifTrue: [^self getWindow]. aRectangle _ self firstSubView transform: self firstSubView boundingBox. subViews do: [:aView | aRectangle _ aRectangle merge: (aView transform: aView boundingBox).]. ^aRectangle expandBy: borderWidth!displayBox "Answer the receiver's inset display box (see View|insetDisplayBox) expanded by the borderWidth. The display box represents the region of the display screen in which the receiver (including the border) is displayed. If the receiver is totally clipped by the display screen and its superView, the resulting Rectangle will be invalid." ^self insetDisplayBox expandBy: borderWidth!insetDisplayBox "Answer the receiver's inset display box. The inset display box is the intersection of the receiver's window, tranformed to display coordinates, and the inset display box of the superView, inset by the border width. The inset display box represents the region of the display screen in which the inside of the receiver (all except the border) is displayed. If the receiver is totally clipped by the display screen and its superView, the resulting Rectangle will be invalid." [insetDisplayBox == nil] whileTrue: [insetDisplayBox _ self computeInsetDisplayBox]. ^insetDisplayBox! !!View methodsFor: 'lock access'!isLocked "Answer whether the receiver is locked. A View is 'locked' if its display transformation and inset display box are defined. If these are undefined, the View is 'unlocked'. The display transformation and inset display box become undefined when the transformation of the View (or the transformation of a View in its superView chain) is changed, or when the superView of the View is changed, or any other change to the View that affects the display screen coordinates of the View. The locking and unlocking of a View is handled automatically by the internal methods of the View, but can also be done explicitly if desired (see View|lock, and View|unlock)." displayTransformation == nil | (insetDisplayBox == nil) ifTrue: [^false] ifFalse: [^true]!isUnlocked "Answer whether the receiver is unlocked. See comment in View|isLocked." ^displayTransformation == nil & (insetDisplayBox == nil)!lock "'Lock' the receiver and all of its subViews (see View|isLocked). This has the effect of computing and storing the display transformation (see View|displayTransformation) and inset display box (see View|insetDisplayBox) of the receiver and all its subViews. The locking and unlocking of a View is handled automatically by the internal methods of the View, but can also be done explicitly if desired." self isLocked ifTrue: [^self]. displayTransformation _ self computeDisplayTransformation. insetDisplayBox _ self computeInsetDisplayBox. subViews do: [:aSubView | aSubView lock]!unlock "'Unlock the receiver and all of its subViews (see View|isUnlocked). This has the effect of forcing the display transformation (see View|displayTransformation) and inset display box (see View|insetDisplayBox) of the receiver and all its subViews to be recomputed the next time they are referenced. The locking and unlocking of a View is handled automatically by the internal methods of the View, but can also be done explicitly if desired." self isUnlocked ifTrue: [^self]. displayTransformation _ nil. insetDisplayBox _ nil. subViews do: [:aSubView | aSubView unlock]! !!View methodsFor: 'subView inserting'!addSubView: aView "Remove aView from the tree of Views it is in (if any) and adds it to the rear of the list of subViews of the receiver. Set the superView of aView to be the receiver. It is typically used to build up a hierarchy of Views (a structured picture). An error is generated if aView is the same as the receiver or its superView, etc." self addSubView: aView ifCyclic: [self error: 'cycle in subView structure.']!addSubView: aSubView above: lowerView "Adds aView (see View|addSubView:) so that it lies above lowerView" self addSubView: aSubView align: aSubView viewport bottomLeft with: lowerView viewport topLeft!addSubView: aSubView align: aPoint1 with: aPoint2 "Add aView to the receiver's list of subViews (see View|addSubView:) and translate aView so that aPoint1 coincides with aPoint2. It is typically used to build up a hierarchy of Views (a structured picture). Normally, aPoint1 is a point on aView's viewport (e.g. aView viewport topLeft, etc.), and aPoint2 is either an arbitrary point in the receiver's coordinate system or a point on the receiver's window (e.g. self window topRight, etc)." self addSubView: aSubView. aSubView align: aPoint1 with: aPoint2!addSubView: aSubView below: lowerView "Adds aView (see View|addSubView:) so that it lies below lowerView" self addSubView: aSubView align: aSubView viewport topLeft with: lowerView viewport bottomLeft!addSubView: aView ifCyclic: exceptionBlock "Remove aView from the tree of Views it is in (if any) and add it to the rear of the list of subViews of the receiver. Set the superView of aView to be the receiver. It is typically used to build up a hierarchy of Views (a structured picture). An error is generated if aView is the same as the receiver or its superView, etc." (self isCyclic: aView) ifTrue: [exceptionBlock value] ifFalse: [aView removeFromSuperView. subViews addLast: aView. aView superView: self]!addSubView: aView in: aRelativeRectangle borderWidth: width "I make 'aView' into a subview. I use 'aRelativeRectangle' and the super view's window to compute (1) a viewport within the superview for 'aView' and (2) the window extent for 'aView'.Note: defining the windowing transformation and deriving the viewport is logically equivalent but does not seem to be easily done" | subViewPort subWindow | self addSubView: aView ifCyclic: [self error: 'cycle in subView structure.']. aView borderWidth: width. subViewPort _ self window extent * aRelativeRectangle origin corner: self window extent * aRelativeRectangle corner. subWindow _ 0 @ 0 extent: (self window extent * aRelativeRectangle extent). aView window: subWindow viewport: subViewPort!addSubView: aSubView toLeftOf: rightView "Adds aView (see addSubView:) so that it lies to the left of rightView." self addSubView: aSubView align: aSubView viewport topRight with: rightView viewport topLeft!addSubView: aSubView toRightOf: leftView "Adds aView (see addSubView:) so that it lies to the right of leftView" self addSubView: aSubView align: aSubView viewport topLeft with: leftView viewport topRight!addSubView: aView viewport: aViewport "Add aView to the receiver's list of subViews (see View|addSubView:) and applies to aView a scale and translation computed from its window and aViewport (such that its window fills aViewport)." self addSubView: aView. aView window: aView window viewport: aViewport!addSubView: aView window: aWindow viewport: aViewport "Add aView to the receiver's list of subViews (see View|addSubView:) and applies to aView a scale and translation computed from aWindow and aViewport (such that aWindow fills aViewport)." self addSubView: aView. aView window: aWindow viewport: aViewport!insertSubView: aSubView above: lowerView "Adds aView (see View|addSubView:) so that it lies above lowerView" self insertSubView: aSubView before: lowerView ifCyclic: [self error: 'cycle in subView structure.']. aSubView align: aSubView viewport bottomLeft with: lowerView viewport topLeft.!insertSubView: aView before: anotherView ifCyclic: exceptionBlock "Remove aView from the tree of Views it is in (if any) and add it to the rear of the list of subViews of the receiver. Set the superView of aView to be the receiver. It is typically used to build up a hierarchy of Views (a structured picture). An error is generated if aView is the same as the receiver or its superView, etc." (self isCyclic: aView) ifTrue: [exceptionBlock value] ifFalse: [aView removeFromSuperView. subViews add: aView before: anotherView. aView superView: self]! !!View methodsFor: 'subView removing'!releaseSubView: aView "Delete aView from the receiver's list of subViews and send it the message 'release' (so that it can break up cycles with subViews, etc.)" self removeSubView: aView. aView release!releaseSubViews "Release (see View|releaseSubView: ) all subViews in the receiver's list of subViews." subViews do: [:aView | aView release]. self resetSubViews!removeFromSuperView "Delete the receiver from its superView's collection of subViews." superView ~= nil ifTrue: [superView removeSubView: self]!removeSubView: aView "Remove aView from the receiver's list of subViews. If the list of subViews does not contain aView, an error window is created." subViews remove: aView. aView superView: nil. aView unlock!removeSubViews "Remove all the receiver's subViews." subViews do: [:aView | aView superView: nil. aView unlock]. self resetSubViews! !!View methodsFor: 'displaying'!display "Display the receiver's border, display the receiver, then display the subViews of the receiver. Can be sent to the top View of a structured picture in order to display the entire structure, or to any particular View in the structure in order to display that View and its subViews. It is typically sent in response to an update request to a View." self displayBorder. self displayView. self displaySubViews!displayBorder "Display the receiver's border (using the receiver's borderColor)." borderWidth = 0 ifTrue: [insideColor == nil ifFalse: [Display fill: self displayBox mask: insideColor]] ifFalse: [insideColor == nil ifTrue: [superView isNil ifTrue: [Display border: self displayBox widthRectangle: borderWidth mask: borderColor] ifFalse: [Display border: self displayBox widthRectangle: borderWidth mask: borderColor clippingBox: superView insetDisplayBox]] ifFalse: [Display fill: self displayBox mask: borderColor. Display fill: self insetDisplayBox mask: insideColor]]!displaySubViews "Display all the subViews of the receiver." subViews do: [:aSubView | aSubView display]!displayView "Subclasses should redefine View|displayView in order to display particular objects associated with the View such as labels, lines, boxes, etc." ^self!inspect "Build an inspector of my model, me, and my controller." | topView titleView className | topView _ StandardSystemView model: nil label: 'MVC inspector' minimumSize: 250 @ 250. titleView _ StringHolderView new. className _ model class name. titleView model: (StringHolder new contents: ' Model: ', ((className at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']), className). titleView controller: Controller new. topView addSubView: titleView in: (0@0 extent: 1@0.06) borderWidth: 1. InspectorView view: (Inspector inspect: model) in: (0@0.06 extent: 1@0.34) of: topView. titleView _ StringHolderView new. className _ self class name. titleView model: (StringHolder new contents: ' View: ', ((className at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']), className). titleView controller: Controller new. topView addSubView: titleView in: (0@0.4 extent: 1@0.06) borderWidth: 1. InspectorView view: (Inspector inspect: self) in: (0@0.46 extent: 1@0.24) of: topView. titleView _ StringHolderView new. className _ controller class name. titleView model: (StringHolder new contents: ' Controller: ', ((className at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']), className). titleView controller: Controller new. topView addSubView: titleView in: (0@0.7 extent: 1@0.06) borderWidth: 1. InspectorView view: (Inspector inspect: controller) in: (0@0.76 extent: 1@0.24) of: topView. topView controller open! !!View methodsFor: 'deEmphasizing'!deEmphasize "Modify the emphasis (highlighting, special tabs) of the receiver. This includes objects such as labels, lines, and boxes. Typically used so that the receiver is not presented as active. Do this for the receiver and then for each of the receiver's subViews." self deEmphasizeView. self deEmphasizeSubViews!deEmphasizeSubViews "Send the deEmphasize message to each of the receiver's subviews." subViews do: [:aSubView | aSubView deEmphasize]!deEmphasizeView "Subclasses should redefine View|deEmphasizeView in order to modify the emphasis (highlighting, special tabs) of particular objects associated with the View such as labels, lines, and boxes." ^self!emphasize "Modify the emphasis (highlighting, special tabs) of the receiver. This includes objects such as labels, lines, and boxes. Typically used so that the receiver is not presented as active. Do this for the receiver and then for each of the receiver's subViews." self emphasizeView. self emphasizeSubViews!emphasizeSubViews "Send the emphasize message to each of the receiver's subviews." subViews do: [:aSubView | aSubView emphasize]!emphasizeView "Subclasses should redefine View|emphasizeView in order to modify the emphasis (highlighting, special tabs) of particular objects associated with the View such as labels, lines, and boxes." ^self! !!View methodsFor: 'display transformation'!displayTransform: anObject "Apply the display transformation of the receiver to anObject (see View|displayTransformation) and answer the resulting scaled, translated object. It is normally applied to Rectangles, Points, and other objects with coordinates defined in the View's local coordinate system in order to get a corresponding object in display coordinates." ^(self displayTransformation applyTo: anObject) rounded!displayTransformation "Answer a WindowingTransformation that is the result of composing all local transformations in the receiver's superView chain with the receiver's own local transformation. The resulting transformation transforms objects in the receiver's coordinate system into objects in the display screen coordinate system. " displayTransformation == nil ifTrue: [displayTransformation _ self computeDisplayTransformation]. ^displayTransformation!inverseDisplayTransform: aPoint "Answer a point that is obtained from aPoint by applying to it the inverse of the receiver's display transformation. It is typically used by the Controller of the receiver in order to convert a point in display coordinates, such as the cursor point, to the local coordinate system of the receiver." ^self displayTransformation applyInverseTo: aPoint! !!View methodsFor: 'transforming'!align: aPoint1 with: aPoint2 "Add a translation of (aPoint2 - aPoint1) to the receiver's local transformation. The point in the receiver's coordinate system that previously was transformed to aPoint1 in the superView's coordinate system will now be transformed to aPoint2 in the superView's coordinate system. Other points will be translated by the same amount. It is normally used when adding subViews to their superView in order to line up the Viewport of one subView with that of another subView (see View|addSubView:align:with:). aPoint1 and aPoint2 are usually points on the viewports that are to be aligned. For example, 'subView2 align: subView2 viewport topLeft with: subView1 viewport topRight' would be used to place the viewport of subView2 next to the viewport of subView1 with the topLeft and topRight corners, respectively, coinciding. It is also possible to align the viewport of a subView with the window of the superView, e.g. 'subView align: subView viewport center with: superView window center'. View|align:with: assumes that the view has been properly scaled, if necessary, to match its superView (see View|scaleBy:). Typically, the coordinate systems of the receiver and its superView will differ only by a translation offset so that no scaling is necessary. " self setTransformation: (transformation align: aPoint1 with: aPoint2)!scale: aScale translation: aTranslation "The x component of aScale (a Point) specifies the scale (translation) in the x direction; the y component specifies the scale (translation) in the y direction. aScale can optionally be an instance of Integer or Float in order to specify uniform scaling in both directions. Create a new local transformation for the receiver with a scale factor of aScale and a translation offset of aTranslation. When the transformation is applied (see View|transform:), the scale is applied first, followed by the translation. It is typically used when building a superView from its subViews in order to line up the viewports of the subViews in the desired way. If no scaling is required between subView and superView, then View|align:with: is often more convenient to use." self setTransformation: (WindowingTransformation scale: aScale translation: aTranslation)!scaleBy: aScale "The x component of aScale (a Point) specifies the scale in the x direction; the y component specifies the scale in the y direction. aScale can, optionally, be an instance of Integer or Float in order to specify uniform scaling in both directions. Scales the View by aScale. The scale is concatenated with the current transformation of the receiver and is applied when View|transform is sent. This happens automatically in the process of displaying the receiver, for example." self setTransformation: (transformation scaleBy: aScale)!transform: anObject "Apply the local transformation of the receiver to anObject and answer the resulting transformation. It is used to get the superView coordinates of an object. For example, the viewport is equal to the window transformed." ^transformation applyTo: anObject!transformation "Answer a copy of the receiver's local transformation." ^transformation copy!transformation: aTransformation "Set the receiver's local transformation to a copy of aTransformation, unlock the receiver (see View|unlock) and set the viewport to undefined (this forces it to be recomputed when needed)." self setTransformation: aTransformation copy!translateBy: aPoint "Translate the receiver by aPoint. The translation is concatenated with the current transformation of the receiver and is applied when View|transform is sent. This happens automatically in the process of displaying the receiver." self setTransformation: (transformation translateBy: aPoint)!window: aWindow viewport: aViewport "Set the receiver's window to aWindow, set its viewport to aViewport, and create a new local transformation for the receiver based on aWindow and aViewport. The receiver is scaled and translated so that aWindow, when transformed, coincides with aViewport. It is used to position a subView's window within some specific region of its superView's area. For example, 'subView window: aRectangle1 viewport: aRectangle2' sets subView's window to aRectangle1, its viewport to aRectangle2, and its local transformation to one that transforms aRectangle1 to aRectange2." self window: aWindow. self setTransformation: (WindowingTransformation window: aWindow viewport: aViewport). self getViewport! !!View methodsFor: 'bordering'!borderColor "Answer the receiver's border color." ^borderColor!borderColor: aColor "Set the receiver's border color to aColor." borderColor _ aColor!borderWidth "Answer either 0, indicating no border, or a Rectangle whose left value is the width in display coordinates of the receiver's left border. Right, top, and bottom widths are analogous. The border width is initially 0. A View with a border width of 0 will not have any border displayed." ^borderWidth!borderWidth: borderValue "Set the four border widths of the receiver to anInteger or rectangle." (borderValue isKindOf: Rectangle) ifTrue: [borderWidth _ borderValue. self unlock] ifFalse: [self borderWidthLeft: borderValue right: borderValue top: borderValue bottom: borderValue].!borderWidthLeft: anInteger1 right: anInteger2 top: anInteger3 bottom: anInteger4 "Set the border widths of the receiver to a Rectangle made up of the four arguments. These arguements represent the left, right, top, and bottom border widths." borderWidth _ Rectangle left: anInteger1 right: anInteger2 top: anInteger3 bottom: anInteger4. self unlock!insideColor "Answer the inside color of the receiver. The inside color determines the color of the inside of the receiver, which is the area inside the receiver's window excluding the border. The inside color is initially nil (meaning transparent), which means that when the receiver is displayed, the inside region will not be affected." ^insideColor!insideColor: aColor "Set the inside color of the receiver to be aColor." insideColor _ aColor! !!View methodsFor: 'scrolling'!scrollBy: aPoint "The x component of aPoint specifies the amount of scrolling in the x direction; the y component specifies the amount of scrolling in the y direction. The amounts are specified in the receiver's local coordinate system. Scroll the receiver up or down, left or right. The window of the receiver is kept stationary and the subViews and other objects in the receiver are translated relative to it. Scrolling doesn't change the insetDisplayBox or the viewport since the change in the transformation is canceled by the change in the window. In other words, all display objects in the view, except the window, are translated by the scrolling operation." | aRectangle | aRectangle _ insetDisplayBox. transformation _ transformation scrollBy: aPoint. window _ self getWindow translateBy: aPoint x negated @ aPoint y negated. self unlock. insetDisplayBox _ aRectangle! !!View methodsFor: 'clearing'!clear "Use the border color to paint the display box (including the border, see View|displayBox) of the receiver." borderColor ~= nil ifTrue: [self clear: borderColor]!clear: aColor "Use aColor to paint the display box (including the border, see View|displayBox) of the receiver." aColor ~= nil ifTrue: [Display fill: self displayBox mask: aColor]!clearInside "Use the inside color to paint the inset display box (excluding the border, see View|insetDisplayBox) of the receiver." insideColor ~= nil ifTrue: [self clearInside: insideColor]!clearInside: aColor "Use aColor to paint the inset display box (excluding the border, see View|insetDisplayBox) of the receiver." aColor ~= nil ifTrue: [Display fill: self insetDisplayBox mask: aColor]! !!View methodsFor: 'indicating'!flash "Cause the inset display box (the display box excluding the border, see View|insetDisplayBox) of the receiver to complement twice in succession." Display flash: self insetDisplayBox!highlight "Cause the inset display box (the display box excluding the border, see View|insetDisplayBox) of the receiver to complement." Display reverse: self insetDisplayBox! !!View methodsFor: 'updating'!update "Normally sent by the receiver's model in order to notify the receiver of a change in the model's state. Subclasses implement this message to do particular update actions." self update: self!update: aParameter "Normally sent by the receiver's model (via 'View|update') in order to notify the receiver that the state of the model has changed. View|update: should be redefined in a subclass if some specific action is to take place when the model changes. A typical action that might be required is to redisplay the receiver." ^self! !!View methodsFor: 'user interface'! !!View methodsFor: 'private'!computeDisplayTransformation "Returns a WindowingTransformation that transforms the coordinate system of the View into that of the display screen. The transformation is computed by composing the View's transformation with all transformations along its superView chain. It is sent by View|displayTransformation when the View is unlocked (see View|unlock)." self isTopView ifTrue: [^transformation] ifFalse: [^superView displayTransformation compose: transformation]!computeInsetDisplayBox "Compute the View's inset display box by intersecting the superView's inset display box with the View's window transformed to display coordinates and then inseting the result by the border width. It is sent by View|insetDisplayBox if the inset display box is nil." self isTopView ifTrue: [^(self displayTransform: self getWindow) insetBy: borderWidth] ifFalse: [^(superView insetDisplayBox intersect: (self displayTransform: self getWindow)) insetBy: borderWidth]!getController "Returns the View's controller if one exists. nil indicates that the default controller is to be used." ^controller!getViewport "Returns the Rectangle representing the View's viewport (in the coordinate system of the superclass). If no viewport has been specified, the View's window transformed into the superView's coordinate system is saved and returned. It should be used by methods of View and subclasses (instead of directly referring to the viewport) unless it is known that a viewport actually exists. It should not be used outside of View or subclasses because the viewport is not sharable." viewport == nil ifTrue: [viewport _ self transform: self getWindow]. ^viewport!getWindow "Returns the Rectangle that represents the window of this View. If no window has been specified, a default window (see View|defaultWindow) is created, saved, and returned. Should be used by methods of View and subclasses to access the View window instead of directly accessing the field unless it is known that a window actually exists. It is not to be used outside of View (or subclasses) because the window is not sharable. View|window should be used for outside access to the window." window == nil ifTrue: [self setWindow: self defaultWindow]. ^window!isCyclic: aView "Answers true if aView is the same as this View or its superView, false otherwise. " self == aView ifTrue: [^true]. self isTopView ifTrue: [^false]. ^superView isCyclic: aView!setTransformation: aTransformation "Sets the View's local transformation to aTransformation, unlocks the View (see View|unlock) and sets the viewport to undefined (this forces it to be recomputed when needed). Should be used instead of setting the transformation directly." transformation _ aTransformation. self unlock. viewport _ nil!setWindow: aWindow "Sets the View's window to aWindow and unlocks the View (see View|unlock). View|setWindow should be used by methods of View and subclasses to set the View window (rather than directly setting the instance variable) to insure that the View is unlocked." window _ aWindow. viewport _ nil. self unlock!superView: aView "Sets the View's superView to aView and unlocks the View (see View|unlock). It is sent by View|addSubView: in order to properly set all the links." superView _ aView. self unlock! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!View class instanceVariableNames: ''!!View class methodsFor: 'instance creation'!identityTransformation "Answer an instance of me with no translation and unity scaling. " ^WindowingTransformation identity!new "Answer an initialized instance of me. The transformation is an identity transformation, the borderWidth is 0, the borderColor is black, and the insideColor is transparent." ^super new initialize! ! Object subclass: #WindowingTransformation instanceVariableNames: 'scale translation ' classVariableNames: '' poolDictionaries: '' category: 'Interface-Framework'!WindowingTransformation comment: 'WindowingTransformation is used to transform objects from a source coordinate system to a destination coordinate system. WindowingTransformation contains a scale and a translation which can be applied to objects that respond to scaleBy: and translateBy:. An instance of WindowingTransformation can be created with a default identity scale and translation, or with a specified scale and translation, or with a scale and translation computed from a window (a Rectangle in the source coordinate system) and a viewport (a Rectangle in the destination coordinate system). In applying a WindowingTransformation to an object, the object is first scaled (around the origin of the source coordinate system) and then translated. WindowingTransformations can be composed to form a single compound transformation.'!!WindowingTransformation methodsFor: 'scrolling'!scrollBy: aPoint "Answer a new WindowingTransformation with the same scale as the receiver and with a translation of the current translation plus aPoint scaled by the current scale. It is used when the translation is known in source coordinates, rather than scaled source coordinates (see WindowingTransformation|translateBy:). An example is that of scrolling objects with respect to a stationary window in the source coordinate system. If no scaling is in effect (scale = nil), then WindowingTransformation|translateBy: and WindowingTransformation|scrollBy: are equivalent." | newTranslation | scale == nil ifTrue: [newTranslation _ aPoint] ifFalse: [newTranslation _ scale * aPoint]. ^self translateBy: newTranslation! !!WindowingTransformation methodsFor: 'transforming'!align: point1 with: point2 "Answer a new WindowingTransformation with the same scale as the receiver and with a translation of (aPoint2 - aPoint1). It is normally used when the source and destination coordinate systems are scaled the same (that is, there is no scaling between them), and is then a convenient way of specifying a translation, given two points that are intended to coincide." ^self translateBy: point2 - point1!noScale "Answer true if the identity scale is in effect; answer false, otherwise." ^scale == nil!scale "Answer a copy of the point that represents the current scale of the receiver." scale == nil ifTrue: [^1.0 @ 1.0] ifFalse: [^scale copy]!scaleBy: aScale "Answer a new WindowingTransformation with the scale and translation of the receiver both scaled by aScale." | checkedScale newScale newTranslation | aScale == nil ifTrue: [newScale _ scale. newTranslation _ translation] ifFalse: [checkedScale _ self checkScale: aScale. scale == nil ifTrue: [newScale _ checkedScale] ifFalse: [newScale _ scale * checkedScale]. newTranslation _ checkedScale * translation]. ^WindowingTransformation scale: newScale translation: newTranslation!scaleOfOne scale _ 1.0 @ 1.0.!translateBy: aPoint "Answer a new WindowingTransformation with the same scale as the receiver and with a translation of the current translation plus aPoint. It is used when the translation is known in scaled source coordinates, rather than source coordinates (see WindowingTransformation|scrollBy:). If no scaling is in effect (scale = nil), then WindowingTransformation|translateBy: and WindowingTransformation|scrollBy: are equivalent." ^WindowingTransformation scale: scale translation: translation + aPoint!translation "Answer a copy of the receiver's translation." ^translation copy! !!WindowingTransformation methodsFor: 'applying transform'!applyInverseTo: anObject "Apply the inverse of the receiver to anObject and answer the result. Used to map some object in destination coordinates to one in source coordinates." | transformedObject | transformedObject _ anObject translateBy: translation x negated @ translation y negated. scale == nil ifFalse: [transformedObject _ transformedObject scaleBy: 1.0 / scale x @ (1.0 / scale y)]. ^transformedObject!applyTo: anObject "Apply the receiver to anObject and answer the result. Used to map some object in source coordinates to one in destination coordinates." | transformedObject | scale == nil ifTrue: [transformedObject _ anObject] ifFalse: [transformedObject _ anObject scaleBy: scale]. transformedObject _ transformedObject translateBy: translation. ^transformedObject!compose: aTransformation "Answer a new WindowingTransformation that is the composition of the receiver and aTransformation. The effect of applying the resulting WindowingTransformation to an object is the same as that of first applying aTransformation to the object and then applying the receiver to its result." | aTransformationScale newScale newTranslation | aTransformationScale _ aTransformation scale. scale == nil ifTrue: [aTransformation noScale ifTrue: [newScale _ nil] ifFalse: [newScale _ aTransformationScale]. newTranslation _ translation + aTransformation translation] ifFalse: [aTransformation noScale ifTrue: [newScale _ scale] ifFalse: [newScale _ scale * aTransformationScale]. newTranslation _ translation + (scale * aTransformation translation)]. ^WindowingTransformation scale: newScale translation: newTranslation! !!WindowingTransformation methodsFor: 'printing'!printOn: aStream aStream nextPutAll: self class name, ' scale: '; print: scale; nextPutAll: ' translation: '; print: translation!storeOn: aStream aStream nextPut: $(; nextPutAll: self species name; nextPutAll: ' scale: '; store: scale; cr; nextPutAll: ' translation: '; store: translation; nextPut: $).! !!WindowingTransformation methodsFor: 'private'!checkScale: aScale "Converts aScale to the internal format of a floating-point Point." | checkedScale | checkedScale _ aScale asPoint. ^checkedScale x asFloat @ checkedScale y asFloat!setScale: aScale translation: aTranslation "Sets the scale to aScale and the translation to aTranslation." scale _ aScale. translation _ aTranslation! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!WindowingTransformation class instanceVariableNames: ''!!WindowingTransformation class methodsFor: 'instance creation'!identity "Answer an instance of me with no scaling (nil) and no translation (0@0)." ^self new setScale: nil translation: 0 @ 0!scale: aScale translation: aTranslation "Answer an instance of me with a scale factor of aScale and a translation offset of aTranslation. When the transformation is applied (see WindowingTransformation|apply:), the scale is applied first, followed by the translation." ^self new setScale: aScale translation: aTranslation!window: aWindow viewport: aViewport "Answer an instance of me with a scale and translation based on aWindow and aViewport. The scale and translation are computed such that aWindow, when transformed, coincides with aViewport. " | scale translation | aViewport width = aWindow width & (aViewport height = aWindow height) ifTrue: [scale _ nil] ifFalse: [scale _ aViewport width asFloat / aWindow width asFloat @ (aViewport height asFloat / aWindow height asFloat)]. scale == nil ifTrue: [translation _ aViewport left - aWindow left @ (aViewport top - aWindow top)] ifFalse: [translation _ aViewport left - (scale x * aWindow left) @ (aViewport top - (scale y * aWindow top))]. ^self new setScale: scale translation: translation! ! ArrayedCollection variableWordSubclass: #WordArray instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Graphics-Support'!WordArray comment:'WordArrays provide contiguous storage of data, primarily to hold the graphical data of Forms. Forms and their subclasses provide the additional structural information as to how the bits should be interpreted in two dimensions.'!!WordArray methodsFor: 'initialize-release'!fromByteStream: aStream "Initialize the array of bits by reading integers from the Stream, aStream." | high low | 1 to: self size do: [:i | high _ aStream next asInteger. "be cautious, it may be a char" low _ aStream next asInteger. self at: i put: (high bitShift: 8) + low]! !!WordArray methodsFor: 'bit counting'!countBits "Answer the number of on bits (1's) in me." | count bitMask | count _ 0. self do: [:word | bitMask _ 1. word highBit timesRepeat: [(word bitAnd: bitMask) ~= 0 ifTrue: [count _ count + 1]]]. ^count! !!WordArray methodsFor: 'printing'!printOn: aStream aStream nextPutAll: 'a WordArray of length '. self size printOn: aStream! !!WordArray methodsFor: 'filing'!toStream: aStream "Store the array of bits onto the Stream, aStream." 1 to: self size do: [:i | aStream nextPut: ((self at: i) bitShift: -8). aStream nextPut: ((self at: i) bitAnd: 255)]! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!WordArray class instanceVariableNames: ''!!WordArray class methodsFor: 'constants'!maxSize "The maximum size of a WordArray is 64640 elements." ^64640! ! PositionableStream subclass: #WriteStream instanceVariableNames: 'writeLimit ' classVariableNames: '' poolDictionaries: '' category: 'Collections-Streams'!WriteStream comment: 'I am a writer of an indexable collection. writeLimit marks the farthest that has been written into the collection, not the actual size of the collection.'!!WriteStream methodsFor: 'accessing'!contents readLimit _ readLimit max: position. ^collection copyFrom: 1 to: position!next self shouldNotImplement!nextPut: anObject "Insert the argument at the next position in the Stream represented by the receiver. Fail if the collection of this stream is not an Array or a String. Fail if the stream is positioned at its end, or if the position is out of bounds in the collection. Fail if the argument is not of the right type for the collection. Optional. See Object documentation whatIsAPrimitive." <primitive: 66> position = writeLimit ifTrue: [^self pastEndPut: anObject] ifFalse: [^collection at: (position _ position + 1) put: anObject]!size ^readLimit _ readLimit max: position! !!WriteStream methodsFor: 'positioning'!position: anInteger readLimit _ readLimit max: position. super position: anInteger!reset readLimit _ readLimit max: position. position _ 0! !!WriteStream methodsFor: 'character writing'!cr "Append a return character to the receiver." self nextPut: Character cr!crtab "Append a return character, followed by a single tab character, to the receiver." self nextPut: Character cr. self nextPut: Character tab!crtab: anInteger "Append a return character, followed by anInteger tab characters, to the receiver." self nextPut: Character cr. anInteger timesRepeat: [self nextPut: Character tab]!emphasis ^ 1 "Allows compatibility with streams which carry emphasis"!emphasis: ignored "Allows compatibility with streams which carry emphasis"!space "Append a space character to the receiver." self nextPut: Character space!tab "Append a tab character to the receiver." self nextPut: Character tab! !!WriteStream methodsFor: 'printing'!print: anObject "Have anObject print on the receiver." anObject printOn: self!store: anObject "Have anObject print on me for rereading." anObject storeOn: self! !!WriteStream methodsFor: 'fileIn/Out'!nextChunkPut: aString "Put aString onto self, doubling embedded terminators." | index stringSize char terminator | terminator _ $!!. index _ 0. stringSize _ aString size. [(index _ index + 1) <= stringSize] whileTrue: [char _ aString at: index. self nextPut: char. char == terminator ifTrue: ["double imbedded terminator" self nextPut: char]]. self nextPut: terminator! !!WriteStream methodsFor: 'private'!on: aCollection super on: aCollection. readLimit _ 0. writeLimit _ aCollection size!on: aCollection from: firstIndex to: lastIndex | len | collection _ aCollection. readLimit _ writeLimit _ lastIndex > (len _ collection size) ifTrue: [len] ifFalse: [lastIndex]. position _ firstIndex <= 1 ifTrue: [0] ifFalse: [firstIndex - 1]!pastEndPut: anObject collection grow. writeLimit _ collection size. collection at: (position _ position + 1) put: anObject!with: aCollection super on: aCollection. position _ readLimit _ writeLimit _ aCollection size! !"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!WriteStream class instanceVariableNames: ''!!WriteStream class methodsFor: 'instance creation'!on: aCollection from: firstIndex to: lastIndex "Answer with a new instance streaming over a copy of aCollection from firstIndex to lastIndex." ^self basicNew on: aCollection from: firstIndex to: lastIndex!with: aCollection "Answer a new instance of me streaming on aCollection. Assume that the collection is already full so the position and the limits are set to the end." ^self basicNew with: aCollection!with: aCollection from: firstIndex to: lastIndex "Answer a new instance of me streaming on the subcollection of aCollection, starting at index firstIndex and ending at lastIndex. Assume that the resulting collection is already full so the position and the limits are set to the end." ^self basicNew with: (aCollection copyFrom: firstIndex to: lastIndex)! ! +\ No newline at end of file diff --git a/web/images/banay-2020.im b/web/images/banay-2020.im Binary files differ. diff --git a/web/images/xerox-v2.im b/web/images/xerox-v2.im Binary files differ. diff --git a/web/index.html b/web/index.html @@ -0,0 +1,98 @@ +<!doctype html> +<html lang="fr"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>Smalltalk-80 dans le navigateur</title> +<meta name="description" content="L'image Smalltalk-80 d'origine de Xerox PARC (version 2, 1er avril 1983) qui tourne dans le navigateur sur la machine virtuelle du livre bleu de Dan Banay, compilée en WebAssembly."> +<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='%23e4e4e0'/%3E%3Crect x='2' y='2' width='12' height='3' fill='%23101010'/%3E%3Crect x='2' y='6' width='12' height='8' fill='none' stroke='%23101010'/%3E%3C/svg%3E"> +<link rel="stylesheet" href="style.css"> +</head> +<body> +<header> + <h1><span class="logo">Smalltalk<span>-80</span></span> dans le navigateur</h1> + <p class="sub">L'image Xerox PARC d'origine (version 2, 1<sup>er</sup> avril 1983), telle qu'elle a été livrée sur bande aux + premiers licenciés, exécutée par une machine virtuelle écrite d'après le livre bleu et compilée en WebAssembly.</p> +</header> + +<main> + <section class="screen" aria-label="Écran de Smalltalk-80"> + <div class="bezel"> + <canvas id="canvas" tabindex="0" width="640" height="480"></canvas> + </div> + <div class="status" id="status" aria-live="polite">Chargement…</div> + </section> + + <section class="toolbar"> + <label>Image + <select id="image"> + <option value="xerox">Xerox 1983, telle que livrée</option> + <option value="banay">Xerox 1983 + sources (Banay 2020)</option> + </select> + </label> + <label>Vitesse + <select id="speed"> + <option value="2">douce</option> + <option value="10" selected>normale</option> + <option value="15">maximale</option> + </select> + </label> + <button id="btn-pause" title="Suspendre / reprendre l'interprétation">Pause</button> + <button id="btn-save" title="Télécharge le fichier image courant (après « save » dans le menu système, c'est votre instantané)">Télécharger l'image</button> + <button id="btn-reset" title="Recharge la page : l'image repart de l'état livré">Redémarrer</button> + </section> + + <section class="help"> + <h2>Comment ça marche</h2> + <div class="cols"> + <div> + <h3>La souris à trois boutons</h3> + <p>Smalltalk-80 attend une souris à trois boutons : <b>rouge</b> (sélection), <b>jaune</b> (menu de la fenêtre : + <i>do it</i>, <i>print it</i>, <i>accept</i>…) et <b>bleu</b> (menu du cadre : <i>close</i>, <i>frame</i>, <i>collapse</i>…).</p> + <table> + <tr><td>Bouton gauche</td><td>rouge</td></tr> + <tr><td>Bouton droit, ou <kbd>Ctrl</kbd>+gauche</td><td>jaune</td></tr> + <tr><td>Bouton du milieu, ou <kbd>Alt</kbd>/<kbd>⌥</kbd>+gauche</td><td>bleu</td></tr> + </table> + <p>Le fond gris est le bureau : un clic jaune dessus ouvre le menu système (<i>browser</i>, <i>workspace</i>, + <i>transcript</i>, <i>save</i>, <i>quit</i>…). Pour ouvrir une fenêtre, on choisit l'entrée du menu puis on + dessine son cadre : clic rouge pour le coin haut-gauche, clic rouge pour le coin bas-droit.</p> + </div> + <div> + <h3>Votre clavier</h3> + <p>Cliquez d'abord dans l'écran pour lui donner le focus. Les caractères sont saisis selon votre disposition de clavier. + Deux signes ont une forme particulière dans la police de 1983 : <kbd>_</kbd> s'affiche en flèche gauche + <b class="inv">←</b> (affectation) et <kbd>^</kbd> en flèche haut <b class="inv">↑</b> (retour).</p> + <p>Essayez, dans un <i>workspace</i> : tapez <code>3 + 4</code>, sélectionnez-le, puis bouton jaune → <i>print it</i>. + Ou <code>Smalltalk browseAllImplementorsOf: #at:put:</code> puis <i>do it</i>.</p> + <p>Les touches <kbd>Ctrl</kbd>, <kbd>Retour arrière</kbd>, <kbd>Suppr</kbd>, <kbd>Tab</kbd>, <kbd>Échap</kbd> et + <kbd>Entrée</kbd> sont transmises telles quelles ; <kbd>Ctrl</kbd>+<kbd>T</kbd> vaut <i>ifTrue:</i>, + <kbd>Ctrl</kbd>+<kbd>F</kbd> <i>ifFalse:</i>, comme sur l'Alto.</p> + </div> + <div> + <h3>Sous le capot</h3> + <p>L'image <code>VirtualImage</code> (596 128 octets) est celle que Mario Wolczko a reçue de Xerox en 1984 sur bande + ½ pouce pour son projet de maîtrise à Manchester, et qu'il a + <a href="http://www.wolczko.com/st80/">mise en ligne</a> ; elle est convertie en petit-boutiste, comme le préconise le + guide de portage de Xerox. La machine virtuelle est l'implémentation « by the Bluebook » de + <a href="https://github.com/dbanay/Smalltalk">Dan Banay</a> (C++, MIT) : interpréteur de bytecodes, mémoire d'objets à + comptage de références, BitBlt, le tout tel que décrit dans <i>Smalltalk-80: The Language and its Implementation</i>. + Elle est compilée en WebAssembly avec Emscripten et affichée par SDL2 dans le canevas.</p> + <p>L'image d'origine ne sait lire que le système de fichiers de l'Alto : dans le <i>browser</i>, le code est donc + <b>décompilé</b> (pas de commentaires ni de noms de temporaires). La seconde image ajoute les classes + <code>PosixFile</code> de Dan Banay et le fichier <code>Smalltalk-80.sources</code> : on y lit les vraies sources. + Les fichiers vivent en mémoire : un <i>save</i> y écrit l'instantané, que le bouton « Télécharger l'image » récupère.</p> + </div> + </div> + </section> +</main> + +<footer> + <p>Smalltalk-80 © 1983 Xerox Corporation ; image et sources distribuées par Mario Wolczko avec l'accord de Xerox PARC. + Machine virtuelle © 2020 Dan Banay (MIT). Page de Jean Schurger, 2026.</p> +</footer> + +<script src="st80.js"></script> +<script type="module" src="app.js"></script> +</body> +</html> diff --git a/web/style.css b/web/style.css @@ -0,0 +1,82 @@ +:root { + --bg: #15161a; + --fg: #e8e6e0; + --muted: #a7a49c; + --accent: #2f6fd9; + --paper: #e4e4e0; + --ink: #101010; + color-scheme: dark; +} +* { box-sizing: border-box; } +html, body { margin: 0; padding: 0; } +body { + background: var(--bg); + color: var(--fg); + font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + padding: 0 16px 40px; +} +a { color: #8fb8ff; } +header { max-width: 980px; margin: 24px auto 12px; } +h1 { font-size: 1.6rem; font-weight: 600; margin: 0 0 6px; letter-spacing: .01em; } +.logo { font-weight: 800; color: #fff; } +.logo span { color: var(--accent); } +.sub { color: var(--muted); margin: 0; } +main { max-width: 980px; margin: 0 auto; } +kbd { + font: 0.85em ui-monospace, SFMono-Regular, Menlo, monospace; + background: #2b2d35; border: 1px solid #3c3f49; border-bottom-width: 2px; + border-radius: 4px; padding: 0 5px; color: #fff; white-space: nowrap; +} +code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: #fff; } +.inv { background: #fff; color: #000; padding: 0 3px; font-family: ui-monospace, monospace; font-style: normal; } + +/* Écran */ +.screen { margin: 0 auto; max-width: 980px; } +.bezel { + background: #050505; + border-radius: 14px; + padding: 2.5%; + box-shadow: 0 10px 40px rgba(0,0,0,.6), inset 0 0 0 2px #222; +} +#canvas { + display: block; + /* SDL pose une taille CSS en pixels ; on la remplace par la largeur disponible */ + width: 100% !important; + height: auto !important; + aspect-ratio: 4 / 3; + background: var(--paper); + image-rendering: pixelated; + image-rendering: crisp-edges; + outline: none; + cursor: none; +} +#canvas:focus { box-shadow: 0 0 0 2px var(--accent); } +.status { + text-align: center; color: var(--muted); font-size: .85rem; margin: 8px 0 0; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; min-height: 1.4em; +} + +/* Barre d'outils */ +.toolbar { + display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; align-items: center; + margin: 14px auto 18px; max-width: 980px; +} +.toolbar button, .toolbar select { + background: #2b2d35; color: #fff; border: 1px solid #40434e; border-radius: 6px; + padding: 7px 14px; font: inherit; font-size: .95rem; cursor: pointer; +} +.toolbar button:hover { background: #363946; } +.toolbar button:active, .toolbar button.on { background: var(--accent); border-color: var(--accent); } +.toolbar label { color: var(--muted); font-size: .9rem; display: inline-flex; gap: 6px; align-items: center; } + +/* Aide */ +.help { max-width: 980px; margin: 28px auto 0; } +.help h2 { font-size: 1.2rem; margin: 0 0 10px; } +.help h3 { font-size: 1rem; margin: 0 0 6px; color: #fff; } +.help p { margin: 0 0 10px; color: var(--fg); font-size: .95rem; } +.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 24px; } +table { border-collapse: collapse; font-size: .9rem; margin: 6px 0 10px; } +td { padding: 3px 10px 3px 0; vertical-align: top; } +td + td { color: var(--muted); } + +footer { max-width: 980px; margin: 36px auto 0; color: var(--muted); font-size: .8rem; }