Merge remote-tracking branch 'origin/main' into claude/project-thread-u025co

This commit is contained in:
Claude committed 2026-11-12 12:45:28 +00:00
commit 2a7c4492d1
25 files changed
+2729 -26

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ behave the same.
- **Phone**: voice calls through the sound card (dial, answer, keypad), and an
answering machine that takes messages on this computer when turned on (off by default)
- **Terminal**: the AT console, and the modem's own setup screens (AT!CF, AT!CT)
- **Remote**: log in to a server by SSH, Telnet or rlogin, in a terminal of its own
- **Settings**: every modem setting as a native control, from AT!M
- **Call Stats**: the last call's rate, modulation, error control and line figures (AT#UD, ATI11)
- **Line settings**: a SIP account, a USB modem, or a modem that already runs
+1
View File
@@ -21,6 +21,7 @@ set(DMODEMCTL_SOURCES
src/vt_vt52.c
src/daemon.c
src/voice.c
src/net.c
src/util.c)
if(DMODEMCTL_SHARED)
+38
View File
@@ -27,6 +27,8 @@
* PC's ANSI-BBS, the Commodores', the Ataris', Viewdata, the Minitel
* and the Tektronix 4014.
* - dmc_daemon_*: starting dmodemd and reading what it prints.
* - dmc_net: a remote login's protocol (Telnet, rlogin) on a TCP
* connection the app makes, for the Remote page.
* - dmc_voice_*: voice calls on the session (V.253's voice mode: the
* call's audio both ways, 8 kHz), the answering machine that takes
* a message, and WAV files for greetings and messages.
@@ -545,6 +547,42 @@ DMC_API int dmc_daemon_ready(const char *line, char *buf, int max);
/* a line that is an error of dmodemd's ("error: ..."): 1 */
DMC_API int dmc_daemon_error(const char *line);
/*
* Remote logins
*
* Telnet and rlogin on a TCP connection the app makes (SSH is the
* system's ssh in a pty, so it needs nothing here). Like the session it
* does no I/O: hand it what the socket read, write what dmc_net_output()
* gives, show what dmc_net_screen() gives.
*/
typedef struct dmc_net dmc_net;
enum { DMC_NET_TELNET = 1, DMC_NET_RLOGIN, DMC_NET_SSH };
/* the protocol's port (23, 513, 22) and its name ("Telnet") */
DMC_API int dmc_net_default_port(int proto);
DMC_API const char *dmc_net_name(int proto);
/* a login by Telnet or rlogin: user is rlogin's (Telnet's may be ""),
term the terminal type the server is told, the screen's size */
DMC_API dmc_net *dmc_net_new(int proto, const char *user, const char *term,
int cols, int rows);
DMC_API void dmc_net_free(dmc_net *n);
/* the connection made: rlogin's handshake, Telnet's first offers */
DMC_API void dmc_net_connected(dmc_net *n);
/* bytes the socket read */
DMC_API void dmc_net_feed(dmc_net *n, const char *data, int len);
/* an urgent (out-of-band) byte the socket read: rlogin's control byte */
DMC_API void dmc_net_urgent(dmc_net *n, int byte);
/* the bytes for the terminal: how many */
DMC_API int dmc_net_screen(dmc_net *n, char *buf, int max);
/* bytes typed */
DMC_API void dmc_net_type(dmc_net *n, const char *data, int len);
/* the bytes to write to the socket: how many */
DMC_API int dmc_net_output(dmc_net *n, char *buf, int max);
/* the screen's new size, told to the server */
DMC_API void dmc_net_resize(dmc_net *n, int cols, int rows);
#ifdef __cplusplus
}
#endif
+349
View File
@@ -0,0 +1,349 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* net.c - a remote login's protocol over a TCP connection the app makes:
* Telnet (RFC 854) and rlogin (RFC 1282). Like the session, it
* does no I/O: the app hands it what the socket read
* (dmc_net_feed), writes what dmc_net_output gives, shows what
* dmc_net_screen gives and passes on what is typed (dmc_net_type).
*
* Telnet: the server's options answered (BINARY, ECHO and
* SUPPRESS-GO-AHEAD taken; TERMINAL-TYPE and NAWS offered; the rest
* refused), each option answered once per change so that no two ends
* loop; IAC doubled both ways; a CR typed sent as CR NUL outside binary
* mode; the window's size sent (NAWS) as it changes.
*
* rlogin: the handshake (NUL, the user twice, "term/speed"), the
* server's NUL that answers it taken off the stream, and the window's
* size sent ("\377\377ss" and four 16-bit numbers) once the server has
* asked for it with the urgent byte 0x80.
*/
#include <stdlib.h>
#include <string.h>
#include "dmodemctl.h"
#include "util.h"
enum {
IAC = 255, DONT = 254, DO = 253, WONT = 252, WILL = 251, SB = 250,
SE = 240,
O_BINARY = 0, O_ECHO = 1, O_SGA = 3, O_TTYPE = 24, O_NAWS = 31
};
/* where the Telnet reader is */
enum { T_DATA, T_IAC, T_OPT, T_SB, T_SB_IAC };
struct dmc_net {
int proto;
char *user, *term;
int cols, rows;
dmc_buf screen, out;
/* Telnet */
int st, verb, last_cr;
unsigned char remote[256], local[256];
dmc_buf sb;
/* Telnet: the server asked for our size (DO NAWS) */
int naws;
/* rlogin: the server's NUL seen; it asked for the window's size */
int ready, want_size;
};
DMC_API int dmc_net_default_port(int proto)
{
switch (proto) {
case DMC_NET_TELNET:
return 23;
case DMC_NET_RLOGIN:
return 513;
case DMC_NET_SSH:
return 22;
}
return 0;
}
DMC_API const char *dmc_net_name(int proto)
{
switch (proto) {
case DMC_NET_TELNET:
return "Telnet";
case DMC_NET_RLOGIN:
return "rlogin";
case DMC_NET_SSH:
return "SSH";
}
return "";
}
DMC_API dmc_net *dmc_net_new(int proto, const char *user, const char *term,
int cols, int rows)
{
dmc_net *n = calloc(1, sizeof(*n));
if (!n)
return NULL;
n->proto = proto;
n->user = dup_str(user ? user : "");
n->term = dup_str(term && *term ? term : "xterm");
n->cols = cols;
n->rows = rows;
return n;
}
DMC_API void dmc_net_free(dmc_net *n)
{
if (!n)
return;
free(n->user);
free(n->term);
buf_free(&n->screen);
buf_free(&n->out);
buf_free(&n->sb);
free(n);
}
static void put(dmc_net *n, int a, int b, int c)
{
char v[3];
v[0] = (char)a;
v[1] = (char)b;
v[2] = (char)c;
buf_add(&n->out, v, 3);
}
/* a 16-bit number, big-endian; for Telnet an 0xff in it doubled */
static void put16(dmc_net *n, int v, int telnet)
{
int i;
if (v < 0)
v = 0;
if (v > 65535)
v = 65535;
for (i = 0; i < 2; i++) {
int b = i ? v & 0xff : v >> 8;
buf_addc(&n->out, (char)b);
if (telnet && b == IAC)
buf_addc(&n->out, (char)IAC);
}
}
static void send_naws(dmc_net *n)
{
put(n, IAC, SB, O_NAWS);
put16(n, n->cols, 1);
put16(n, n->rows, 1);
buf_addc(&n->out, (char)IAC);
buf_addc(&n->out, (char)SE);
}
static void send_window(dmc_net *n)
{
buf_add(&n->out, "\377\377ss", 4);
put16(n, n->rows, 0);
put16(n, n->cols, 0);
put16(n, n->cols * 8, 0);
put16(n, n->rows * 16, 0);
}
DMC_API void dmc_net_connected(dmc_net *n)
{
if (n->proto == DMC_NET_RLOGIN) {
/* NUL, the local and the remote user, "term/speed" */
buf_addc(&n->out, '\0');
buf_add(&n->out, n->user, (int)strlen(n->user) + 1);
buf_add(&n->out, n->user, (int)strlen(n->user) + 1);
buf_adds(&n->out, n->term);
buf_add(&n->out, "/38400", 7);
} else if (n->proto == DMC_NET_TELNET) {
/* what a Telnet client offers at once: its type and size,
and no go-aheads; marked as asked, so that the server's
yes is not answered again */
put(n, IAC, WILL, O_TTYPE);
put(n, IAC, WILL, O_NAWS);
put(n, IAC, DO, O_SGA);
n->local[O_TTYPE] = n->local[O_NAWS] = 1;
n->remote[O_SGA] = 1;
}
}
/* the server's WILL, WONT, DO or DONT */
static void option(dmc_net *n, int verb, int opt)
{
int ok;
switch (verb) {
case WILL:
ok = opt == O_BINARY || opt == O_ECHO || opt == O_SGA;
if (ok != n->remote[opt] || !ok) {
n->remote[opt] = (unsigned char)ok;
put(n, IAC, ok ? DO : DONT, opt);
}
break;
case WONT:
if (n->remote[opt]) {
n->remote[opt] = 0;
put(n, IAC, DONT, opt);
}
break;
case DO:
ok = opt == O_BINARY || opt == O_SGA || opt == O_TTYPE ||
opt == O_NAWS;
if (ok != n->local[opt] || !ok) {
n->local[opt] = (unsigned char)ok;
put(n, IAC, ok ? WILL : WONT, opt);
}
/* (its size, each time it asks) */
if (ok && opt == O_NAWS) {
n->naws = 1;
send_naws(n);
}
break;
case DONT:
if (opt == O_NAWS)
n->naws = 0;
if (n->local[opt]) {
n->local[opt] = 0;
put(n, IAC, WONT, opt);
}
break;
}
}
/* the server's subnegotiation: TERMINAL-TYPE SEND answered with IS */
static void subneg(dmc_net *n)
{
const unsigned char *p = (const unsigned char *)n->sb.p;
if (n->sb.n >= 2 && p[0] == O_TTYPE && p[1] == 1) {
put(n, IAC, SB, O_TTYPE);
buf_addc(&n->out, '\0');
buf_adds(&n->out, n->term);
buf_addc(&n->out, (char)IAC);
buf_addc(&n->out, (char)SE);
}
}
static void feed_telnet(dmc_net *n, const unsigned char *p, int len)
{
int i;
for (i = 0; i < len; i++) {
int b = p[i];
switch (n->st) {
case T_DATA:
if (b == IAC)
n->st = T_IAC;
/* CR NUL is a CR: the NUL goes */
else if (!(b == 0 && n->last_cr && !n->remote[O_BINARY]))
buf_addc(&n->screen, (char)b);
break;
case T_IAC:
if (b == IAC) {
buf_addc(&n->screen, (char)IAC);
n->st = T_DATA;
} else if (b == WILL || b == WONT || b == DO ||
b == DONT) {
n->verb = b;
n->st = T_OPT;
} else if (b == SB) {
buf_clear(&n->sb);
n->st = T_SB;
} else {
/* NOP, GA, AYT and the rest: nothing to do */
n->st = T_DATA;
}
break;
case T_OPT:
option(n, n->verb, b);
n->st = T_DATA;
break;
case T_SB:
if (b == IAC)
n->st = T_SB_IAC;
else if (n->sb.n < 1024)
buf_addc(&n->sb, (char)b);
break;
case T_SB_IAC:
if (b == SE) {
subneg(n);
n->st = T_DATA;
} else {
if (b == IAC && n->sb.n < 1024)
buf_addc(&n->sb, (char)IAC);
n->st = T_SB;
}
break;
}
n->last_cr = n->st == T_DATA && b == '\r';
}
}
DMC_API void dmc_net_feed(dmc_net *n, const char *data, int len)
{
if (len <= 0)
return;
if (n->proto == DMC_NET_TELNET) {
feed_telnet(n, (const unsigned char *)data, len);
return;
}
if (n->proto == DMC_NET_RLOGIN && !n->ready) {
/* the server's NUL: the handshake taken */
n->ready = 1;
if (data[0] == '\0') {
data++;
len--;
}
}
buf_add(&n->screen, data, len);
}
DMC_API void dmc_net_urgent(dmc_net *n, int byte)
{
if (n->proto != DMC_NET_RLOGIN)
return;
/* TIOCPKT_WINDOW: the server takes window sizes, and wants ours */
if (byte & 0x80) {
n->want_size = 1;
send_window(n);
}
/* TIOCPKT_FLUSHWRITE: what it sent before is to be dropped */
if (byte & 0x02)
buf_clear(&n->screen);
}
DMC_API int dmc_net_screen(dmc_net *n, char *buf, int max)
{
return buf_take(&n->screen, buf, max);
}
DMC_API void dmc_net_type(dmc_net *n, const char *data, int len)
{
int i;
if (n->proto != DMC_NET_TELNET) {
buf_add(&n->out, data, len);
return;
}
for (i = 0; i < len; i++) {
unsigned char b = (unsigned char)data[i];
buf_addc(&n->out, (char)b);
if (b == IAC)
buf_addc(&n->out, (char)IAC);
/* a lone CR is CR NUL, outside binary mode */
if (b == '\r' && !n->local[O_BINARY] &&
(i + 1 >= len || data[i + 1] != '\n'))
buf_addc(&n->out, '\0');
}
}
DMC_API int dmc_net_output(dmc_net *n, char *buf, int max)
{
return buf_take(&n->out, buf, max);
}
DMC_API void dmc_net_resize(dmc_net *n, int cols, int rows)
{
if (cols == n->cols && rows == n->rows)
return;
n->cols = cols;
n->rows = rows;
if (n->proto == DMC_NET_TELNET && n->naws)
send_naws(n);
else if (n->proto == DMC_NET_RLOGIN && n->want_size)
send_window(n);
}
+83
View File
@@ -878,6 +878,88 @@ static void test_formats(void)
CHECK(dmc_audio_decode("ID3\4\0\0\0\0\0\0\0\0", 12, &pcm) == -1);
}
/* what the codec has for the socket, as a string of escaped bytes */
static int out_is(dmc_net *n, const char *want, int wn)
{
char b[512];
int k = dmc_net_output(n, b, sizeof(b));
return k == wn && !memcmp(b, want, (size_t)wn);
}
static int screen_is(dmc_net *n, const char *want, int wn)
{
char b[512];
int k = dmc_net_screen(n, b, sizeof(b));
return k == wn && !memcmp(b, want, (size_t)wn);
}
static void test_net(void)
{
CHECK(dmc_net_default_port(DMC_NET_TELNET) == 23);
CHECK(dmc_net_default_port(DMC_NET_RLOGIN) == 513);
CHECK(dmc_net_default_port(DMC_NET_SSH) == 22);
CHECK_STR(dmc_net_name(DMC_NET_RLOGIN), "rlogin");
/* Telnet: the first offers, then the server's */
dmc_net *n = dmc_net_new(DMC_NET_TELNET, "", "ANSI", 80, 24);
dmc_net_connected(n);
CHECK(out_is(n, "\xff\xfb\x18\xff\xfb\x1f\xff\xfd\x03", 9));
/* DO TTYPE, DO NAWS (our size), WILL ECHO, WILL SGA (asked:
not answered again), DO LINEMODE (refused), text, IAC IAC */
const char *in = "\xff\xfd\x18\xff\xfd\x1f\xff\xfb\x01\xff\xfb\x03"
"\xff\xfd\x22Hi\xff\xff!";
dmc_net_feed(n, in, 20);
CHECK(out_is(n, "\xff\xfa\x1f\x00\x50\x00\x18\xff\xf0"
"\xff\xfd\x01\xff\xfc\x22", 15));
CHECK(screen_is(n, "Hi\xff!", 4));
/* TERMINAL-TYPE SEND, split across two reads */
dmc_net_feed(n, "\xff\xfa\x18", 3);
dmc_net_feed(n, "\x01\xff\xf0", 3);
CHECK(out_is(n, "\xff\xfa\x18\x00" "ANSI\xff\xf0", 10));
/* CR NUL is a CR */
dmc_net_feed(n, "a\r\0b", 4);
CHECK(screen_is(n, "a\rb", 3));
/* typed: a lone CR as CR NUL, IAC doubled */
dmc_net_type(n, "ls\r\xff", 4);
CHECK(out_is(n, "ls\r\0\xff\xff", 6));
dmc_net_type(n, "\r\n", 2);
CHECK(out_is(n, "\r\n", 2));
/* resized: NAWS, an 0xff in it doubled */
dmc_net_resize(n, 255, 50);
CHECK(out_is(n, "\xff\xfa\x1f\x00\xff\xff\x00\x32\xff\xf0", 10));
dmc_net_resize(n, 255, 50);
CHECK(out_is(n, "", 0));
/* WONT ECHO: DONT; and again: nothing */
dmc_net_feed(n, "\xff\xfc\x01\xff\xfc\x01", 6);
CHECK(out_is(n, "\xff\xfe\x01", 3));
dmc_net_free(n);
/* rlogin */
n = dmc_net_new(DMC_NET_RLOGIN, "alice", "xterm", 80, 24);
dmc_net_connected(n);
CHECK(out_is(n, "\0alice\0alice\0xterm/38400\0", 25));
/* the server's NUL, then its text */
dmc_net_feed(n, "\0Password:", 10);
CHECK(screen_is(n, "Password:", 9));
dmc_net_feed(n, "\0", 1);
CHECK(screen_is(n, "\0", 1));
/* no size until it is asked for */
dmc_net_resize(n, 100, 30);
CHECK(out_is(n, "", 0));
dmc_net_urgent(n, 0x80);
CHECK(out_is(n, "\xff\xffss\x00\x1e\x00\x64\x03\x20\x01\xe0", 12));
dmc_net_resize(n, 80, 24);
CHECK(out_is(n, "\xff\xffss\x00\x18\x00\x50\x02\x80\x01\x80", 12));
/* typed as it is */
dmc_net_type(n, "\r\xff", 2);
CHECK(out_is(n, "\r\xff", 2));
/* flush */
dmc_net_feed(n, "old", 3);
dmc_net_urgent(n, 0x02);
CHECK(screen_is(n, "", 0));
dmc_net_free(n);
}
int main(int argc, char **argv)
{
const char *dir = argc > 1 ? argv[1] : ".";
@@ -894,6 +976,7 @@ int main(int argc, char **argv)
test_voicemail();
test_wav();
test_formats();
test_net();
printf("%d checks, %d failed\n", checks, failures);
return failures ? 1 : 0;
}
+24 -1
View File
@@ -15,6 +15,7 @@ keeps it easy to call from C (GTK), C++ (Win32) and Swift, and easy to test
| `dmc_model` | The modem's settings from AT!M, with each setting's check and the command that sets it |
| `dmc_diag` | The last call's statistics from AT#UD, as labelled rows (the V.58 code tables decoded) |
| `dmc_vt` | A small VT100/ANSI screen, for Windows and macOS, whose toolkits have no terminal widget |
| `dmc_net` | Telnet (option negotiation, terminal type, window size) and rlogin (the handshake, window size on the server's urgent request), for the Remote page |
| `dmc_daemon_*` | Reading what dmodemd prints when it starts: the device it made, or its error |
## Where the settings come from
@@ -33,13 +34,14 @@ each time the modem opens.
## The same screens everywhere
Each app has the same six pages, with the same words:
Each app has the same seven pages, with the same words:
| Page | Contents |
| --- | --- |
| Modem | The state ("Idle", "Dialling", "Online") and its detail (the CONNECT line, the caller), Dial, Answer, Hang Up, the line and the device, Start or Stop |
| Phone | A voice call's state, Call and Answer, the keypad (DTMF), Mute and Listen; the answering machine (on or off, rings, the greeting) and its messages |
| Terminal | The AT console; the buttons **Full-screen setup** (AT!CF) and **Command-line setup** (AT!CT) |
| Remote | SSH, Telnet or rlogin; the server, its port (empty: the protocol's) and the user; Connect; a terminal of its own, whose size goes to the server as it changes |
| Settings | Groups of settings as native controls, changed ones marked; Defaults (ATZ), the init string and Keep |
| Call Stats | AT#UD's rows and ATI11's report, refreshed after each call |
| Log | What dmodemd printed, and the command line it was started with |
@@ -63,6 +65,27 @@ own group (`-g`), so that dmodemd needs no root.
Each app can instead use a modem that already runs: a device path on
Linux and macOS; a TCP address or a COM port on Windows.
## Remote logins
The Remote page logs in to a server, beside the modem, in a terminal of
its own. Telnet and rlogin are a TCP connection each app makes in its own
way, with libdmodemctl's `dmc_net` for the protocol (sans-I/O, as the
session). SSH is the system's OpenSSH client, so that the user's keys,
agent, `known_hosts` and `~/.ssh/config` apply:
| | Telnet and rlogin | SSH | Kept in |
| --- | --- | --- | --- |
| Linux | GSocketClient, its socket on the main loop (G_IO_PRI for rlogin's urgent byte) | `ssh` on a pty of the page's own (forkpty), TERM `xterm-256color` | `settings.ini`, `[remote]` |
| Windows | Winsock 1.1, `WSAAsyncSelect` (FD_OOB for rlogin), on every Windows from 95 | Windows' `ssh.exe` (the OpenSSH Client feature) in a pseudo console: Windows 10 1809 and later, looked up at run time | `dmodem.ini`, `[remote]` |
| macOS | a BSD socket on a dispatch source | `/usr/bin/ssh` on a pty (`PtySpawn.c`) | UserDefaults |
Telnet tells the server the terminal type and the window's size (NAWS),
and sends a typed CR as CR NUL. rlogin sends the user as both the local
and the remote name; a server that insists on a client port below 1024
(classic BSD `rlogind`) won't take an unprivileged app, but BBSes and
most rlogin services do. Backspace sends DEL, as a host expects (the
modem's console sends BS).
## Voice calls and the answering machine
Voice uses dmodemd's V.253 voice mode: `AT+FCLASS=8`, `AT+VSM=4` (G.711
+8
View File
@@ -7,6 +7,7 @@ add_executable(dmodem-gui
src/settings.c
src/stats.c
src/voice.c
src/remote.c
src/audio.c)
target_link_libraries(dmodem-gui PRIVATE dmodemctl PkgConfig::GTK)
# the sound of voice calls: PulseAudio's client (PipeWire serves it
@@ -27,6 +28,13 @@ if(SNDFILE_FOUND)
else()
message(STATUS "libsndfile not found: greetings are read from WAV, AIFF and .au files only")
endif()
# forkpty(), for the Remote page's ssh: in libutil on the BSDs and older
# glibc, in libc itself since glibc 2.34
include(CheckFunctionExists)
check_function_exists(forkpty HAVE_FORKPTY_IN_LIBC)
if(NOT HAVE_FORKPTY_IN_LIBC)
target_link_libraries(dmodem-gui PRIVATE util)
endif()
target_compile_options(dmodem-gui PRIVATE -Wall -Wextra -Wno-unused-parameter)
include(GNUInstallDirs)
+9
View File
@@ -31,6 +31,10 @@ typedef struct Config {
message's longest (s) */
gboolean voicemail;
int vm_rings, vm_max;
/* the Remote page's last login ([remote]): "SSH", "Telnet" or
"rlogin", the server, its port (0: the protocol's), the user */
char *remote_proto, *remote_host, *remote_user;
int remote_port;
} Config;
typedef struct App App;
@@ -137,6 +141,11 @@ gboolean audio_start(App *a, AudioPull pull, AudioPush push);
void audio_stop(App *a);
gboolean audio_available(void);
/* remote.c: the Remote page, a login by SSH, Telnet or rlogin */
GtkWidget *remote_page_new(App *a);
/* its connection ended (the app is quitting) */
void remote_stop(App *a);
/* stats.c */
GtkWidget *stats_page_new(App *a);
void stats_refresh(App *a);
+17
View File
@@ -67,6 +67,16 @@ void config_load(Config *c)
if (e || c->vm_max < 10)
c->vm_max = 120;
g_clear_error(&e);
c->remote_proto = g_key_file_get_string(k, "remote", "protocol", NULL);
if (!c->remote_proto)
c->remote_proto = g_strdup("SSH");
c->remote_host = g_key_file_get_string(k, "remote", "host", NULL);
if (!c->remote_host)
c->remote_host = g_strdup("");
c->remote_port = g_key_file_get_integer(k, "remote", "port", NULL);
c->remote_user = g_key_file_get_string(k, "remote", "user", NULL);
if (!c->remote_user)
c->remote_user = g_strdup("");
g_key_file_unref(k);
}
@@ -92,6 +102,10 @@ void config_save(const Config *c)
g_key_file_set_boolean(k, "voice", "voicemail", c->voicemail);
g_key_file_set_integer(k, "voice", "rings", c->vm_rings);
g_key_file_set_integer(k, "voice", "max-seconds", c->vm_max);
g_key_file_set_string(k, "remote", "protocol", c->remote_proto);
g_key_file_set_string(k, "remote", "host", c->remote_host);
g_key_file_set_integer(k, "remote", "port", c->remote_port);
g_key_file_set_string(k, "remote", "user", c->remote_user);
char *p = path();
char *dir = g_path_get_dirname(p);
g_mkdir_with_parents(dir, 0700);
@@ -119,6 +133,9 @@ void config_free(Config *c)
g_free(c->device);
g_free(c->dmodemd);
g_free(c->init);
g_free(c->remote_proto);
g_free(c->remote_host);
g_free(c->remote_user);
}
char *config_summary(const Config *c)
+1
View File
@@ -29,6 +29,7 @@ static void shutdown(GApplication *g, gpointer data)
{
App *a = data;
(void)g;
remote_stop(a);
if (modem_running(a))
modem_stop(a);
g_cancellable_cancel(a->cancel);
+581
View File
@@ -0,0 +1,581 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* remote.c - the Remote page: a login to a server by SSH, Telnet or
* rlogin, in a terminal of its own, beside the modem's
*
* Telnet and rlogin are a TCP connection made here and libdmodemctl's
* dmc_net for the protocol. SSH is the system's ssh in a pty of this
* page's own, so that its host keys, agent and config are the user's.
* Either way the terminal only shows bytes and gives what is typed.
*/
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#if defined(__linux__)
#include <pty.h>
#elif defined(__FreeBSD__) || defined(__DragonFly__)
#include <libutil.h>
#else
#include <util.h>
#endif
#include <glib-unix.h>
#include "app.h"
/* the protocols in the drop-down's order */
static const int protos[] = { DMC_NET_SSH, DMC_NET_TELNET, DMC_NET_RLOGIN };
typedef struct Remote {
App *a;
GtkWidget *proto, *host, *port, *user, *go, *status;
VteTerminal *term;
int cols, rows;
/* what runs: its protocol (0: none) */
int running;
/* Telnet, rlogin: the socket and the protocol */
GSocketClient *client;
GCancellable *cancel;
GSocketConnection *conn;
GSocket *sock;
GSource *in_src, *out_src;
dmc_net *net;
GByteArray *pending;
/* SSH: the pty's master, ssh's pid */
int fd;
GPid pid;
guint fd_watch, child_watch, size_tick;
} Remote;
static Remote *R;
static void set_status(Remote *r, const char *text)
{
gtk_label_set_text(GTK_LABEL(r->status), text);
}
static void controls(Remote *r)
{
gboolean idle = !r->running;
gtk_widget_set_sensitive(r->proto, idle);
gtk_widget_set_sensitive(r->host, idle);
gtk_widget_set_sensitive(r->port, idle);
gtk_widget_set_sensitive(r->user, idle);
gtk_button_set_label(GTK_BUTTON(r->go), idle ? "Connect" : "Disconnect");
if (idle) {
gtk_widget_add_css_class(r->go, "suggested-action");
gtk_widget_remove_css_class(r->go, "destructive-action");
} else {
gtk_widget_remove_css_class(r->go, "suggested-action");
gtk_widget_add_css_class(r->go, "destructive-action");
}
}
static void show(Remote *r, const char *data, gssize n)
{
vte_terminal_feed(r->term, data, n);
}
/* the connection over, with why (NULL: the user's doing) */
static void ended(Remote *r, const char *why)
{
if (!r->running)
return;
r->running = 0;
if (r->cancel) {
g_cancellable_cancel(r->cancel);
g_clear_object(&r->cancel);
}
if (r->in_src) {
g_source_destroy(r->in_src);
g_clear_pointer(&r->in_src, g_source_unref);
}
if (r->out_src) {
g_source_destroy(r->out_src);
g_clear_pointer(&r->out_src, g_source_unref);
}
if (r->conn)
g_io_stream_close(G_IO_STREAM(r->conn), NULL, NULL);
g_clear_object(&r->conn);
r->sock = NULL;
g_clear_object(&r->client);
g_clear_pointer(&r->net, dmc_net_free);
if (r->pending)
g_byte_array_set_size(r->pending, 0);
if (r->fd_watch)
g_source_remove(r->fd_watch);
r->fd_watch = 0;
if (r->fd >= 0)
close(r->fd);
r->fd = -1;
if (r->pid > 0)
kill(r->pid, SIGHUP);
if (r->size_tick)
g_source_remove(r->size_tick);
r->size_tick = 0;
char *line = g_strdup_printf("\r\n\x1b[0m[%s]\r\n", why ? why :
"Disconnected");
show(r, line, -1);
g_free(line);
set_status(r, why ? why : "Disconnected");
controls(r);
}
/*
* Telnet and rlogin
*/
static gboolean writable(GSocket *s, GIOCondition c, gpointer data);
/* the protocol's output to the socket, as much as it takes now */
static void flush(Remote *r)
{
char buf[4096];
int n;
while ((n = dmc_net_output(r->net, buf, sizeof(buf))) > 0)
g_byte_array_append(r->pending, (guint8 *)buf, n);
while (r->pending->len > 0) {
GError *e = NULL;
gssize w = g_socket_send(r->sock, (char *)r->pending->data,
r->pending->len, NULL, &e);
if (w < 0) {
if (g_error_matches(e, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
g_error_free(e);
if (!r->out_src) {
r->out_src = g_socket_create_source(
r->sock, G_IO_OUT, NULL);
g_source_set_callback(r->out_src,
(GSourceFunc)(void (*)(void))writable,
r, NULL);
g_source_attach(r->out_src, NULL);
}
return;
}
char *why = g_strdup(e->message);
g_error_free(e);
ended(r, why);
g_free(why);
return;
}
g_byte_array_remove_range(r->pending, 0, (guint)w);
}
}
static gboolean writable(GSocket *s, GIOCondition c, gpointer data)
{
Remote *r = data;
(void)s;
(void)c;
g_clear_pointer(&r->out_src, g_source_unref);
flush(r);
return G_SOURCE_REMOVE;
}
static void pump(Remote *r)
{
char buf[8192];
int n;
while ((n = dmc_net_screen(r->net, buf, sizeof(buf))) > 0)
show(r, buf, n);
flush(r);
}
static gboolean readable(GSocket *s, GIOCondition c, gpointer data)
{
Remote *r = data;
char buf[8192];
/* rlogin's control byte, sent urgent */
if (c & G_IO_PRI) {
char b;
if (recv(g_socket_get_fd(s), &b, 1, MSG_OOB) == 1)
dmc_net_urgent(r->net, (unsigned char)b);
}
if (c & (G_IO_IN | G_IO_HUP | G_IO_ERR)) {
GError *e = NULL;
gssize n = g_socket_receive(s, buf, sizeof(buf), NULL, &e);
if (n < 0 && g_error_matches(e, G_IO_ERROR,
G_IO_ERROR_WOULD_BLOCK)) {
g_error_free(e);
} else if (n <= 0) {
char *why = e ? g_strdup(e->message) :
g_strdup("Connection closed by the server");
g_clear_error(&e);
pump(r);
ended(r, why);
g_free(why);
return G_SOURCE_REMOVE;
} else {
dmc_net_feed(r->net, buf, (int)n);
}
}
pump(r);
return G_SOURCE_CONTINUE;
}
static void connected(GObject *src, GAsyncResult *res, gpointer data)
{
Remote *r = data;
GError *e = NULL;
GSocketConnection *c = g_socket_client_connect_to_host_finish(
G_SOCKET_CLIENT(src), res, &e);
if (!c) {
/* (cancelled: ended() has said so) */
if (!g_error_matches(e, G_IO_ERROR, G_IO_ERROR_CANCELLED))
ended(r, e->message);
g_error_free(e);
return;
}
r->conn = c;
r->sock = g_socket_connection_get_socket(c);
g_socket_set_blocking(r->sock, FALSE);
g_socket_set_option(r->sock, IPPROTO_TCP, TCP_NODELAY, 1, NULL);
r->in_src = g_socket_create_source(r->sock, G_IO_IN | G_IO_PRI |
G_IO_HUP | G_IO_ERR, NULL);
g_source_set_callback(r->in_src, (GSourceFunc)(void (*)(void))readable,
r, NULL);
g_source_attach(r->in_src, NULL);
set_status(r, "Connected");
dmc_net_connected(r->net);
pump(r);
}
/*
* SSH: the system's ssh in a pty
*/
static gboolean pty_readable(int fd, GIOCondition c, gpointer data)
{
Remote *r = data;
char buf[8192];
ssize_t n = read(fd, buf, sizeof(buf));
if (n > 0) {
show(r, buf, n);
return G_SOURCE_CONTINUE;
}
if (n < 0 && (errno == EAGAIN || errno == EINTR))
return G_SOURCE_CONTINUE;
/* (EIO: ssh has gone and the pty is shut; its exit says why) */
r->fd_watch = 0;
return G_SOURCE_REMOVE;
}
static void child_exited(GPid pid, int status, gpointer data)
{
Remote *r = data;
g_spawn_close_pid(pid);
r->child_watch = 0;
if (r->pid != pid)
return;
r->pid = 0;
/* what is left in the pty first */
if (r->fd >= 0) {
char buf[8192];
ssize_t n;
while ((n = read(r->fd, buf, sizeof(buf))) > 0)
show(r, buf, n);
}
char *why = WIFEXITED(status) && WEXITSTATUS(status) ?
g_strdup_printf("ssh exited with status %d", WEXITSTATUS(status)) :
g_strdup("Connection closed");
ended(r, why);
g_free(why);
}
static void set_pty_size(Remote *r)
{
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)r->cols;
ws.ws_row = (unsigned short)r->rows;
ioctl(r->fd, TIOCSWINSZ, &ws);
}
static gboolean start_ssh(Remote *r, const char *host, int port,
const char *user)
{
char *ssh = g_find_program_in_path("ssh");
if (!ssh) {
window_toast(r->a, "ssh was not found: install OpenSSH's client");
return FALSE;
}
char ps[16];
g_snprintf(ps, sizeof(ps), "%d", port);
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)r->cols;
ws.ws_row = (unsigned short)r->rows;
int fd;
pid_t pid = forkpty(&fd, NULL, NULL, &ws);
if (pid < 0) {
g_free(ssh);
window_toast(r->a, "Could not make a pty for ssh");
return FALSE;
}
if (pid == 0) {
/* the child: ssh, with VTE's terminal type */
const char *argv[10];
int i = 0;
argv[i++] = "ssh";
argv[i++] = "-p";
argv[i++] = ps;
if (*user) {
argv[i++] = "-l";
argv[i++] = user;
}
argv[i++] = "--";
argv[i++] = host;
argv[i] = NULL;
setenv("TERM", "xterm-256color", 1);
execv(ssh, (char **)argv);
_exit(127);
}
g_free(ssh);
g_unix_set_fd_nonblocking(fd, TRUE, NULL);
r->fd = fd;
r->pid = pid;
r->fd_watch = g_unix_fd_add(fd, G_IO_IN | G_IO_HUP | G_IO_ERR,
pty_readable, r);
r->child_watch = g_child_watch_add(pid, child_exited, r);
return TRUE;
}
/*
* the page
*/
/* the terminal's size, told to the far end as it changes */
static gboolean size_check(gpointer data)
{
Remote *r = data;
int c = (int)vte_terminal_get_column_count(r->term);
int w = (int)vte_terminal_get_row_count(r->term);
if (c == r->cols && w == r->rows)
return G_SOURCE_CONTINUE;
r->cols = c;
r->rows = w;
if (r->net && r->sock) {
dmc_net_resize(r->net, c, w);
flush(r);
} else if (r->fd >= 0) {
set_pty_size(r);
}
return G_SOURCE_CONTINUE;
}
static void committed(VteTerminal *t, char *text, guint size, gpointer data)
{
Remote *r = data;
(void)t;
if (!r->running)
return;
if (r->fd >= 0) {
/* (a pty takes small writes whole) */
ssize_t w = write(r->fd, text, size);
(void)w;
} else if (r->net && r->sock) {
dmc_net_type(r->net, text, (int)size);
flush(r);
}
}
static int chosen_proto(Remote *r)
{
guint i = gtk_drop_down_get_selected(GTK_DROP_DOWN(r->proto));
return i < G_N_ELEMENTS(protos) ? protos[i] : DMC_NET_SSH;
}
/* the default port shown for the protocol */
static void proto_changed(GObject *o, GParamSpec *p, gpointer data)
{
Remote *r = data;
(void)o;
(void)p;
char ps[16];
g_snprintf(ps, sizeof(ps), "%d", dmc_net_default_port(chosen_proto(r)));
gtk_entry_set_placeholder_text(GTK_ENTRY(r->port), ps);
}
static void connect_clicked(GtkWidget *w, gpointer data)
{
Remote *r = data;
App *a = r->a;
(void)w;
if (r->running) {
ended(r, NULL);
return;
}
char *host = g_strstrip(g_strdup(
gtk_editable_get_text(GTK_EDITABLE(r->host))));
const char *user = gtk_editable_get_text(GTK_EDITABLE(r->user));
const char *pt = gtk_editable_get_text(GTK_EDITABLE(r->port));
int proto = chosen_proto(r);
int port = *pt ? atoi(pt) : dmc_net_default_port(proto);
if (!*host) {
window_toast(a, "Enter the server to connect to");
g_free(host);
return;
}
if (port <= 0 || port > 65535) {
window_toast(a, "The port is a number from 1 to 65535");
g_free(host);
return;
}
if (proto == DMC_NET_RLOGIN && !*user) {
window_toast(a, "rlogin needs a user name");
g_free(host);
return;
}
/* kept for next time */
g_free(a->cfg.remote_proto);
a->cfg.remote_proto = g_strdup(dmc_net_name(proto));
g_free(a->cfg.remote_host);
a->cfg.remote_host = g_strdup(host);
a->cfg.remote_port = *pt ? port : 0;
g_free(a->cfg.remote_user);
a->cfg.remote_user = g_strdup(user);
config_save(&a->cfg);
vte_terminal_reset(r->term, TRUE, TRUE);
r->cols = (int)vte_terminal_get_column_count(r->term);
r->rows = (int)vte_terminal_get_row_count(r->term);
char *what = g_strdup_printf("Connecting to %s port %d by %s", host,
port, dmc_net_name(proto));
set_status(r, what);
char *line = g_strdup_printf("[%s]\r\n", what);
show(r, line, -1);
g_free(line);
g_free(what);
if (proto == DMC_NET_SSH) {
if (!start_ssh(r, host, port, user)) {
set_status(r, "Not connected");
g_free(host);
return;
}
set_status(r, "Connected by SSH");
} else {
r->net = dmc_net_new(proto, user, "xterm-256color", r->cols,
r->rows);
r->client = g_socket_client_new();
g_socket_client_set_timeout(r->client, 20);
r->cancel = g_cancellable_new();
g_socket_client_connect_to_host_async(r->client, host,
(guint16)port, r->cancel,
connected, r);
}
r->running = proto;
r->size_tick = g_timeout_add(250, size_check, r);
controls(r);
gtk_widget_grab_focus(GTK_WIDGET(r->term));
g_free(host);
}
static int proto_index(const char *name)
{
guint i;
for (i = 0; i < G_N_ELEMENTS(protos); i++)
if (name && !g_ascii_strcasecmp(name, dmc_net_name(protos[i])))
return (int)i;
return 0;
}
GtkWidget *remote_page_new(App *a)
{
Remote *r = g_new0(Remote, 1);
R = r;
r->a = a;
r->fd = -1;
r->pending = g_byte_array_new();
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_widget_set_margin_start(bar, 6);
gtk_widget_set_margin_end(bar, 6);
gtk_widget_set_margin_top(bar, 6);
gtk_widget_set_margin_bottom(bar, 6);
const char *names[] = { "SSH", "Telnet", "rlogin", NULL };
r->proto = gtk_drop_down_new_from_strings(names);
gtk_widget_set_tooltip_text(r->proto, "How to log in");
gtk_box_append(GTK_BOX(bar), r->proto);
r->host = gtk_entry_new();
gtk_entry_set_placeholder_text(GTK_ENTRY(r->host), "Server");
gtk_widget_set_hexpand(r->host, TRUE);
gtk_box_append(GTK_BOX(bar), r->host);
r->port = gtk_entry_new();
gtk_entry_set_input_purpose(GTK_ENTRY(r->port), GTK_INPUT_PURPOSE_DIGITS);
gtk_editable_set_width_chars(GTK_EDITABLE(r->port), 6);
gtk_editable_set_max_width_chars(GTK_EDITABLE(r->port), 6);
gtk_widget_set_tooltip_text(r->port, "Port (empty: the protocol's)");
gtk_box_append(GTK_BOX(bar), r->port);
r->user = gtk_entry_new();
gtk_entry_set_placeholder_text(GTK_ENTRY(r->user), "User");
gtk_editable_set_width_chars(GTK_EDITABLE(r->user), 12);
gtk_box_append(GTK_BOX(bar), r->user);
r->go = gtk_button_new_with_label("Connect");
g_signal_connect(r->go, "clicked", G_CALLBACK(connect_clicked), r);
g_signal_connect(r->host, "activate", G_CALLBACK(connect_clicked), r);
gtk_box_append(GTK_BOX(bar), r->go);
gtk_box_append(GTK_BOX(box), bar);
/* what was used last */
gtk_drop_down_set_selected(GTK_DROP_DOWN(r->proto),
(guint)proto_index(a->cfg.remote_proto));
gtk_editable_set_text(GTK_EDITABLE(r->host), a->cfg.remote_host);
if (a->cfg.remote_port > 0) {
char ps[16];
g_snprintf(ps, sizeof(ps), "%d", a->cfg.remote_port);
gtk_editable_set_text(GTK_EDITABLE(r->port), ps);
}
gtk_editable_set_text(GTK_EDITABLE(r->user), a->cfg.remote_user);
g_signal_connect(r->proto, "notify::selected", G_CALLBACK(proto_changed), r);
proto_changed(NULL, NULL, r);
r->term = VTE_TERMINAL(vte_terminal_new());
vte_terminal_set_scrollback_lines(r->term, 5000);
vte_terminal_set_backspace_binding(r->term, VTE_ERASE_ASCII_DELETE);
vte_terminal_set_size(r->term, 80, 24);
PangoFontDescription *f = pango_font_description_from_string("Monospace 11");
vte_terminal_set_font(r->term, f);
pango_font_description_free(f);
GdkRGBA fg, bg;
gdk_rgba_parse(&fg, "#e8f0ff");
gdk_rgba_parse(&bg, "#0a0f1c");
vte_terminal_set_colors(r->term, &fg, &bg, NULL, 0);
gtk_widget_set_vexpand(GTK_WIDGET(r->term), TRUE);
gtk_widget_set_hexpand(GTK_WIDGET(r->term), TRUE);
g_signal_connect(r->term, "commit", G_CALLBACK(committed), r);
GtkWidget *scroll = gtk_scrolled_window_new();
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scroll),
GTK_WIDGET(r->term));
gtk_widget_set_vexpand(scroll, TRUE);
gtk_box_append(GTK_BOX(box), scroll);
r->status = gtk_label_new("Not connected");
gtk_label_set_xalign(GTK_LABEL(r->status), 0);
gtk_widget_add_css_class(r->status, "dim-label");
gtk_widget_set_margin_start(r->status, 8);
gtk_widget_set_margin_top(r->status, 4);
gtk_widget_set_margin_bottom(r->status, 4);
gtk_box_append(GTK_BOX(box), r->status);
controls(r);
return box;
}
void remote_stop(App *a)
{
(void)a;
if (R && R->running)
ended(R, NULL);
}
+5 -2
View File
@@ -2,8 +2,8 @@
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* window.c - the main window: the Modem, Terminal, Settings, Call and
* Log pages, the same pages as the Windows and macOS apps
* window.c - the main window: the Modem, Phone, Terminal, Remote,
* Settings, Call and Log pages, the same pages as the Windows and macOS apps
* (docs/design.md)
*/
#include <string.h>
@@ -459,6 +459,9 @@ void window_build(App *a)
adw_view_stack_add_titled_with_icon(a->stack, terminal_page(a),
"terminal", "Terminal",
"utilities-terminal-symbolic");
adw_view_stack_add_titled_with_icon(a->stack, remote_page_new(a),
"remote", "Remote",
"network-server-symbolic");
adw_view_stack_add_titled_with_icon(a->stack, settings_page_new(a),
"settings", "Settings",
"preferences-system-symbolic");
+1
View File
@@ -5,3 +5,4 @@
* Bridging.h - libdmodemctl, for Swift
*/
#include "dmodemctl.h"
#include "PtySpawn.h"
+7 -3
View File
@@ -1,13 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 D-Modem Authors
//
// ContentView.swift - the window: its pages (Modem, Terminal, Settings,
// Call Stats, Log) in a sidebar
// ContentView.swift - the window: its pages (Modem, Phone, Terminal,
// Remote, Settings, Call Stats, Log) in a sidebar
import SwiftUI
enum Page: String, CaseIterable, Identifiable {
case modem = "Modem", phone = "Phone", terminal = "Terminal", settings = "Settings"
case modem = "Modem", phone = "Phone", terminal = "Terminal", remote = "Remote"
case settings = "Settings"
case stats = "Call Stats", log = "Log"
var id: String { rawValue }
var icon: String {
@@ -15,6 +16,7 @@ enum Page: String, CaseIterable, Identifiable {
case .modem: return "phone.connection"
case .phone: return "phone"
case .terminal: return "terminal"
case .remote: return "network"
case .settings: return "slider.horizontal.3"
case .stats: return "chart.bar"
case .log: return "doc.plaintext"
@@ -24,6 +26,7 @@ enum Page: String, CaseIterable, Identifiable {
struct ContentView: View {
@EnvironmentObject var modem: Modem
@EnvironmentObject var remote: RemoteSession
@State private var page: Page? = Page(rawValue: ProcessInfo.processInfo.environment["DMODEM_GUI_PAGE"] ?? "") ?? .modem
var body: some View {
@@ -38,6 +41,7 @@ struct ContentView: View {
case .modem: ModemPage()
case .phone: PhonePage()
case .terminal: TerminalPane()
case .remote: RemotePage(session: remote)
case .settings: SettingsPage()
case .stats: StatsPage()
case .log: LogPage()
+8 -1
View File
@@ -9,14 +9,19 @@ import SwiftUI
struct DModemApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
@StateObject private var modem = Modem()
@StateObject private var remote = RemoteSession()
var body: some Scene {
Window("D-Modem", id: "main") {
ContentView()
.environmentObject(modem)
.environmentObject(modem.voice)
.environmentObject(remote)
.frame(minWidth: 760, minHeight: 520)
.onAppear { delegate.modem = modem }
.onAppear {
delegate.modem = modem
delegate.remote = remote
}
}
.commands {
CommandMenu("Modem") {
@@ -41,12 +46,14 @@ struct DModemApp: App {
final class AppDelegate: NSObject, NSApplicationDelegate {
weak var modem: Modem?
weak var remote: RemoteSession?
func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
remote?.stop()
modem?.stop()
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* PtySpawn.c - a program started on a new pty, for the Remote page's ssh
*/
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <util.h>
#include "PtySpawn.h"
int dm_pty_spawn(const char *path, const char *const *argv, const char *term,
int cols, int rows, pid_t *pid)
{
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)cols;
ws.ws_row = (unsigned short)rows;
int fd;
pid_t p = forkpty(&fd, NULL, NULL, &ws);
if (p < 0)
return -1;
if (p == 0) {
setenv("TERM", term, 1);
execv(path, (char *const *)argv);
_exit(127);
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
fcntl(fd, F_SETFD, FD_CLOEXEC);
*pid = p;
return fd;
}
void dm_pty_resize(int fd, int cols, int rows)
{
struct winsize ws = { 0 };
ws.ws_col = (unsigned short)cols;
ws.ws_row = (unsigned short)rows;
ioctl(fd, TIOCSWINSZ, &ws);
}
+21
View File
@@ -0,0 +1,21 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* PtySpawn.h - a program started on a new pty (the Remote page's ssh):
* Swift can't fork, so this is C
*/
#ifndef DMODEM_PTY_SPAWN_H
#define DMODEM_PTY_SPAWN_H
#include <sys/types.h>
/* path started with argv (NULL-ended) and TERM=term on a pty of cols by
rows, as the leader of its own session: the pty's master (non-blocking),
and its pid in *pid; -1 if it could not be */
int dm_pty_spawn(const char *path, const char *const *argv, const char *term,
int cols, int rows, pid_t *pid);
/* the pty's new size, told to the program (SIGWINCH) */
void dm_pty_resize(int fd, int cols, int rows);
#endif
+406
View File
@@ -0,0 +1,406 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 D-Modem Authors
//
// RemoteView.swift - the Remote page: a login to a server by SSH, Telnet
// or rlogin, in a terminal of its own (TerminalView.swift's view)
//
// Telnet and rlogin are a socket made here and libdmodemctl's dmc_net
// for the protocol. SSH is the system's /usr/bin/ssh on a pty
// (PtySpawn.c), so that its keys, agent and config are the user's.
import Darwin
import Foundation
import SwiftUI
final class RemoteSession: ObservableObject, TerminalHost {
enum Proto: String, CaseIterable, Identifiable {
case ssh = "SSH", telnet = "Telnet", rlogin = "rlogin"
var id: String { rawValue }
var net: Int32 {
switch self {
case .ssh: return Int32(DMC_NET_SSH)
case .telnet: return Int32(DMC_NET_TELNET)
case .rlogin: return Int32(DMC_NET_RLOGIN)
}
}
var defaultPort: Int { Int(dmc_net_default_port(net)) }
}
@Published var proto: Proto
@Published var host: String
/// empty: the protocol's
@Published var port: String
@Published var user: String
@Published private(set) var running = false
@Published private(set) var status = "Not connected"
/// bumped when the screen changed, to draw it again
@Published private(set) var screenVersion = 0
let vt: OpaquePointer
private var fd: Int32 = -1 // the socket, or the pty's master
private var source: DispatchSourceRead?
private var writer: DispatchSourceWrite?
private var exitSource: DispatchSourceProcess?
private var net: OpaquePointer?
private var pid: pid_t = 0
private var pending: [UInt8] = []
private var cols = 80, rows = 24
private var timer: Timer?
/// a connection under way: older ones' results ignored
private var gen = 0
private let defaults = UserDefaults.standard
init() {
vt = dmc_vt_new(80, 24, 2000)
proto = Proto(rawValue: defaults.string(forKey: "remoteProtocol") ?? "") ?? .ssh
host = defaults.string(forKey: "remoteHost") ?? ""
port = defaults.string(forKey: "remotePort") ?? ""
user = defaults.string(forKey: "remoteUser") ?? ""
}
deinit {
stop()
dmc_vt_free(vt)
}
// MARK: - TerminalHost
func type(_ text: String) { send(Array(text.utf8)) }
func key(_ k: Int) {
// (Backspace is DEL to a host, not the modem's BS)
if k == Int(DMC_KEY_BACKSPACE) {
send([0x7f])
return
}
var buf = [CChar](repeating: 0, count: 16)
let n = dmc_vt_key(vt, Int32(k), &buf, Int32(buf.count))
if n > 0 { send(buf[0..<Int(n)].map { UInt8(bitPattern: $0) }) }
}
private func send(_ bytes: [UInt8]) {
guard running, fd >= 0, !bytes.isEmpty else { return }
if let net {
bytes.withUnsafeBufferPointer { b in
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
dmc_net_type(net, $0, Int32(b.count))
}
}
} else {
pending.append(contentsOf: bytes)
}
pump()
}
// MARK: - connecting
func connect() {
if running { return }
let h = host.trimmingCharacters(in: .whitespaces)
guard !h.isEmpty else { status = "Enter the server to connect to"; return }
let p = port.isEmpty ? proto.defaultPort : (Int(port) ?? 0)
guard p > 0 && p <= 65535 else { status = "The port is a number from 1 to 65535"; return }
if proto == .rlogin && user.isEmpty { status = "rlogin needs a user name"; return }
defaults.set(proto.rawValue, forKey: "remoteProtocol")
defaults.set(h, forKey: "remoteHost")
defaults.set(port, forKey: "remotePort")
defaults.set(user, forKey: "remoteUser")
dmc_vt_reset(vt)
cols = Int(dmc_vt_cols(vt))
rows = Int(dmc_vt_rows(vt))
let what = "Connecting to \(h) port \(p) by \(proto.rawValue)"
status = what
show("[\(what)]\r\n")
gen += 1
running = true
if proto == .ssh {
guard startSSH(host: h, port: p) else {
ended("Could not start ssh")
return
}
status = "Connected by SSH"
} else {
net = dmc_net_new(proto.net, user, "ansi", Int32(cols), Int32(rows))
connectSocket(host: h, port: p, gen: gen)
}
let t = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in self?.tick() }
RunLoop.main.add(t, forMode: .common)
timer = t
}
func stop() { ended(nil) }
private func startSSH(host: String, port: Int) -> Bool {
var args = ["ssh", "-p", String(port)]
if !user.isEmpty { args += ["-l", user] }
args += ["--", host]
let cargs: [UnsafeMutablePointer<CChar>?] = args.map { strdup($0) } + [nil]
defer { for a in cargs { free(a) } }
var p: pid_t = 0
let f = cargs.map { UnsafePointer($0) }.withUnsafeBufferPointer {
dm_pty_spawn("/usr/bin/ssh", $0.baseAddress, "xterm", Int32(cols), Int32(rows), &p)
}
guard f >= 0 else { return false }
fd = f
pid = p
watch()
let e = DispatchSource.makeProcessSource(identifier: p, eventMask: .exit, queue: .main)
e.setEventHandler { [weak self] in self?.childExited(p) }
e.resume()
exitSource = e
return true
}
private func childExited(_ p: pid_t) {
var st: Int32 = 0
waitpid(p, &st, 0)
guard p == pid else { return }
pid = 0
readable() // (what is left)
let code = (st & 0x7f) == 0 ? (st >> 8) & 0xff : 0
ended(code != 0 ? "ssh exited with status \(code)" : "Connection closed")
}
private func connectSocket(host: String, port: Int, gen: Int) {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
var hints = addrinfo()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
var res: UnsafeMutablePointer<addrinfo>?
var s: Int32 = -1
var err = ""
let rc = getaddrinfo(host, String(port), &hints, &res)
if rc != 0 {
err = String(cString: gai_strerror(rc))
} else {
var a = res
while let ai = a {
let k = socket(ai.pointee.ai_family, ai.pointee.ai_socktype, ai.pointee.ai_protocol)
if k >= 0 {
if Darwin.connect(k, ai.pointee.ai_addr, ai.pointee.ai_addrlen) == 0 {
s = k
break
}
err = String(cString: strerror(errno))
close(k)
}
a = ai.pointee.ai_next
}
freeaddrinfo(res)
}
DispatchQueue.main.async {
guard let self, self.gen == gen, self.running else {
if s >= 0 { close(s) }
return
}
self.socketConnected(s, err)
}
}
}
private func socketConnected(_ s: Int32, _ err: String) {
guard s >= 0, let net else {
ended(err.isEmpty ? "Could not connect" : err)
return
}
var one: Int32 = 1
setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.size))
_ = fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK)
fd = s
watch()
status = "Connected"
dmc_net_connected(net)
pump()
}
private func watch() {
let s = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
s.setEventHandler { [weak self] in self?.readable() }
s.resume()
source = s
}
// MARK: - the bytes
/// rlogin's control byte, sent urgent
private func urgent() {
guard let net, fd >= 0 else { return }
var b: UInt8 = 0
if recv(fd, &b, 1, Int32(MSG_OOB)) == 1 { dmc_net_urgent(net, Int32(b)) }
}
private func readable() {
guard fd >= 0 else { return }
urgent()
var buf = [CChar](repeating: 0, count: 8192)
while fd >= 0 {
let n = Darwin.read(fd, &buf, buf.count)
if n > 0 {
if let net {
dmc_net_feed(net, buf, Int32(n))
} else {
dmc_vt_feed(vt, buf, Int32(n))
}
continue
}
if n < 0 && errno == EINTR { continue }
if n < 0 && errno == EAGAIN { break }
// the end: the server closed, or ssh's pty (its exit says why)
pump()
if net != nil {
ended("Connection closed by the server")
} else {
source?.cancel()
source = nil
}
return
}
pump()
}
private func pump() {
var buf = [CChar](repeating: 0, count: 8192)
if let net {
while true {
let n = dmc_net_screen(net, &buf, Int32(buf.count))
if n <= 0 { break }
dmc_vt_feed(vt, buf, n)
}
}
// the screen's answers (where the cursor is), as if typed
while true {
let k = dmc_vt_reply(vt, &buf, Int32(buf.count))
if k <= 0 { break }
if let net { dmc_net_type(net, buf, k) } else {
pending.append(contentsOf: buf[0..<Int(k)].map { UInt8(bitPattern: $0) })
}
}
if let net {
while true {
let n = dmc_net_output(net, &buf, Int32(buf.count))
if n <= 0 { break }
pending.append(contentsOf: buf[0..<Int(n)].map { UInt8(bitPattern: $0) })
}
}
flush()
if dmc_vt_changed(vt) != 0 { screenVersion += 1 }
}
private func flush() {
while fd >= 0 && !pending.isEmpty {
let w = pending.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
if w > 0 {
pending.removeFirst(w)
continue
}
if w < 0 && errno == EINTR { continue }
if w < 0 && errno == EAGAIN {
if writer == nil {
let s = DispatchSource.makeWriteSource(fileDescriptor: fd, queue: .main)
s.setEventHandler { [weak self] in
self?.writer?.cancel()
self?.writer = nil
self?.flush()
}
s.resume()
writer = s
}
return
}
return
}
}
/// the screen's size, told to the far end as it changes
private func tick() {
urgent()
let c = Int(dmc_vt_cols(vt)), r = Int(dmc_vt_rows(vt))
if c != cols || r != rows {
cols = c
rows = r
if let net {
dmc_net_resize(net, Int32(c), Int32(r))
} else if fd >= 0 {
dm_pty_resize(fd, Int32(c), Int32(r))
}
}
pump()
}
private func show(_ s: String) {
let b = Array(s.utf8).map { CChar(bitPattern: $0) }
dmc_vt_feed(vt, b, Int32(b.count))
screenVersion += 1
}
private func ended(_ why: String?) {
guard running else { return }
running = false
gen += 1
timer?.invalidate()
timer = nil
source?.cancel()
source = nil
writer?.cancel()
writer = nil
exitSource?.cancel()
exitSource = nil
if pid > 0 {
kill(pid, SIGHUP)
let p = pid
DispatchQueue.global().async { var st: Int32 = 0; waitpid(p, &st, 0) }
pid = 0
}
if fd >= 0 {
close(fd)
fd = -1
}
if let net { dmc_net_free(net) }
net = nil
pending.removeAll()
show("\r\n\u{1b}[0m[\(why ?? "Disconnected")]\r\n")
status = why ?? "Disconnected"
}
}
struct RemotePage: View {
@ObservedObject var session: RemoteSession
var body: some View {
VStack(spacing: 0) {
HStack {
Picker("", selection: $session.proto) {
ForEach(RemoteSession.Proto.allCases) { Text($0.rawValue).tag($0) }
}
.labelsHidden()
.frame(width: 100)
.disabled(session.running)
TextField("Server", text: $session.host)
.onSubmit { session.connect() }
.disabled(session.running)
TextField(String(session.proto.defaultPort), text: $session.port)
.frame(width: 60)
.help("Port (empty: the protocol's)")
.disabled(session.running)
TextField("User", text: $session.user)
.frame(width: 120)
.disabled(session.running)
if session.running {
Button("Disconnect", role: .destructive) { session.stop() }
} else {
Button("Connect") { session.connect() }
.keyboardShortcut(.defaultAction)
}
}
.padding(8)
TerminalView(host: session, version: session.screenVersion)
HStack {
Text(session.status).foregroundStyle(.secondary)
Spacer()
}
.padding(.horizontal, 8).padding(.vertical, 4)
}
}
}
+23 -13
View File
@@ -7,6 +7,16 @@
import AppKit
import SwiftUI
/// what a terminal view shows and where its keys go: the modem, or a
/// remote login (RemoteView.swift)
protocol TerminalHost: AnyObject {
var vt: OpaquePointer { get }
func type(_ text: String)
func key(_ k: Int)
}
extension Modem: TerminalHost {}
struct TerminalPane: View {
@EnvironmentObject var modem: Modem
@@ -22,29 +32,29 @@ struct TerminalPane: View {
}
.disabled(!modem.isIdle)
.padding(8)
TerminalView(modem: modem, version: modem.screenVersion)
TerminalView(host: modem, version: modem.screenVersion)
}
}
}
struct TerminalView: NSViewRepresentable {
let modem: Modem
let host: TerminalHost
let version: Int
func makeNSView(context: Context) -> TerminalNSView {
let v = TerminalNSView()
v.modem = modem
v.host = host
return v
}
func updateNSView(_ v: TerminalNSView, context: Context) {
v.modem = modem
v.host = host
v.needsDisplay = true
}
}
final class TerminalNSView: NSView {
weak var modem: Modem?
weak var host: TerminalHost?
private let font = NSFont(name: "Menlo", size: 13) ?? .monospacedSystemFont(ofSize: 13, weight: .regular)
private lazy var bold = NSFontManager.shared.convert(font, toHaveTrait: .boldFontMask)
private var cell = NSSize(width: 8, height: 16)
@@ -74,7 +84,7 @@ final class TerminalNSView: NSView {
override func setFrameSize(_ size: NSSize) {
super.setFrameSize(size)
guard let vt = modem?.vt else { return }
guard let vt = host?.vt else { return }
let cols = max(20, min(160, Int((size.width - 8) / cell.width)))
let rows = max(5, min(100, Int((size.height - 8) / cell.height)))
if cols != Int(dmc_vt_cols(vt)) || rows != Int(dmc_vt_rows(vt)) {
@@ -93,7 +103,7 @@ final class TerminalNSView: NSView {
override func draw(_ dirty: NSRect) {
Self.background.setFill()
bounds.fill()
guard let vt = modem?.vt else { return }
guard let vt = host?.vt else { return }
let rows = Int(dmc_vt_rows(vt)), cols = Int(dmc_vt_cols(vt))
scroll = min(scroll, Int(dmc_vt_history(vt)))
let ox: CGFloat = 4, oy: CGFloat = 4
@@ -151,7 +161,7 @@ final class TerminalNSView: NSView {
}
override func scrollWheel(with event: NSEvent) {
guard let vt = modem?.vt else { return }
guard let vt = host?.vt else { return }
let d = Int((event.scrollingDeltaY / (event.hasPreciseScrollingDeltas ? cell.height : 1)).rounded())
scroll = max(0, min(Int(dmc_vt_history(vt)), scroll + d))
needsDisplay = true
@@ -160,7 +170,7 @@ final class TerminalNSView: NSView {
// MARK: - keys
override func keyDown(with event: NSEvent) {
guard let modem else { return }
guard let host else { return }
scroll = 0
let mods = event.modifierFlags
if mods.contains(.command) {
@@ -168,7 +178,7 @@ final class TerminalNSView: NSView {
return
}
if let k = special(event) {
modem.key(k)
host.key(k)
return
}
guard var s = event.characters, !s.isEmpty else { return }
@@ -176,7 +186,7 @@ final class TerminalNSView: NSView {
if mods.contains(.option), let plain = event.charactersIgnoringModifiers {
s = "\u{1b}" + plain
}
modem.type(s)
host.type(s)
}
private func special(_ e: NSEvent) -> Int? {
@@ -207,8 +217,8 @@ final class TerminalNSView: NSView {
@objc func paste(_ sender: Any?) {
guard let s = NSPasteboard.general.string(forType: .string) else { return }
// lines end in CR, as the modem takes them
modem?.type(s.replacingOccurrences(of: "\r\n", with: "\r")
// lines end in CR, as a terminal sends them
host?.type(s.replacingOccurrences(of: "\r\n", with: "\r")
.replacingOccurrences(of: "\n", with: "\r"))
}
+2
View File
@@ -11,6 +11,8 @@ add_executable(dmodem WIN32
src/config.cpp
src/voice.cpp
src/audio.cpp
src/termview.cpp
src/remote.cpp
res/app.rc)
target_include_directories(dmodem PRIVATE src)
target_link_libraries(dmodem PRIVATE dmodemctl comctl32 wsock32 comdlg32 gdi32 winmm msacm32)
+24 -1
View File
@@ -76,7 +76,7 @@ typedef void (*ResponseFn)(const dmc_event *ev, void *data);
struct App {
HINSTANCE inst;
HWND main, tabs;
HWND pages[6];
HWND pages[7];
HFONT font, bold_font, big_font, mono_font;
Config cfg;
dmc_session *s;
@@ -104,6 +104,8 @@ void link_wait(int tag, ResponseFn fn, void *data);
#define WM_APP_SOCKET (WM_APP + 1)
#define TIMER_PUMP 1
#define TIMER_VOICE 2
#define WM_APP_REMOTE (WM_APP + 2)
#define TIMER_REMOTE 3
/* main.cpp */
void app_log(const char *line);
@@ -134,6 +136,27 @@ void term_page_layout(HWND page, int w, int h);
void term_feed(const char *data, int n);
void term_state();
/* termview.cpp: a terminal control of its own screen (dmc_vt), whose
keys go to fn */
typedef void (*TermTypedFn)(const char *data, int n, void *ctx);
HWND termview_new(HWND parent, int id, TermTypedFn fn, void *ctx);
/* bytes from the far end */
void termview_feed(HWND w, const char *data, int n);
void termview_reset(HWND w);
void termview_size(HWND w, int *cols, int *rows);
/* what Backspace sends (DEL unless set) */
void termview_set_backspace(HWND w, char b);
/* remote.cpp: the Remote page, a login by SSH, Telnet or rlogin */
HWND remote_page_new(HWND parent);
void remote_page_layout(HWND page, int w, int h);
/* its socket's messages (WM_APP_REMOTE) and its timer (TIMER_REMOTE) */
void remote_socket(WPARAM w, LPARAM l);
void remote_tick();
/* the focus to its first control */
bool remote_focus();
void remote_stop();
/* settings.cpp: the Settings page */
HWND settings_page_new(HWND parent);
void settings_page_layout(HWND page, int w, int h);
+17 -5
View File
@@ -2,8 +2,9 @@
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* main.cpp - the main window: a tab for each page (Modem, Terminal,
* Settings, Call Stats, Log, as the macOS and Linux apps
* main.cpp - the main window: a tab for each page (Modem, Phone,
* Terminal, Remote, Settings, Call Stats, Log, as the macOS
* and Linux apps
* have them) and a status bar
*/
#include <stdio.h>
@@ -16,10 +17,11 @@ App app;
static HWND status_bar;
enum { PAGE_MODEM, PAGE_PHONE, PAGE_TERM, PAGE_SETTINGS, PAGE_STATS,
PAGE_LOG, PAGES };
enum { PAGE_MODEM, PAGE_PHONE, PAGE_TERM, PAGE_REMOTE, PAGE_SETTINGS,
PAGE_STATS, PAGE_LOG, PAGES };
static const char *const page_names[PAGES] = {
"Modem", "Phone", "Terminal", "Settings", "Call Stats", "Log"
"Modem", "Phone", "Terminal", "Remote", "Settings", "Call Stats",
"Log"
};
HWND make_child(const char *cls, const char *text, DWORD style, HWND parent,
@@ -177,6 +179,8 @@ static void show_page(int i)
ShowWindow(app.pages[p], p == i ? SW_SHOW : SW_HIDE);
if (i == PAGE_TERM)
SetFocus(GetWindow(app.pages[i], GW_CHILD));
else if (i == PAGE_REMOTE)
remote_focus();
}
static void layout()
@@ -199,6 +203,7 @@ static void layout()
modem_page_layout(app.pages[PAGE_MODEM], w, h);
voice_page_layout(app.pages[PAGE_PHONE], w, h);
term_page_layout(app.pages[PAGE_TERM], w, h);
remote_page_layout(app.pages[PAGE_REMOTE], w, h);
settings_page_layout(app.pages[PAGE_SETTINGS], w, h);
stats_page_layout(app.pages[PAGE_STATS], w, h);
log_page_layout(app.pages[PAGE_LOG], w, h);
@@ -233,6 +238,7 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
app.pages[PAGE_MODEM] = modem_page_new(w);
app.pages[PAGE_PHONE] = voice_page_new(w);
app.pages[PAGE_TERM] = term_page_new(w);
app.pages[PAGE_REMOTE] = remote_page_new(w);
app.pages[PAGE_SETTINGS] = settings_page_new(w);
app.pages[PAGE_STATS] = stats_page_new(w);
app.pages[PAGE_LOG] = log_page_new(w);
@@ -284,14 +290,20 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
case WM_TIMER:
if (wp == TIMER_PUMP || wp == TIMER_VOICE)
link_pump();
else if (wp == TIMER_REMOTE)
remote_tick();
return 0;
case WM_APP_SOCKET:
link_socket(wp, lp);
return 0;
case WM_APP_REMOTE:
remote_socket(wp, lp);
return 0;
case WM_DESTROY:
KillTimer(w, TIMER_PUMP);
KillTimer(w, TIMER_VOICE);
audio_stop();
remote_stop();
if (link_running())
link_stop();
PostQuitMessage(0);
+627
View File
@@ -0,0 +1,627 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* remote.cpp - the Remote page: a login to a server by SSH, Telnet or
* rlogin, in a terminal of its own (termview.cpp)
*
* Telnet and rlogin: a Winsock 1.1 socket (WSAAsyncSelect, as the
* modem's link), the protocol libdmodemctl's dmc_net; every Windows from
* 95 on has them. SSH: Windows' own OpenSSH client, ssh.exe, in a
* pseudo console (ConPTY), so it needs Windows 10 1809 or later with
* the OpenSSH client feature; the ConPTY calls are looked up at run
* time, so that the app still starts on Windows 95. Its output is read
* from a timer (PeekNamedPipe), with no threads.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "app.h"
#include "resource.h"
static HWND page, view, proto_box, host_ed, port_ed, user_ed, go_btn,
status_txt;
/* the protocols in the list's order */
static const int protos[] = { DMC_NET_SSH, DMC_NET_TELNET, DMC_NET_RLOGIN };
#define NPROTOS 3
/* what runs: its protocol (0: none) */
static int running;
static int cols, rows;
/* Telnet, rlogin */
static SOCKET sock = INVALID_SOCKET;
static dmc_net *net;
static bool sock_open;
static char *pending;
static int pending_n, pending_cap;
/* SSH: the pseudo console, its pipes, ssh.exe */
static void *hpc;
static HANDLE con_in = INVALID_HANDLE_VALUE, con_out = INVALID_HANDLE_VALUE;
static HANDLE proc;
/*
* ConPTY, looked up at run time (Windows 10 1809 and later)
*/
#ifndef EXTENDED_STARTUPINFO_PRESENT
#define EXTENDED_STARTUPINFO_PRESENT 0x00080000
#endif
#define ATTR_PSEUDOCONSOLE 0x00020016
typedef long (WINAPI *CreatePCFn)(COORD, HANDLE, HANDLE, DWORD, void **);
typedef long (WINAPI *ResizePCFn)(void *, COORD);
typedef void (WINAPI *ClosePCFn)(void *);
typedef BOOL (WINAPI *InitAttrsFn)(void *, DWORD, DWORD, size_t *);
typedef BOOL (WINAPI *UpdateAttrFn)(void *, DWORD, size_t, void *, size_t,
void *, size_t *);
typedef void (WINAPI *DeleteAttrsFn)(void *);
static CreatePCFn create_pc;
static ResizePCFn resize_pc;
static ClosePCFn close_pc;
static InitAttrsFn init_attrs;
static UpdateAttrFn update_attr;
static DeleteAttrsFn delete_attrs;
/* STARTUPINFOEX, for headers without it */
struct StartupInfoEx {
STARTUPINFOA si;
void *attrs;
};
/* (through a plain function pointer: the cast that compilers take) */
#define LOOKUP(k, name) (void (*)(void))GetProcAddress(k, name)
static bool conpty_available()
{
HMODULE k = GetModuleHandle("kernel32.dll");
if (!k)
return false;
create_pc = (CreatePCFn)LOOKUP(k, "CreatePseudoConsole");
resize_pc = (ResizePCFn)LOOKUP(k, "ResizePseudoConsole");
close_pc = (ClosePCFn)LOOKUP(k, "ClosePseudoConsole");
init_attrs = (InitAttrsFn)LOOKUP(k, "InitializeProcThreadAttributeList");
update_attr = (UpdateAttrFn)LOOKUP(k, "UpdateProcThreadAttribute");
delete_attrs = (DeleteAttrsFn)LOOKUP(k, "DeleteProcThreadAttributeList");
return create_pc && resize_pc && close_pc && init_attrs &&
update_attr && delete_attrs;
}
static bool exists(const char *p)
{
DWORD a = GetFileAttributes(p);
return a != 0xFFFFFFFF && !(a & FILE_ATTRIBUTE_DIRECTORY);
}
/* ssh.exe: on the PATH, or Windows' own (Sysnative: the 64-bit System32
seen from this 32-bit app) */
static bool find_ssh(char *out, int n)
{
char *part;
if (SearchPath(NULL, "ssh.exe", NULL, (DWORD)n, out, &part))
return true;
char root[MAX_PATH];
if (!GetEnvironmentVariable("SystemRoot", root, sizeof(root)))
return false;
static const char *const dirs[] = { "Sysnative", "System32" };
for (int i = 0; i < 2; i++) {
_snprintf(out, n, "%s\\%s\\OpenSSH\\ssh.exe", root, dirs[i]);
out[n - 1] = '\0';
if (exists(out))
return true;
}
return false;
}
/*
* the page
*/
static void set_status(const char *s)
{
char a[300];
to_ansi(s, a, sizeof(a));
SetWindowText(status_txt, a);
}
static void controls()
{
bool idle = !running;
EnableWindow(proto_box, idle);
EnableWindow(host_ed, idle);
EnableWindow(port_ed, idle);
EnableWindow(user_ed, idle);
SetWindowText(go_btn, idle ? "&Connect" : "&Disconnect");
}
static void show(const char *s, int n)
{
termview_feed(view, s, n);
}
static void show_line(const char *s)
{
show(s, (int)strlen(s));
}
static void ended(const char *why)
{
if (!running)
return;
running = 0;
KillTimer(app.main, TIMER_REMOTE);
if (sock != INVALID_SOCKET) {
WSAAsyncSelect(sock, app.main, 0, 0);
closesocket(sock);
sock = INVALID_SOCKET;
}
sock_open = false;
if (net) {
dmc_net_free(net);
net = NULL;
}
pending_n = 0;
if (proc) {
TerminateProcess(proc, 0);
CloseHandle(proc);
proc = NULL;
}
/* (our end of its output shut first, so that closing the console
can't wait on a full pipe) */
if (con_out != INVALID_HANDLE_VALUE) {
CloseHandle(con_out);
con_out = INVALID_HANDLE_VALUE;
}
if (hpc) {
close_pc(hpc);
hpc = NULL;
}
if (con_in != INVALID_HANDLE_VALUE) {
CloseHandle(con_in);
con_in = INVALID_HANDLE_VALUE;
}
char line[300];
_snprintf(line, sizeof(line), "\r\n\x1b[0m[%s]\r\n",
why ? why : "Disconnected");
line[sizeof(line) - 1] = '\0';
show_line(line);
set_status(why ? why : "Disconnected");
controls();
}
/* Telnet and rlogin: the protocol's output written, as much as goes */
static void flush()
{
char buf[2048];
int n;
while (net && (n = dmc_net_output(net, buf, sizeof(buf))) > 0) {
if (pending_n + n > pending_cap) {
pending_cap = (pending_n + n) * 2;
pending = (char *)realloc(pending, (size_t)pending_cap);
}
memcpy(pending + pending_n, buf, (size_t)n);
pending_n += n;
}
while (sock_open && pending_n > 0) {
int w = send(sock, pending, pending_n, 0);
if (w == SOCKET_ERROR) {
if (WSAGetLastError() == WSAEWOULDBLOCK)
return; /* FD_WRITE: more */
ended("The connection failed");
return;
}
memmove(pending, pending + w, (size_t)(pending_n - w));
pending_n -= w;
}
}
static void pump()
{
char buf[4096];
int n;
while (net && (n = dmc_net_screen(net, buf, sizeof(buf))) > 0)
show(buf, n);
flush();
}
/* what the terminal gives: to the far end */
static void typed(const char *data, int n, void *ctx)
{
(void)ctx;
if (!running)
return;
if (net && sock_open) {
dmc_net_type(net, data, n);
flush();
} else if (con_in != INVALID_HANDLE_VALUE) {
DWORD w;
WriteFile(con_in, data, (DWORD)n, &w, NULL);
}
}
void remote_socket(WPARAM wp, LPARAM lp)
{
if ((SOCKET)wp != sock || !net)
return;
int err = WSAGETSELECTERROR(lp);
switch (WSAGETSELECTEVENT(lp)) {
case FD_CONNECT:
if (err) {
char m[160];
_snprintf(m, sizeof(m), "Could not connect (error %d)", err);
m[sizeof(m) - 1] = '\0';
ended(m);
return;
}
sock_open = true;
set_status("Connected");
dmc_net_connected(net);
pump();
break;
case FD_OOB: {
char b;
if (recv(sock, &b, 1, MSG_OOB) == 1)
dmc_net_urgent(net, (unsigned char)b);
pump();
break;
}
case FD_READ: {
char buf[4096];
int n = recv(sock, buf, sizeof(buf), 0);
if (n > 0)
dmc_net_feed(net, buf, n);
pump();
break;
}
case FD_WRITE:
flush();
break;
case FD_CLOSE: {
char buf[4096];
int n;
while ((n = recv(sock, buf, sizeof(buf), 0)) > 0)
dmc_net_feed(net, buf, n);
pump();
ended("Connection closed by the server");
break;
}
}
}
/* the timer: ssh's output, its end, and the terminal's size */
void remote_tick()
{
if (!running)
return;
int c, r;
termview_size(view, &c, &r);
if (c != cols || r != rows) {
cols = c;
rows = r;
if (net) {
dmc_net_resize(net, c, r);
flush();
} else if (hpc) {
COORD sz;
sz.X = (SHORT)c;
sz.Y = (SHORT)r;
resize_pc(hpc, sz);
}
}
if (con_out == INVALID_HANDLE_VALUE)
return;
for (;;) {
DWORD avail = 0;
if (!PeekNamedPipe(con_out, NULL, 0, NULL, &avail, NULL) ||
!avail)
break;
char buf[4096];
DWORD n = 0;
if (!ReadFile(con_out, buf, avail < sizeof(buf) ? avail :
sizeof(buf), &n, NULL) || !n)
break;
show(buf, (int)n);
}
if (proc && WaitForSingleObject(proc, 0) == WAIT_OBJECT_0) {
DWORD code = 0;
GetExitCodeProcess(proc, &code);
char m[80];
if (code)
_snprintf(m, sizeof(m), "ssh exited with status %lu",
(unsigned long)code);
else
_snprintf(m, sizeof(m), "Connection closed");
m[sizeof(m) - 1] = '\0';
ended(m);
}
}
static bool start_ssh(const char *host, int port, const char *user)
{
if (!conpty_available()) {
app_message("SSH needs Windows 10 (1809) or later, with "
"OpenSSH's client");
return false;
}
char ssh[MAX_PATH];
if (!find_ssh(ssh, sizeof(ssh))) {
app_message("ssh.exe was not found: add Windows' OpenSSH "
"Client (Settings, Optional features)");
return false;
}
HANDLE in_r, in_w, out_r, out_w;
if (!CreatePipe(&in_r, &in_w, NULL, 0))
return false;
if (!CreatePipe(&out_r, &out_w, NULL, 0)) {
CloseHandle(in_r);
CloseHandle(in_w);
return false;
}
COORD sz;
sz.X = (SHORT)cols;
sz.Y = (SHORT)rows;
if (create_pc(sz, in_r, out_w, 0, &hpc) < 0) {
hpc = NULL;
CloseHandle(in_r);
CloseHandle(in_w);
CloseHandle(out_r);
CloseHandle(out_w);
app_message("Could not make a console for ssh");
return false;
}
/* (the console has its own copies) */
CloseHandle(in_r);
CloseHandle(out_w);
con_in = in_w;
con_out = out_r;
size_t size = 0;
init_attrs(NULL, 1, 0, &size);
void *attrs = malloc(size);
StartupInfoEx si;
memset(&si, 0, sizeof(si));
si.si.cb = sizeof(si);
si.attrs = attrs;
bool ok = attrs && init_attrs(attrs, 1, 0, &size) &&
update_attr(attrs, 0, ATTR_PSEUDOCONSOLE, hpc, sizeof(hpc),
NULL, NULL);
char cmd[1024];
if (*user)
_snprintf(cmd, sizeof(cmd), "\"%s\" -p %d -l \"%s\" -- \"%s\"",
ssh, port, user, host);
else
_snprintf(cmd, sizeof(cmd), "\"%s\" -p %d -- \"%s\"", ssh, port,
host);
cmd[sizeof(cmd) - 1] = '\0';
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
SetEnvironmentVariable("TERM", "xterm");
if (ok)
ok = CreateProcess(NULL, cmd, NULL, NULL, FALSE,
EXTENDED_STARTUPINFO_PRESENT, NULL, NULL,
(STARTUPINFOA *)&si, &pi) != 0;
if (attrs) {
delete_attrs(attrs);
free(attrs);
}
if (!ok) {
running = DMC_NET_SSH; /* (for ended() to tidy up) */
ended("Could not start ssh.exe");
return false;
}
CloseHandle(pi.hThread);
proc = pi.hProcess;
return true;
}
static bool start_socket(int proto, const char *host, int port,
const char *user)
{
sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons((u_short)port);
sa.sin_addr.s_addr = inet_addr(host);
if (sa.sin_addr.s_addr == INADDR_NONE) {
hostent *h = gethostbyname(host);
if (!h) {
app_message("That server's name was not found");
return false;
}
memcpy(&sa.sin_addr, h->h_addr, sizeof(sa.sin_addr));
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
return false;
net = dmc_net_new(proto, user, "ansi", cols, rows);
sock_open = false;
WSAAsyncSelect(sock, app.main, WM_APP_REMOTE,
FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE | FD_OOB);
connect(sock, (sockaddr *)&sa, sizeof(sa));
return true;
}
static int chosen_proto()
{
int i = (int)SendMessage(proto_box, CB_GETCURSEL, 0, 0);
return i >= 0 && i < NPROTOS ? protos[i] : DMC_NET_SSH;
}
static void ini(char *out, int n)
{
char dir[MAX_PATH];
app_data_dir(dir, sizeof(dir));
_snprintf(out, n, "%s\\dmodem.ini", dir);
out[n - 1] = '\0';
}
static void connect_clicked()
{
if (running) {
ended(NULL);
return;
}
char host[256], user[128], pt[16];
GetWindowText(host_ed, host, sizeof(host));
GetWindowText(user_ed, user, sizeof(user));
GetWindowText(port_ed, pt, sizeof(pt));
int proto = chosen_proto();
int port = pt[0] ? atoi(pt) : dmc_net_default_port(proto);
if (!host[0]) {
app_message("Enter the server to connect to");
return;
}
if (strpbrk(host, " \"") || strchr(user, '"')) {
app_message("The server's name has no spaces or quotes");
return;
}
if (port <= 0 || port > 65535) {
app_message("The port is a number from 1 to 65535");
return;
}
if (proto == DMC_NET_RLOGIN && !user[0]) {
app_message("rlogin needs a user name");
return;
}
/* kept for next time */
char path[MAX_PATH];
ini(path, sizeof(path));
WritePrivateProfileString("remote", "protocol", dmc_net_name(proto), path);
WritePrivateProfileString("remote", "host", host, path);
WritePrivateProfileString("remote", "port", pt, path);
WritePrivateProfileString("remote", "user", user, path);
termview_reset(view);
termview_size(view, &cols, &rows);
char what[400];
_snprintf(what, sizeof(what), "Connecting to %s port %d by %s", host,
port, dmc_net_name(proto));
what[sizeof(what) - 1] = '\0';
set_status(what);
char line[420];
_snprintf(line, sizeof(line), "[%s]\r\n", what);
line[sizeof(line) - 1] = '\0';
show_line(line);
bool ok = proto == DMC_NET_SSH ? start_ssh(host, port, user) :
start_socket(proto, host, port, user);
if (!ok) {
set_status("Not connected");
return;
}
if (proto == DMC_NET_SSH)
set_status("Connected by SSH");
running = proto;
SetTimer(app.main, TIMER_REMOTE, 30, NULL);
controls();
SetFocus(view);
}
static void proto_changed()
{
char p[16];
_snprintf(p, sizeof(p), "%d", dmc_net_default_port(chosen_proto()));
p[sizeof(p) - 1] = '\0';
/* (the default shown when the port is left empty) */
char cur[16];
GetWindowText(port_ed, cur, sizeof(cur));
if (!cur[0] || !strcmp(cur, "22") || !strcmp(cur, "23") ||
!strcmp(cur, "513"))
SetWindowText(port_ed, p);
}
static void remote_command(HWND p, int id, int code)
{
(void)p;
switch (id) {
case IDC_R_GO:
connect_clicked();
break;
case IDC_R_PROTO:
if (code == CBN_SELCHANGE)
proto_changed();
break;
}
}
HWND remote_page_new(HWND parent)
{
page = page_new(parent, remote_command);
proto_box = make_child("COMBOBOX", "", WS_TABSTOP | CBS_DROPDOWNLIST |
WS_VSCROLL, page, IDC_R_PROTO);
for (int i = 0; i < NPROTOS; i++)
SendMessage(proto_box, CB_ADDSTRING, 0,
(LPARAM)dmc_net_name(protos[i]));
make_child("STATIC", "&Server:", SS_RIGHT, page, IDC_R_HOSTLABEL);
host_ed = make_child("EDIT", "", WS_TABSTOP | ES_AUTOHSCROLL, page,
IDC_R_HOST, WS_EX_CLIENTEDGE);
make_child("STATIC", "&Port:", SS_RIGHT, page, IDC_R_PORTLABEL);
port_ed = make_child("EDIT", "", WS_TABSTOP | ES_NUMBER, page,
IDC_R_PORT, WS_EX_CLIENTEDGE);
make_child("STATIC", "&User:", SS_RIGHT, page, IDC_R_USERLABEL);
user_ed = make_child("EDIT", "", WS_TABSTOP | ES_AUTOHSCROLL, page,
IDC_R_USER, WS_EX_CLIENTEDGE);
go_btn = make_child("BUTTON", "&Connect", WS_TABSTOP | BS_DEFPUSHBUTTON,
page, IDC_R_GO);
view = termview_new(page, IDC_R_TERM, typed, NULL);
status_txt = make_child("STATIC", "Not connected", SS_LEFTNOWORDWRAP,
page, IDC_R_STATUS);
/* what was used last */
char path[MAX_PATH], v[256];
ini(path, sizeof(path));
GetPrivateProfileString("remote", "protocol", "SSH", v, sizeof(v), path);
int sel = 0;
for (int i = 0; i < NPROTOS; i++)
if (!lstrcmpi(v, dmc_net_name(protos[i])))
sel = i;
SendMessage(proto_box, CB_SETCURSEL, (WPARAM)sel, 0);
GetPrivateProfileString("remote", "host", "", v, sizeof(v), path);
SetWindowText(host_ed, v);
GetPrivateProfileString("remote", "port", "", v, sizeof(v), path);
SetWindowText(port_ed, v);
GetPrivateProfileString("remote", "user", "", v, sizeof(v), path);
SetWindowText(user_ed, v);
proto_changed();
controls();
return page;
}
void remote_page_layout(HWND p, int w, int h)
{
int m = 8, bh = 24, x = m;
MoveWindow(proto_box, x, m, 80, 200, TRUE);
x += 88;
MoveWindow(GetDlgItem(p, IDC_R_HOSTLABEL), x, m + 4, 44, bh, TRUE);
x += 48;
int hw = w - x - 44 - 52 - 40 - 96 - 90 - 4 * m;
if (hw < 80)
hw = 80;
MoveWindow(host_ed, x, m, hw, bh, TRUE);
x += hw + m;
MoveWindow(GetDlgItem(p, IDC_R_PORTLABEL), x, m + 4, 32, bh, TRUE);
x += 36;
MoveWindow(port_ed, x, m, 52, bh, TRUE);
x += 52 + m;
MoveWindow(GetDlgItem(p, IDC_R_USERLABEL), x, m + 4, 36, bh, TRUE);
x += 40;
MoveWindow(user_ed, x, m, 96, bh, TRUE);
MoveWindow(go_btn, w - m - 90, m, 90, bh, TRUE);
MoveWindow(view, m, 2 * m + bh, w - 2 * m, h - 4 * m - 2 * bh + 6, TRUE);
MoveWindow(status_txt, m, h - m - bh + 6, w - 2 * m, bh - 6, TRUE);
}
bool remote_focus()
{
SetFocus(running ? view : host_ed);
return true;
}
void remote_stop()
{
if (running)
ended(NULL);
}
+12
View File
@@ -39,6 +39,18 @@
#define IDC_SETUP_CT 502
#define IDC_CLEAR 503
/* the Remote page */
#define IDC_R_PROTO 1100
#define IDC_R_HOSTLABEL 1101
#define IDC_R_HOST 1102
#define IDC_R_PORTLABEL 1103
#define IDC_R_PORT 1104
#define IDC_R_USERLABEL 1105
#define IDC_R_USER 1106
#define IDC_R_GO 1107
#define IDC_R_TERM 1108
#define IDC_R_STATUS 1109
/* the Settings page */
#define IDC_GROUPS 600
#define IDC_SETTINGS 601
+422
View File
@@ -0,0 +1,422 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 D-Modem Authors
*
* termview.cpp - a terminal control: a screen of libdmodemctl's dmc_vt,
* drawn with GDI, its keys handed to whoever owns it.
* The Remote page's terminal; each control has a screen
* of its own, so that there can be more than one.
*
* The text is drawn with ExtTextOutW, which Windows 95 has. Keys are a
* VT100's; the right button pastes; Backspace is DEL unless the owner
* says otherwise.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "app.h"
struct TermView {
HWND w;
dmc_vt *vt;
int cw, ch; /* a cell's size */
int scroll; /* 0 the screen, -n back in history */
bool focused;
char backspace;
TermTypedFn fn;
void *ctx;
};
static const COLORREF BG = RGB(0x0a, 0x0f, 0x1c), FG = RGB(0xe8, 0xf0, 0xff);
static TermView *of(HWND w)
{
return (TermView *)GetWindowLongPtr(w, GWLP_USERDATA);
}
static COLORREF colour(int c, COLORREF def)
{
if (c < 0)
return def;
unsigned long v = dmc_vt_palette(c);
return RGB((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF);
}
static void update_scrollbar(TermView *t)
{
SCROLLINFO si;
memset(&si, 0, sizeof(si));
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
si.nMin = 0;
si.nMax = dmc_vt_history(t->vt) + dmc_vt_rows(t->vt) - 1;
si.nPage = dmc_vt_rows(t->vt);
si.nPos = dmc_vt_history(t->vt) + t->scroll;
SetScrollInfo(t->w, SB_VERT, &si, TRUE);
}
static void place_caret(TermView *t)
{
if (!t->focused)
return;
if (t->scroll == 0 && dmc_vt_cursor_visible(t->vt)) {
SetCaretPos(dmc_vt_cursor_col(t->vt) * t->cw,
dmc_vt_cursor_row(t->vt) * t->ch + t->ch - 2);
ShowCaret(t->w);
} else {
HideCaret(t->w);
}
}
static void paint(TermView *t, HDC dc, RECT *area)
{
RECT r;
GetClientRect(t->w, &r);
HDC mem = CreateCompatibleDC(dc);
HBITMAP bmp = CreateCompatibleBitmap(dc, r.right, r.bottom);
HGDIOBJ oldb = SelectObject(mem, bmp);
HGDIOBJ oldf = SelectObject(mem, app.mono_font);
HBRUSH bg = CreateSolidBrush(BG);
FillRect(mem, &r, bg);
DeleteObject(bg);
dmc_vt *vt = t->vt;
int rows = dmc_vt_rows(vt), cols = dmc_vt_cols(vt);
int cw = t->cw, ch = t->ch;
WCHAR text[512];
INT dx[512];
for (int y = 0; y < rows; y++) {
int row = y + t->scroll;
int x = 0;
while (x < cols) {
int fg = dmc_vt_fg(vt, row, x), bgc = dmc_vt_bg(vt, row, x);
int at = dmc_vt_attr(vt, row, x);
int n = 0;
while (x + n < cols && n < 511 &&
dmc_vt_fg(vt, row, x + n) == fg &&
dmc_vt_bg(vt, row, x + n) == bgc &&
dmc_vt_attr(vt, row, x + n) == at) {
unsigned long c = dmc_vt_char(vt, row, x + n);
text[n] = c < 0x10000 ? (WCHAR)c : (WCHAR)'?';
dx[n] = cw;
n++;
}
int f = fg >= 0 && fg < 8 && (at & DMC_BOLD) ? fg + 8 : fg;
COLORREF fc = colour(f, FG), bc = colour(bgc, BG);
if (at & DMC_REVERSE) {
COLORREF s = fc;
fc = bc;
bc = s;
}
SetTextColor(mem, fc);
SetBkColor(mem, bc);
RECT cell = { x * cw, y * ch, (x + n) * cw, (y + 1) * ch };
ExtTextOutW(mem, x * cw, y * ch, ETO_OPAQUE | ETO_CLIPPED,
&cell, text, n, dx);
if (at & DMC_UNDERLINE) {
RECT u = { x * cw, (y + 1) * ch - 1, (x + n) * cw,
(y + 1) * ch };
HBRUSH b = CreateSolidBrush(fc);
FillRect(mem, &u, b);
DeleteObject(b);
}
x += n;
}
}
BitBlt(dc, area->left, area->top, area->right - area->left,
area->bottom - area->top, mem, area->left, area->top, SRCCOPY);
SelectObject(mem, oldf);
SelectObject(mem, oldb);
DeleteObject(bmp);
DeleteDC(mem);
}
static void measure(TermView *t)
{
HDC dc = GetDC(t->w);
HGDIOBJ old = SelectObject(dc, app.mono_font);
TEXTMETRIC tm;
GetTextMetrics(dc, &tm);
t->cw = tm.tmAveCharWidth > 0 ? tm.tmAveCharWidth : 8;
t->ch = tm.tmHeight > 0 ? tm.tmHeight : 16;
SelectObject(dc, old);
ReleaseDC(t->w, dc);
}
static void send_text(TermView *t, const char *s, int n)
{
if (t->fn && n > 0)
t->fn(s, n, t->ctx);
}
/* a character the keyboard gave, in the ANSI code page, as UTF-8 */
static void send_char(TermView *t, unsigned char c)
{
if (c == 0x08)
c = (unsigned char)t->backspace;
if (c < 0x80) {
char b = (char)c;
send_text(t, &b, 1);
return;
}
WCHAR w;
char mb = (char)c;
if (MultiByteToWideChar(CP_ACP, 0, &mb, 1, &w, 1) != 1)
return;
char o[4];
send_text(t, o, utf8_encode(w, o));
}
static void paste(TermView *t)
{
if (!OpenClipboard(t->w))
return;
HANDLE h = GetClipboardData(CF_TEXT);
if (h) {
const char *s = (const char *)GlobalLock(h);
if (s) {
for (const char *p = s; *p; p++) {
if (*p == '\n' && p > s && p[-1] == '\r')
continue;
send_char(t, *p == '\n' ? '\r' : (unsigned char)*p);
}
GlobalUnlock(h);
}
}
CloseClipboard();
}
static void to_bottom(TermView *t)
{
if (t->scroll) {
t->scroll = 0;
update_scrollbar(t);
InvalidateRect(t->w, NULL, FALSE);
}
}
static void send_key(TermView *t, int key)
{
char b[16];
int n = dmc_vt_key(t->vt, key, b, sizeof(b));
to_bottom(t);
send_text(t, b, n);
}
static LRESULT CALLBACK view_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
{
TermView *t = of(w);
if (!t)
return DefWindowProc(w, m, wp, lp);
switch (m) {
case WM_GETDLGCODE:
return DLGC_WANTALLKEYS | DLGC_WANTARROWS | DLGC_WANTCHARS |
DLGC_WANTTAB;
case WM_SETFOCUS:
t->focused = true;
CreateCaret(w, NULL, t->cw, 2);
place_caret(t);
return 0;
case WM_KILLFOCUS:
t->focused = false;
DestroyCaret();
return 0;
case WM_LBUTTONDOWN:
SetFocus(w);
return 0;
case WM_RBUTTONUP:
paste(t);
return 0;
case WM_ERASEBKGND:
return 1;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC dc = BeginPaint(w, &ps);
paint(t, dc, &ps.rcPaint);
EndPaint(w, &ps);
return 0;
}
case WM_SIZE: {
int cols = LOWORD(lp) / t->cw, rows = HIWORD(lp) / t->ch;
if (cols < 20)
cols = 20;
if (rows < 5)
rows = 5;
if (cols > 200)
cols = 200;
if (rows > 80)
rows = 80;
dmc_vt_resize(t->vt, cols, rows);
update_scrollbar(t);
InvalidateRect(w, NULL, FALSE);
return 0;
}
case WM_VSCROLL: {
int hist = dmc_vt_history(t->vt), pos = hist + t->scroll;
switch (LOWORD(wp)) {
case SB_LINEUP: pos--; break;
case SB_LINEDOWN: pos++; break;
case SB_PAGEUP: pos -= dmc_vt_rows(t->vt); break;
case SB_PAGEDOWN: pos += dmc_vt_rows(t->vt); break;
case SB_THUMBTRACK:
case SB_THUMBPOSITION: pos = HIWORD(wp); break;
case SB_TOP: pos = 0; break;
case SB_BOTTOM: pos = hist; break;
}
if (pos < 0)
pos = 0;
if (pos > hist)
pos = hist;
t->scroll = pos - hist;
update_scrollbar(t);
place_caret(t);
InvalidateRect(w, NULL, FALSE);
return 0;
}
case WM_KEYDOWN: {
int key = 0;
bool shift = GetKeyState(VK_SHIFT) < 0;
switch (wp) {
case VK_UP: key = DMC_KEY_UP; break;
case VK_DOWN: key = DMC_KEY_DOWN; break;
case VK_LEFT: key = DMC_KEY_LEFT; break;
case VK_RIGHT: key = DMC_KEY_RIGHT; break;
case VK_HOME: key = DMC_KEY_HOME; break;
case VK_END: key = DMC_KEY_END; break;
case VK_PRIOR:
if (shift) {
SendMessage(w, WM_VSCROLL, SB_PAGEUP, 0);
return 0;
}
key = DMC_KEY_PGUP;
break;
case VK_NEXT:
if (shift) {
SendMessage(w, WM_VSCROLL, SB_PAGEDOWN, 0);
return 0;
}
key = DMC_KEY_PGDN;
break;
case VK_INSERT:
if (shift) {
paste(t);
return 0;
}
key = DMC_KEY_INSERT;
break;
case VK_DELETE: key = DMC_KEY_DELETE; break;
case VK_TAB:
if (shift)
key = DMC_KEY_BACKTAB;
break;
default:
if (wp >= VK_F1 && wp <= VK_F10)
key = DMC_KEY_F1 + (int)(wp - VK_F1);
break;
}
if (!key)
break;
send_key(t, key);
return 0;
}
case WM_SYSKEYDOWN:
if (wp == VK_F10) {
send_key(t, DMC_KEY_F10);
return 0;
}
break;
case WM_SYSCHAR:
/* Alt and a letter: ESC and it */
if (wp >= 0x20 && wp < 0x7f) {
char b[2] = { 0x1b, (char)wp };
to_bottom(t);
send_text(t, b, 2);
return 0;
}
break;
case WM_CHAR:
if (wp == '\t' && GetKeyState(VK_SHIFT) < 0)
return 0;
to_bottom(t);
send_char(t, (unsigned char)wp);
return 0;
case WM_NCDESTROY:
SetWindowLongPtr(w, GWLP_USERDATA, 0);
dmc_vt_free(t->vt);
free(t);
return 0;
}
return DefWindowProc(w, m, wp, lp);
}
HWND termview_new(HWND parent, int id, TermTypedFn fn, void *ctx)
{
static bool registered;
if (!registered) {
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = view_proc;
wc.hInstance = app.inst;
wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
wc.lpszClassName = "DModemTermView";
RegisterClass(&wc);
registered = true;
}
TermView *t = (TermView *)calloc(1, sizeof(TermView));
t->vt = dmc_vt_new(80, 24, 2000);
t->cw = 8;
t->ch = 16;
t->backspace = 0x7f;
t->fn = fn;
t->ctx = ctx;
HWND w = make_child("DModemTermView", "", WS_TABSTOP | WS_VSCROLL,
parent, id, WS_EX_CLIENTEDGE);
t->w = w;
SetWindowLongPtr(w, GWLP_USERDATA, (LONG_PTR)t);
measure(t);
return w;
}
void termview_feed(HWND w, const char *data, int n)
{
TermView *t = of(w);
if (!t || n <= 0)
return;
int before = dmc_vt_history(t->vt);
dmc_vt_feed(t->vt, data, n);
if (t->scroll)
t->scroll -= dmc_vt_history(t->vt) - before;
char r[64];
int k;
while ((k = dmc_vt_reply(t->vt, r, sizeof(r))) > 0)
send_text(t, r, k);
update_scrollbar(t);
place_caret(t);
InvalidateRect(w, NULL, FALSE);
}
void termview_reset(HWND w)
{
TermView *t = of(w);
if (!t)
return;
dmc_vt_reset(t->vt);
t->scroll = 0;
update_scrollbar(t);
InvalidateRect(w, NULL, FALSE);
}
void termview_size(HWND w, int *cols, int *rows)
{
TermView *t = of(w);
*cols = t ? dmc_vt_cols(t->vt) : 80;
*rows = t ? dmc_vt_rows(t->vt) : 24;
}
void termview_set_backspace(HWND w, char b)
{
TermView *t = of(w);
if (t)
t->backspace = b;
}