Import Amiga applications and desktop tools

This commit is contained in:
Alberto committed 2026-11-11 16:21:50 +01:00
commit 1c144c9a3c
347 files changed
+423483

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
build/
*.o
*.asm
RetroTerm.prefs
__pycache__/
+50
View File
@@ -0,0 +1,50 @@
# RetroTerm for Amiga
Native Amiga BBS Telnet client with Commodore PETSCII and monochrome ASCII/ANSI terminal modes. Independent project, separate from the desktop demos.
## Requirements
AmigaOS 3.1, graphics.library v40, a 15-bit or higher RTG Workbench with Picasso96API.library v2, bsdsocket.library v4, Fast RAM. Developed/tested on WinUAE 68040 + JIT. Real hardware performance untested.
## Use
Enter host/port and press Connetti. RetroCampus: bbs.retrocampus.com:6510 for 40x25 PETSCII; port 23 for the platform selector, then 4 for plain ASCII or 8 for Linux UTF-8. Changing terminal mode disconnects and clears the screen; changing phosphor colour updates the existing normal screen immediately. PETSCII keeps the Commodore palette. Settings are saved beside the executable.
F1 green, F2 amber, F3 white; F4 ASCII/ANSI; F5 PETSCII; F6 connect; F7 disconnect; F8 local echo. Arrow keys, Return and Backspace are translated for the selected terminal. Close gadget exits.
Supports Telnet IAC escaping, binary/echo/SGA/TTYPE/NAWS negotiation, a bounded nonblocking transmit queue and connection timeout. PETSCII supports the upper/graphics and lower/upper sets, 16 colours, reverse, clear/home, cursor movement, insert/delete and scrolling. ANSI support is a practical subset: cursor addressing, erase, SGR, save/restore, scroll region, wrap. UTF-8 decoding accepts fragmented sequences and maps supported Unicode to CP437/block glyphs; malformed sequences fall back to CP437. UTF-8 auto-detection can be ambiguous with some legacy CP437 byte sequences. Unsupported Unicode shows ?. No SSH or file-transfer protocols in this version.
The renderer caches the terminal cells and sleeps between incoming data, UI events and cursor blinks. No continuously running animation loop.
## Build
Install VBCC m68k-amigaos, VASM, VLINK and NDK/network headers, then:
```powershell
./build.ps1 -Toolchain C:/path/to/toolchain
```
Copy build/RetroTerm, font.bin, bell.raw and RetroTerm.info together. Use Stack 131072 for CLI launch.
The generated bitmap font and icon are included. Recreate them with Python, Pillow, fontTools and the bundled CC0 fonts:
```
python generate_font.py
python icon.py
python generate_bell.py
```
## Font sources
- zeiche/c64font (CC0): https://github.com/zeiche/c64font
- Damian Vila, BESCII (CC0): https://github.com/damianvila/font-bescii
Original font files and notices are under third_party/. No Amiga/C64 ROM is bundled.
## Verification
core-tests.c checks PETSCII controls/colour/reverse, ANSI cursor/SGR/erase/wrap, fragmented UTF-8 and malformed fallback; it also feeds 60,000 deterministic fuzz bytes and checks cursor bounds. Run the native CoreTests executable to write core-tests.log beside it. Live connection and keyboard navigation tested against RetroCampus.
PETSCII font rasterization samples the original CC0 outline coordinates directly on the 8x8 grid, bypassing FreeType bearing/hinting shifts in semigraphics. Run python test_font.py for block/join regression checks.
## Terminal bell
ASCII BEL (0x07) and PETSCII 0x07 play an original soft 740 Hz sine chime with a quiet overtone. Duration 140 ms, cosine attack/release, Paula volume 18/64, stereo. Playback is asynchronous; repeats are coalesced and limited to one start per 360 ms. Audio channels are requested at minimum priority with NOWAIT and released on completion. The device BeginIO entry is called directly so ADIOF_PERVOL is preserved; Exec SendIO must not be used for audio.device. If no channel can be allocated, that bell is skipped. No sound is played for BEL used as an OSC title terminator.
F9 previews the sound. F10 toggles mute, saved with the other settings. The default is enabled. BellTest provides a native audio.device completion check; build with build-tests.ps1.
Ctrl+Invio: alterna finestra e tutto schermo sul Workbench. Mantiene connessione, contenuto del terminale e ripristina posizione e dimensioni della finestra.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+15
View File
@@ -0,0 +1,15 @@
#include "bell.c"
#include <proto/dos.h>
struct GfxBase *GfxBase;
int main(void){FILE*f=fopen("PROGDIR:bell-test.log","w");int i,error=99,started;ULONG unit,period;
if(!f)return 20;GfxBase=(struct GfxBase*)OpenLibrary("graphics.library",40);
if(!GfxBase){fprintf(f,"Graphics library unavailable.\n");fclose(f);return 20;}
if(!bell_init()){fprintf(f,"Sample/device resources unavailable.\n");fclose(f);CloseLibrary((struct Library*)GfxBase);return 20;}
bell_play(0);started=active;unit=(ULONG)audio->ioa_Request.io_Unit;period=audio->ioa_Period;unit=allocated;
for(i=0;active&&i<100;i++){
if(CheckIO((struct IORequest*)audio))error=audio->ioa_Request.io_Error;
bell_poll();if(active)Delay(1);
}
fprintf(f,"Started=%d completed=%d audio.device error=%d length=%lu volume=18/64 stereo\n",started,!active,error,length);fprintf(f,"poll_ticks=%d unit_mask=%lu period=%lu\n",i,unit,period);
bell_exit();CloseLibrary((struct Library*)GfxBase);fclose(f);return started&&!active&&error==0?0:20;
}
+72
View File
@@ -0,0 +1,72 @@
#include <exec/types.h>
#include <exec/memory.h>
#include <exec/nodes.h>
#include <devices/audio.h>
#include <graphics/gfxbase.h>
#include <proto/exec.h>
#include <stdio.h>
#include "bell.h"
extern struct GfxBase *GfxBase;
/* BeginIO is the device entry at -30, NOT exec SendIO (which strips
ADIOF_PERVOL and loses the sample's volume/period settings). */
void __bellBeginIO(__reg("a6")void*,__reg("a1")struct IORequest*)="\tjsr\t-30(a6)";
static struct MsgPort *port;
static struct IOAudio *audio,*right;
static UBYTE *sample;
static ULONG length,lastBell,allocated;
static int opened,active,played;
int bell_init(void){FILE*f;long n;
f=fopen("PROGDIR:bell.raw","rb");if(!f)return 0;
fseek(f,0,SEEK_END);n=ftell(f);rewind(f);
if(n<2||n>16384||(n&1)){fclose(f);return 0;}
length=n;sample=AllocMem(length,MEMF_CHIP|MEMF_PUBLIC);
if(!sample){fclose(f);return 0;}
if(fread(sample,1,length,f)!=length){fclose(f);bell_exit();return 0;}fclose(f);
port=CreateMsgPort();if(!port){bell_exit();return 0;}
audio=(struct IOAudio*)CreateIORequest(port,sizeof(struct IOAudio));
right=(struct IOAudio*)CreateIORequest(port,sizeof(struct IOAudio));
if(!audio||!right){bell_exit();return 0;}return 1;
}
void bell_poll(void){struct Message *m;
if(!port)return;
while((m=GetMsg(port))!=0){
if(m==(struct Message*)audio)active&=~1;
if(m==(struct Message*)right)active&=~2;
}
if(opened&&!active){
audio->ioa_Request.io_Unit=(struct Unit*)allocated;
CloseDevice((struct IORequest*)audio);opened=0;
}
}
static void start(struct IOAudio *io,ULONG unit){
io->ioa_Request.io_Message.mn_Node.ln_Type=NT_MESSAGE;
io->ioa_Request.io_Unit=(struct Unit*)unit;
io->ioa_Request.io_Command=CMD_WRITE;
io->ioa_Request.io_Flags=ADIOF_PERVOL;
io->ioa_Data=sample;io->ioa_Length=length;
io->ioa_Period=((GfxBase->DisplayFlags&PAL)?3546895UL:3579545UL)/11025;
io->ioa_Volume=18;io->ioa_Cycles=1;
__bellBeginIO(io->ioa_Request.io_Device,(struct IORequest*)io);
}
void bell_play(unsigned long now){static UBYTE channels[]={3,12,5,10};ULONG first,second;
bell_poll();if(!audio||active||(played&&now-lastBell<18))return;
played=1;lastBell=now;
/* One channel per ear, minimum allocation precedence, no waiting. */
audio->ioa_Request.io_Message.mn_Node.ln_Pri=-128;
audio->ioa_Request.io_Flags=ADIOF_NOWAIT;
audio->ioa_AllocKey=0;audio->ioa_Data=channels;audio->ioa_Length=sizeof(channels);
if(OpenDevice(AUDIONAME,0,(struct IORequest*)audio,0))return;
opened=1;allocated=(ULONG)audio->ioa_Request.io_Unit;
*right=*audio;first=allocated&(~allocated+1);second=allocated&~first;
active=3;start(audio,first);start(right,second);
}
void bell_exit(void){
if(active&1)if(!CheckIO((struct IORequest*)audio))AbortIO((struct IORequest*)audio);
if(active&2)if(!CheckIO((struct IORequest*)right))AbortIO((struct IORequest*)right);
while(active){WaitPort(port);bell_poll();}
if(opened){audio->ioa_Request.io_Unit=(struct Unit*)allocated;CloseDevice((struct IORequest*)audio);opened=0;}
if(right){DeleteIORequest((struct IORequest*)right);right=0;}
if(audio){DeleteIORequest((struct IORequest*)audio);audio=0;}
if(port){DeleteMsgPort(port);port=0;}
if(sample){FreeMem(sample,length);sample=0;}
}
+7
View File
@@ -0,0 +1,7 @@
#ifndef RETROTERM_BELL_H
#define RETROTERM_BELL_H
int bell_init(void);
void bell_play(unsigned long ticks);
void bell_poll(void);
void bell_exit(void);
#endif
+13
View File
@@ -0,0 +1,13 @@
param([Parameter(Mandatory=$true)][string]$Toolchain)
$ErrorActionPreference='Stop'
& "$PSScriptRoot/build.ps1" -Toolchain $Toolchain
$oldVBCC=$env:VBCC
$oldPath=$env:PATH
try {
$env:VBCC=Join-Path $PSScriptRoot 'build/vbcc'
$env:PATH=(Join-Path $Toolchain 'bin')+';'+$env:PATH
& (Join-Path $Toolchain 'bin/vc.exe') +boing -O2 -c99 -o "$PSScriptRoot/build/CoreTests" "$PSScriptRoot/core-tests.c" "$PSScriptRoot/terminal.c"
if($LASTEXITCODE -ne 0){throw 'Test build failed.'}
& (Join-Path $Toolchain 'bin/vc.exe') +boing -O2 -c99 -o "$PSScriptRoot/build/BellTest" "$PSScriptRoot/bell-smoke.c"
if($LASTEXITCODE -ne 0){throw 'Bell test build failed.'}
} finally {$env:VBCC=$oldVBCC;$env:PATH=$oldPath}
+26
View File
@@ -0,0 +1,26 @@
param([string]$Toolchain = $env:AMIGA_TOOLCHAIN)
$ErrorActionPreference = 'Stop'
if (!$Toolchain) { throw 'Specificare -Toolchain con la cartella che contiene bin e targets/m68k-amigaos.' }
$Toolchain = (Resolve-Path -LiteralPath $Toolchain).Path
$targetPath = Join-Path $Toolchain 'targets/m68k-amigaos'
$buildPath = Join-Path $PSScriptRoot 'build'
$configPath = Join-Path $buildPath 'vbcc'
New-Item -ItemType Directory -Path (Join-Path $configPath 'config') -Force | Out-Null
$config = [IO.File]::ReadAllText((Join-Path $PSScriptRoot 'vbcc-config.in')).Replace('@TARGET@', $targetPath.Replace('\','/'))
[IO.File]::WriteAllText((Join-Path $configPath 'config/boing'), $config)
$previousVBCC = $env:VBCC
$previousPath = $env:PATH
try {
$env:VBCC = $configPath
$env:PATH = (Join-Path $Toolchain 'bin') + ';' + $env:PATH
Push-Location -LiteralPath $PSScriptRoot
try {
& (Join-Path $Toolchain 'bin/vc.exe') +boing -O2 -c99 -o build/RetroTerm retroterm.c terminal.c bell.c
if ($LASTEXITCODE -ne 0) { throw 'Compilazione fallita.' }
Copy-Item -LiteralPath assets/font.bin,assets/bell.raw,assets/RetroTerm.info -Destination $buildPath -Force
} finally { Pop-Location }
} finally {
$env:VBCC = $previousVBCC
$env:PATH = $previousPath
}
Write-Output ('Pronto per Amiga: ' + $buildPath)
+33
View File
@@ -0,0 +1,33 @@
#include "terminal.h"
#include <stdio.h>
#include <string.h>
static struct Terminal t;static int failures,checks;static FILE *logfile;
#define CHECK(x) do{checks++;if(!(x)){failures++;fprintf(logfile,"FAIL line %d: %s\n",__LINE__,#x);}}while(0)
static void feed(char*s){while(*s)term_feed(&t,(unsigned char)*s++);}
int main(void){int i,m;unsigned long seed=0x37b5;
logfile=fopen("PROGDIR:core-tests.log","w");if(!logfile)return 20;
term_init(&t,0);term_feed(&t,7);CHECK(t.bell==1&&t.x==0&&t.y==0);
term_init(&t,0);feed("\033]0;title\007");CHECK(t.bell==0);
term_init(&t,1);term_feed(&t,7);CHECK(t.bell==1&&t.x==0&&t.y==0);
term_init(&t,1);term_feed(&t,147);term_feed(&t,28);term_feed(&t,18);term_feed(&t,'A');
CHECK(t.cell[0].glyph==1);CHECK(t.cell[0].fg==0&&t.cell[0].bg==2);CHECK(t.x==1&&t.y==0);
term_feed(&t,13);CHECK(t.x==0&&t.y==1&&t.reverse==0);term_feed(&t,14);CHECK(t.charset==1);
term_feed(&t,0xc1);CHECK(t.cell[40].glyph==65);term_feed(&t,0xff);CHECK(t.cell[41].glyph==94);
term_feed(&t,19);term_feed(&t,148);CHECK(t.cell[0].glyph==32);term_feed(&t,20);CHECK(t.x==0&&t.y==0);
term_init(&t,0);feed("\033[2;5HABC");CHECK(t.x==7&&t.y==1);CHECK(t.cell[84].glyph=='A');
feed("\033[31;7mX");CHECK(t.cell[87].fg==0&&t.cell[87].bg==1);
feed("\033[2J");CHECK(t.x==8&&t.y==1);CHECK(t.cell[87].glyph==32);
feed("\033[H\033[0m");term_feed(&t,0xc3);term_feed(&t,0xa9);CHECK(t.cell[0].glyph==130&&t.x==1);
term_feed(&t,0xe2);term_feed(&t,0x96);term_feed(&t,0x88);CHECK(t.cell[1].glyph==8&&t.x==2);
term_feed(&t,0xc4);term_feed(&t,'A');CHECK(t.cell[2].glyph==0xc4&&t.cell[3].glyph=='A');
term_init(&t,0);for(i=0;i<80;i++)term_feed(&t,'A');CHECK(t.y==0&&t.x==79&&t.pendingwrap);term_feed(&t,'B');CHECK(t.y==1&&t.x==1&&t.cell[80].glyph=='B');
for(m=0;m<2;m++){
term_init(&t,m);
for(i=0;i<30000;i++){
seed^=seed<<13;seed^=seed>>17;seed^=seed<<5;term_feed(&t,seed&255);
if(t.x<0||t.x>=t.cols||t.y<0||t.y>=25||t.argc>16){CHECK(0);break;}
}
CHECK(i==30000);
}
fprintf(logfile,"%d checks, %d failures; 60000 fuzz bytes processed.\n",checks,failures);fclose(logfile);return failures?20:0;
}
+13
View File
@@ -0,0 +1,13 @@
from pathlib import Path
import math
# 140 ms soft sine chime, raised-cosine attack/release, signed 8-bit Paula PCM.
rate=11025;n=1544
samples=[]
for i in range(n):
t=i/rate
attack=min(1,t/.008)
release=min(1,(n-1-i)/rate/.100)
envelope=(.5-.5*math.cos(math.pi*attack))*(.5-.5*math.cos(math.pi*release))
wave=math.sin(2*math.pi*740*t)+.10*math.sin(2*math.pi*1480*t)
samples.append(int(100*envelope*wave)&255)
(Path(__file__).parent/'assets/bell.raw').write_bytes(bytes(samples))
+47
View File
@@ -0,0 +1,47 @@
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from fontTools.ttLib import TTFont
root=Path(__file__).parent
# CC0 fonts; original files and license notices are retained in third_party.
c64=ImageFont.truetype(str(root/'third_party/c64.ttf'),8)
ascii_font=ImageFont.truetype(str(root/'third_party/Bescii-Mono.ttf'),8)
def raster(font,code,baseline):
im=Image.new('1',(8,8));ImageDraw.Draw(im).text((0,baseline),chr(code),font=font,anchor='ls',fill=1)
return bytes(sum((128>>x) for x in range(8) if im.getpixel((x,y))) for y in range(8))
# Read the CC0 C64 outline coordinates directly. FreeType applies the
# hmtx left bearing and grid fitting at 8px, which shifts partial blocks
# and loses rows. Sample the original 125-unit pixel grid without hints.
outline=TTFont(root/'third_party/c64.ttf')
cmap=outline.getBestCmap()
def exact_c64(code):
glyph=outline['glyf'][cmap[code]]
coords,ends,flags=glyph.getCoordinates(outline['glyf'])
polygons=[];start=0
for end in ends:
polygons.append(list(coords[start:end+1]));start=end+1
def inside(poly,x,y):
hit=False
for i,(ax,ay) in enumerate(poly):
bx,by=poly[i-1]
if (ay>y)!=(by>y) and x<(bx-ax)*(y-ay)/(by-ay)+ax:hit=not hit
return hit
return bytes(sum(128>>x for x in range(8)
if any(inside(poly,62.5+x*125,1062.5-y*125) for poly in polygons))
for y in range(8))
upper=[bytes(v^255 for v in exact_c64(0xe000+i)) for i in range(128)]
lower=upper.copy()
# The shifted bank's alphabet uses the same exact grid coordinates.
for i in range(26):
lower[i+1]=exact_c64(97+i)
lower[i+65]=upper[i+1]
# Shifted C64 bank has distinct checker/diagonal patterns and a tick.
def pattern(predicate):
return bytes(sum(128>>x for x in range(8) if predicate(x,y)) for y in range(8))
lower[0x5e]=pattern(lambda x,y: ((x//2+y//2)&1)==1)
lower[0x5f]=pattern(lambda x,y: (x-y)%4>=2)
lower[0x69]=pattern(lambda x,y: (x+y)%4<2)
lower[0x7a]=pattern(lambda x,y: (y<=4 and 7-y<=x<=8-y) or
(3<=y<=6 and x in (1,2)) or (y==5 and x==3))
ascii_glyphs=[raster(ascii_font,ord(bytes([i]).decode('cp437')),7) for i in range(256)]
for i in range(32):ascii_glyphs[i]=raster(ascii_font,0x2580+i,7)
(root/'assets/font.bin').write_bytes(b''.join(upper+lower+ascii_glyphs))
+23
View File
@@ -0,0 +1,23 @@
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import struct
p=Path(__file__).parent
u16=lambda n:struct.pack('>H',n)
u32=lambda n:struct.pack('>I',n&0xffffffff)
h=bytearray(78);h[0:4]=u16(0xe310)+u16(1)
h[12:16]=u16(48)+u16(40);h[16:18]=u16(6);h[48]=3
for off in (22,26):h[off:off+4]=u32(1)
h[58:66]=u32(-1)+u32(-1);h[74:78]=u32(131072)
data=bytearray(h)
for selected in (False,True):
im=Image.new('P',(48,40),0);d=ImageDraw.Draw(im)
d.rounded_rectangle((2,1,45,34),radius=3,fill=2,outline=1 if selected else 3,width=2)
d.rectangle((6,5,41,29),fill=0,outline=3)
d.text((9,7),'BBS',font=ImageFont.load_default(),fill=1)
d.line((10,23,15,23),fill=3,width=2);d.line((18,23,34,23),fill=3)
d.rectangle((18,35,30,37),fill=3)
data+=u16(0)+u16(0)+u16(48)+u16(40)+u16(2)+u32(1)+bytes([3,0])+u32(0)
for plane in range(2):
for y in range(40):
for x in range(0,48,8):data.append(sum((128>>i) if im.getpixel((x+i,y))&(1<<plane) else 0 for i in range(8)))
(p/'assets/RetroTerm.info').write_bytes(data)
+229
View File
@@ -0,0 +1,229 @@
#include <exec/types.h>
#include <intuition/intuition.h>
#include <graphics/gfxbase.h>
#include <devices/inputevent.h>
#include <libraries/gadtools.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/intuition.h>
#include <proto/graphics.h>
#include <proto/gadtools.h>
#include <proto/keymap.h>
#include <proto/layers.h>
#include <proto/socket.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "terminal.h"
#include "bell.h"
#define FW 640
#define FH 400
struct IntuitionBase *IntuitionBase;
struct GfxBase *GfxBase;
struct Library *GadToolsBase,*KeymapBase,*SocketBase,*LayersBase;
static struct Library *P96Base;
struct RenderInfo {APTR Memory;WORD BytesPerRow,pad;ULONG RGBFormat;};
void __p96write(__reg("a6")void*,__reg("a0")struct RenderInfo*,__reg("d0")UWORD,__reg("d1")UWORD,__reg("a1")struct RastPort*,__reg("d2")UWORD,__reg("d3")UWORD,__reg("d4")UWORD,__reg("d5")UWORD)="\tjsr\t-102(a6)";
static struct Screen *sc;static struct Window *win;static struct Gadget *glist,*ghost,*gport,*gmode,*gtheme;
static struct TextAttr gadgetFont={"topaz.font",8,0,0};
static APTR vi;static struct BitMap *bitmap;static struct RastPort backrp;
static struct Terminal term;
static UBYTE font[512*8],rx[8192],tx[16384];static int txlen;
static UWORD *frame,*scaled,*xmap,colors[16];
static int bw,bh,mode=1,theme=1,sock=-1,connecting,localEcho,done,dirty=1,uiDirty=1,cursor=1,oldCursor;
static int bellEnabled=1,bellReady;
static int fullscreen,togglePending,savedLeft=230,savedTop=70,savedWidth,savedHeight;
static ULONG connectStart,blinkTick;
static char host[256]="bbs.retrocampus.com",portstr[8]="6510",status[160]="Pronto | Ctrl+Invio: tutto schermo | Connetti per chiamare.";
static char *modes[]={"ASCII / ANSI 80","Commodore PETSCII",0};
static char *themes[]={"Fosfori verdi","Fosfori ambra","Fosfori bianchi",0};
static UBYTE localOpt[256],remoteOpt[256];static int telstate,telcmd,sblen;static UBYTE sb[256];
static ULONG ticks(void){struct DateStamp ds;DateStamp(&ds);return ((ULONG)ds.ds_Days*1440+ds.ds_Minute)*3000+ds.ds_Tick;}
static UWORD rgb(int r,int g,int b){return ((r>>3)<<10)|((g>>3)<<5)|(b>>3);}
static void setStatus(char *s){strncpy(status,s,sizeof(status)-1);status[sizeof(status)-1]=0;uiDirty=1;}
static void palette(void){int i;static const UBYTE c64[16][3]={{0,0,0},{255,255,255},{136,57,50},{103,182,189},{139,63,150},{85,160,73},{64,49,141},{191,206,114},{139,84,41},{87,66,0},{184,105,98},{80,80,80},{120,120,120},{148,224,137},{120,105,196},{159,159,159}};
for(i=0;i<16;i++)if(mode)colors[i]=rgb(c64[i][0],c64[i][1],c64[i][2]);else{
int lum=i==0?0:(i>=8?255:(i==7?225:165));
colors[i]=theme==0?rgb(lum*36/255,lum,lum*85/255):theme==1?rgb(lum,lum*181/255,lum*55/255):rgb(lum*230/255,lum*242/255,lum);
}
term_dirty(&term);dirty=1;
}
static int queueRaw(const UBYTE*b,int n){if(n<0||txlen+n>(int)sizeof(tx)){setStatus("Buffer invio pieno: attendi la rete.");return 0;}memcpy(tx+txlen,b,n);txlen+=n;return 1;}
static void sendChar(int c){UBYTE b[2];b[0]=c;b[1]=c;queueRaw(b,c==255?2:1);}
static void command(int cmd,int option){UBYTE b[3];b[0]=255;b[1]=cmd;b[2]=option;queueRaw(b,3);}
static void naws(void){UBYTE b[]={255,250,31,0,80,0,25,255,240};b[4]=mode?40:80;queueRaw(b,sizeof(b));}
static void negotiate(int cmd,int opt){int accept;
if(cmd==253){accept=opt==0||opt==3||opt==24||opt==31;
if(accept&&localOpt[opt]!=1){if(!localOpt[opt])command(251,opt);localOpt[opt]=1;if(opt==31)naws();}
else if(!accept)command(252,opt);
}else if(cmd==254){if(localOpt[opt]==1)command(252,opt);localOpt[opt]=0;}
else if(cmd==251){accept=opt==0||opt==1||opt==3;
if(accept&&remoteOpt[opt]!=1){if(!remoteOpt[opt])command(253,opt);remoteOpt[opt]=1;}else if(!accept)command(254,opt);
}else if(cmd==252){if(remoteOpt[opt]==1)command(254,opt);remoteOpt[opt]=0;}
}
static void subneg(void){if(sblen>=2&&sb[0]==24&&sb[1]==1&&localOpt[24]){
UBYTE start[]={255,250,24,0},end[]={255,240};char *name=mode?"C64":"ANSI";queueRaw(start,4);queueRaw((UBYTE*)name,strlen(name));queueRaw(end,2);
}}
static void incoming(UBYTE c){
if(telstate==0){if(c==255)telstate=1;else term_feed(&term,c);return;}
if(telstate==1){if(c==255){term_feed(&term,c);telstate=0;}else if(c>=251&&c<=254){telcmd=c;telstate=2;}else if(c==250){sblen=0;telstate=3;}else telstate=0;return;}
if(telstate==2){negotiate(telcmd,c);telstate=0;return;}
if(telstate==3){if(c==255)telstate=4;else if(sblen<(int)sizeof(sb))sb[sblen++]=c;return;}
if(telstate==4){if(c==240){subneg();telstate=0;}else{if(c==255&&sblen<(int)sizeof(sb))sb[sblen++]=255;telstate=3;}}
}
static void disconnect(char *message){if(sock>=0)CloseSocket(sock);sock=-1;connecting=0;txlen=0;setStatus(message);}
static void prefs(void){FILE*f=fopen("PROGDIR:RetroTerm.prefs","w");if(f){fprintf(f,"%s %s %d %d %d %d\n",host,portstr,mode,theme,localEcho,bellEnabled);fclose(f);}}
static void readFields(void){struct StringInfo *si=(struct StringInfo*)ghost->SpecialInfo;strncpy(host,si->Buffer,255);host[255]=0;si=(struct StringInfo*)gport->SpecialInfo;strncpy(portstr,si->Buffer,7);portstr[7]=0;}
static void connected(void){connecting=0;setStatus("CONNESSO | F1 Verde F2 Ambra F3 Bianco | F8 Eco locale | F7 Disconnetti");
command(251,24);localOpt[24]=2;command(251,31);localOpt[31]=2;naws();command(253,3);remoteOpt[3]=2;command(253,1);remoteOpt[1]=2;
if(mode){command(251,0);localOpt[0]=2;command(253,0);remoteOpt[0]=2;}
}
static void startConnect(void){struct hostent *he;struct sockaddr_in sa;LONG nb=1;int rc,p;
readFields();p=atoi(portstr);if(!host[0]||p<1||p>65535){setStatus("Inserisci host e porta validi (1-65535).");return;}
if(!SocketBase){setStatus("bsdsocket.library non disponibile: controlla la rete Amiga.");return;}
if(sock>=0)disconnect("Disconnesso.");
setStatus("Risoluzione DNS...");he=gethostbyname((UBYTE*)host);
if(!he||he->h_addrtype!=AF_INET||he->h_length!=4){setStatus("Host non trovato: controlla indirizzo e DNS.");return;}
memset(&sa,0,sizeof(sa));sa.sin_len=sizeof(sa);sa.sin_family=AF_INET;sa.sin_port=htons(p);memcpy(&sa.sin_addr,he->h_addr,4);
sock=socket(AF_INET,SOCK_STREAM,0);if(sock<0){setStatus("Impossibile aprire il socket.");return;}
if(IoctlSocket(sock,FIONBIO,(char*)&nb)<0){disconnect("Socket non bloccante non disponibile.");return;}
txlen=telstate=sblen=0;memset(localOpt,0,sizeof(localOpt));memset(remoteOpt,0,sizeof(remoteOpt));
term_init(&term,mode);palette();cursor=1;oldCursor=0;connectStart=ticks();prefs();
rc=connect(sock,(struct sockaddr*)&sa,sizeof(sa));
if(rc==0)connected();else if(Errno()==36||Errno()==35||Errno()==37){connecting=1;setStatus("Connessione in corso...");}
else{char b[100];sprintf(b,"Connessione fallita (socket %ld).",Errno());disconnect(b);}
}
static void changeMode(int m){if(mode==m)return;readFields();if(sock>=0)disconnect("Modo cambiato: premi Connetti.");mode=m;term_init(&term,mode);palette();
if(!strcmp(portstr,"6510")||!strcmp(portstr,"23")){strcpy(portstr,mode?"6510":"23");GT_SetGadgetAttrs(gport,win,0,GTST_String,(ULONG)portstr,TAG_DONE);}
GT_SetGadgetAttrs(gmode,win,0,GTCY_Active,mode,TAG_DONE);prefs();setStatus("Modo cambiato: premi Connetti. RetroCampus: 6510 PETSCII, 23 normale.");
}
static void paintCell(int n,int cursorOn){int cx=n%term.cols,cy=n/term.cols,xx,yy,rep=mode?2:1;struct Cell *c=&term.cell[n];
UBYTE *g=font+(mode?(term.charset*128+c->glyph):256+c->glyph)*8;
UWORD fg=colors[c->fg&15],bg=colors[c->bg&15];
for(yy=0;yy<16;yy++){
UWORD *dst=frame+(cy*16+yy)*FW+cx*8*rep;UBYTE bits=g[yy/2];
for(xx=0;xx<8*rep;xx++)dst[xx]=(bits&(128>>(xx/rep)))?fg:bg;
if(cursorOn&&(mode||yy>=14))for(xx=0;xx<8*rep;xx++)dst[xx]=dst[xx]==bg?fg:bg;
}
}
static void paint(void){int i,iw=win->Width-win->BorderLeft-win->BorderRight,ih=win->Height-win->BorderTop-win->BorderBottom;
int aw=iw-16,ah=ih-94,dw,dh,ox,oy,x,y,sy,prev=-1;struct RenderInfo ri;
if(iw<1||ih<100||iw>sc->Width||ih>sc->Height)return;
if(uiDirty){struct RastPort *rp=win->RPort;SetAPen(rp,0);RectFill(rp,win->BorderLeft+4,win->Height-win->BorderBottom-19,win->Width-win->BorderRight-4,win->Height-win->BorderBottom-2);
SetAPen(rp,1);SetBPen(rp,0);SetDrMd(rp,JAM1);Move(rp,win->BorderLeft+8,win->Height-win->BorderBottom-6);Text(rp,status,strlen(status)<(iw-16)/8?strlen(status):(iw-16)/8);uiDirty=0;}
if(!dirty)return;
if(aw!=bw||ah!=bh){struct BitMap *replacement=AllocBitMap(aw,ah,GetBitMapAttr(sc->RastPort.BitMap,BMA_DEPTH),BMF_CLEAR,sc->RastPort.BitMap);
if(!replacement){setStatus("Memoria grafica insufficiente.");return;}WaitBlit();if(bitmap)FreeBitMap(bitmap);bitmap=replacement;bw=aw;bh=ah;InitRastPort(&backrp);backrp.BitMap=bitmap;
}
term.dirty[oldCursor]=1;i=term.y*term.cols+term.x;term.dirty[i]=1;
for(i=0;i<term.cols*25;i++)if(term.dirty[i]){paintCell(i,cursor&&i==term.y*term.cols+term.x);term.dirty[i]=0;}
oldCursor=term.y*term.cols+term.x;
dw=aw;dh=aw*FH/FW;if(dh>ah){dh=ah;dw=ah*FW/FH;}ox=(aw-dw)/2;oy=(ah-dh)/2;
memset(scaled,0,(ULONG)aw*ah*2);for(x=0;x<dw;x++)xmap[x]=(ULONG)x*FW/dw;
for(y=0;y<dh;y++){
UWORD *dst=scaled+(ULONG)(oy+y)*aw+ox;sy=(ULONG)y*FH/dh;
if(sy==prev)memcpy(dst,dst-aw,dw*2);else{UWORD *src=frame+sy*FW;for(x=0;x<dw;x++)dst[x]=src[xmap[x]];}prev=sy;
}
ri.Memory=scaled;ri.BytesPerRow=aw*2;ri.pad=0;ri.RGBFormat=11;
__p96write(P96Base,&ri,0,0,&backrp,0,0,aw,ah);WaitBlit();LockLayer(0,win->WLayer);
if(iw==win->Width-win->BorderLeft-win->BorderRight&&ih==win->Height-win->BorderTop-win->BorderBottom){BltBitMapRastPort(bitmap,0,0,win->RPort,win->BorderLeft+8,win->BorderTop+68,aw,ah,0xc0);WaitBlit();dirty=0;}
UnlockLayer(win->WLayer);
}
static void rawkey(UWORD code,UWORD qual,APTR address){struct InputEvent ie;char buf[16];int n,i,c;
if(code&0x80)return;
if(code==0x44&&(qual&IEQUALIFIER_CONTROL)){togglePending=1;return;}
if(code>=0x50&&code<=0x52){theme=code-0x50;GT_SetGadgetAttrs(gtheme,win,0,GTCY_Active,theme,TAG_DONE);palette();prefs();return;}
if(code==0x53){changeMode(0);return;}if(code==0x54){changeMode(1);return;}
if(code==0x55){startConnect();return;}if(code==0x56){disconnect("Disconnesso.");return;}
if(code==0x57){localEcho=!localEcho;prefs();setStatus(localEcho?"Eco locale attivo (F8 per disattivare).":"Eco locale disattivato.");return;}
if(code==0x58){if(bellReady&&bellEnabled)bell_play(ticks());setStatus(bellEnabled?"Beep discreto: prova suono (F9). F10 attiva/disattiva.":"Beep disattivato: F10 per attivare.");return;}
if(code==0x59){bellEnabled=!bellEnabled;prefs();setStatus(bellEnabled?"Beep terminale attivo, volume basso. F9 prova / F10 silenzia.":"Beep terminale disattivato. F10 per riattivare.");return;}
if(sock<0||connecting)return;
if(code>=0x4c&&code<=0x4f){
if(mode){static UBYTE arrows[]={145,17,29,157};sendChar(arrows[code-0x4c]);}
else{static char arrows[]="ABCD";sendChar(27);sendChar('[');sendChar(arrows[code-0x4c]);}return;
}
memset(&ie,0,sizeof(ie));ie.ie_Class=IECLASS_RAWKEY;ie.ie_Code=code;ie.ie_Qualifier=qual;ie.ie_EventAddress=address;
n=MapRawKey(&ie,buf,sizeof(buf),0);
for(i=0;i<n;i++){
c=(UBYTE)buf[i];if(mode){if(c>='a'&&c<='z')c-=32;else if(c>='A'&&c<='Z')c+=128;else if(c==8||c==127)c=20;else if(c==27)c=3;}
sendChar(c);if(!mode&&c==13)sendChar(10);
if(localEcho&&remoteOpt[1]!=1){term_feed(&term,c);if(!mode&&c==13)term_feed(&term,10);dirty=1;}
}
}
static struct Gadget *addg(ULONG kind,struct Gadget *prev,int id,int x,int y,int width,char*label,ULONG tag,ULONG value){struct NewGadget ng;memset(&ng,0,sizeof(ng));ng.ng_LeftEdge=win->BorderLeft+x;ng.ng_TopEdge=win->BorderTop+y;ng.ng_Width=width;ng.ng_Height=20;ng.ng_TextAttr=&gadgetFont;ng.ng_GadgetText=label;ng.ng_GadgetID=id;ng.ng_Flags=kind==BUTTON_KIND?PLACETEXT_IN:PLACETEXT_LEFT;ng.ng_VisualInfo=vi;return CreateGadget(kind,prev,&ng,tag,value,GTST_MaxChars,kind==STRING_KIND?255:0,TAG_DONE);}
static int openView(void){struct Gadget *g;
win=OpenWindowTags(0,WA_PubScreen,(ULONG)sc,WA_Left,fullscreen?0:savedLeft,WA_Top,fullscreen?0:savedTop,
WA_Width,fullscreen?sc->Width:savedWidth,WA_Height,fullscreen?sc->Height:savedHeight,
WA_Title,(ULONG)"RetroTerm | Ctrl+Invio: tutto schermo",WA_Borderless,fullscreen,WA_CloseGadget,!fullscreen,WA_DragBar,!fullscreen,WA_DepthGadget,!fullscreen,WA_Activate,TRUE,WA_SizeGadget,!fullscreen,WA_SizeBBottom,!fullscreen,
WA_MinWidth,710,WA_MinHeight,350,WA_MaxWidth,sc->Width,WA_MaxHeight,sc->Height,WA_SimpleRefresh,TRUE,
WA_IDCMP,IDCMP_CLOSEWINDOW|IDCMP_RAWKEY|IDCMP_REFRESHWINDOW|IDCMP_NEWSIZE|STRINGIDCMP|BUTTONIDCMP|CYCLEIDCMP,TAG_DONE);
if(!win)return 0;
g=CreateContext(&glist);if(!g)return 0;
ghost=g=addg(STRING_KIND,g,1,58,8,255,"BBS",GTST_String,(ULONG)host);if(!g)return 0;
gport=g=addg(STRING_KIND,g,2,365,8,65,"Porta",GTST_String,(ULONG)portstr);if(!g)return 0;
g=addg(BUTTON_KIND,g,3,445,8,100,"Connetti",TAG_DONE,0);if(!g)return 0;
g=addg(BUTTON_KIND,g,4,557,8,125,"Disconnetti",TAG_DONE,0);if(!g)return 0;
gmode=g=addg(CYCLE_KIND,g,5,58,37,220,"Modo",GTCY_Labels,(ULONG)modes);if(!g)return 0;
gtheme=g=addg(CYCLE_KIND,g,6,365,37,180,"Fosfori",GTCY_Labels,(ULONG)themes);if(!g)return 0;
g=addg(BUTTON_KIND,g,7,557,37,125,"Pulisci",TAG_DONE,0);if(!g)return 0;
GT_SetGadgetAttrs(gmode,0,0,GTCY_Active,mode,TAG_DONE);GT_SetGadgetAttrs(gtheme,0,0,GTCY_Active,theme,TAG_DONE);
AddGList(win,glist,-1,-1,0);RefreshGList(glist,win,0,-1);GT_RefreshWindow(win,0);dirty=uiDirty=1;term_dirty(&term);return 1;
}
static void closeView(void){if(win){if(glist)RemoveGList(win,glist,-1);CloseWindow(win);win=0;}if(glist)FreeGadgets(glist);glist=0;}
int main(void){struct Gadget *g;struct IntuiMessage *m;FILE *f;ULONG cls,mask,now;UWORD code,qual;APTR address;int i,n;
IntuitionBase=(struct IntuitionBase*)OpenLibrary("intuition.library",39);GfxBase=(struct GfxBase*)OpenLibrary("graphics.library",40);GadToolsBase=OpenLibrary("gadtools.library",39);KeymapBase=OpenLibrary("keymap.library",37);LayersBase=OpenLibrary("layers.library",39);SocketBase=OpenLibrary("bsdsocket.library",4);P96Base=OpenLibrary("Picasso96API.library",2);
if(!IntuitionBase||!GfxBase||!GadToolsBase||!KeymapBase||!LayersBase||!P96Base)goto end;
sc=LockPubScreen(0);if(!sc)goto end;if(GetBitMapAttr(sc->RastPort.BitMap,BMA_DEPTH)<15)goto end;
frame=malloc(FW*FH*2);scaled=malloc((ULONG)sc->Width*sc->Height*2);xmap=malloc(sc->Width*2);if(!frame||!scaled||!xmap)goto end;
f=fopen("PROGDIR:font.bin","rb");if(!f)goto end;n=fread(font,1,sizeof(font),f);fclose(f);if(n!=sizeof(font))goto end;
f=fopen("PROGDIR:RetroTerm.prefs","r");if(f){fscanf(f,"%255s %7s %d %d %d %d",host,portstr,&mode,&theme,&localEcho,&bellEnabled);fclose(f);}mode=mode?1:0;if(theme<0||theme>2)theme=1;
bellReady=bell_init();
term_init(&term,mode);palette();
vi=GetVisualInfo(sc,TAG_DONE);if(!vi)goto end;
savedWidth=760+sc->WBorLeft+sc->WBorRight;savedHeight=500+sc->WBorTop+sc->Font->ta_YSize+1+sc->WBorBottom;
if(!openView())goto end;blinkTick=ticks();
while(!done){
while((m=GT_GetIMsg(win->UserPort))!=0){cls=m->Class;code=m->Code;qual=m->Qualifier;g=(struct Gadget*)m->IAddress;address=(cls==IDCMP_RAWKEY&&m->IAddress)?*((APTR*)m->IAddress):0;
GT_ReplyIMsg(m);
if(cls==IDCMP_CLOSEWINDOW)done=1;
else if(cls==IDCMP_RAWKEY)rawkey(code,qual,address);
else if(cls==IDCMP_REFRESHWINDOW){GT_BeginRefresh(win);GT_EndRefresh(win,TRUE);term_dirty(&term);dirty=uiDirty=1;}
else if(cls==IDCMP_NEWSIZE){dirty=uiDirty=1;}
else if(cls==IDCMP_GADGETUP&&g){switch(g->GadgetID){case 1:case 2:readFields();break;case 3:startConnect();break;case 4:disconnect("Disconnesso.");break;case 5:changeMode(code);break;case 6:theme=code;palette();prefs();break;case 7:term_clear(&term);dirty=1;break;}}
}
if(done)break;
if(togglePending){togglePending=0;readFields();if(!fullscreen){savedLeft=win->LeftEdge;savedTop=win->TopEdge;savedWidth=win->Width;savedHeight=win->Height;}
closeView();fullscreen=!fullscreen;if(!openView()){closeView();fullscreen=!fullscreen;if(!openView()){done=1;break;}}
setStatus(fullscreen?"Tutto schermo | Ctrl+Invio torna in finestra":"Finestra | Ctrl+Invio tutto schermo");
}
bell_poll();
now=ticks();if(term.bell){term.bell=0;if(bellEnabled&&bellReady)bell_play(now);}
if(now-blinkTick>=25){blinkTick=now;cursor=!cursor;dirty=1;}
paint();
mask=1UL<<win->UserPort->mp_SigBit;
if(sock>=0){fd_set rd,wr;struct timeval timeout;LONG e=0,elen=sizeof(e);
memset(&rd,0,sizeof(rd));memset(&wr,0,sizeof(wr));FD_SET(sock,&rd);if(connecting||txlen)FD_SET(sock,&wr);
timeout.tv_sec=0;timeout.tv_usec=100000;
n=WaitSelect(sock+1,&rd,&wr,0,&timeout,&mask);
if(n<0){disconnect("Errore della connessione.");continue;}
if(connecting){
if(FD_ISSET(sock,&wr)||FD_ISSET(sock,&rd)){
if(getsockopt(sock,SOL_SOCKET,SO_ERROR,&e,&elen)<0||e){disconnect("Connessione rifiutata o host non raggiungibile.");continue;}connected();
}else if(now-connectStart>500){disconnect("Tempo di connessione scaduto.");continue;}
}
if(!connecting&&FD_ISSET(sock,&wr)&&txlen){n=send(sock,tx,txlen,0);if(n>0){txlen-=n;memmove(tx,tx+n,txlen);}else if(n<0&&Errno()!=35){disconnect("Errore durante l'invio.");continue;}}
if(!connecting&&FD_ISSET(sock,&rd)){n=recv(sock,rx,sizeof(rx),0);if(n>0){term.dirty[term.y*term.cols+term.x]=1;for(i=0;i<n;i++)incoming(rx[i]);dirty=1;}else if(!n){disconnect("Connessione chiusa dalla BBS.");}else if(Errno()!=35)disconnect("Errore di ricezione.");}
}else Delay(5);
}
readFields();prefs();
end:
bell_exit();
if(sock>=0)CloseSocket(sock);if(GfxBase){WaitBlit();if(bitmap)FreeBitMap(bitmap);}
closeView();if(vi)FreeVisualInfo(vi);if(sc)UnlockPubScreen(0,sc);
free(frame);free(scaled);free(xmap);
if(P96Base)CloseLibrary(P96Base);if(SocketBase)CloseLibrary(SocketBase);if(LayersBase)CloseLibrary(LayersBase);if(KeymapBase)CloseLibrary(KeymapBase);if(GadToolsBase)CloseLibrary(GadToolsBase);if(GfxBase)CloseLibrary((struct Library*)GfxBase);if(IntuitionBase)CloseLibrary((struct Library*)IntuitionBase);return 0;
}
+94
View File
@@ -0,0 +1,94 @@
#include "terminal.h"
#include <string.h>
static int clamp(int x,int lo,int hi){return x<lo?lo:x>hi?hi:x;}
void term_dirty(struct Terminal*t){memset(t->dirty,1,sizeof(t->dirty));}
static struct Cell blank(struct Terminal*t){struct Cell c;c.glyph=32;c.fg=t->fg;c.bg=t->bg;return c;}
static void erase(struct Terminal*t,int first,int last){int i;struct Cell c=blank(t);for(i=first;i<=last;i++){t->cell[i]=c;t->dirty[i]=1;}}
void term_clear(struct Terminal*t){erase(t,0,t->cols*TC_ROWS-1);t->x=t->y=t->pendingwrap=0;}
void term_init(struct Terminal*t,int petscii){memset(t,0,sizeof(*t));t->petscii=petscii;t->cols=petscii?40:80;t->fg=petscii?14:7;t->wrap=1;t->scrollbottom=24;term_clear(t);}
static void scroll(struct Terminal*t){int c=t->cols,top=t->scrolltop,bot=t->scrollbottom;memmove(t->cell+top*c,t->cell+(top+1)*c,(bot-top)*c*sizeof(struct Cell));erase(t,bot*c,(bot+1)*c-1);term_dirty(t);}
static void down(struct Terminal*t){if(t->y==t->scrollbottom)scroll(t);else if(t->y<24)t->y++;}
static void put(struct Terminal*t,int g){int i;if(t->pendingwrap){t->x=0;down(t);t->pendingwrap=0;}i=t->y*t->cols+t->x;t->cell[i].glyph=g;t->cell[i].fg=t->reverse?t->bg:t->fg;t->cell[i].bg=t->reverse?t->fg:t->bg;t->dirty[i]=1;if(t->x<t->cols-1)t->x++;else if(t->petscii){t->x=0;down(t);}else t->pendingwrap=t->wrap;}
static void petscii(struct Terminal*t,unsigned char c){int i,g;static const unsigned char cc[16]={144,5,28,159,156,30,31,158,129,149,150,151,152,153,154,155};
for(i=0;i<16;i++)if(c==cc[i]){t->fg=i;return;}
switch(c){
case 13:t->x=0;t->reverse=0;down(t);return;
case 141:t->x=0;down(t);return;
case 17:down(t);return;case 145:if(t->y)t->y--;return;
case 29:if(++t->x>=40){t->x=0;down(t);}return;
case 157:if(t->x)t->x--;else if(t->y){t->y--;t->x=39;}return;
case 19:t->x=t->y=0;return;case 147:term_clear(t);return;
case 18:t->reverse=1;return;case 146:t->reverse=0;return;
case 14:t->charset=1;term_dirty(t);return;case 142:t->charset=0;term_dirty(t);return;
case 20:if(t->x)t->x--;else if(t->y){t->y--;t->x=39;}i=t->y*40+t->x;memmove(t->cell+i,t->cell+i+1,(39-t->x)*sizeof(struct Cell));erase(t,t->y*40+39,t->y*40+39);term_dirty(t);return;
case 148:i=t->y*40+t->x;memmove(t->cell+i+1,t->cell+i,(39-t->x)*sizeof(struct Cell));erase(t,i,i);term_dirty(t);return;
case 7:t->bell=1;return;
case 8:case 9:case 10:case 11:return;
}
if(c<32||(c>=128&&c<160))return;
if(c<64)g=c;else if(c<96)g=c-64;else if(c<128)g=c-32;else if(c<192)g=c-64;else if(c<255)g=c-128;else g=94;
put(t,g);
}
static int param(struct Terminal*t,int n,int def){return n>=t->argc||!t->arg[n]?def:t->arg[n];}
static void csi(struct Terminal*t,int ch){int n=param(t,0,1),i,a,start=t->y*t->cols+t->x,total=t->cols*25;
switch(ch){
case 'A':t->y=clamp(t->y-n,0,24);break;case 'B':t->y=clamp(t->y+n,0,24);break;
case 'C':t->x=clamp(t->x+n,0,t->cols-1);break;case 'D':t->x=clamp(t->x-n,0,t->cols-1);break;
case 'E':t->x=0;t->y=clamp(t->y+n,0,24);break;case 'F':t->x=0;t->y=clamp(t->y-n,0,24);break;
case 'G':t->x=clamp(n-1,0,t->cols-1);break;case 'd':t->y=clamp(n-1,0,24);break;
case 'H':case 'f':t->y=clamp(n-1,0,24);t->x=clamp(param(t,1,1)-1,0,t->cols-1);break;
case 'J':a=t->arg[0];if(a==2||a==3)erase(t,0,total-1);else if(a==1)erase(t,0,start);else erase(t,start,total-1);break;
case 'K':a=t->arg[0];if(a==2)erase(t,t->y*t->cols,(t->y+1)*t->cols-1);else if(a==1)erase(t,t->y*t->cols,start);else erase(t,start,(t->y+1)*t->cols-1);break;
case 's':t->sx=t->x;t->sy=t->y;break;case 'u':t->x=t->sx;t->y=t->sy;break;
case 'r':a=param(t,0,1)-1;i=param(t,1,25)-1;if(a>=0&&i<25&&a<i){t->scrolltop=a;t->scrollbottom=i;t->x=t->y=0;}break;
case 'h':case 'l':if(t->privatecsi&&t->arg[0]==7)t->wrap=ch=='h';break;
case 'm':for(i=0;i<t->argc;i++){
a=t->arg[i];if(!a){t->fg=7;t->bg=t->reverse=t->bold=0;}
else if(a==1)t->bold=1;else if(a==22)t->bold=0;else if(a==7)t->reverse=1;else if(a==27)t->reverse=0;
else if(a>=30&&a<=37)t->fg=a-30+(t->bold?8:0);else if(a>=40&&a<=47)t->bg=a-40;
else if(a>=90&&a<=97)t->fg=a-90+8;else if(a>=100&&a<=107)t->bg=a-100+8;
else if(a==39)t->fg=7;else if(a==49)t->bg=0;
else if(a==38||a==48){/* Consume unsupported extended colour parameters safely. */if(i+1<t->argc){if(t->arg[i+1]==5)i+=2;else if(t->arg[i+1]==2)i+=4;}}
}break;
}
t->pendingwrap=0;
}
static void ansi(struct Terminal*t,unsigned char c){
if(t->petscii){petscii(t,c);return;}
if(t->esc==1){t->esc=0;if(c=='['){t->esc=2;t->argc=1;t->privatecsi=0;memset(t->arg,0,sizeof(t->arg));}
else if(c==']')t->esc=3;else if(c=='('||c==')')t->esc=5;else if(c=='7'){t->sx=t->x;t->sy=t->y;}
else if(c=='8'){t->x=t->sx;t->y=t->sy;}else if(c=='c')term_init(t,0);else if(c=='D')down(t);return;}
if(t->esc==2){if(c=='?'){t->privatecsi=1;return;}if(c>='0'&&c<='9'){int *a=&t->arg[t->argc-1];if(*a<1000)*a=*a*10+c-'0';return;}if(c==';'){if(t->argc<16)t->argc++;return;}if(c>=0x40&&c<=0x7e){csi(t,c);t->esc=0;}else if(c==27)t->esc=1;return;}
if(t->esc==3){if(c==7)t->esc=0;else if(c==27)t->esc=4;return;}
if(t->esc==4){t->esc=c=='\\'?0:3;return;}if(t->esc==5){t->esc=0;return;}
if(c==27){t->esc=1;return;}if(c==13){t->x=0;t->pendingwrap=0;return;}if(c==10){t->pendingwrap=0;down(t);return;}
if(c==7){t->bell=1;return;}if(c==8||c==127){if(t->x)t->x--;t->pendingwrap=0;return;}if(c==9){t->x=clamp((t->x+8)&~7,0,t->cols-1);return;}if(c<32)return;
put(t,c);
}
static const unsigned short cp437[128]={199,252,233,226,228,224,229,231,234,235,232,239,238,236,196,197,201,230,198,244,246,242,251,249,255,214,220,162,163,165,8359,402,225,237,243,250,241,209,170,186,191,8976,172,189,188,161,171,187,9617,9618,9619,9474,9508,9569,9570,9558,9557,9571,9553,9559,9565,9564,9563,9488,9492,9524,9516,9500,9472,9532,9566,9567,9562,9556,9577,9574,9568,9552,9580,9575,9576,9572,9573,9561,9560,9554,9555,9579,9578,9496,9484,9608,9604,9612,9616,9600,945,223,915,960,931,963,181,964,934,920,937,948,8734,966,949,8745,8801,177,8805,8804,8992,8993,247,8776,176,8729,183,8730,8319,178,9632,160};
static void unicodeChar(struct Terminal*t,unsigned long u){int i;
if(u>=0x2580&&u<=0x259f){put(t,u-0x2580);return;}
for(i=0;i<128;i++)if(cp437[i]==u){put(t,i+128);return;}
if(u==0x2018||u==0x2019)put(t,39);else if(u==0x201c||u==0x201d)put(t,34);
else if(u==0x2013||u==0x2014)put(t,'-');else if(u==0x2026){put(t,'.');put(t,'.');put(t,'.');}
else if(u==0xa0)put(t,32);else put(t,'?');
}
void term_feed(struct Terminal*t,unsigned char c){int i;
if(t->petscii){petscii(t,c);return;}
again:
if(t->utfNeed){
if((c&0xc0)==0x80){t->utfBytes[t->utfHave++]=c;t->utfCode=(t->utfCode<<6)|(c&63);
if(--t->utfNeed==0){unsigned long u=t->utfCode;
if((t->utfHave==2&&u<128)||(t->utfHave==3&&u<2048)||(t->utfHave==4&&u<65536)||u>0x10ffff||(u>=0xd800&&u<=0xdfff)){
for(i=0;i<t->utfHave;i++)ansi(t,t->utfBytes[i]);
}else unicodeChar(t,u);
t->utfHave=0;
}return;
}
t->utfNeed=0;for(i=0;i<t->utfHave;i++)ansi(t,t->utfBytes[i]);t->utfHave=0;goto again;
}
if(!t->esc&&c>=0xc2&&c<=0xf4){t->utfNeed=c<0xe0?1:c<0xf0?2:3;t->utfHave=1;t->utfBytes[0]=c;t->utfCode=c&((1<<(6-t->utfNeed))-1);return;}
ansi(t,c);
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef RETROTERM_CORE_H
#define RETROTERM_CORE_H
#define TC_ROWS 25
#define TC_MAXCOLS 80
struct Cell {unsigned char glyph,fg,bg;};
struct Terminal {
struct Cell cell[TC_MAXCOLS*TC_ROWS];unsigned char dirty[TC_MAXCOLS*TC_ROWS];
int cols,x,y,sx,sy,fg,bg,reverse,charset,petscii,wrap,scrolltop,scrollbottom;
int utfNeed,utfHave;unsigned long utfCode;unsigned char utfBytes[4];
int bell;
int esc,argc,arg[16],privatecsi,bold,pendingwrap;
};
void term_init(struct Terminal*,int);
void term_clear(struct Terminal*);
void term_dirty(struct Terminal*);
void term_feed(struct Terminal*,unsigned char);
#endif
+14
View File
@@ -0,0 +1,14 @@
from pathlib import Path
b=(Path(__file__).parent/'assets/font.bin').read_bytes()
assert len(b)==4096
for bank in range(2):
o=bank*1024
def glyph(n):return b[o+n*8:o+(n+1)*8]
assert glyph(0x61)==bytes([240]*8), 'left half block'
assert glyph(0x62)==bytes([0]*4+[255]*4), 'lower half block'
assert glyph(0x6c)==bytes([0]*4+[15]*4), 'lower right quarter'
assert glyph(0x7b)==bytes([0]*4+[240]*4), 'lower left quarter'
assert glyph(0x7c)==bytes([15]*4+[0]*4), 'upper right quarter'
assert glyph(0x7e)==bytes([240]*4+[0]*4), 'upper left quarter'
assert glyph(0x40)==bytes([0,0,0,255,255,0,0,0]), 'horizontal join'
print('14 PETSCII alignment checks passed.')
+45
View File
@@ -0,0 +1,45 @@
Creative Commons Legal Code
CC0 1.0 Universal
Official translations of this legal tool are available
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
+34
View File
@@ -0,0 +1,34 @@
> [!IMPORTANT]
> This repository has moved to https://codeberg.org/Dmian/font-bescii
> [!WARNING]
> This repository is now archived and no longer mantained on GitHub.
# BESCII pixel font
An 8x8 pixel font based on PETSCII for [BASIC Engine](http://basicengine.org/).
![All characters](images/bescii-chars.png?raw=true)
This font was inspired by the Commodore 64 font (PETSCII), but with some modifications to correct a few flaws, and a unique idiosyncracy that gives it a special flavour. You can read a _post mortem_ that details how it was created in [my blog](https://damianvila.com/blog/20240515-designing-the-bescii-font.html).
Pixel art is included in the Private Use Are, to allow for easy game creation.
A glyphs reference chart is included in the **demo** folder.
## Features
- Wide strokes, suitable for low resolution screens.
- Improved x-height in lower case letters, for better readability.
- All Western European languages supported.
- Support for Greek and Cyrillic.
- Full kana support (hiragana and katakana).
- PETSCII symbols + some Amstrad CPC 464.
- PETSCII characters mapped using [Direct PETSCII](https://style64.org/petscii/) mapping.
- Pixel art for games.
- TTF, WOFF and WOFF2 files provided.
## License
This project is licensed under a [CC0 1.0 Universal licence](https://creativecommons.org/publicdomain/zero/1.0/).
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
This work is dedicated to the public domain under CC0 1.0 Universal.
https://creativecommons.org/publicdomain/zero/1.0/
+21
View File
@@ -0,0 +1,21 @@
# C64 Font
TrueType and OpenType fonts containing the Commodore 64 character set.
## Files
- `c64.ttf` - TrueType format
- `c64.otf` - OpenType format (CFF outlines)
## Unicode Coverage
- Basic Latin (A-Z, 0-9, punctuation)
- PETSCII graphics mapped to **Symbols for Legacy Computing** (U+1FB00-U+1FBFF)
- Box drawing characters (U+2500 range)
- Block elements (U+2580 range)
- Card suits, arrows, pi
- Reverse video characters in Private Use Area (U+E000-U+E0FF)
## License
Public domain under [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/).
BIN
View File
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
-cc=vbccm68k -quiet -hunkdebug %s -o= %s %s -O=%ld -I"@TARGET@/include" -I"@TARGET@/ndk/include_h" -I"@TARGET@/netinclude"
-ccv=vbccm68k -hunkdebug %s -o= %s %s -O=%ld -I"@TARGET@/include" -I"@TARGET@/ndk/include_h" -I"@TARGET@/netinclude"
-as=vasmm68k_mot -quiet -Fhunk -phxass -opt-fconst -nowarn=62 %s -o %s
-asv=vasmm68k_mot -Fhunk -phxass -opt-fconst -nowarn=62 %s -o %s
-ld=vlink -bamigahunk -x -Bstatic -Cvbcc -nostdlib "@TARGET@/lib/startup.o" %s %s -L"@TARGET@/lib" -lvc -o %s
-l2=vlink -bamigahunk -x -Bstatic -Cvbcc -nostdlib %s %s -L"@TARGET@/lib" -o %s
-ldv=vlink -bamigahunk -t -x -Bstatic -Cvbcc -nostdlib "@TARGET@/lib/startup.o" %s %s -L"@TARGET@/lib" -lvc -o %s
-l2v=vlink -bamigahunk -t -x -Bstatic -Cvbcc -nostdlib %s %s -L"@TARGET@/lib" -o %s
-ldnodb=-s -Rshort
-ul=-l%s
-cf=-F%s
-ml=500