Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b43ed62c50 | ||
|
|
08fb43aea1 | ||
|
|
db26d85be0 | ||
|
|
d61696ba18 | ||
|
|
82fd1227d9 | ||
|
|
11a023bf0b | ||
|
|
feb8e66d11 | ||
|
|
f62777b994 | ||
|
|
bbcc1548c1 | ||
|
|
8b350409e2 |
No files matched your search
@@ -0,0 +1,92 @@
|
||||
# Builds and tests the three apps and the library they share
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux (GTK 4)
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Packages
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
cmake ninja-build pkg-config libgtk-4-dev libadwaita-1-dev \
|
||||
libvte-2.91-gtk4-dev
|
||||
- name: Build
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
cmake --build build
|
||||
- name: Test
|
||||
run: ctest --test-dir build --output-on-failure
|
||||
- name: Test with the sanitizers
|
||||
run: |
|
||||
cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_C_FLAGS="-fsanitize=address,undefined -fno-sanitize-recover=all"
|
||||
cmake --build build-asan --target dmodemctl_test
|
||||
ctest --test-dir build-asan --output-on-failure
|
||||
|
||||
windows-9x:
|
||||
name: Windows 95 and later (Open Watcom)
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: open-watcom/setup-watcom@v0
|
||||
with:
|
||||
version: "2.0"
|
||||
- name: Build
|
||||
run: sh windows/build-watcom.sh build/watcom
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmodem-windows-9x
|
||||
path: build/watcom/dmodem.exe
|
||||
|
||||
windows:
|
||||
name: Windows (MSVC)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: |
|
||||
cmake -S . -B build -A Win32
|
||||
cmake --build build --config Release
|
||||
- name: Test
|
||||
run: ctest --test-dir build -C Release --output-on-failure
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmodem-windows
|
||||
path: build/windows/Release/dmodem.exe
|
||||
|
||||
macos:
|
||||
name: macOS (SwiftUI)
|
||||
runs-on: macos-15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Library tests
|
||||
run: |
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
cmake --build build
|
||||
ctest --test-dir build --output-on-failure
|
||||
- name: Project
|
||||
run: |
|
||||
brew install xcodegen
|
||||
cd macos && xcodegen
|
||||
- name: Build
|
||||
run: |
|
||||
cd macos
|
||||
xcodebuild -project DModem.xcodeproj -scheme DModem \
|
||||
-configuration Release -derivedDataPath ../build/xcode \
|
||||
CODE_SIGN_IDENTITY=- build
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmodem-macos
|
||||
path: build/xcode/Build/Products/Release/D-Modem.app
|
||||
@@ -0,0 +1,11 @@
|
||||
build/
|
||||
build-*/
|
||||
.vs/
|
||||
bin/
|
||||
obj/
|
||||
*.user
|
||||
.build/
|
||||
.swiftpm/
|
||||
*.xcodeproj/xcuserdata/
|
||||
DerivedData/
|
||||
.flatpak-builder/
|
||||
@@ -0,0 +1,32 @@
|
||||
# D-Modem's desktop apps: the shared C core (libdmodemctl), and the
|
||||
# Linux app (GTK 4 and libadwaita) when its libraries are there, or the
|
||||
# Windows app with MinGW or MSVC. The Windows 95 build of the Windows
|
||||
# app (windows/build-watcom.sh) and the macOS app (macos/) build with
|
||||
# their own tools and take the core from here.
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(dmodem-gui VERSION 1.0.0 LANGUAGES C)
|
||||
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||
|
||||
option(DMODEM_GUI_LINUX "Build the GTK 4 app (linux/)" ON)
|
||||
|
||||
add_subdirectory(core)
|
||||
enable_testing()
|
||||
add_subdirectory(core/test)
|
||||
|
||||
if(WIN32)
|
||||
add_subdirectory(windows)
|
||||
endif()
|
||||
|
||||
if(DMODEM_GUI_LINUX AND UNIX AND NOT APPLE)
|
||||
find_package(PkgConfig)
|
||||
if(PkgConfig_FOUND)
|
||||
pkg_check_modules(GTK IMPORTED_TARGET gtk4>=4.10 libadwaita-1>=1.5 vte-2.91-gtk4)
|
||||
endif()
|
||||
if(GTK_FOUND)
|
||||
add_subdirectory(linux)
|
||||
else()
|
||||
message(STATUS "gtk4, libadwaita-1 or vte-2.91-gtk4 not found: the Linux app is not built")
|
||||
endif()
|
||||
endif()
|
||||
@@ -1,3 +1,62 @@
|
||||
<img src=".github/banner.png" alt="D-Modem/gui: D-Modem on the desktop" width="100%">
|
||||
|
||||
# gui
|
||||
# D-Modem desktop apps
|
||||
|
||||
Native apps for D-Modem on Windows, macOS and Linux.
|
||||
|
||||
Each app starts dmodemd (or reaches one that already runs), and shows the
|
||||
modem as a desktop program should: dial and answer from a window, change
|
||||
its settings without AT commands, and see how the last call went. All three
|
||||
are thin native shells over one small C library, libdmodemctl, so they
|
||||
behave the same.
|
||||
|
||||
- **Modem**: the call's state, dial, answer and hang up, and the line it uses
|
||||
- **Terminal**: the AT console, and the modem's own setup screens (AT!CF, AT!CT)
|
||||
- **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
|
||||
- **Windows 95 and later**: plain Win32, built with Open Watcom; on Windows 9x it reaches a modem over TCP or a COM port
|
||||
|
||||
| | Windows | macOS | Linux |
|
||||
| --- | --- | --- | --- |
|
||||
| Toolkit | Win32, C++ | SwiftUI | GTK 4, libadwaita, VTE |
|
||||
| Runs on | Windows 95 and later | macOS 13 and later | GTK 4.10, libadwaita 1.5 and VTE 0.76 or later (Ubuntu 24.04, Fedora 40) |
|
||||
|
||||
<img src="docs/images/linux-settings.png" width="49%" alt="The Linux app's Settings page"> <img src="docs/images/windows-setup-screen.png" width="49%" alt="The Windows app's Terminal with the modem's setup screen">
|
||||
|
||||
## Quick start
|
||||
|
||||
Linux:
|
||||
|
||||
sudo apt install cmake libgtk-4-dev libadwaita-1-dev libvte-2.91-gtk4-dev
|
||||
cmake -S . -B build && cmake --build build && ./build/linux/dmodem-gui
|
||||
|
||||
Windows: `cmake -S . -B build -A Win32 && cmake --build build --config Release`,
|
||||
or for Windows 95 and later, `windows/build-watcom.sh` with Open Watcom 2.0.
|
||||
|
||||
macOS: `brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`.
|
||||
|
||||
The Settings page needs a dmodemd with AT!M (D-Modem's main branch since
|
||||
D-Modem/D-Modem#103); the other pages work with any D-Modem 1.0.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Design](docs/design.md): how the apps are built, what they share, and the Windows 9x notes
|
||||
- [libdmodemctl](core/include/dmodemctl.h): the library's API
|
||||
|
||||
## The D-Modem suite
|
||||
|
||||
| Repository | What it is |
|
||||
| --- | --- |
|
||||
| [D-Modem](https://github.com/D-Modem/D-Modem) | The open V.92 softmodem: dmodemd, libdmodem and the Asterisk, FreeSWITCH and ARI modules |
|
||||
| [app](https://github.com/D-Modem/app) | The D-Modem app for Android and iOS: a dial-up modem on a SIP call |
|
||||
| [gui](https://github.com/D-Modem/gui) | D-Modem on the desktop: native apps for Windows, macOS and Linux |
|
||||
| [hardware](https://github.com/D-Modem/hardware) | pico-serial: RP2040 serial adapters and phone-line USB sticks |
|
||||
| [menu](https://github.com/D-Modem/menu) | modemmenu: the login and menu dial-up callers reach |
|
||||
| [bbs](https://github.com/D-Modem/bbs) | A bulletin board for telnet, SSH, TN3270 and modem callers |
|
||||
| [go3270](https://github.com/D-Modem/go3270) | A Go library for 3270 terminal servers, used by bbs |
|
||||
| [brand](https://github.com/D-Modem/brand) | Logos, colours, type and the naming guide |
|
||||
|
||||
## Licence
|
||||
|
||||
BSD 3-Clause ([LICENSE](LICENSE)).
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="14 14 80 80">
|
||||
<!-- D-Modem's app icon (D-Modem/brand, tools/app_icon.py) on a desktop tile -->
|
||||
<rect x="16" y="16" width="76" height="76" rx="17" fill="#0a0f1c"/>
|
||||
<defs><linearGradient id="stripes" x1="0" y1="0" x2="0" y2="1"><stop offset="0.0000" stop-color="#ff4d5e"/><stop offset="0.1667" stop-color="#ff4d5e"/><stop offset="0.1667" stop-color="#ff8a3d"/><stop offset="0.3333" stop-color="#ff8a3d"/><stop offset="0.3333" stop-color="#ffd23d"/><stop offset="0.5000" stop-color="#ffd23d"/><stop offset="0.5000" stop-color="#3ddc84"/><stop offset="0.6667" stop-color="#3ddc84"/><stop offset="0.6667" stop-color="#3d8bff"/><stop offset="0.8333" stop-color="#3d8bff"/><stop offset="0.8333" stop-color="#a66bff"/><stop offset="1.0000" stop-color="#a66bff"/></linearGradient></defs><path d="M34,34 H74 V66 H62.0 V75.6 H46.0 V66 H34 Z" fill="none" stroke="url(#stripes)" stroke-width="3.4"/><path d="M39.0,50.0 L39.1,49.6 L39.2,49.2 L39.4,48.8 L39.5,48.4 L39.6,48.1 L39.8,47.7 L39.9,47.3 L40.0,47.0 L40.1,46.7 L40.2,46.3 L40.4,46.0 L40.5,45.8 L40.6,45.5 L40.8,45.2 L40.9,45.0 L41.0,44.8 L41.1,44.6 L41.2,44.5 L41.4,44.3 L41.5,44.2 L41.6,44.1 L41.8,44.1 L41.9,44.0 L42.0,44.0 L42.1,44.0 L42.2,44.1 L42.4,44.1 L42.5,44.2 L42.6,44.3 L42.8,44.5 L42.9,44.6 L43.0,44.8 L43.1,45.0 L43.2,45.2 L43.4,45.5 L43.5,45.8 L43.6,46.0 L43.8,46.3 L43.9,46.7 L44.0,47.0 L44.1,47.3 L44.2,47.7 L44.4,48.1 L44.5,48.4 L44.6,48.8 L44.8,49.2 L44.9,49.6 L45.0,50.0 L45.1,50.4 L45.2,50.8 L45.4,51.2 L45.5,51.6 L45.6,51.9 L45.8,52.3 L45.9,52.7 L46.0,53.0 L46.1,53.3 L46.2,53.7 L46.4,54.0 L46.5,54.2 L46.6,54.5 L46.8,54.8 L46.9,55.0 L47.0,55.2 L47.1,55.4 L47.2,55.5 L47.4,55.7 L47.5,55.8 L47.6,55.9 L47.8,55.9 L47.9,56.0 L48.0,56.0 L48.1,56.0 L48.2,55.9 L48.4,55.9 L48.5,55.8 L48.6,55.7 L48.8,55.5 L48.9,55.4 L49.0,55.2 L49.1,55.0 L49.2,54.8 L49.4,54.5 L49.5,54.2 L49.6,54.0 L49.8,53.7 L49.9,53.3 L50.0,53.0 L50.1,52.7 L50.2,52.3 L50.4,51.9 L50.5,51.6 L50.6,51.2 L50.8,50.8 L50.9,50.4 L51.0,50.0 L51.1,49.6 L51.2,49.2 L51.4,48.8 L51.5,48.4 L51.6,48.1 L51.8,47.7 L51.9,47.3 L52.0,47.0 L52.1,46.7 L52.2,46.3 L52.4,46.0 L52.5,45.8 L52.6,45.5 L52.8,45.2 L52.9,45.0 L53.0,44.8 L53.1,44.6 L53.2,44.5 L53.4,44.3 L53.5,44.2 L53.6,44.1 L53.8,44.1 L53.9,44.0 L54.0,44.0 H57.0 V56.0 H63.0 V44.0 H69.0" fill="none" stroke="#e8f0ff" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,26 @@
|
||||
# libdmodemctl: what the desktop apps share, in plain C with no
|
||||
# dependencies. Static for the Linux app; a DLL for the Windows app's
|
||||
# P/Invoke (-DDMODEMCTL_SHARED=ON).
|
||||
option(DMODEMCTL_SHARED "Build libdmodemctl as a shared library" OFF)
|
||||
|
||||
set(DMODEMCTL_SOURCES
|
||||
src/session.c
|
||||
src/model.c
|
||||
src/diag.c
|
||||
src/vt.c
|
||||
src/daemon.c
|
||||
src/util.c)
|
||||
|
||||
if(DMODEMCTL_SHARED)
|
||||
add_library(dmodemctl SHARED ${DMODEMCTL_SOURCES})
|
||||
target_compile_definitions(dmodemctl PRIVATE DMC_BUILD_DLL)
|
||||
set_target_properties(dmodemctl PROPERTIES C_VISIBILITY_PRESET hidden)
|
||||
else()
|
||||
add_library(dmodemctl STATIC ${DMODEMCTL_SOURCES})
|
||||
endif()
|
||||
target_include_directories(dmodemctl PUBLIC include)
|
||||
if(MSVC)
|
||||
target_compile_options(dmodemctl PRIVATE /W4 /wd4996)
|
||||
else()
|
||||
target_compile_options(dmodemctl PRIVATE -Wall -Wextra -Wshadow)
|
||||
endif()
|
||||
@@ -0,0 +1,298 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* dmodemctl.h - the part of D-Modem's desktop apps that is not drawing.
|
||||
*
|
||||
* The Windows, macOS and Linux apps are thin native shells over this
|
||||
* small C library, so that each of them is only views. It does no I/O
|
||||
* of its own and starts no threads: each app opens the modem's DTE (a
|
||||
* pty, a TCP socket) in its own way, hands the bytes it reads to
|
||||
* dmc_feed(), writes what dmc_output() gives it, and calls dmc_poll()
|
||||
* from a timer. That keeps it simple to call from C (GTK), C#
|
||||
* (P/Invoke) and Swift.
|
||||
*
|
||||
* Its parts:
|
||||
* - dmc_session: the AT conversation with dmodemd: commands and their
|
||||
* responses, the call's state from the result codes (RING, CONNECT,
|
||||
* NO CARRIER), the escape to command mode and hanging up, and the
|
||||
* stream for the app's terminal view.
|
||||
* - dmc_model: the modem's settings, from AT!M, for a native settings
|
||||
* page.
|
||||
* - dmc_diag: the last call's statistics, from AT#UD (Microsoft's
|
||||
* Unimodem diagnostics), as labelled rows.
|
||||
* - dmc_vt: a small ANSI terminal screen, for the apps whose toolkit
|
||||
* has no terminal widget (Windows and macOS): the AT console and the
|
||||
* full-screen configurator (AT!CF).
|
||||
* - dmc_daemon_*: starting dmodemd and reading what it prints.
|
||||
*
|
||||
* Strings are UTF-8. A const char * the library returns stays valid
|
||||
* until the next call on the same object.
|
||||
*/
|
||||
#ifndef DMODEMCTL_H
|
||||
#define DMODEMCTL_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32) && defined(DMC_BUILD_DLL)
|
||||
#define DMC_API __declspec(dllexport)
|
||||
#elif defined(_WIN32) && defined(DMC_USE_DLL)
|
||||
#define DMC_API __declspec(dllimport)
|
||||
#elif defined(__GNUC__)
|
||||
#define DMC_API __attribute__((visibility("default")))
|
||||
#else
|
||||
#define DMC_API
|
||||
#endif
|
||||
|
||||
/* the library's version: major * 10000 + minor * 100 + patch */
|
||||
#define DMC_VERSION 10000
|
||||
DMC_API int dmc_version(void);
|
||||
|
||||
/*
|
||||
* The session
|
||||
*/
|
||||
|
||||
typedef struct dmc_session dmc_session;
|
||||
|
||||
/* (the enums have no tags: Swift takes their names as plain
|
||||
constants) */
|
||||
|
||||
/* the call's state, as the result codes tell it (dmc_state()) */
|
||||
enum {
|
||||
DMC_CLOSED = 0, /* no DTE open */
|
||||
DMC_IDLE, /* command mode, on hook */
|
||||
DMC_DIALING, /* ATD sent, no result yet */
|
||||
DMC_RINGING, /* RING heard, not answered */
|
||||
DMC_ANSWERING, /* ATA sent, no result yet */
|
||||
DMC_ONLINE, /* CONNECT: data mode */
|
||||
DMC_ONLINE_COMMAND, /* escaped (+++) during a call */
|
||||
DMC_HANGING_UP, /* going back on hook */
|
||||
DMC_CONFIGURATOR /* AT!C, AT!CF or AT!CT runs */
|
||||
};
|
||||
|
||||
/* what dmc_next_event() reports */
|
||||
enum {
|
||||
DMC_EV_NONE = 0,
|
||||
/* a command of dmc_command()'s is done: tag, ok, text (its lines,
|
||||
apart by '\n', without the echo and the final result), result
|
||||
(the final result: OK, ERROR, CONNECT 33600..., or "timeout") */
|
||||
DMC_EV_RESPONSE,
|
||||
/* the state changed: state */
|
||||
DMC_EV_STATE,
|
||||
/* a result code nobody waited for (RING, NO CARRIER...): result */
|
||||
DMC_EV_RESULT,
|
||||
/* caller ID after a RING: text "NMBR=5551234" and the like */
|
||||
DMC_EV_CALLER
|
||||
};
|
||||
|
||||
typedef struct dmc_event {
|
||||
int type;
|
||||
int tag;
|
||||
int ok;
|
||||
int state;
|
||||
const char *text;
|
||||
const char *result;
|
||||
} dmc_event;
|
||||
|
||||
/* flags of dmc_command() */
|
||||
enum {
|
||||
/* its echo and response kept out of the terminal stream (the app's
|
||||
own queries: AT!M, AT#UD) */
|
||||
DMC_QUIET = 1
|
||||
};
|
||||
|
||||
DMC_API dmc_session *dmc_session_new(void);
|
||||
DMC_API void dmc_session_free(dmc_session *s);
|
||||
|
||||
/* the DTE opened (state IDLE) or closed (state CLOSED); either clears
|
||||
what was queued */
|
||||
DMC_API void dmc_open(dmc_session *s, int64_t now_ms);
|
||||
DMC_API void dmc_close(dmc_session *s);
|
||||
|
||||
/* bytes the modem sent */
|
||||
DMC_API void dmc_feed(dmc_session *s, const char *data, int n);
|
||||
/* bytes the user typed in the terminal view, sent as they are (the
|
||||
session reads the command lines in them, to follow ATD, ATA, ATH and
|
||||
AT!C typed by hand) */
|
||||
DMC_API void dmc_type(dmc_session *s, const char *data, int n);
|
||||
/* the time now: runs the timers (a command's timeout, the escape's
|
||||
guard times); returns the ms until it next needs to be called, -1 if
|
||||
only when something happens */
|
||||
DMC_API int dmc_poll(dmc_session *s, int64_t now_ms);
|
||||
|
||||
/* bytes to write to the modem: up to max into buf, how many */
|
||||
DMC_API int dmc_output(dmc_session *s, char *buf, int max);
|
||||
/* bytes for the terminal view: up to max into buf, how many (what the
|
||||
modem sent, less the DMC_QUIET commands') */
|
||||
DMC_API int dmc_terminal(dmc_session *s, char *buf, int max);
|
||||
/* the next event into *ev: 1, or 0 for none */
|
||||
DMC_API int dmc_next_event(dmc_session *s, dmc_event *ev);
|
||||
|
||||
/* an AT command (with or without the AT, no CR), queued behind any
|
||||
other; timeout_ms 0 for the usual (5 s, ATD and ATA two minutes);
|
||||
returns its tag (above 0) for the DMC_EV_RESPONSE, or -1 (closed,
|
||||
or online) */
|
||||
DMC_API int dmc_command(dmc_session *s, const char *cmd, int flags,
|
||||
int timeout_ms);
|
||||
/* dial a number (ATD), answer (ATA): a tag as dmc_command()'s */
|
||||
DMC_API int dmc_dial(dmc_session *s, const char *number);
|
||||
DMC_API int dmc_answer(dmc_session *s);
|
||||
/* hang up whatever the state: online, the escape (+++, with its guard
|
||||
times) and ATH; dialling, a key to stop it; else ATH */
|
||||
DMC_API void dmc_hangup(dmc_session *s);
|
||||
|
||||
DMC_API int dmc_state(const dmc_session *s);
|
||||
/* the state's name for people: "Idle", "Dialling", "Online" */
|
||||
DMC_API const char *dmc_state_name(int state);
|
||||
/* the last CONNECT's text ("CONNECT 33600/ARQ/V34/LAPM/V42BIS"), its
|
||||
rate (0 none), the caller ID's number and name of the last RING */
|
||||
DMC_API const char *dmc_connect_text(const dmc_session *s);
|
||||
DMC_API int dmc_connect_rate(const dmc_session *s);
|
||||
DMC_API const char *dmc_caller_number(const dmc_session *s);
|
||||
DMC_API const char *dmc_caller_name(const dmc_session *s);
|
||||
|
||||
/*
|
||||
* The settings model (AT!M)
|
||||
*/
|
||||
|
||||
typedef struct dmc_model dmc_model;
|
||||
|
||||
enum { DMC_PICK = 0, DMC_NUMBER, DMC_TEXT };
|
||||
|
||||
/* the model from AT!M's response text (dmc_event.text); NULL if it is
|
||||
not one */
|
||||
DMC_API dmc_model *dmc_model_parse(const char *text);
|
||||
DMC_API void dmc_model_free(dmc_model *m);
|
||||
|
||||
DMC_API int dmc_model_count(const dmc_model *m);
|
||||
/* setting i's fields */
|
||||
DMC_API const char *dmc_setting_key(const dmc_model *m, int i);
|
||||
DMC_API int dmc_setting_kind(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_value(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_default(const dmc_model *m, int i);
|
||||
DMC_API long dmc_setting_lo(const dmc_model *m, int i);
|
||||
DMC_API long dmc_setting_hi(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_form(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_group(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_label(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_setting_help(const dmc_model *m, int i);
|
||||
DMC_API int dmc_setting_choices(const dmc_model *m, int i);
|
||||
DMC_API const char *dmc_choice_value(const dmc_model *m, int i, int c);
|
||||
DMC_API const char *dmc_choice_name(const dmc_model *m, int i, int c);
|
||||
DMC_API const char *dmc_choice_label(const dmc_model *m, int i, int c);
|
||||
/* the choice of setting i whose value is v, -1 none */
|
||||
DMC_API int dmc_setting_choice_of(const dmc_model *m, int i,
|
||||
const char *v);
|
||||
/* the setting whose key is key, -1 none */
|
||||
DMC_API int dmc_model_find(const dmc_model *m, const char *key);
|
||||
|
||||
/* the groups, in the order the settings list them */
|
||||
DMC_API int dmc_model_groups(const dmc_model *m);
|
||||
DMC_API const char *dmc_model_group(const dmc_model *m, int g);
|
||||
|
||||
/* "" if setting i takes value, else why not */
|
||||
DMC_API const char *dmc_setting_check(const dmc_model *m, int i,
|
||||
const char *value);
|
||||
/* the command that sets setting i to value ("AT" and its form, the
|
||||
value in it), "" if it does not take it */
|
||||
DMC_API const char *dmc_setting_command(const dmc_model *m, int i,
|
||||
const char *value);
|
||||
/* setting i's value now value (after its command's OK) */
|
||||
DMC_API void dmc_setting_set(dmc_model *m, int i, const char *value);
|
||||
|
||||
/*
|
||||
* The last call's statistics (AT#UD)
|
||||
*/
|
||||
|
||||
typedef struct dmc_diag dmc_diag;
|
||||
|
||||
/* the statistics from AT#UD's response text; never NULL */
|
||||
DMC_API dmc_diag *dmc_diag_parse(const char *text);
|
||||
DMC_API void dmc_diag_free(dmc_diag *d);
|
||||
/* how many rows, each its key (the specification's, hexadecimal), its
|
||||
label and its value for people ("33600 bit/s", "V.34") */
|
||||
DMC_API int dmc_diag_count(const dmc_diag *d);
|
||||
DMC_API int dmc_diag_key(const dmc_diag *d, int i);
|
||||
DMC_API const char *dmc_diag_label(const dmc_diag *d, int i);
|
||||
DMC_API const char *dmc_diag_value(const dmc_diag *d, int i);
|
||||
/* the raw value of key, NULL if it was not reported */
|
||||
DMC_API const char *dmc_diag_raw(const dmc_diag *d, int key);
|
||||
/* there was a call to report (key 1 not "no previous call") */
|
||||
DMC_API int dmc_diag_has_call(const dmc_diag *d);
|
||||
|
||||
/*
|
||||
* The terminal screen
|
||||
*/
|
||||
|
||||
typedef struct dmc_vt dmc_vt;
|
||||
|
||||
/* a cell's attributes */
|
||||
enum {
|
||||
DMC_BOLD = 1,
|
||||
DMC_UNDERLINE = 2,
|
||||
DMC_REVERSE = 4
|
||||
};
|
||||
|
||||
/* the keys dmc_vt_key() encodes */
|
||||
enum {
|
||||
DMC_KEY_UP = 1, DMC_KEY_DOWN, DMC_KEY_RIGHT, DMC_KEY_LEFT,
|
||||
DMC_KEY_HOME, DMC_KEY_END, DMC_KEY_PGUP, DMC_KEY_PGDN,
|
||||
DMC_KEY_INSERT, DMC_KEY_DELETE, DMC_KEY_BACKTAB,
|
||||
DMC_KEY_F1, DMC_KEY_F2, DMC_KEY_F3, DMC_KEY_F4, DMC_KEY_F5,
|
||||
DMC_KEY_F6, DMC_KEY_F7, DMC_KEY_F8, DMC_KEY_F9, DMC_KEY_F10,
|
||||
DMC_KEY_ENTER, DMC_KEY_BACKSPACE, DMC_KEY_TAB, DMC_KEY_ESCAPE
|
||||
};
|
||||
|
||||
/* a screen of cols by rows, with scrollback lines kept above it */
|
||||
DMC_API dmc_vt *dmc_vt_new(int cols, int rows, int scrollback);
|
||||
DMC_API void dmc_vt_free(dmc_vt *t);
|
||||
DMC_API void dmc_vt_resize(dmc_vt *t, int cols, int rows);
|
||||
DMC_API void dmc_vt_reset(dmc_vt *t);
|
||||
DMC_API int dmc_vt_cols(const dmc_vt *t);
|
||||
DMC_API int dmc_vt_rows(const dmc_vt *t);
|
||||
/* bytes from the modem (dmc_terminal()'s) */
|
||||
DMC_API void dmc_vt_feed(dmc_vt *t, const char *data, int n);
|
||||
/* the screen's answers to the modem's questions (where the cursor is:
|
||||
ESC [6n), to write to the modem as if typed */
|
||||
DMC_API int dmc_vt_reply(dmc_vt *t, char *buf, int max);
|
||||
/* how many lines of scrollback there are now */
|
||||
DMC_API int dmc_vt_history(const dmc_vt *t);
|
||||
/* a cell: row 0 the screen's top, -1 the newest scrollback line and so
|
||||
on; its character (a Unicode code point, 32 for none), colours (0 to
|
||||
15 the ANSI palette, -1 the default) and attributes */
|
||||
DMC_API uint32_t dmc_vt_char(const dmc_vt *t, int row, int col);
|
||||
DMC_API int dmc_vt_fg(const dmc_vt *t, int row, int col);
|
||||
DMC_API int dmc_vt_bg(const dmc_vt *t, int row, int col);
|
||||
DMC_API int dmc_vt_attr(const dmc_vt *t, int row, int col);
|
||||
/* a row as UTF-8 text, trailing blanks dropped */
|
||||
DMC_API const char *dmc_vt_text(dmc_vt *t, int row);
|
||||
DMC_API int dmc_vt_cursor_row(const dmc_vt *t);
|
||||
DMC_API int dmc_vt_cursor_col(const dmc_vt *t);
|
||||
DMC_API int dmc_vt_cursor_visible(const dmc_vt *t);
|
||||
/* the screen changed since the last call (and clears the mark) */
|
||||
DMC_API int dmc_vt_changed(dmc_vt *t);
|
||||
/* the bytes a key sends, into buf: how many */
|
||||
DMC_API int dmc_vt_key(const dmc_vt *t, int key, char *buf, int max);
|
||||
/* the RGB of palette colour c (0 to 15), as 0xRRGGBB */
|
||||
DMC_API uint32_t dmc_vt_palette(int c);
|
||||
|
||||
/*
|
||||
* dmodemd
|
||||
*/
|
||||
|
||||
/* a line dmodemd printed when it started: 1 and its DTE (a pty's
|
||||
path, "TCP 127.0.0.1:2323", "pipe \\.\pipe\dmodem") into buf if it is
|
||||
the line that says the modem is ready, else 0 */
|
||||
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);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* daemon.c - reading what dmodemd prints as it starts (dmodemctl.h)
|
||||
*
|
||||
* On Linux, macOS, BSD and Haiku it says
|
||||
* Use `/dev/ttyDM0' as modem device, Ctrl+C for termination.
|
||||
* (the pty's own path, /dev/pts/3, when it may not make the link), and
|
||||
* on Windows
|
||||
* Use TCP 127.0.0.1:2323 as the modem, Ctrl+C for termination.
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
|
||||
static int copy(const char *from, size_t n, char *buf, int max)
|
||||
{
|
||||
if (!buf || max <= 0)
|
||||
return 1;
|
||||
if (n >= (size_t)max)
|
||||
n = (size_t)max - 1;
|
||||
memcpy(buf, from, n);
|
||||
buf[n] = '\0';
|
||||
return 1;
|
||||
}
|
||||
|
||||
int dmc_daemon_ready(const char *line, char *buf, int max)
|
||||
{
|
||||
if (!line)
|
||||
return 0;
|
||||
const char *p = strstr(line, "Use `");
|
||||
if (p) {
|
||||
p += 5;
|
||||
const char *e = strchr(p, '\'');
|
||||
if (e && strstr(e, "as modem device"))
|
||||
return copy(p, (size_t)(e - p), buf, max);
|
||||
}
|
||||
p = strstr(line, "Use ");
|
||||
if (p) {
|
||||
p += 4;
|
||||
const char *e = strstr(p, " as the modem");
|
||||
if (e)
|
||||
return copy(p, (size_t)(e - p), buf, max);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dmc_daemon_error(const char *line)
|
||||
{
|
||||
return line && !strncmp(line, "error:", 6);
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* diag.c - the last call's statistics from AT#UD (dmodemctl.h)
|
||||
*
|
||||
* AT#UD follows Microsoft's Unimodem Diagnostics Command Reference
|
||||
* Specification, version 1.0 (D-Modem's docs/specs/umud10.rtf): lines
|
||||
* "DIAG <2A4D3263 key=value ...>", the keys and values in hexadecimal
|
||||
* and the code tables V.58's. Each key becomes a row with its label
|
||||
* and its value for people.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
#include "util.h"
|
||||
|
||||
/* how a key's value reads */
|
||||
enum fmt {
|
||||
F_HEX, /* as it is */
|
||||
F_NUM, /* a count */
|
||||
F_BPS, /* bit/s */
|
||||
F_DBM, /* -dBm */
|
||||
F_DB, /* dB */
|
||||
F_MS, /* ms */
|
||||
F_HZ, /* Hz */
|
||||
F_BAUD, /* symbols a second */
|
||||
F_BYTES, /* bytes */
|
||||
F_TABLE, /* one of the code tables */
|
||||
F_STRING, /* quoted octets */
|
||||
F_VERSION /* digit.digit */
|
||||
};
|
||||
|
||||
struct code {
|
||||
unsigned v;
|
||||
const char *label;
|
||||
};
|
||||
|
||||
static const struct code setup[] = {
|
||||
{ 0x0, "No previous call" },
|
||||
{ 0x1, "No dial tone" },
|
||||
{ 0x2, "Network busy (reorder)" },
|
||||
{ 0x3, "Busy" },
|
||||
{ 0x4, "No signal recognised" },
|
||||
{ 0x5, "Voice" },
|
||||
{ 0x6, "Text telephone" },
|
||||
{ 0x7, "Data answer tone heard" },
|
||||
{ 0x8, "Data calling tone heard" },
|
||||
{ 0x9, "Fax answer tone heard" },
|
||||
{ 0xA, "Fax calling tone heard" },
|
||||
{ 0xB, "V.8bis" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
static const struct code media[] = {
|
||||
{ 0x0, "Data" },
|
||||
{ 0x1, "Fax" },
|
||||
{ 0x2, "Voice" },
|
||||
{ 0x3, "VoiceView" },
|
||||
{ 0x4, "ASVD (V.61)" },
|
||||
{ 0x5, "ASVD (V.34Q)" },
|
||||
{ 0x6, "DSVD (Multi-Tech)" },
|
||||
{ 0x7, "DSVD 1.2" },
|
||||
{ 0x8, "DSVD (V.70)" },
|
||||
{ 0x9, "Video telephony (H.324)" },
|
||||
{ 0xA, "Other V.80 call" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
static const struct code dte_mode[] = {
|
||||
{ 0x0, "Asynchronous" },
|
||||
{ 0x1, "V.80 transparent synchronous" },
|
||||
{ 0x2, "V.80 framed synchronous" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
/* V.58's gstnModulationSchemeActive, and the manufacturers' */
|
||||
static const struct code modulation[] = {
|
||||
{ 0x0, "V.17" }, { 0x1, "V.21" }, { 0x2, "V.22" },
|
||||
{ 0x3, "V.22bis" }, { 0x4, "V.23" }, { 0x5, "V.23 (half duplex)" },
|
||||
{ 0x6, "V.26bis" }, { 0x7, "V.26ter" }, { 0x8, "V.27ter" },
|
||||
{ 0x9, "V.29" }, { 0xA, "V.32" }, { 0xB, "V.32bis" },
|
||||
{ 0xC, "V.34" }, { 0xD, "V.34 half duplex" },
|
||||
{ 0xE, "V.90 (PCM)" }, { 0xF, "V.91 (PCM both ways)" },
|
||||
{ 0x80, "X2" }, { 0x81, "K56flex" }, { 0x82, "V.FC" },
|
||||
{ 0x83, "V.32terbo" }, { 0x84, "Bell 212A" }, { 0x85, "Bell 103" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
static const struct code error_control[] = {
|
||||
{ 0x0, "None" },
|
||||
{ 0x1, "V.42 LAPM" },
|
||||
{ 0x2, "MNP" },
|
||||
{ 0x80, "MNP 10" },
|
||||
{ 0x81, "ECP" },
|
||||
{ 0x82, "ETC" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
static const struct code compression[] = {
|
||||
{ 0x0, "None" },
|
||||
{ 0x1, "V.42bis" },
|
||||
{ 0x80, "MNP 5" },
|
||||
{ 0x81, "V.44" },
|
||||
{ 0x82, "zstd" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
static const struct code flow[] = {
|
||||
{ 0x0, "Off" },
|
||||
{ 0x1, "XON/XOFF" },
|
||||
{ 0x2, "RTS/CTS" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
/* V.58's callCleared */
|
||||
static const struct code cleared[] = {
|
||||
{ 0x0, "Cause unknown" },
|
||||
{ 0x1, "No previous call" },
|
||||
{ 0x2, "Call in progress" },
|
||||
{ 0x3, "Call waiting signal" },
|
||||
{ 0x4, "Delayed" },
|
||||
{ 0x19, "Inactivity timer" },
|
||||
{ 0x1F, "DTR off stops the dial" },
|
||||
{ 0x20, "DTR turned off" },
|
||||
{ 0x28, "No number" },
|
||||
{ 0x29, "Blacklisted number" },
|
||||
{ 0x2A, "Too many attempts" },
|
||||
{ 0x2B, "Extension off hook" },
|
||||
{ 0x2C, "No answer in time (S7)" },
|
||||
{ 0x2D, "Incoming call while dialling" },
|
||||
{ 0x2E, "Loop current lost" },
|
||||
{ 0x2F, "No dial tone" },
|
||||
{ 0x30, "Voice" },
|
||||
{ 0x31, "Reorder tone" },
|
||||
{ 0x32, "SIT tone" },
|
||||
{ 0x33, "Busy" },
|
||||
{ 0x34, "Long space" },
|
||||
{ 0x3C, "Carrier lost" },
|
||||
{ 0x3D, "Training failed" },
|
||||
{ 0x3E, "No modulation in common" },
|
||||
{ 0x3F, "Retrain failed" },
|
||||
{ 0x40, "Too many retrains" },
|
||||
{ 0x41, "The other modem hung up" },
|
||||
{ 0x42, "Fax detected" },
|
||||
{ 0x50, "Stopped by a key" },
|
||||
{ 0x51, "Hung up (ATH)" },
|
||||
{ 0x52, "Reset (ATZ)" },
|
||||
{ 0x5A, "Frame reject" },
|
||||
{ 0x5B, "No error control" },
|
||||
{ 0x5C, "Protocol violation" },
|
||||
{ 0x5D, "Too many retransmissions" },
|
||||
{ 0x5E, "Negotiation failed" },
|
||||
{ 0x5F, "Disconnect frame received" },
|
||||
{ 0x60, "SABME frame received" },
|
||||
{ 0x64, "Lost synchronisation" },
|
||||
{ 0, NULL }
|
||||
};
|
||||
|
||||
struct keyinfo {
|
||||
int key;
|
||||
const char *label;
|
||||
int fmt;
|
||||
const struct code *table;
|
||||
};
|
||||
|
||||
static const struct keyinfo keys[] = {
|
||||
{ 0x00, "Report version", F_VERSION, NULL },
|
||||
{ 0x01, "Call setup", F_TABLE, setup },
|
||||
{ 0x02, "Mode", F_TABLE, media },
|
||||
{ 0x03, "DTE interface", F_TABLE, dte_mode },
|
||||
{ 0x04, "V.8 CM", F_STRING, NULL },
|
||||
{ 0x05, "V.8 JM", F_STRING, NULL },
|
||||
{ 0x10, "Received level", F_DBM, NULL },
|
||||
{ 0x11, "Transmit level", F_DBM, NULL },
|
||||
{ 0x12, "Noise level", F_DBM, NULL },
|
||||
{ 0x13, "Mean squared error", F_NUM, NULL },
|
||||
{ 0x14, "Near echo loss", F_DB, NULL },
|
||||
{ 0x15, "Far echo loss", F_DB, NULL },
|
||||
{ 0x16, "Far echo delay", F_MS, NULL },
|
||||
{ 0x17, "Round trip delay", F_MS, NULL },
|
||||
{ 0x18, "V.34 INFO bits", F_HEX, NULL },
|
||||
{ 0x20, "Transmit modulation", F_TABLE, modulation },
|
||||
{ 0x21, "Receive modulation", F_TABLE, modulation },
|
||||
{ 0x22, "Transmit symbol rate", F_BAUD, NULL },
|
||||
{ 0x23, "Receive symbol rate", F_BAUD, NULL },
|
||||
{ 0x24, "Transmit carrier", F_HZ, NULL },
|
||||
{ 0x25, "Receive carrier", F_HZ, NULL },
|
||||
{ 0x26, "First transmit rate", F_BPS, NULL },
|
||||
{ 0x27, "First receive rate", F_BPS, NULL },
|
||||
{ 0x30, "Carrier losses", F_NUM, NULL },
|
||||
{ 0x31, "Rate renegotiations", F_NUM, NULL },
|
||||
{ 0x32, "Retrains asked for", F_NUM, NULL },
|
||||
{ 0x33, "Retrains granted", F_NUM, NULL },
|
||||
{ 0x34, "Last transmit rate", F_BPS, NULL },
|
||||
{ 0x35, "Last receive rate", F_BPS, NULL },
|
||||
{ 0x40, "Error control", F_TABLE, error_control },
|
||||
{ 0x41, "Frame size", F_BYTES, NULL },
|
||||
{ 0x42, "Link timeouts", F_NUM, NULL },
|
||||
{ 0x43, "NAKs received", F_NUM, NULL },
|
||||
{ 0x44, "Compression", F_TABLE, compression },
|
||||
{ 0x45, "Dictionary size", F_BYTES, NULL },
|
||||
{ 0x50, "Transmit flow control", F_TABLE, flow },
|
||||
{ 0x51, "Receive flow control", F_TABLE, flow },
|
||||
{ 0x52, "Characters sent", F_NUM, NULL },
|
||||
{ 0x53, "Characters received", F_NUM, NULL },
|
||||
{ 0x54, "Characters lost sending", F_NUM, NULL },
|
||||
{ 0x55, "Characters lost receiving", F_NUM, NULL },
|
||||
{ 0x56, "Frames sent", F_NUM, NULL },
|
||||
{ 0x57, "Frames received", F_NUM, NULL },
|
||||
{ 0x58, "Frames sent again", F_NUM, NULL },
|
||||
{ 0x59, "Frames received in error", F_NUM, NULL },
|
||||
{ 0x60, "Why the call ended", F_TABLE, cleared },
|
||||
{ 0x61, "Call waiting events", F_NUM, NULL },
|
||||
{ -1, NULL, 0, NULL }
|
||||
};
|
||||
|
||||
struct row {
|
||||
int key;
|
||||
char *raw, *label, *value;
|
||||
};
|
||||
|
||||
struct dmc_diag {
|
||||
struct row *rows;
|
||||
int n;
|
||||
};
|
||||
|
||||
static const struct keyinfo *info(int key)
|
||||
{
|
||||
for (const struct keyinfo *k = keys; k->label; k++)
|
||||
if (k->key == key)
|
||||
return k;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *code_label(const struct code *t, unsigned v)
|
||||
{
|
||||
for (; t->label; t++)
|
||||
if (t->v == v)
|
||||
return t->label;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* a number with thousands apart by commas */
|
||||
static void grouped(char *out, size_t n, unsigned long v)
|
||||
{
|
||||
char digits[32];
|
||||
snprintf(digits, sizeof(digits), "%lu", v);
|
||||
size_t len = strlen(digits), o = 0;
|
||||
for (size_t i = 0; i < len && o + 2 < n; i++) {
|
||||
if (i && (len - i) % 3 == 0)
|
||||
out[o++] = ',';
|
||||
out[o++] = digits[i];
|
||||
}
|
||||
out[o] = '\0';
|
||||
}
|
||||
|
||||
static char *shown(const struct keyinfo *k, const char *raw)
|
||||
{
|
||||
char out[160];
|
||||
unsigned long v = strtoul(raw, NULL, 16);
|
||||
char num[40];
|
||||
grouped(num, sizeof(num), v);
|
||||
switch (k ? k->fmt : F_HEX) {
|
||||
case F_NUM:
|
||||
snprintf(out, sizeof(out), "%s", num);
|
||||
break;
|
||||
case F_BPS:
|
||||
snprintf(out, sizeof(out), "%s bit/s", num);
|
||||
break;
|
||||
case F_DBM:
|
||||
snprintf(out, sizeof(out), "%s%lu dBm", v ? "-" : "", v);
|
||||
break;
|
||||
case F_DB:
|
||||
snprintf(out, sizeof(out), "%lu dB", v);
|
||||
break;
|
||||
case F_MS:
|
||||
snprintf(out, sizeof(out), "%lu ms", v);
|
||||
break;
|
||||
case F_HZ:
|
||||
snprintf(out, sizeof(out), "%lu Hz", v);
|
||||
break;
|
||||
case F_BAUD:
|
||||
snprintf(out, sizeof(out), "%lu baud", v);
|
||||
break;
|
||||
case F_BYTES:
|
||||
snprintf(out, sizeof(out), "%s bytes", num);
|
||||
break;
|
||||
case F_TABLE: {
|
||||
const char *l = code_label(k->table, (unsigned)v);
|
||||
if (l)
|
||||
snprintf(out, sizeof(out), "%s", l);
|
||||
else
|
||||
snprintf(out, sizeof(out), "Code %lX", v);
|
||||
break;
|
||||
}
|
||||
case F_VERSION:
|
||||
if (strlen(raw) == 2)
|
||||
snprintf(out, sizeof(out), "%c.%c", raw[0], raw[1]);
|
||||
else
|
||||
snprintf(out, sizeof(out), "%s", raw);
|
||||
break;
|
||||
case F_STRING: {
|
||||
/* the octets, apart by spaces */
|
||||
size_t o = 0;
|
||||
for (const char *p = raw; *p && o + 4 < sizeof(out); p++) {
|
||||
if (*p == '"')
|
||||
continue;
|
||||
if (o && (o + 1) % 3 == 0)
|
||||
out[o++] = ' ';
|
||||
out[o++] = *p;
|
||||
}
|
||||
out[o] = '\0';
|
||||
break;
|
||||
}
|
||||
default:
|
||||
snprintf(out, sizeof(out), "%s", raw);
|
||||
break;
|
||||
}
|
||||
return dup_str(out);
|
||||
}
|
||||
|
||||
static void add(dmc_diag *d, int key, const char *raw, size_t n)
|
||||
{
|
||||
/* a key again: its last value */
|
||||
for (int i = 0; i < d->n; i++)
|
||||
if (d->rows[i].key == key) {
|
||||
free(d->rows[i].raw);
|
||||
free(d->rows[i].value);
|
||||
d->rows[i].raw = dup_n(raw, n);
|
||||
d->rows[i].value = shown(info(key), d->rows[i].raw);
|
||||
return;
|
||||
}
|
||||
struct row *r = realloc(d->rows, sizeof(*r) * (size_t)(d->n + 1));
|
||||
if (!r)
|
||||
abort();
|
||||
d->rows = r;
|
||||
r = &d->rows[d->n++];
|
||||
const struct keyinfo *k = info(key);
|
||||
char label[32];
|
||||
if (!k)
|
||||
snprintf(label, sizeof(label), "Key %X", key);
|
||||
r->key = key;
|
||||
r->raw = dup_n(raw, n);
|
||||
r->label = dup_str(k ? k->label : label);
|
||||
r->value = shown(k, r->raw);
|
||||
}
|
||||
|
||||
dmc_diag *dmc_diag_parse(const char *text)
|
||||
{
|
||||
dmc_diag *d = calloc(1, sizeof(*d));
|
||||
if (!d)
|
||||
abort();
|
||||
const char *p = text ? text : "";
|
||||
while ((p = strstr(p, "DIAG <")) != NULL) {
|
||||
p += 6;
|
||||
const char *end = strchr(p, '>');
|
||||
if (!end)
|
||||
break;
|
||||
/* the tag (2A4D3263), then key=value pairs */
|
||||
while (p < end && *p != ' ')
|
||||
p++;
|
||||
while (p < end) {
|
||||
while (p < end && *p == ' ')
|
||||
p++;
|
||||
const char *eq = p;
|
||||
while (eq < end && *eq != '=')
|
||||
eq++;
|
||||
if (eq >= end)
|
||||
break;
|
||||
int key = (int)strtol(p, NULL, 16);
|
||||
const char *v = eq + 1, *ve = v;
|
||||
if (*v == '"') {
|
||||
ve = strchr(v + 1, '"');
|
||||
ve = ve && ve < end ? ve + 1 : end;
|
||||
} else {
|
||||
while (ve < end && *ve != ' ')
|
||||
ve++;
|
||||
}
|
||||
add(d, key, v, (size_t)(ve - v));
|
||||
p = ve;
|
||||
}
|
||||
p = end + 1;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
void dmc_diag_free(dmc_diag *d)
|
||||
{
|
||||
if (!d)
|
||||
return;
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
free(d->rows[i].raw);
|
||||
free(d->rows[i].label);
|
||||
free(d->rows[i].value);
|
||||
}
|
||||
free(d->rows);
|
||||
free(d);
|
||||
}
|
||||
|
||||
int dmc_diag_count(const dmc_diag *d)
|
||||
{
|
||||
return d ? d->n : 0;
|
||||
}
|
||||
|
||||
int dmc_diag_key(const dmc_diag *d, int i)
|
||||
{
|
||||
return d && i >= 0 && i < d->n ? d->rows[i].key : -1;
|
||||
}
|
||||
|
||||
const char *dmc_diag_label(const dmc_diag *d, int i)
|
||||
{
|
||||
return d && i >= 0 && i < d->n ? d->rows[i].label : "";
|
||||
}
|
||||
|
||||
const char *dmc_diag_value(const dmc_diag *d, int i)
|
||||
{
|
||||
return d && i >= 0 && i < d->n ? d->rows[i].value : "";
|
||||
}
|
||||
|
||||
const char *dmc_diag_raw(const dmc_diag *d, int key)
|
||||
{
|
||||
for (int i = 0; d && i < d->n; i++)
|
||||
if (d->rows[i].key == key)
|
||||
return d->rows[i].raw;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int dmc_diag_has_call(const dmc_diag *d)
|
||||
{
|
||||
const char *v = dmc_diag_raw(d, 1);
|
||||
return v && strtoul(v, NULL, 16) != 0;
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* model.c - the modem's settings from AT!M (dmodemctl.h)
|
||||
*
|
||||
* AT!M's lines, their fields apart by tabs:
|
||||
*
|
||||
* model 1 <settings>
|
||||
* setting <key> <kind> <value> <default> <lo> <hi> <form> <group>
|
||||
* <label> <help>
|
||||
* choice <value> <name> <label> (a pick's, after it)
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
#include "util.h"
|
||||
|
||||
struct choice {
|
||||
char *value, *name, *label;
|
||||
};
|
||||
|
||||
struct setting {
|
||||
char *key, *value, *def, *form, *group, *label, *help;
|
||||
int kind;
|
||||
long lo, hi;
|
||||
struct choice *choices;
|
||||
int n_choices;
|
||||
};
|
||||
|
||||
struct dmc_model {
|
||||
struct setting *s;
|
||||
int n;
|
||||
char **groups;
|
||||
int n_groups;
|
||||
dmc_buf scratch;
|
||||
char why[96];
|
||||
};
|
||||
|
||||
/* the line's fields: up to max, how many (the line cut in place) */
|
||||
static int fields(char *line, char **f, int max)
|
||||
{
|
||||
int n = 0;
|
||||
char *p = line;
|
||||
while (n < max) {
|
||||
f[n++] = p;
|
||||
char *t = strchr(p, '\t');
|
||||
if (!t)
|
||||
break;
|
||||
*t = '\0';
|
||||
p = t + 1;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static void add_group(dmc_model *m, const char *g)
|
||||
{
|
||||
for (int i = 0; i < m->n_groups; i++)
|
||||
if (!strcmp(m->groups[i], g))
|
||||
return;
|
||||
char **p = realloc(m->groups, sizeof(*p) * (size_t)(m->n_groups + 1));
|
||||
if (!p)
|
||||
abort();
|
||||
m->groups = p;
|
||||
m->groups[m->n_groups++] = dup_str(g);
|
||||
}
|
||||
|
||||
dmc_model *dmc_model_parse(const char *text)
|
||||
{
|
||||
if (!text)
|
||||
return NULL;
|
||||
char *copy = dup_str(text);
|
||||
dmc_model *m = calloc(1, sizeof(*m));
|
||||
if (!m)
|
||||
abort();
|
||||
int seen_model = 0, declared = -1;
|
||||
char *save = copy;
|
||||
while (save) {
|
||||
char *line = save;
|
||||
char *nl = strchr(line, '\n');
|
||||
if (nl) {
|
||||
*nl = '\0';
|
||||
save = nl + 1;
|
||||
} else {
|
||||
save = NULL;
|
||||
}
|
||||
size_t len = strlen(line);
|
||||
if (len && line[len - 1] == '\r')
|
||||
line[len - 1] = '\0';
|
||||
char *f[12];
|
||||
int n = fields(line, f, 12);
|
||||
if (!strcmp(f[0], "model") && n >= 3) {
|
||||
if (atoi(f[1]) != 1)
|
||||
break; /* a format we do not know */
|
||||
seen_model = 1;
|
||||
declared = atoi(f[2]);
|
||||
} else if (!strcmp(f[0], "setting") && n >= 11 && seen_model) {
|
||||
struct setting *p = realloc(m->s, sizeof(*p) *
|
||||
(size_t)(m->n + 1));
|
||||
if (!p)
|
||||
abort();
|
||||
m->s = p;
|
||||
struct setting *s = &m->s[m->n++];
|
||||
memset(s, 0, sizeof(*s));
|
||||
s->key = dup_str(f[1]);
|
||||
s->kind = !strcmp(f[2], "pick") ? DMC_PICK :
|
||||
!strcmp(f[2], "number") ? DMC_NUMBER : DMC_TEXT;
|
||||
s->value = dup_str(f[3]);
|
||||
s->def = dup_str(f[4]);
|
||||
s->lo = strtol(f[5], NULL, 10);
|
||||
s->hi = strtol(f[6], NULL, 10);
|
||||
s->form = dup_str(f[7]);
|
||||
s->group = dup_str(f[8]);
|
||||
s->label = dup_str(f[9]);
|
||||
s->help = dup_str(f[10]);
|
||||
add_group(m, s->group);
|
||||
} else if (!strcmp(f[0], "choice") && n >= 4 && m->n) {
|
||||
struct setting *s = &m->s[m->n - 1];
|
||||
struct choice *c = realloc(s->choices, sizeof(*c) *
|
||||
(size_t)(s->n_choices + 1));
|
||||
if (!c)
|
||||
abort();
|
||||
s->choices = c;
|
||||
c = &s->choices[s->n_choices++];
|
||||
c->value = dup_str(f[1]);
|
||||
c->name = dup_str(f[2]);
|
||||
c->label = dup_str(f[3]);
|
||||
}
|
||||
}
|
||||
free(copy);
|
||||
if (!seen_model || (declared >= 0 && declared != m->n)) {
|
||||
dmc_model_free(m);
|
||||
return NULL;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
void dmc_model_free(dmc_model *m)
|
||||
{
|
||||
if (!m)
|
||||
return;
|
||||
for (int i = 0; i < m->n; i++) {
|
||||
struct setting *s = &m->s[i];
|
||||
free(s->key);
|
||||
free(s->value);
|
||||
free(s->def);
|
||||
free(s->form);
|
||||
free(s->group);
|
||||
free(s->label);
|
||||
free(s->help);
|
||||
for (int j = 0; j < s->n_choices; j++) {
|
||||
free(s->choices[j].value);
|
||||
free(s->choices[j].name);
|
||||
free(s->choices[j].label);
|
||||
}
|
||||
free(s->choices);
|
||||
}
|
||||
free(m->s);
|
||||
for (int i = 0; i < m->n_groups; i++)
|
||||
free(m->groups[i]);
|
||||
free(m->groups);
|
||||
buf_free(&m->scratch);
|
||||
free(m);
|
||||
}
|
||||
|
||||
int dmc_model_count(const dmc_model *m)
|
||||
{
|
||||
return m ? m->n : 0;
|
||||
}
|
||||
|
||||
static const struct setting *at(const dmc_model *m, int i)
|
||||
{
|
||||
static const struct setting none = { "", "", "", "", "", "", "", 0,
|
||||
0, 0, NULL, 0 };
|
||||
return m && i >= 0 && i < m->n ? &m->s[i] : &none;
|
||||
}
|
||||
|
||||
const char *dmc_setting_key(const dmc_model *m, int i) { return at(m, i)->key; }
|
||||
int dmc_setting_kind(const dmc_model *m, int i) { return at(m, i)->kind; }
|
||||
const char *dmc_setting_value(const dmc_model *m, int i) { return at(m, i)->value; }
|
||||
const char *dmc_setting_default(const dmc_model *m, int i) { return at(m, i)->def; }
|
||||
long dmc_setting_lo(const dmc_model *m, int i) { return at(m, i)->lo; }
|
||||
long dmc_setting_hi(const dmc_model *m, int i) { return at(m, i)->hi; }
|
||||
const char *dmc_setting_form(const dmc_model *m, int i) { return at(m, i)->form; }
|
||||
const char *dmc_setting_group(const dmc_model *m, int i) { return at(m, i)->group; }
|
||||
const char *dmc_setting_label(const dmc_model *m, int i) { return at(m, i)->label; }
|
||||
const char *dmc_setting_help(const dmc_model *m, int i) { return at(m, i)->help; }
|
||||
int dmc_setting_choices(const dmc_model *m, int i) { return at(m, i)->n_choices; }
|
||||
|
||||
static const struct choice *choice_at(const dmc_model *m, int i, int c)
|
||||
{
|
||||
static const struct choice none = { "", "", "" };
|
||||
const struct setting *s = at(m, i);
|
||||
return c >= 0 && c < s->n_choices ? &s->choices[c] : &none;
|
||||
}
|
||||
|
||||
const char *dmc_choice_value(const dmc_model *m, int i, int c)
|
||||
{
|
||||
return choice_at(m, i, c)->value;
|
||||
}
|
||||
|
||||
const char *dmc_choice_name(const dmc_model *m, int i, int c)
|
||||
{
|
||||
return choice_at(m, i, c)->name;
|
||||
}
|
||||
|
||||
const char *dmc_choice_label(const dmc_model *m, int i, int c)
|
||||
{
|
||||
return choice_at(m, i, c)->label;
|
||||
}
|
||||
|
||||
int dmc_setting_choice_of(const dmc_model *m, int i, const char *v)
|
||||
{
|
||||
const struct setting *s = at(m, i);
|
||||
for (int c = 0; c < s->n_choices; c++)
|
||||
if (same_ci(s->choices[c].value, v ? v : ""))
|
||||
return c;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int dmc_model_find(const dmc_model *m, const char *key)
|
||||
{
|
||||
for (int i = 0; m && i < m->n; i++)
|
||||
if (!strcmp(m->s[i].key, key ? key : ""))
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int dmc_model_groups(const dmc_model *m)
|
||||
{
|
||||
return m ? m->n_groups : 0;
|
||||
}
|
||||
|
||||
const char *dmc_model_group(const dmc_model *m, int g)
|
||||
{
|
||||
return m && g >= 0 && g < m->n_groups ? m->groups[g] : "";
|
||||
}
|
||||
|
||||
/* the value a number: digits only, within lo and hi */
|
||||
static int number_ok(const struct setting *s, const char *v, char *why,
|
||||
size_t n)
|
||||
{
|
||||
if (!*v) {
|
||||
snprintf(why, n, "Enter a number");
|
||||
return 0;
|
||||
}
|
||||
for (const char *p = v; *p; p++)
|
||||
if (*p < '0' || *p > '9') {
|
||||
snprintf(why, n, "Enter a number");
|
||||
return 0;
|
||||
}
|
||||
if (strlen(v) > 10) {
|
||||
snprintf(why, n, "From %ld to %ld", s->lo, s->hi);
|
||||
return 0;
|
||||
}
|
||||
long x = strtol(v, NULL, 10);
|
||||
if (x < s->lo || x > s->hi) {
|
||||
snprintf(why, n, "From %ld to %ld", s->lo, s->hi);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *dmc_setting_check(const dmc_model *m, int i, const char *value)
|
||||
{
|
||||
static char none[] = "No such setting";
|
||||
if (!m || i < 0 || i >= m->n)
|
||||
return none;
|
||||
char *why = ((dmc_model *)m)->why;
|
||||
const size_t size = sizeof(m->why);
|
||||
const struct setting *s = at(m, i);
|
||||
const char *v = value ? value : "";
|
||||
why[0] = '\0';
|
||||
switch (s->kind) {
|
||||
case DMC_PICK:
|
||||
if (dmc_setting_choice_of(m, i, v) < 0)
|
||||
snprintf(why, size, "Not one of the choices");
|
||||
break;
|
||||
case DMC_NUMBER:
|
||||
number_ok(s, v, why, size);
|
||||
break;
|
||||
default:
|
||||
/* a list of numbers, apart by commas (some may be left
|
||||
out, as AT takes them) */
|
||||
if (!*v)
|
||||
snprintf(why, size, "Enter the values");
|
||||
for (const char *p = v; *p; p++)
|
||||
if ((*p < '0' || *p > '9') && *p != ',') {
|
||||
snprintf(why, size,
|
||||
"Numbers apart by commas");
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return why;
|
||||
}
|
||||
|
||||
const char *dmc_setting_command(const dmc_model *m, int i, const char *value)
|
||||
{
|
||||
dmc_model *mm = (dmc_model *)m;
|
||||
if (!m)
|
||||
return "";
|
||||
buf_clear(&mm->scratch);
|
||||
if (*dmc_setting_check(m, i, value))
|
||||
return "";
|
||||
const struct setting *s = at(m, i);
|
||||
const char *v = value;
|
||||
/* (a pick takes its value as the modem lists it) */
|
||||
if (s->kind == DMC_PICK)
|
||||
v = s->choices[dmc_setting_choice_of(m, i, value)].value;
|
||||
buf_adds(&mm->scratch, "AT");
|
||||
for (const char *p = s->form; *p; p++) {
|
||||
if (p[0] == '%' && p[1]) {
|
||||
p++;
|
||||
if (*p == 's')
|
||||
buf_adds(&mm->scratch, v);
|
||||
else
|
||||
buf_addc(&mm->scratch, *p);
|
||||
} else {
|
||||
buf_addc(&mm->scratch, *p);
|
||||
}
|
||||
}
|
||||
return buf_str(&mm->scratch);
|
||||
}
|
||||
|
||||
void dmc_setting_set(dmc_model *m, int i, const char *value)
|
||||
{
|
||||
if (!m || i < 0 || i >= m->n)
|
||||
return;
|
||||
set_str(&m->s[i].value, value);
|
||||
}
|
||||
@@ -0,0 +1,763 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* session.c - the AT conversation with dmodemd (dmodemctl.h)
|
||||
*
|
||||
* The modem's bytes are read a line at a time (the ends of lines CR LF,
|
||||
* the CRs dropped). A command of dmc_command()'s is written when the
|
||||
* one before it has its final result; the lines between its echo and
|
||||
* that result are its response. Result codes nobody waits for (RING,
|
||||
* NO CARRIER, a CONNECT after an automatic answer) and the command
|
||||
* lines the user types in the terminal move the call's state too.
|
||||
*
|
||||
* Online, the bytes are the call's data and only NO CARRIER is looked
|
||||
* for; while a configurator runs, only the OK that ends it (or the
|
||||
* ERROR that refuses it). Results need the modem's verbose result
|
||||
* codes (V1, its default).
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
#include "util.h"
|
||||
|
||||
/* the usual time a command may take, and dialling's or answering's */
|
||||
#define COMMAND_MS 5000
|
||||
#define CALL_MS 120000
|
||||
/* the escape's guard time (S12's default, and a margin) */
|
||||
#define GUARD_MS 1100
|
||||
/* how long after the escape its OK may take */
|
||||
#define ESCAPE_OK_MS 3000
|
||||
/* RINGs are this far apart at most (a ring cadence is 6 s) */
|
||||
#define RING_GAP_MS 8000
|
||||
/* a line longer than this keeps only its end (a configurator's
|
||||
screens come with no line ends, and its OK after the last one) */
|
||||
#define LINE_MAX 4096
|
||||
|
||||
struct command {
|
||||
int tag; /* 0: the session's own */
|
||||
char *cmd; /* with its AT */
|
||||
int flags, timeout_ms;
|
||||
struct command *next;
|
||||
};
|
||||
|
||||
struct event {
|
||||
dmc_event ev;
|
||||
char *text, *result;
|
||||
struct event *next;
|
||||
};
|
||||
|
||||
/* the steps of a hang-up from online */
|
||||
enum { HANG_NONE, HANG_GUARD, HANG_ESCAPED };
|
||||
|
||||
struct dmc_session {
|
||||
int state;
|
||||
int64_t now;
|
||||
dmc_buf out, term, line, typed;
|
||||
/* the queue, and the one written that waits for its result */
|
||||
struct command *queue, *active;
|
||||
int64_t active_until;
|
||||
int echo_seen;
|
||||
dmc_buf response;
|
||||
int next_tag;
|
||||
/* the events, and the one dmc_next_event() last gave */
|
||||
struct event *events, *events_tail, *current;
|
||||
/* a hang-up from online: its step and when the next is due */
|
||||
int hang;
|
||||
int64_t hang_at;
|
||||
/* the user typed +++ online */
|
||||
int user_escape;
|
||||
int64_t ring_until;
|
||||
char *connect_text, *caller_number, *caller_name;
|
||||
int connect_rate;
|
||||
};
|
||||
|
||||
static void command_free(struct command *c)
|
||||
{
|
||||
if (!c)
|
||||
return;
|
||||
free(c->cmd);
|
||||
free(c);
|
||||
}
|
||||
|
||||
static void event_free(struct event *e)
|
||||
{
|
||||
if (!e)
|
||||
return;
|
||||
free(e->text);
|
||||
free(e->result);
|
||||
free(e);
|
||||
}
|
||||
|
||||
static void push_event(dmc_session *s, int type, int tag, int ok,
|
||||
const char *text, const char *result)
|
||||
{
|
||||
struct event *e = calloc(1, sizeof(*e));
|
||||
if (!e)
|
||||
abort();
|
||||
e->text = dup_str(text);
|
||||
e->result = dup_str(result);
|
||||
e->ev.type = type;
|
||||
e->ev.tag = tag;
|
||||
e->ev.ok = ok;
|
||||
e->ev.state = s->state;
|
||||
e->ev.text = e->text;
|
||||
e->ev.result = e->result;
|
||||
if (s->events_tail)
|
||||
s->events_tail->next = e;
|
||||
else
|
||||
s->events = e;
|
||||
s->events_tail = e;
|
||||
}
|
||||
|
||||
static void set_state(dmc_session *s, int state)
|
||||
{
|
||||
if (s->state == state)
|
||||
return;
|
||||
s->state = state;
|
||||
if (state != DMC_RINGING) {
|
||||
s->ring_until = 0;
|
||||
}
|
||||
if (state == DMC_IDLE || state == DMC_CLOSED) {
|
||||
s->hang = HANG_NONE;
|
||||
s->user_escape = 0;
|
||||
}
|
||||
push_event(s, DMC_EV_STATE, 0, 1, "", "");
|
||||
}
|
||||
|
||||
static void clear_queue(dmc_session *s)
|
||||
{
|
||||
while (s->queue) {
|
||||
struct command *c = s->queue;
|
||||
s->queue = c->next;
|
||||
command_free(c);
|
||||
}
|
||||
command_free(s->active);
|
||||
s->active = NULL;
|
||||
buf_clear(&s->response);
|
||||
}
|
||||
|
||||
dmc_session *dmc_session_new(void)
|
||||
{
|
||||
dmc_session *s = calloc(1, sizeof(*s));
|
||||
if (!s)
|
||||
abort();
|
||||
s->next_tag = 1;
|
||||
s->connect_text = dup_str("");
|
||||
s->caller_number = dup_str("");
|
||||
s->caller_name = dup_str("");
|
||||
return s;
|
||||
}
|
||||
|
||||
void dmc_session_free(dmc_session *s)
|
||||
{
|
||||
if (!s)
|
||||
return;
|
||||
clear_queue(s);
|
||||
while (s->events) {
|
||||
struct event *e = s->events;
|
||||
s->events = e->next;
|
||||
event_free(e);
|
||||
}
|
||||
event_free(s->current);
|
||||
buf_free(&s->out);
|
||||
buf_free(&s->term);
|
||||
buf_free(&s->line);
|
||||
buf_free(&s->typed);
|
||||
buf_free(&s->response);
|
||||
free(s->connect_text);
|
||||
free(s->caller_number);
|
||||
free(s->caller_name);
|
||||
free(s);
|
||||
}
|
||||
|
||||
void dmc_open(dmc_session *s, int64_t now_ms)
|
||||
{
|
||||
clear_queue(s);
|
||||
buf_clear(&s->out);
|
||||
buf_clear(&s->line);
|
||||
buf_clear(&s->typed);
|
||||
s->now = now_ms;
|
||||
s->hang = HANG_NONE;
|
||||
set_state(s, DMC_IDLE);
|
||||
}
|
||||
|
||||
void dmc_close(dmc_session *s)
|
||||
{
|
||||
struct command *a = s->active;
|
||||
s->active = NULL;
|
||||
if (a && a->tag)
|
||||
push_event(s, DMC_EV_RESPONSE, a->tag, 0, "", "closed");
|
||||
command_free(a);
|
||||
while (s->queue) {
|
||||
struct command *c = s->queue;
|
||||
s->queue = c->next;
|
||||
if (c->tag)
|
||||
push_event(s, DMC_EV_RESPONSE, c->tag, 0, "", "closed");
|
||||
command_free(c);
|
||||
}
|
||||
buf_clear(&s->out);
|
||||
buf_clear(&s->line);
|
||||
buf_clear(&s->typed);
|
||||
buf_clear(&s->response);
|
||||
set_state(s, DMC_CLOSED);
|
||||
}
|
||||
|
||||
/* the command's letter after AT and what comes before it, skipping
|
||||
spaces: its first command (D, A, H, O, or '!' for AT!) */
|
||||
static char first_command(const char *cmd)
|
||||
{
|
||||
const char *p = cmd;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
if (!starts_ci(p, "AT"))
|
||||
return 0;
|
||||
p += 2;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
return (char)toupper((unsigned char)*p);
|
||||
}
|
||||
|
||||
/* the command starts a configurator: AT!C, AT!CF, AT!CT */
|
||||
static int is_configurator(const char *cmd)
|
||||
{
|
||||
const char *p = cmd;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
if (!starts_ci(p, "AT"))
|
||||
return 0;
|
||||
p += 2;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
return p[0] == '!' && toupper((unsigned char)p[1]) == 'C';
|
||||
}
|
||||
|
||||
/* the state a command written puts the call in */
|
||||
static void command_sent(dmc_session *s, const char *cmd)
|
||||
{
|
||||
char c = first_command(cmd);
|
||||
if (is_configurator(cmd)) {
|
||||
if (s->state == DMC_IDLE)
|
||||
set_state(s, DMC_CONFIGURATOR);
|
||||
} else if (c == 'D') {
|
||||
if (s->state == DMC_IDLE || s->state == DMC_ONLINE_COMMAND)
|
||||
set_state(s, DMC_DIALING);
|
||||
} else if (c == 'A') {
|
||||
set_state(s, DMC_ANSWERING);
|
||||
} else if (c == 'H' && s->state == DMC_ONLINE_COMMAND) {
|
||||
set_state(s, DMC_HANGING_UP);
|
||||
}
|
||||
}
|
||||
|
||||
/* the next command written, if none waits */
|
||||
static void pump(dmc_session *s)
|
||||
{
|
||||
if (s->active || !s->queue || s->state == DMC_CLOSED ||
|
||||
s->state == DMC_ONLINE || s->state == DMC_CONFIGURATOR ||
|
||||
s->state == DMC_DIALING || s->state == DMC_ANSWERING)
|
||||
return;
|
||||
if (s->hang == HANG_GUARD || s->hang == HANG_ESCAPED)
|
||||
return;
|
||||
struct command *c = s->queue;
|
||||
s->queue = c->next;
|
||||
c->next = NULL;
|
||||
s->active = c;
|
||||
s->active_until = s->now + c->timeout_ms;
|
||||
s->echo_seen = 0;
|
||||
buf_clear(&s->response);
|
||||
buf_adds(&s->out, c->cmd);
|
||||
buf_addc(&s->out, '\r');
|
||||
command_sent(s, c->cmd);
|
||||
}
|
||||
|
||||
static int enqueue(dmc_session *s, const char *cmd, int flags,
|
||||
int timeout_ms, int tag, int front)
|
||||
{
|
||||
struct command *c = calloc(1, sizeof(*c));
|
||||
if (!c)
|
||||
abort();
|
||||
const char *p = cmd;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
if (starts_ci(p, "AT")) {
|
||||
c->cmd = dup_str(p);
|
||||
} else {
|
||||
size_t n = strlen(p);
|
||||
c->cmd = malloc(n + 3);
|
||||
if (!c->cmd)
|
||||
abort();
|
||||
memcpy(c->cmd, "AT", 2);
|
||||
memcpy(c->cmd + 2, p, n + 1);
|
||||
}
|
||||
/* (no CR or LF in it: one command line) */
|
||||
for (char *q = c->cmd; *q; q++)
|
||||
if (*q == '\r' || *q == '\n')
|
||||
*q = ' ';
|
||||
char first = first_command(c->cmd);
|
||||
c->tag = tag;
|
||||
c->flags = flags;
|
||||
c->timeout_ms = timeout_ms > 0 ? timeout_ms :
|
||||
(first == 'D' || first == 'A') ? CALL_MS : COMMAND_MS;
|
||||
if (front) {
|
||||
c->next = s->queue;
|
||||
s->queue = c;
|
||||
} else {
|
||||
struct command **q = &s->queue;
|
||||
while (*q)
|
||||
q = &(*q)->next;
|
||||
*q = c;
|
||||
}
|
||||
pump(s);
|
||||
return tag;
|
||||
}
|
||||
|
||||
int dmc_command(dmc_session *s, const char *cmd, int flags, int timeout_ms)
|
||||
{
|
||||
if (!cmd || s->state == DMC_CLOSED || s->state == DMC_ONLINE ||
|
||||
s->state == DMC_CONFIGURATOR)
|
||||
return -1;
|
||||
int tag = s->next_tag++;
|
||||
if (s->next_tag <= 0)
|
||||
s->next_tag = 1;
|
||||
return enqueue(s, cmd, flags, timeout_ms, tag, 0);
|
||||
}
|
||||
|
||||
int dmc_dial(dmc_session *s, const char *number)
|
||||
{
|
||||
dmc_buf b = { 0 };
|
||||
buf_adds(&b, "ATD");
|
||||
for (const char *p = number ? number : ""; *p; p++)
|
||||
if (*p != '\r' && *p != '\n' && *p != ';')
|
||||
buf_addc(&b, *p);
|
||||
int tag = dmc_command(s, buf_str(&b), 0, 0);
|
||||
buf_free(&b);
|
||||
return tag;
|
||||
}
|
||||
|
||||
int dmc_answer(dmc_session *s)
|
||||
{
|
||||
return dmc_command(s, "ATA", 0, 0);
|
||||
}
|
||||
|
||||
void dmc_hangup(dmc_session *s)
|
||||
{
|
||||
switch (s->state) {
|
||||
case DMC_ONLINE:
|
||||
if (s->hang == HANG_NONE) {
|
||||
s->hang = HANG_GUARD;
|
||||
s->hang_at = s->now + GUARD_MS;
|
||||
set_state(s, DMC_HANGING_UP);
|
||||
}
|
||||
break;
|
||||
case DMC_DIALING:
|
||||
case DMC_ANSWERING:
|
||||
/* any character stops it, with NO CARRIER */
|
||||
buf_addc(&s->out, '\r');
|
||||
break;
|
||||
case DMC_IDLE:
|
||||
case DMC_RINGING:
|
||||
case DMC_ONLINE_COMMAND:
|
||||
enqueue(s, "ATH", 0, 0, 0, 1);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* the line is a final result code: its kind (0 none) */
|
||||
enum { R_NONE, R_OK, R_ERROR, R_CONNECT, R_NO_CARRIER, R_FAIL };
|
||||
|
||||
static int result_kind(const char *l)
|
||||
{
|
||||
if (!strcmp(l, "OK"))
|
||||
return R_OK;
|
||||
if (!strcmp(l, "ERROR") || !strcmp(l, "+FCERROR"))
|
||||
return R_ERROR;
|
||||
if (!strncmp(l, "CONNECT", 7) && (!l[7] || l[7] == ' '))
|
||||
return R_CONNECT;
|
||||
if (!strcmp(l, "NO CARRIER"))
|
||||
return R_NO_CARRIER;
|
||||
if (!strcmp(l, "BUSY") || !strcmp(l, "NO DIALTONE") ||
|
||||
!strcmp(l, "NO DIAL TONE") || !strcmp(l, "NO ANSWER") ||
|
||||
!strcmp(l, "DELAYED") || !strcmp(l, "BLACKLISTED") ||
|
||||
!strcmp(l, "NO LINE"))
|
||||
return R_FAIL;
|
||||
return R_NONE;
|
||||
}
|
||||
|
||||
static void connected(dmc_session *s, const char *l)
|
||||
{
|
||||
set_str(&s->connect_text, l);
|
||||
s->connect_rate = atoi(l + 7);
|
||||
s->hang = HANG_NONE;
|
||||
set_state(s, DMC_ONLINE);
|
||||
}
|
||||
|
||||
/* the caller ID's lines after a RING: "NMBR = 5551234" */
|
||||
static int caller_line(dmc_session *s, const char *l)
|
||||
{
|
||||
static const char *const names[] = { "DATE", "TIME", "NMBR", "NAME",
|
||||
"MESG", "DDN_NMBR", NULL };
|
||||
for (int i = 0; names[i]; i++) {
|
||||
size_t n = strlen(names[i]);
|
||||
if (strncmp(l, names[i], n))
|
||||
continue;
|
||||
const char *p = l + n;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
if (*p != '=')
|
||||
continue;
|
||||
p++;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
if (!strcmp(names[i], "NMBR"))
|
||||
set_str(&s->caller_number, p);
|
||||
else if (!strcmp(names[i], "NAME"))
|
||||
set_str(&s->caller_name, p);
|
||||
dmc_buf b = { 0 };
|
||||
buf_adds(&b, names[i]);
|
||||
buf_addc(&b, '=');
|
||||
buf_adds(&b, p);
|
||||
push_event(s, DMC_EV_CALLER, 0, 1, buf_str(&b), "");
|
||||
buf_free(&b);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* a result nobody's command waited for */
|
||||
static void unsolicited(dmc_session *s, const char *l, int kind)
|
||||
{
|
||||
if (!strcmp(l, "RING")) {
|
||||
if (s->state == DMC_IDLE || s->state == DMC_RINGING) {
|
||||
if (s->state == DMC_IDLE) {
|
||||
set_str(&s->caller_number, "");
|
||||
set_str(&s->caller_name, "");
|
||||
}
|
||||
set_state(s, DMC_RINGING);
|
||||
s->ring_until = s->now + RING_GAP_MS;
|
||||
}
|
||||
push_event(s, DMC_EV_RESULT, 0, 1, "", l);
|
||||
return;
|
||||
}
|
||||
if (caller_line(s, l))
|
||||
return;
|
||||
switch (kind) {
|
||||
case R_CONNECT:
|
||||
connected(s, l);
|
||||
break;
|
||||
case R_NO_CARRIER:
|
||||
case R_FAIL:
|
||||
set_state(s, DMC_IDLE);
|
||||
break;
|
||||
case R_OK:
|
||||
if (s->state == DMC_HANGING_UP)
|
||||
set_state(s, DMC_IDLE);
|
||||
else if (s->state == DMC_DIALING || s->state == DMC_ANSWERING)
|
||||
set_state(s, DMC_IDLE); /* ATD...; and the like */
|
||||
return;
|
||||
case R_ERROR:
|
||||
if (s->state == DMC_DIALING || s->state == DMC_ANSWERING ||
|
||||
s->state == DMC_CONFIGURATOR)
|
||||
set_state(s, DMC_IDLE);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
push_event(s, DMC_EV_RESULT, 0, kind != R_FAIL && kind != R_NO_CARRIER,
|
||||
"", l);
|
||||
}
|
||||
|
||||
/* the active command's final result */
|
||||
static void finish(dmc_session *s, const char *result, int kind)
|
||||
{
|
||||
struct command *c = s->active;
|
||||
s->active = NULL;
|
||||
char first = first_command(c->cmd);
|
||||
switch (kind) {
|
||||
case R_CONNECT:
|
||||
connected(s, result);
|
||||
break;
|
||||
case R_NO_CARRIER:
|
||||
case R_FAIL:
|
||||
set_state(s, DMC_IDLE);
|
||||
break;
|
||||
case R_OK:
|
||||
if (s->state == DMC_HANGING_UP || first == 'H' ||
|
||||
(first == 'Z' && s->state != DMC_CONFIGURATOR))
|
||||
set_state(s, DMC_IDLE);
|
||||
else if (s->state == DMC_DIALING || s->state == DMC_ANSWERING ||
|
||||
s->state == DMC_CONFIGURATOR)
|
||||
set_state(s, DMC_IDLE);
|
||||
break;
|
||||
case R_ERROR:
|
||||
if (s->state != DMC_ONLINE_COMMAND && s->state != DMC_IDLE)
|
||||
set_state(s, DMC_IDLE);
|
||||
break;
|
||||
}
|
||||
if (c->tag)
|
||||
push_event(s, DMC_EV_RESPONSE, c->tag,
|
||||
kind == R_OK || kind == R_CONNECT,
|
||||
buf_str(&s->response), result);
|
||||
command_free(c);
|
||||
buf_clear(&s->response);
|
||||
pump(s);
|
||||
}
|
||||
|
||||
/* a whole line from the modem (no CR or LF) */
|
||||
static void line_in(dmc_session *s, const char *l)
|
||||
{
|
||||
/* online: the call's data, but for its end */
|
||||
if (s->state == DMC_ONLINE ||
|
||||
(s->state == DMC_HANGING_UP && s->hang == HANG_GUARD)) {
|
||||
if (!strcmp(l, "NO CARRIER")) {
|
||||
set_state(s, DMC_IDLE);
|
||||
push_event(s, DMC_EV_RESULT, 0, 0, "", l);
|
||||
} else if (!strcmp(l, "OK") && s->user_escape) {
|
||||
s->user_escape = 0;
|
||||
set_state(s, DMC_ONLINE_COMMAND);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (s->state == DMC_HANGING_UP && s->hang == HANG_ESCAPED) {
|
||||
if (!strcmp(l, "OK")) {
|
||||
s->hang = HANG_NONE;
|
||||
enqueue(s, "ATH", 0, 0, 0, 1);
|
||||
} else if (!strcmp(l, "NO CARRIER")) {
|
||||
set_state(s, DMC_IDLE);
|
||||
push_event(s, DMC_EV_RESULT, 0, 0, "", l);
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* a configurator: only its end */
|
||||
if (s->state == DMC_CONFIGURATOR) {
|
||||
const char *p = l;
|
||||
/* (its last screen may come before the OK on that line) */
|
||||
size_t n = strlen(p);
|
||||
int ok = n >= 2 && !strcmp(p + n - 2, "OK");
|
||||
int err = !strcmp(p, "ERROR");
|
||||
if (!ok && !err && strcmp(p, "RING"))
|
||||
return;
|
||||
if (s->active && (ok || err)) {
|
||||
finish(s, ok ? "OK" : "ERROR", ok ? R_OK : R_ERROR);
|
||||
return;
|
||||
}
|
||||
if (!strcmp(p, "RING")) {
|
||||
/* a RING ends it, with no OK */
|
||||
set_state(s, DMC_IDLE);
|
||||
unsolicited(s, p, R_NONE);
|
||||
return;
|
||||
}
|
||||
set_state(s, DMC_IDLE);
|
||||
return;
|
||||
}
|
||||
int kind = result_kind(l);
|
||||
if (s->active) {
|
||||
if (!s->echo_seen && same_ci(l, s->active->cmd)) {
|
||||
s->echo_seen = 1;
|
||||
return;
|
||||
}
|
||||
if (!*l && !s->response.n)
|
||||
return;
|
||||
if (!strcmp(l, "RING")) {
|
||||
/* a RING in a quiet response still reaches the
|
||||
screen */
|
||||
if (s->active->flags & DMC_QUIET)
|
||||
buf_adds(&s->term, "\r\nRING\r\n");
|
||||
unsolicited(s, l, R_NONE);
|
||||
return;
|
||||
}
|
||||
if (kind != R_NONE) {
|
||||
/* (the response without its blank lines at the end) */
|
||||
while (s->response.n &&
|
||||
s->response.p[s->response.n - 1] == '\n')
|
||||
buf_pop(&s->response);
|
||||
finish(s, l, kind);
|
||||
return;
|
||||
}
|
||||
if (s->response.n)
|
||||
buf_addc(&s->response, '\n');
|
||||
buf_adds(&s->response, l);
|
||||
return;
|
||||
}
|
||||
if (!*l)
|
||||
return;
|
||||
unsolicited(s, l, kind);
|
||||
}
|
||||
|
||||
void dmc_feed(dmc_session *s, const char *data, int n)
|
||||
{
|
||||
if (s->state == DMC_CLOSED)
|
||||
return;
|
||||
for (int i = 0; i < n; i++) {
|
||||
char c = data[i];
|
||||
int quiet = s->active && (s->active->flags & DMC_QUIET);
|
||||
if (!quiet)
|
||||
buf_addc(&s->term, c);
|
||||
if (c == '\n') {
|
||||
line_in(s, buf_str(&s->line));
|
||||
buf_clear(&s->line);
|
||||
continue;
|
||||
}
|
||||
if (c == '\r')
|
||||
continue;
|
||||
if (s->line.n >= LINE_MAX)
|
||||
buf_drop(&s->line, s->line.n - LINE_MAX / 2);
|
||||
buf_addc(&s->line, c);
|
||||
}
|
||||
}
|
||||
|
||||
void dmc_type(dmc_session *s, const char *data, int n)
|
||||
{
|
||||
if (s->state == DMC_CLOSED)
|
||||
return;
|
||||
buf_add(&s->out, data, n);
|
||||
if (s->state == DMC_ONLINE) {
|
||||
/* the escape typed by hand: its OK is command mode */
|
||||
for (int i = 0; i < n; i++)
|
||||
if (data[i] == '+')
|
||||
s->user_escape = 1;
|
||||
return;
|
||||
}
|
||||
if (s->state == DMC_CONFIGURATOR)
|
||||
return;
|
||||
for (int i = 0; i < n; i++) {
|
||||
char c = data[i];
|
||||
if (c == '\r' || c == '\n') {
|
||||
if (s->typed.n)
|
||||
command_sent(s, buf_str(&s->typed));
|
||||
buf_clear(&s->typed);
|
||||
} else if (c == '\b' || c == 0x7f) {
|
||||
buf_pop(&s->typed);
|
||||
} else if (s->typed.n < LINE_MAX) {
|
||||
buf_addc(&s->typed, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int dmc_poll(dmc_session *s, int64_t now_ms)
|
||||
{
|
||||
s->now = now_ms;
|
||||
int64_t next = -1;
|
||||
if (s->state == DMC_CLOSED)
|
||||
return -1;
|
||||
if (s->hang == HANG_GUARD && now_ms >= s->hang_at) {
|
||||
buf_adds(&s->out, "+++");
|
||||
s->hang = HANG_ESCAPED;
|
||||
s->hang_at = now_ms + GUARD_MS + ESCAPE_OK_MS;
|
||||
} else if (s->hang == HANG_ESCAPED && now_ms >= s->hang_at) {
|
||||
/* no OK: ATH all the same */
|
||||
s->hang = HANG_NONE;
|
||||
enqueue(s, "ATH", 0, 0, 0, 1);
|
||||
}
|
||||
if (s->hang != HANG_NONE)
|
||||
next = s->hang_at - now_ms;
|
||||
if (s->state == DMC_RINGING && s->ring_until && now_ms >= s->ring_until)
|
||||
set_state(s, DMC_IDLE);
|
||||
if (s->state == DMC_RINGING && s->ring_until) {
|
||||
int64_t d = s->ring_until - now_ms;
|
||||
if (next < 0 || d < next)
|
||||
next = d;
|
||||
}
|
||||
if (s->active) {
|
||||
if (now_ms >= s->active_until) {
|
||||
struct command *c = s->active;
|
||||
s->active = NULL;
|
||||
if (s->state == DMC_DIALING || s->state == DMC_ANSWERING) {
|
||||
buf_addc(&s->out, '\r');
|
||||
set_state(s, DMC_IDLE);
|
||||
}
|
||||
if (c->tag)
|
||||
push_event(s, DMC_EV_RESPONSE, c->tag, 0,
|
||||
buf_str(&s->response), "timeout");
|
||||
command_free(c);
|
||||
buf_clear(&s->response);
|
||||
} else {
|
||||
int64_t d = s->active_until - now_ms;
|
||||
if (next < 0 || d < next)
|
||||
next = d;
|
||||
}
|
||||
}
|
||||
pump(s);
|
||||
if (s->active && next < 0)
|
||||
next = s->active_until - now_ms;
|
||||
if (next > 0x7fffffff)
|
||||
next = 0x7fffffff;
|
||||
return (int)next;
|
||||
}
|
||||
|
||||
int dmc_output(dmc_session *s, char *buf, int max)
|
||||
{
|
||||
return buf_take(&s->out, buf, max);
|
||||
}
|
||||
|
||||
int dmc_terminal(dmc_session *s, char *buf, int max)
|
||||
{
|
||||
return buf_take(&s->term, buf, max);
|
||||
}
|
||||
|
||||
int dmc_next_event(dmc_session *s, dmc_event *ev)
|
||||
{
|
||||
event_free(s->current);
|
||||
s->current = NULL;
|
||||
struct event *e = s->events;
|
||||
if (!e) {
|
||||
memset(ev, 0, sizeof(*ev));
|
||||
ev->text = ev->result = "";
|
||||
return 0;
|
||||
}
|
||||
s->events = e->next;
|
||||
if (!s->events)
|
||||
s->events_tail = NULL;
|
||||
s->current = e;
|
||||
*ev = e->ev;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int dmc_state(const dmc_session *s)
|
||||
{
|
||||
return s->state;
|
||||
}
|
||||
|
||||
const char *dmc_state_name(int state)
|
||||
{
|
||||
switch (state) {
|
||||
case DMC_CLOSED: return "Not connected";
|
||||
case DMC_IDLE: return "Idle";
|
||||
case DMC_DIALING: return "Dialling";
|
||||
case DMC_RINGING: return "Ringing";
|
||||
case DMC_ANSWERING: return "Answering";
|
||||
case DMC_ONLINE: return "Online";
|
||||
case DMC_ONLINE_COMMAND: return "Online (command mode)";
|
||||
case DMC_HANGING_UP: return "Hanging up";
|
||||
case DMC_CONFIGURATOR: return "Configurator";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
const char *dmc_connect_text(const dmc_session *s)
|
||||
{
|
||||
return s->connect_text;
|
||||
}
|
||||
|
||||
int dmc_connect_rate(const dmc_session *s)
|
||||
{
|
||||
return s->connect_rate;
|
||||
}
|
||||
|
||||
const char *dmc_caller_number(const dmc_session *s)
|
||||
{
|
||||
return s->caller_number;
|
||||
}
|
||||
|
||||
const char *dmc_caller_name(const dmc_session *s)
|
||||
{
|
||||
return s->caller_name;
|
||||
}
|
||||
|
||||
int dmc_version(void)
|
||||
{
|
||||
return DMC_VERSION;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* util.c - growable byte buffers and string helpers
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "util.h"
|
||||
|
||||
static void grow(dmc_buf *b, int need)
|
||||
{
|
||||
if (b->n + need + 1 <= b->cap)
|
||||
return;
|
||||
int cap = b->cap ? b->cap : 64;
|
||||
while (cap < b->n + need + 1)
|
||||
cap *= 2;
|
||||
char *p = realloc(b->p, (size_t)cap);
|
||||
if (!p)
|
||||
abort();
|
||||
b->p = p;
|
||||
b->cap = cap;
|
||||
}
|
||||
|
||||
void buf_add(dmc_buf *b, const char *s, int n)
|
||||
{
|
||||
if (n <= 0)
|
||||
return;
|
||||
grow(b, n);
|
||||
memcpy(b->p + b->n, s, (size_t)n);
|
||||
b->n += n;
|
||||
b->p[b->n] = '\0';
|
||||
}
|
||||
|
||||
void buf_adds(dmc_buf *b, const char *s)
|
||||
{
|
||||
buf_add(b, s, (int)strlen(s));
|
||||
}
|
||||
|
||||
void buf_addc(dmc_buf *b, char c)
|
||||
{
|
||||
buf_add(b, &c, 1);
|
||||
}
|
||||
|
||||
void buf_drop(dmc_buf *b, int n)
|
||||
{
|
||||
if (n >= b->n) {
|
||||
buf_clear(b);
|
||||
return;
|
||||
}
|
||||
memmove(b->p, b->p + n, (size_t)(b->n - n));
|
||||
b->n -= n;
|
||||
b->p[b->n] = '\0';
|
||||
}
|
||||
|
||||
void buf_pop(dmc_buf *b)
|
||||
{
|
||||
if (b->n > 0)
|
||||
b->p[--b->n] = '\0';
|
||||
}
|
||||
|
||||
void buf_clear(dmc_buf *b)
|
||||
{
|
||||
b->n = 0;
|
||||
if (b->p)
|
||||
b->p[0] = '\0';
|
||||
}
|
||||
|
||||
void buf_free(dmc_buf *b)
|
||||
{
|
||||
free(b->p);
|
||||
b->p = NULL;
|
||||
b->n = b->cap = 0;
|
||||
}
|
||||
|
||||
int buf_take(dmc_buf *b, char *out, int max)
|
||||
{
|
||||
int n = b->n < max ? b->n : max;
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
memcpy(out, b->p, (size_t)n);
|
||||
buf_drop(b, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
const char *buf_str(dmc_buf *b)
|
||||
{
|
||||
return b->p ? b->p : "";
|
||||
}
|
||||
|
||||
char *dup_n(const char *s, size_t n)
|
||||
{
|
||||
char *p = malloc(n + 1);
|
||||
if (!p)
|
||||
abort();
|
||||
memcpy(p, s, n);
|
||||
p[n] = '\0';
|
||||
return p;
|
||||
}
|
||||
|
||||
char *dup_str(const char *s)
|
||||
{
|
||||
return dup_n(s ? s : "", strlen(s ? s : ""));
|
||||
}
|
||||
|
||||
static char lower(char c)
|
||||
{
|
||||
return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
|
||||
}
|
||||
|
||||
int same_ci(const char *s, const char *t)
|
||||
{
|
||||
while (*s && *t && lower(*s) == lower(*t)) {
|
||||
s++;
|
||||
t++;
|
||||
}
|
||||
return !*s && !*t;
|
||||
}
|
||||
|
||||
int starts_ci(const char *s, const char *p)
|
||||
{
|
||||
while (*p) {
|
||||
if (lower(*s) != lower(*p))
|
||||
return 0;
|
||||
s++;
|
||||
p++;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
void set_str(char **p, const char *s)
|
||||
{
|
||||
free(*p);
|
||||
*p = dup_str(s);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* util.h - growable byte buffers and string helpers shared by the
|
||||
* library's parts
|
||||
*/
|
||||
#ifndef DMC_UTIL_H
|
||||
#define DMC_UTIL_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/* a growable run of bytes, always ended by a '\0' past n */
|
||||
typedef struct dmc_buf {
|
||||
char *p;
|
||||
int n, cap;
|
||||
} dmc_buf;
|
||||
|
||||
void buf_add(dmc_buf *b, const char *s, int n);
|
||||
void buf_adds(dmc_buf *b, const char *s);
|
||||
void buf_addc(dmc_buf *b, char c);
|
||||
/* the last byte taken off (none: nothing) */
|
||||
void buf_pop(dmc_buf *b);
|
||||
/* the first n bytes taken out */
|
||||
void buf_drop(dmc_buf *b, int n);
|
||||
void buf_clear(dmc_buf *b);
|
||||
void buf_free(dmc_buf *b);
|
||||
/* up to max bytes moved into out: how many */
|
||||
int buf_take(dmc_buf *b, char *out, int max);
|
||||
/* its text ("" when empty) */
|
||||
const char *buf_str(dmc_buf *b);
|
||||
|
||||
/* a copy of s (or of its first n bytes) */
|
||||
char *dup_str(const char *s);
|
||||
char *dup_n(const char *s, size_t n);
|
||||
/* s and t the same, ignoring ASCII case */
|
||||
int same_ci(const char *s, const char *t);
|
||||
/* s begins with p, ignoring ASCII case */
|
||||
int starts_ci(const char *s, const char *p);
|
||||
/* *p set to a copy of s (the old one freed) */
|
||||
void set_str(char **p, const char *s);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,782 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* vt.c - a small ANSI terminal screen (dmodemctl.h)
|
||||
*
|
||||
* Enough of a VT100 and ANSI X3.64 for the modem's command mode and its
|
||||
* full-screen configurator (AT!CF): UTF-8 text, CR, LF, BS, TAB, the
|
||||
* cursor moves (CUP, CUU, CUD, CUF, CUB, CHA, VPA, ESC 7 and 8), erasing
|
||||
* (ED, EL, ECH), inserting and deleting (ICH, DCH, IL, DL), the scroll
|
||||
* region (DECSTBM), SGR's colours and bold, underline and reverse, the
|
||||
* cursor shown or hidden (?25), and the cursor position report the
|
||||
* modem asks for (DSR 6) to learn the screen's size. What it does not
|
||||
* know it skips.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
#include "util.h"
|
||||
|
||||
struct cell {
|
||||
uint32_t ch;
|
||||
int8_t fg, bg;
|
||||
uint8_t attr;
|
||||
};
|
||||
|
||||
struct line {
|
||||
struct cell *c;
|
||||
int n;
|
||||
};
|
||||
|
||||
enum { GROUND, ESCAPE, CSI, OSC, OSC_ESC, CHARSET };
|
||||
|
||||
#define MAX_PARAMS 16
|
||||
|
||||
struct dmc_vt {
|
||||
int cols, rows;
|
||||
struct cell *screen; /* rows * cols */
|
||||
/* the scrollback, newest last */
|
||||
struct line *hist;
|
||||
int hist_n, hist_max;
|
||||
int cx, cy; /* the cursor */
|
||||
int wrap; /* the next character wraps */
|
||||
int top, bottom; /* the scroll region, 0-based */
|
||||
int sx, sy; /* ESC 7's */
|
||||
int8_t fg, bg;
|
||||
uint8_t attr;
|
||||
int cursor_on;
|
||||
int changed;
|
||||
/* the parser */
|
||||
int state;
|
||||
int params[MAX_PARAMS], n_params;
|
||||
int private_mark;
|
||||
/* UTF-8 being read */
|
||||
uint32_t u;
|
||||
int u_left;
|
||||
dmc_buf reply, text;
|
||||
};
|
||||
|
||||
static struct cell blank(const dmc_vt *t)
|
||||
{
|
||||
/* (assigned: C89 compilers, Watcom's, take constants only in an
|
||||
initialiser) */
|
||||
struct cell c;
|
||||
c.ch = ' ';
|
||||
c.fg = -1;
|
||||
c.bg = t ? t->bg : -1;
|
||||
c.attr = 0;
|
||||
return c;
|
||||
}
|
||||
|
||||
static struct cell *cell(dmc_vt *t, int y, int x)
|
||||
{
|
||||
return &t->screen[y * t->cols + x];
|
||||
}
|
||||
|
||||
static void clear_cells(dmc_vt *t, int y, int x0, int x1)
|
||||
{
|
||||
struct cell b = blank(t);
|
||||
for (int x = x0; x < x1 && x < t->cols; x++)
|
||||
*cell(t, y, x) = b;
|
||||
}
|
||||
|
||||
dmc_vt *dmc_vt_new(int cols, int rows, int scrollback)
|
||||
{
|
||||
dmc_vt *t = calloc(1, sizeof(*t));
|
||||
if (!t)
|
||||
abort();
|
||||
t->hist_max = scrollback > 0 ? scrollback : 0;
|
||||
t->cols = cols > 0 ? cols : 80;
|
||||
t->rows = rows > 0 ? rows : 24;
|
||||
t->screen = calloc((size_t)(t->cols * t->rows), sizeof(struct cell));
|
||||
if (!t->screen)
|
||||
abort();
|
||||
dmc_vt_reset(t);
|
||||
return t;
|
||||
}
|
||||
|
||||
static void free_hist(dmc_vt *t)
|
||||
{
|
||||
for (int i = 0; i < t->hist_n; i++)
|
||||
free(t->hist[i].c);
|
||||
free(t->hist);
|
||||
t->hist = NULL;
|
||||
t->hist_n = 0;
|
||||
}
|
||||
|
||||
void dmc_vt_free(dmc_vt *t)
|
||||
{
|
||||
if (!t)
|
||||
return;
|
||||
free_hist(t);
|
||||
free(t->screen);
|
||||
buf_free(&t->reply);
|
||||
buf_free(&t->text);
|
||||
free(t);
|
||||
}
|
||||
|
||||
void dmc_vt_reset(dmc_vt *t)
|
||||
{
|
||||
t->fg = t->bg = -1;
|
||||
t->attr = 0;
|
||||
for (int y = 0; y < t->rows; y++)
|
||||
clear_cells(t, y, 0, t->cols);
|
||||
t->cx = t->cy = t->sx = t->sy = 0;
|
||||
t->wrap = 0;
|
||||
t->top = 0;
|
||||
t->bottom = t->rows - 1;
|
||||
t->cursor_on = 1;
|
||||
t->state = GROUND;
|
||||
t->u_left = 0;
|
||||
t->changed = 1;
|
||||
}
|
||||
|
||||
void dmc_vt_resize(dmc_vt *t, int cols, int rows)
|
||||
{
|
||||
if (cols < 2 || rows < 2 || (cols == t->cols && rows == t->rows))
|
||||
return;
|
||||
struct cell *s = calloc((size_t)(cols * rows), sizeof(struct cell));
|
||||
if (!s)
|
||||
abort();
|
||||
struct cell b = { ' ', -1, -1, 0 };
|
||||
for (int i = 0; i < cols * rows; i++)
|
||||
s[i] = b;
|
||||
/* the bottom of the old screen at the bottom of the new, where
|
||||
the cursor's line would otherwise go */
|
||||
int shift = t->cy >= rows ? t->cy - rows + 1 : 0;
|
||||
for (int y = 0; y < rows && y + shift < t->rows; y++)
|
||||
for (int x = 0; x < cols && x < t->cols; x++)
|
||||
s[y * cols + x] = *cell(t, y + shift, x);
|
||||
free(t->screen);
|
||||
t->screen = s;
|
||||
t->cols = cols;
|
||||
t->rows = rows;
|
||||
t->cy -= shift;
|
||||
if (t->cx >= cols)
|
||||
t->cx = cols - 1;
|
||||
if (t->cy >= rows)
|
||||
t->cy = rows - 1;
|
||||
t->top = 0;
|
||||
t->bottom = rows - 1;
|
||||
t->wrap = 0;
|
||||
t->changed = 1;
|
||||
}
|
||||
|
||||
int dmc_vt_cols(const dmc_vt *t) { return t->cols; }
|
||||
int dmc_vt_rows(const dmc_vt *t) { return t->rows; }
|
||||
|
||||
/* the top line of the screen to the scrollback */
|
||||
static void keep_line(dmc_vt *t, int y)
|
||||
{
|
||||
if (!t->hist_max)
|
||||
return;
|
||||
if (t->hist_n == t->hist_max) {
|
||||
free(t->hist[0].c);
|
||||
memmove(t->hist, t->hist + 1,
|
||||
sizeof(*t->hist) * (size_t)(t->hist_n - 1));
|
||||
t->hist_n--;
|
||||
} else {
|
||||
struct line *h = realloc(t->hist, sizeof(*h) *
|
||||
(size_t)(t->hist_n + 1));
|
||||
if (!h)
|
||||
abort();
|
||||
t->hist = h;
|
||||
}
|
||||
struct line *l = &t->hist[t->hist_n++];
|
||||
l->n = t->cols;
|
||||
l->c = malloc(sizeof(struct cell) * (size_t)t->cols);
|
||||
if (!l->c)
|
||||
abort();
|
||||
memcpy(l->c, cell(t, y, 0), sizeof(struct cell) * (size_t)t->cols);
|
||||
}
|
||||
|
||||
/* the region from top to bottom up n lines */
|
||||
static void scroll_up(dmc_vt *t, int top, int bottom, int n)
|
||||
{
|
||||
for (int k = 0; k < n; k++) {
|
||||
if (top == 0 && bottom == t->rows - 1)
|
||||
keep_line(t, 0);
|
||||
memmove(cell(t, top, 0), cell(t, top + 1, 0),
|
||||
sizeof(struct cell) * (size_t)(t->cols * (bottom - top)));
|
||||
clear_cells(t, bottom, 0, t->cols);
|
||||
}
|
||||
}
|
||||
|
||||
static void scroll_down(dmc_vt *t, int top, int bottom, int n)
|
||||
{
|
||||
for (int k = 0; k < n; k++) {
|
||||
memmove(cell(t, top + 1, 0), cell(t, top, 0),
|
||||
sizeof(struct cell) * (size_t)(t->cols * (bottom - top)));
|
||||
clear_cells(t, top, 0, t->cols);
|
||||
}
|
||||
}
|
||||
|
||||
static void line_feed(dmc_vt *t)
|
||||
{
|
||||
if (t->cy == t->bottom)
|
||||
scroll_up(t, t->top, t->bottom, 1);
|
||||
else if (t->cy < t->rows - 1)
|
||||
t->cy++;
|
||||
}
|
||||
|
||||
static void put(dmc_vt *t, uint32_t ch)
|
||||
{
|
||||
if (t->wrap) {
|
||||
t->cx = 0;
|
||||
line_feed(t);
|
||||
t->wrap = 0;
|
||||
}
|
||||
struct cell *c = cell(t, t->cy, t->cx);
|
||||
c->ch = ch;
|
||||
c->fg = t->fg;
|
||||
c->bg = t->bg;
|
||||
c->attr = t->attr;
|
||||
if (t->cx == t->cols - 1)
|
||||
t->wrap = 1;
|
||||
else
|
||||
t->cx++;
|
||||
}
|
||||
|
||||
static int param(const dmc_vt *t, int i, int def)
|
||||
{
|
||||
return i < t->n_params && t->params[i] > 0 ? t->params[i] : def;
|
||||
}
|
||||
|
||||
static void clamp_cursor(dmc_vt *t)
|
||||
{
|
||||
if (t->cx < 0)
|
||||
t->cx = 0;
|
||||
if (t->cx >= t->cols)
|
||||
t->cx = t->cols - 1;
|
||||
if (t->cy < 0)
|
||||
t->cy = 0;
|
||||
if (t->cy >= t->rows)
|
||||
t->cy = t->rows - 1;
|
||||
t->wrap = 0;
|
||||
}
|
||||
|
||||
static void sgr(dmc_vt *t)
|
||||
{
|
||||
if (!t->n_params) {
|
||||
t->fg = t->bg = -1;
|
||||
t->attr = 0;
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < t->n_params; i++) {
|
||||
int p = t->params[i] < 0 ? 0 : t->params[i];
|
||||
if (p == 0) {
|
||||
t->fg = t->bg = -1;
|
||||
t->attr = 0;
|
||||
} else if (p == 1) {
|
||||
t->attr |= DMC_BOLD;
|
||||
} else if (p == 4) {
|
||||
t->attr |= DMC_UNDERLINE;
|
||||
} else if (p == 7) {
|
||||
t->attr |= DMC_REVERSE;
|
||||
} else if (p == 22) {
|
||||
t->attr &= (uint8_t)~DMC_BOLD;
|
||||
} else if (p == 24) {
|
||||
t->attr &= (uint8_t)~DMC_UNDERLINE;
|
||||
} else if (p == 27) {
|
||||
t->attr &= (uint8_t)~DMC_REVERSE;
|
||||
} else if (p >= 30 && p <= 37) {
|
||||
t->fg = (int8_t)(p - 30);
|
||||
} else if (p == 39) {
|
||||
t->fg = -1;
|
||||
} else if (p >= 40 && p <= 47) {
|
||||
t->bg = (int8_t)(p - 40);
|
||||
} else if (p == 49) {
|
||||
t->bg = -1;
|
||||
} else if (p >= 90 && p <= 97) {
|
||||
t->fg = (int8_t)(p - 90 + 8);
|
||||
} else if (p >= 100 && p <= 107) {
|
||||
t->bg = (int8_t)(p - 100 + 8);
|
||||
} else if ((p == 38 || p == 48) && i + 1 < t->n_params) {
|
||||
/* 256 colours: the first 16 kept, the rest skipped */
|
||||
if (t->params[i + 1] == 5 && i + 2 < t->n_params) {
|
||||
int c = t->params[i + 2];
|
||||
if (c >= 0 && c < 16) {
|
||||
if (p == 38)
|
||||
t->fg = (int8_t)c;
|
||||
else
|
||||
t->bg = (int8_t)c;
|
||||
}
|
||||
i += 2;
|
||||
} else if (t->params[i + 1] == 2) {
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void csi(dmc_vt *t, char final)
|
||||
{
|
||||
int n = param(t, 0, 1);
|
||||
switch (final) {
|
||||
case 'A':
|
||||
t->cy -= n;
|
||||
if (t->cy < t->top && t->cy + n >= t->top)
|
||||
t->cy = t->top;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'B':
|
||||
t->cy += n;
|
||||
if (t->cy > t->bottom && t->cy - n <= t->bottom)
|
||||
t->cy = t->bottom;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'C':
|
||||
t->cx += n;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'D':
|
||||
t->cx -= n;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'E':
|
||||
t->cy += n;
|
||||
t->cx = 0;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'F':
|
||||
t->cy -= n;
|
||||
t->cx = 0;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'G':
|
||||
case '`':
|
||||
t->cx = n - 1;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'd':
|
||||
t->cy = n - 1;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'H':
|
||||
case 'f':
|
||||
t->cy = param(t, 0, 1) - 1;
|
||||
t->cx = param(t, 1, 1) - 1;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'J': {
|
||||
int p = t->n_params ? t->params[0] : 0;
|
||||
if (p == 0) {
|
||||
clear_cells(t, t->cy, t->cx, t->cols);
|
||||
for (int y = t->cy + 1; y < t->rows; y++)
|
||||
clear_cells(t, y, 0, t->cols);
|
||||
} else if (p == 1) {
|
||||
for (int y = 0; y < t->cy; y++)
|
||||
clear_cells(t, y, 0, t->cols);
|
||||
clear_cells(t, t->cy, 0, t->cx + 1);
|
||||
} else if (p == 2 || p == 3) {
|
||||
for (int y = 0; y < t->rows; y++)
|
||||
clear_cells(t, y, 0, t->cols);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'K': {
|
||||
int p = t->n_params ? t->params[0] : 0;
|
||||
if (p == 0)
|
||||
clear_cells(t, t->cy, t->cx, t->cols);
|
||||
else if (p == 1)
|
||||
clear_cells(t, t->cy, 0, t->cx + 1);
|
||||
else if (p == 2)
|
||||
clear_cells(t, t->cy, 0, t->cols);
|
||||
break;
|
||||
}
|
||||
case 'X':
|
||||
clear_cells(t, t->cy, t->cx, t->cx + n);
|
||||
break;
|
||||
case '@': {
|
||||
if (n > t->cols - t->cx)
|
||||
n = t->cols - t->cx;
|
||||
memmove(cell(t, t->cy, t->cx + n), cell(t, t->cy, t->cx),
|
||||
sizeof(struct cell) * (size_t)(t->cols - t->cx - n));
|
||||
clear_cells(t, t->cy, t->cx, t->cx + n);
|
||||
break;
|
||||
}
|
||||
case 'P': {
|
||||
if (n > t->cols - t->cx)
|
||||
n = t->cols - t->cx;
|
||||
memmove(cell(t, t->cy, t->cx), cell(t, t->cy, t->cx + n),
|
||||
sizeof(struct cell) * (size_t)(t->cols - t->cx - n));
|
||||
clear_cells(t, t->cy, t->cols - n, t->cols);
|
||||
break;
|
||||
}
|
||||
case 'L':
|
||||
if (t->cy >= t->top && t->cy <= t->bottom) {
|
||||
if (n > t->bottom - t->cy + 1)
|
||||
n = t->bottom - t->cy + 1;
|
||||
scroll_down(t, t->cy, t->bottom, n);
|
||||
}
|
||||
break;
|
||||
case 'M':
|
||||
if (t->cy >= t->top && t->cy <= t->bottom) {
|
||||
if (n > t->bottom - t->cy + 1)
|
||||
n = t->bottom - t->cy + 1;
|
||||
for (int k = 0; k < n; k++) {
|
||||
memmove(cell(t, t->cy, 0), cell(t, t->cy + 1, 0),
|
||||
sizeof(struct cell) *
|
||||
(size_t)(t->cols * (t->bottom - t->cy)));
|
||||
clear_cells(t, t->bottom, 0, t->cols);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'S':
|
||||
scroll_up(t, t->top, t->bottom, n);
|
||||
break;
|
||||
case 'T':
|
||||
scroll_down(t, t->top, t->bottom, n);
|
||||
break;
|
||||
case 'm':
|
||||
sgr(t);
|
||||
break;
|
||||
case 'r': {
|
||||
int top = param(t, 0, 1) - 1, bottom = param(t, 1, t->rows) - 1;
|
||||
if (bottom >= t->rows)
|
||||
bottom = t->rows - 1;
|
||||
if (top < bottom) {
|
||||
t->top = top;
|
||||
t->bottom = bottom;
|
||||
t->cx = t->cy = 0;
|
||||
t->wrap = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 's':
|
||||
t->sx = t->cx;
|
||||
t->sy = t->cy;
|
||||
break;
|
||||
case 'u':
|
||||
t->cx = t->sx;
|
||||
t->cy = t->sy;
|
||||
clamp_cursor(t);
|
||||
break;
|
||||
case 'n':
|
||||
if (t->n_params && t->params[0] == 6) {
|
||||
char r[32];
|
||||
snprintf(r, sizeof(r), "\x1b[%d;%dR", t->cy + 1, t->cx + 1);
|
||||
buf_adds(&t->reply, r);
|
||||
} else if (t->n_params && t->params[0] == 5) {
|
||||
buf_adds(&t->reply, "\x1b[0n");
|
||||
}
|
||||
break;
|
||||
case 'c':
|
||||
if (!t->private_mark)
|
||||
buf_adds(&t->reply, "\x1b[?1;2c");
|
||||
break;
|
||||
case 'h':
|
||||
case 'l':
|
||||
if (t->private_mark == '?') {
|
||||
for (int i = 0; i < t->n_params; i++) {
|
||||
if (t->params[i] == 25)
|
||||
t->cursor_on = final == 'h';
|
||||
else if (t->params[i] == 1049 ||
|
||||
t->params[i] == 47 ||
|
||||
t->params[i] == 1047) {
|
||||
for (int y = 0; y < t->rows; y++)
|
||||
clear_cells(t, y, 0, t->cols);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void control(dmc_vt *t, uint32_t c)
|
||||
{
|
||||
switch (c) {
|
||||
case '\r':
|
||||
t->cx = 0;
|
||||
t->wrap = 0;
|
||||
break;
|
||||
case '\n':
|
||||
case '\v':
|
||||
case '\f':
|
||||
line_feed(t);
|
||||
t->wrap = 0;
|
||||
break;
|
||||
case '\b':
|
||||
if (t->cx > 0)
|
||||
t->cx--;
|
||||
t->wrap = 0;
|
||||
break;
|
||||
case '\t':
|
||||
t->cx = (t->cx / 8 + 1) * 8;
|
||||
if (t->cx >= t->cols)
|
||||
t->cx = t->cols - 1;
|
||||
t->wrap = 0;
|
||||
break;
|
||||
case 0x1b:
|
||||
t->state = ESCAPE;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void byte(dmc_vt *t, unsigned char b)
|
||||
{
|
||||
switch (t->state) {
|
||||
case ESCAPE:
|
||||
t->state = GROUND;
|
||||
if (b == '[') {
|
||||
t->state = CSI;
|
||||
t->n_params = 0;
|
||||
t->private_mark = 0;
|
||||
memset(t->params, -1, sizeof(t->params));
|
||||
} else if (b == ']') {
|
||||
t->state = OSC;
|
||||
} else if (b == '(' || b == ')' || b == '*' || b == '+') {
|
||||
t->state = CHARSET;
|
||||
} else if (b == '7') {
|
||||
t->sx = t->cx;
|
||||
t->sy = t->cy;
|
||||
} else if (b == '8') {
|
||||
t->cx = t->sx;
|
||||
t->cy = t->sy;
|
||||
clamp_cursor(t);
|
||||
} else if (b == 'D') {
|
||||
line_feed(t);
|
||||
} else if (b == 'E') {
|
||||
t->cx = 0;
|
||||
line_feed(t);
|
||||
} else if (b == 'M') {
|
||||
if (t->cy == t->top)
|
||||
scroll_down(t, t->top, t->bottom, 1);
|
||||
else if (t->cy > 0)
|
||||
t->cy--;
|
||||
} else if (b == 'c') {
|
||||
dmc_vt_reset(t);
|
||||
}
|
||||
return;
|
||||
case CHARSET:
|
||||
t->state = GROUND;
|
||||
return;
|
||||
case OSC:
|
||||
if (b == 7)
|
||||
t->state = GROUND;
|
||||
else if (b == 0x1b)
|
||||
t->state = OSC_ESC;
|
||||
return;
|
||||
case OSC_ESC:
|
||||
t->state = b == '\\' ? GROUND : OSC;
|
||||
return;
|
||||
case CSI:
|
||||
if (b >= '0' && b <= '9') {
|
||||
if (!t->n_params)
|
||||
t->n_params = 1;
|
||||
int *p = &t->params[t->n_params - 1];
|
||||
if (*p < 0)
|
||||
*p = 0;
|
||||
if (*p < 100000)
|
||||
*p = *p * 10 + (b - '0');
|
||||
} else if (b == ';' || b == ':') {
|
||||
if (!t->n_params)
|
||||
t->n_params = 1;
|
||||
if (t->n_params < MAX_PARAMS)
|
||||
t->n_params++;
|
||||
} else if (b == '?' || b == '>' || b == '=' || b == '<') {
|
||||
t->private_mark = b;
|
||||
} else if (b >= 0x40 && b <= 0x7e) {
|
||||
t->state = GROUND;
|
||||
csi(t, (char)b);
|
||||
} else if (b == 0x1b) {
|
||||
t->state = ESCAPE;
|
||||
} else if (b < 0x20) {
|
||||
control(t, b);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
/* the ground state: UTF-8 */
|
||||
if (t->u_left) {
|
||||
if ((b & 0xC0) == 0x80) {
|
||||
t->u = (t->u << 6) | (b & 0x3F);
|
||||
if (--t->u_left == 0)
|
||||
put(t, t->u);
|
||||
return;
|
||||
}
|
||||
t->u_left = 0;
|
||||
put(t, 0xFFFD);
|
||||
}
|
||||
if (b < 0x20 || b == 0x7f) {
|
||||
control(t, b);
|
||||
} else if (b < 0x80) {
|
||||
put(t, b);
|
||||
} else if ((b & 0xE0) == 0xC0) {
|
||||
t->u = b & 0x1F;
|
||||
t->u_left = 1;
|
||||
} else if ((b & 0xF0) == 0xE0) {
|
||||
t->u = b & 0x0F;
|
||||
t->u_left = 2;
|
||||
} else if ((b & 0xF8) == 0xF0) {
|
||||
t->u = b & 0x07;
|
||||
t->u_left = 3;
|
||||
} else {
|
||||
put(t, 0xFFFD);
|
||||
}
|
||||
}
|
||||
|
||||
void dmc_vt_feed(dmc_vt *t, const char *data, int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
byte(t, (unsigned char)data[i]);
|
||||
if (n > 0)
|
||||
t->changed = 1;
|
||||
}
|
||||
|
||||
int dmc_vt_reply(dmc_vt *t, char *buf, int max)
|
||||
{
|
||||
return buf_take(&t->reply, buf, max);
|
||||
}
|
||||
|
||||
int dmc_vt_history(const dmc_vt *t)
|
||||
{
|
||||
return t->hist_n;
|
||||
}
|
||||
|
||||
static const struct cell *get(const dmc_vt *t, int row, int col)
|
||||
{
|
||||
static const struct cell none = { ' ', -1, -1, 0 };
|
||||
if (row >= 0) {
|
||||
if (row >= t->rows || col < 0 || col >= t->cols)
|
||||
return &none;
|
||||
return &t->screen[row * t->cols + col];
|
||||
}
|
||||
int h = t->hist_n + row;
|
||||
if (h < 0 || col < 0 || col >= t->hist[h].n)
|
||||
return &none;
|
||||
return &t->hist[h].c[col];
|
||||
}
|
||||
|
||||
uint32_t dmc_vt_char(const dmc_vt *t, int row, int col)
|
||||
{
|
||||
return get(t, row, col)->ch;
|
||||
}
|
||||
|
||||
int dmc_vt_fg(const dmc_vt *t, int row, int col)
|
||||
{
|
||||
return get(t, row, col)->fg;
|
||||
}
|
||||
|
||||
int dmc_vt_bg(const dmc_vt *t, int row, int col)
|
||||
{
|
||||
return get(t, row, col)->bg;
|
||||
}
|
||||
|
||||
int dmc_vt_attr(const dmc_vt *t, int row, int col)
|
||||
{
|
||||
return get(t, row, col)->attr;
|
||||
}
|
||||
|
||||
static void utf8(dmc_buf *b, uint32_t c)
|
||||
{
|
||||
char o[4];
|
||||
if (c < 0x80) {
|
||||
buf_addc(b, (char)c);
|
||||
} else if (c < 0x800) {
|
||||
o[0] = (char)(0xC0 | (c >> 6));
|
||||
o[1] = (char)(0x80 | (c & 0x3F));
|
||||
buf_add(b, o, 2);
|
||||
} else if (c < 0x10000) {
|
||||
o[0] = (char)(0xE0 | (c >> 12));
|
||||
o[1] = (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
o[2] = (char)(0x80 | (c & 0x3F));
|
||||
buf_add(b, o, 3);
|
||||
} else {
|
||||
o[0] = (char)(0xF0 | (c >> 18));
|
||||
o[1] = (char)(0x80 | ((c >> 12) & 0x3F));
|
||||
o[2] = (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
o[3] = (char)(0x80 | (c & 0x3F));
|
||||
buf_add(b, o, 4);
|
||||
}
|
||||
}
|
||||
|
||||
const char *dmc_vt_text(dmc_vt *t, int row)
|
||||
{
|
||||
buf_clear(&t->text);
|
||||
int n = row >= 0 ? t->cols : (t->hist_n + row >= 0 ?
|
||||
t->hist[t->hist_n + row].n : 0);
|
||||
while (n > 0 && get(t, row, n - 1)->ch == ' ')
|
||||
n--;
|
||||
for (int x = 0; x < n; x++)
|
||||
utf8(&t->text, get(t, row, x)->ch);
|
||||
return buf_str(&t->text);
|
||||
}
|
||||
|
||||
int dmc_vt_cursor_row(const dmc_vt *t) { return t->cy; }
|
||||
int dmc_vt_cursor_col(const dmc_vt *t) { return t->cx; }
|
||||
int dmc_vt_cursor_visible(const dmc_vt *t) { return t->cursor_on; }
|
||||
|
||||
int dmc_vt_changed(dmc_vt *t)
|
||||
{
|
||||
int c = t->changed;
|
||||
t->changed = 0;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* the bytes a key sends (a switch, not a table with designators:
|
||||
Open Watcom builds this for Windows 95) */
|
||||
static const char *key_seq(int key)
|
||||
{
|
||||
switch (key) {
|
||||
case DMC_KEY_UP: return "\x1b[A";
|
||||
case DMC_KEY_DOWN: return "\x1b[B";
|
||||
case DMC_KEY_RIGHT: return "\x1b[C";
|
||||
case DMC_KEY_LEFT: return "\x1b[D";
|
||||
case DMC_KEY_HOME: return "\x1b[H";
|
||||
case DMC_KEY_END: return "\x1b[F";
|
||||
case DMC_KEY_PGUP: return "\x1b[5~";
|
||||
case DMC_KEY_PGDN: return "\x1b[6~";
|
||||
case DMC_KEY_INSERT: return "\x1b[2~";
|
||||
case DMC_KEY_DELETE: return "\x1b[3~";
|
||||
case DMC_KEY_BACKTAB: return "\x1b[Z";
|
||||
case DMC_KEY_F1: return "\x1bOP";
|
||||
case DMC_KEY_F2: return "\x1bOQ";
|
||||
case DMC_KEY_F3: return "\x1bOR";
|
||||
case DMC_KEY_F4: return "\x1bOS";
|
||||
case DMC_KEY_F5: return "\x1b[15~";
|
||||
case DMC_KEY_F6: return "\x1b[17~";
|
||||
case DMC_KEY_F7: return "\x1b[18~";
|
||||
case DMC_KEY_F8: return "\x1b[19~";
|
||||
case DMC_KEY_F9: return "\x1b[20~";
|
||||
case DMC_KEY_F10: return "\x1b[21~";
|
||||
case DMC_KEY_ENTER: return "\r";
|
||||
case DMC_KEY_BACKSPACE: return "\b";
|
||||
case DMC_KEY_TAB: return "\t";
|
||||
case DMC_KEY_ESCAPE: return "\x1b";
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int dmc_vt_key(const dmc_vt *t, int key, char *buf, int max)
|
||||
{
|
||||
const char *seq = key_seq(key);
|
||||
(void)t;
|
||||
if (!seq)
|
||||
return 0;
|
||||
int n = (int)strlen(seq);
|
||||
if (n > max)
|
||||
return 0;
|
||||
memcpy(buf, seq, (size_t)n);
|
||||
return n;
|
||||
}
|
||||
|
||||
uint32_t dmc_vt_palette(int c)
|
||||
{
|
||||
/* the CGA's colours, as the configurator was drawn for them */
|
||||
static const uint32_t pal[16] = {
|
||||
0x000000, 0xAA0000, 0x00AA00, 0xAA5500,
|
||||
0x0000AA, 0xAA00AA, 0x00AAAA, 0xAAAAAA,
|
||||
0x555555, 0xFF5555, 0x55FF55, 0xFFFF55,
|
||||
0x5555FF, 0xFF55FF, 0x55FFFF, 0xFFFFFF,
|
||||
};
|
||||
return c >= 0 && c < 16 ? pal[c] : 0;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
add_executable(dmodemctl_test dmodemctl_test.c)
|
||||
target_link_libraries(dmodemctl_test PRIVATE dmodemctl)
|
||||
target_include_directories(dmodemctl_test PRIVATE ../src)
|
||||
add_test(NAME dmodemctl COMMAND dmodemctl_test ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
@@ -0,0 +1,5 @@
|
||||
AT#UD␍
|
||||
DIAG <2A4D3263 0=10>
|
||||
DIAG <2A4D3263 1=0>
|
||||
DIAG <2A4D3263 60=1>
|
||||
OK
|
||||
@@ -0,0 +1,490 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* dmodemctl_test.c - libdmodemctl's tests: a session against a scripted
|
||||
* modem, AT!M and AT#UD as dmodemd prints them, and the terminal screen
|
||||
*
|
||||
* dmodemctl_test <the directory of model.txt>
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
|
||||
static int failures, checks;
|
||||
|
||||
#define CHECK(c) check((c), #c, __FILE__, __LINE__)
|
||||
#define CHECK_STR(a, b) check_str((a), (b), #a, __FILE__, __LINE__)
|
||||
|
||||
static void check(int ok, const char *what, const char *file, int line)
|
||||
{
|
||||
checks++;
|
||||
if (!ok) {
|
||||
failures++;
|
||||
fprintf(stderr, "%s:%d: failed: %s\n", file, line, what);
|
||||
}
|
||||
}
|
||||
|
||||
static void check_str(const char *a, const char *b, const char *what,
|
||||
const char *file, int line)
|
||||
{
|
||||
checks++;
|
||||
if (strcmp(a ? a : "(null)", b ? b : "(null)")) {
|
||||
failures++;
|
||||
fprintf(stderr, "%s:%d: %s is \"%s\", not \"%s\"\n", file, line,
|
||||
what, a ? a : "(null)", b);
|
||||
}
|
||||
}
|
||||
|
||||
/* what the session wrote to the modem, as text */
|
||||
static const char *out(dmc_session *s)
|
||||
{
|
||||
static char b[4096];
|
||||
int n = dmc_output(s, b, sizeof(b) - 1);
|
||||
b[n] = '\0';
|
||||
return b;
|
||||
}
|
||||
|
||||
static const char *term(dmc_session *s)
|
||||
{
|
||||
static char b[8192];
|
||||
int n = dmc_terminal(s, b, sizeof(b) - 1);
|
||||
b[n] = '\0';
|
||||
return b;
|
||||
}
|
||||
|
||||
static void feed(dmc_session *s, const char *t)
|
||||
{
|
||||
dmc_feed(s, t, (int)strlen(t));
|
||||
}
|
||||
|
||||
/* the next event of type, skipping the others; 0 if none */
|
||||
static int next_of(dmc_session *s, int type, dmc_event *ev)
|
||||
{
|
||||
while (dmc_next_event(s, ev))
|
||||
if (ev->type == type)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static char *read_file(const char *dir, const char *name)
|
||||
{
|
||||
char path[1024];
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, name);
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "can't open %s\n", path);
|
||||
exit(2);
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
char *b = malloc((size_t)n + 1);
|
||||
if (!b || fread(b, 1, (size_t)n, f) != (size_t)n)
|
||||
exit(2);
|
||||
b[n] = '\0';
|
||||
fclose(f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/* a command, its echo, its response and OK */
|
||||
static void test_command(void)
|
||||
{
|
||||
dmc_session *s = dmc_session_new();
|
||||
dmc_event ev;
|
||||
CHECK(dmc_state(s) == DMC_CLOSED);
|
||||
CHECK(dmc_command(s, "ATI3", 0, 0) == -1);
|
||||
dmc_open(s, 0);
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
int tag = dmc_command(s, "I3", 0, 0);
|
||||
CHECK(tag > 0);
|
||||
CHECK_STR(out(s), "ATI3\r");
|
||||
/* a second waits for the first */
|
||||
int tag2 = dmc_command(s, "ATI0", DMC_QUIET, 0);
|
||||
CHECK_STR(out(s), "");
|
||||
feed(s, "ATI3\r\r\nD-Modem 1.0.0\r\n\r\nOK\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag);
|
||||
CHECK(ev.ok);
|
||||
CHECK_STR(ev.text, "D-Modem 1.0.0");
|
||||
CHECK_STR(ev.result, "OK");
|
||||
CHECK_STR(term(s), "ATI3\r\r\nD-Modem 1.0.0\r\n\r\nOK\r\n");
|
||||
/* the quiet one: written now, kept off the screen */
|
||||
CHECK_STR(out(s), "ATI0\r");
|
||||
feed(s, "ATI0\r\r\n56000\r\nRING\r\nOK\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag2);
|
||||
CHECK_STR(ev.text, "56000");
|
||||
CHECK_STR(term(s), "\r\nRING\r\n");
|
||||
CHECK(dmc_state(s) == DMC_RINGING);
|
||||
/* ERROR */
|
||||
tag = dmc_command(s, "ATX9", 0, 0);
|
||||
out(s);
|
||||
feed(s, "ATX9\r\r\nERROR\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag && !ev.ok);
|
||||
CHECK_STR(ev.result, "ERROR");
|
||||
/* a timeout */
|
||||
dmc_poll(s, 1000);
|
||||
tag = dmc_command(s, "ATI4", 0, 0);
|
||||
out(s);
|
||||
CHECK(dmc_poll(s, 1000) > 0);
|
||||
dmc_poll(s, 7000);
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag && !ev.ok);
|
||||
CHECK_STR(ev.result, "timeout");
|
||||
dmc_close(s);
|
||||
CHECK(dmc_state(s) == DMC_CLOSED);
|
||||
dmc_session_free(s);
|
||||
}
|
||||
|
||||
/* a call: dial, connect, online data, hang up through the escape */
|
||||
static void test_call(void)
|
||||
{
|
||||
dmc_session *s = dmc_session_new();
|
||||
dmc_event ev;
|
||||
dmc_open(s, 0);
|
||||
int tag = dmc_dial(s, "555-1234");
|
||||
CHECK_STR(out(s), "ATD555-1234\r");
|
||||
CHECK(dmc_state(s) == DMC_DIALING);
|
||||
/* no other command while dialling */
|
||||
int later = dmc_command(s, "ATI11", DMC_QUIET, 0);
|
||||
CHECK_STR(out(s), "");
|
||||
feed(s, "ATD555-1234\r\r\nCONNECT 33600/ARQ/V34/LAPM/V42BIS\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag && ev.ok);
|
||||
CHECK(dmc_state(s) == DMC_ONLINE);
|
||||
CHECK(dmc_connect_rate(s) == 33600);
|
||||
CHECK_STR(dmc_connect_text(s), "CONNECT 33600/ARQ/V34/LAPM/V42BIS");
|
||||
/* online: data, not results; no commands */
|
||||
feed(s, "OK\r\nERROR\r\nhello\r\n");
|
||||
CHECK(dmc_state(s) == DMC_ONLINE);
|
||||
CHECK(dmc_command(s, "ATI0", 0, 0) == -1);
|
||||
/* hang up: the guard time, +++, OK, ATH */
|
||||
dmc_poll(s, 100);
|
||||
dmc_hangup(s);
|
||||
CHECK(dmc_state(s) == DMC_HANGING_UP);
|
||||
CHECK_STR(out(s), "");
|
||||
dmc_poll(s, 1300);
|
||||
CHECK_STR(out(s), "+++");
|
||||
feed(s, "\r\nOK\r\n");
|
||||
dmc_poll(s, 1400);
|
||||
CHECK_STR(out(s), "ATH\r");
|
||||
feed(s, "ATH\r\r\nOK\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* the command that waited goes now */
|
||||
CHECK_STR(out(s), "ATI11\r");
|
||||
feed(s, "ATI11\r\r\nLast call: 33600\r\nOK\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == later && ev.ok);
|
||||
dmc_session_free(s);
|
||||
}
|
||||
|
||||
/* the far end hangs up; a call comes in with caller ID and is
|
||||
answered; a dial stopped */
|
||||
static void test_unsolicited(void)
|
||||
{
|
||||
dmc_session *s = dmc_session_new();
|
||||
dmc_event ev;
|
||||
dmc_open(s, 0);
|
||||
dmc_poll(s, 10);
|
||||
feed(s, "\r\nRING\r\n\r\nDATE = 1106\r\nTIME = 1316\r\n"
|
||||
"NMBR = 5551234\r\nNAME = D-Modem BBS\r\n\r\nRING\r\n");
|
||||
CHECK(dmc_state(s) == DMC_RINGING);
|
||||
CHECK_STR(dmc_caller_number(s), "5551234");
|
||||
CHECK_STR(dmc_caller_name(s), "D-Modem BBS");
|
||||
CHECK(next_of(s, DMC_EV_CALLER, &ev));
|
||||
CHECK_STR(ev.text, "DATE=1106");
|
||||
/* no more rings: idle again */
|
||||
dmc_poll(s, 9000);
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
feed(s, "\r\nRING\r\n");
|
||||
int tag = dmc_answer(s);
|
||||
CHECK_STR(out(s), "ATA\r");
|
||||
CHECK(dmc_state(s) == DMC_ANSWERING);
|
||||
feed(s, "ATA\r\r\nCONNECT 28800\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag);
|
||||
CHECK(dmc_state(s) == DMC_ONLINE);
|
||||
feed(s, "data\r\nNO CARRIER\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* an automatic answer (S0) */
|
||||
feed(s, "\r\nRING\r\n\r\nCONNECT 9600\r\n");
|
||||
CHECK(dmc_state(s) == DMC_ONLINE);
|
||||
feed(s, "\r\nNO CARRIER\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* a dial stopped by a key */
|
||||
dmc_dial(s, "1");
|
||||
out(s);
|
||||
dmc_hangup(s);
|
||||
CHECK_STR(out(s), "\r");
|
||||
feed(s, "ATD1\r\r\nNO CARRIER\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
dmc_session_free(s);
|
||||
}
|
||||
|
||||
/* what the user types: ATD, the configurator */
|
||||
static void test_typed(void)
|
||||
{
|
||||
dmc_session *s = dmc_session_new();
|
||||
dmc_open(s, 0);
|
||||
dmc_type(s, "atdt12", 6);
|
||||
dmc_type(s, "3\r", 2);
|
||||
CHECK_STR(out(s), "atdt123\r");
|
||||
CHECK(dmc_state(s) == DMC_DIALING);
|
||||
feed(s, "atdt123\r\r\nBUSY\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
dmc_type(s, "AT!CF\r", 6);
|
||||
out(s);
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
feed(s, "AT!CF\r\x1b[6n\x1b[0m\x1b[2J\x1b[1;1HD-Modem setup\r\n");
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
feed(s, "\x1b[0m\x1b[2J\x1b[H\x1b[?25h\r\nOK\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* its screens as one line longer than a line is kept, the OK at the
|
||||
end of it (as AT!CF's Alt-X sends it) */
|
||||
dmc_type(s, "AT!CF\r", 6);
|
||||
out(s);
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
for (int i = 0; i < 1000; i++)
|
||||
feed(s, "\x1b[0;30;47m\xe2\x96\x91");
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
feed(s, "\x1b[0m\x1b[2J\x1b[H\x1b[?25hOK\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* refused (off hook) */
|
||||
dmc_type(s, "AT!CT\r", 6);
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
feed(s, "AT!CT\r\r\nERROR\r\n");
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
/* the configurator from a command */
|
||||
dmc_event ev;
|
||||
int tag = dmc_command(s, "AT!CT", 0, 60000);
|
||||
out(s);
|
||||
CHECK(dmc_state(s) == DMC_CONFIGURATOR);
|
||||
feed(s, "AT!CT\r\r\ndmodem#exit\r\n\r\nOK\r\n");
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.tag == tag && ev.ok);
|
||||
CHECK(dmc_state(s) == DMC_IDLE);
|
||||
dmc_session_free(s);
|
||||
}
|
||||
|
||||
static void test_model(const char *dir)
|
||||
{
|
||||
char *text = read_file(dir, "model.txt");
|
||||
/* the response as the session gives it: no echo, no OK, LF */
|
||||
dmc_session *s = dmc_session_new();
|
||||
dmc_event ev;
|
||||
dmc_open(s, 0);
|
||||
dmc_command(s, "AT!M", DMC_QUIET, 0);
|
||||
out(s);
|
||||
feed(s, text);
|
||||
CHECK(next_of(s, DMC_EV_RESPONSE, &ev));
|
||||
CHECK(ev.ok);
|
||||
CHECK_STR(term(s), "");
|
||||
dmc_model *m = dmc_model_parse(ev.text);
|
||||
CHECK(m != NULL);
|
||||
CHECK(dmc_model_count(m) == 73);
|
||||
int c = dmc_model_find(m, "country");
|
||||
CHECK(c == 0);
|
||||
CHECK(dmc_setting_kind(m, c) == DMC_PICK);
|
||||
CHECK_STR(dmc_setting_value(m, c), "B5");
|
||||
CHECK_STR(dmc_setting_group(m, c), "Line");
|
||||
CHECK(dmc_setting_choices(m, c) > 40);
|
||||
int de = -1;
|
||||
for (int i = 0; i < dmc_setting_choices(m, c); i++)
|
||||
if (!strcmp(dmc_choice_name(m, c, i), "germany"))
|
||||
de = i;
|
||||
CHECK(de >= 0);
|
||||
CHECK_STR(dmc_setting_command(m, c, dmc_choice_value(m, c, de)),
|
||||
"AT+GCI=42");
|
||||
CHECK_STR(dmc_setting_check(m, c, "ZZ"), "Not one of the choices");
|
||||
CHECK(dmc_setting_choice_of(m, c, "b5") >= 0);
|
||||
int a = dmc_model_find(m, "auto-answer");
|
||||
CHECK(a >= 0);
|
||||
CHECK(dmc_setting_kind(m, a) == DMC_NUMBER);
|
||||
CHECK(dmc_setting_lo(m, a) == 0 && dmc_setting_hi(m, a) == 255);
|
||||
CHECK_STR(dmc_setting_check(m, a, "2"), "");
|
||||
CHECK_STR(dmc_setting_check(m, a, "256"), "From 0 to 255");
|
||||
CHECK_STR(dmc_setting_check(m, a, "x"), "Enter a number");
|
||||
CHECK_STR(dmc_setting_command(m, a, "2"), "ATS0=2");
|
||||
CHECK_STR(dmc_setting_command(m, a, "300"), "");
|
||||
dmc_setting_set(m, a, "2");
|
||||
CHECK_STR(dmc_setting_value(m, a), "2");
|
||||
CHECK(dmc_model_groups(m) >= 4);
|
||||
CHECK_STR(dmc_model_group(m, 0), "Line");
|
||||
int text_kind = 0;
|
||||
for (int i = 0; i < dmc_model_count(m); i++)
|
||||
if (dmc_setting_kind(m, i) == DMC_TEXT) {
|
||||
text_kind = 1;
|
||||
CHECK_STR(dmc_setting_check(m, i, "1,0,1"), "");
|
||||
CHECK(*dmc_setting_check(m, i, "a"));
|
||||
}
|
||||
CHECK(text_kind);
|
||||
dmc_model_free(m);
|
||||
CHECK(dmc_model_parse("OK") == NULL);
|
||||
CHECK(dmc_model_parse("model\t2\t0") == NULL);
|
||||
free(text);
|
||||
dmc_session_free(s);
|
||||
}
|
||||
|
||||
static void test_diag(const char *dir)
|
||||
{
|
||||
char *text = read_file(dir, "diag-none.txt");
|
||||
dmc_diag *d = dmc_diag_parse(text);
|
||||
CHECK(dmc_diag_count(d) == 3);
|
||||
CHECK(!dmc_diag_has_call(d));
|
||||
CHECK_STR(dmc_diag_label(d, 0), "Report version");
|
||||
CHECK_STR(dmc_diag_value(d, 0), "1.0");
|
||||
CHECK_STR(dmc_diag_value(d, 2), "No previous call");
|
||||
dmc_diag_free(d);
|
||||
free(text);
|
||||
|
||||
d = dmc_diag_parse(
|
||||
"DIAG <2A4D3263 0=10>\nDIAG <2A4D3263 1=7>\n"
|
||||
"DIAG <2A4D3263 2=0 3=0>\n"
|
||||
"DIAG <2A4D3263 4=\"E0C14513\">\n"
|
||||
"DIAG <2A4D3263 10=0C>\nDIAG <2A4D3263 20=C>\n"
|
||||
"DIAG <2A4D3263 22=0D05>\n"
|
||||
"DIAG <2A4D3263 26=8340>\nDIAG <2A4D3263 34=7080>\n"
|
||||
"DIAG <2A4D3263 40=1>\nDIAG <2A4D3263 44=81>\n"
|
||||
"DIAG <2A4D3263 52=0001E240>\nDIAG <2A4D3263 60=41>\n"
|
||||
"DIAG <2A4D3263 9A=1>\n");
|
||||
CHECK(dmc_diag_has_call(d));
|
||||
CHECK(dmc_diag_count(d) == 15);
|
||||
const char *want[][2] = {
|
||||
{ "Call setup", "Data answer tone heard" },
|
||||
{ "Mode", "Data" },
|
||||
{ "DTE interface", "Asynchronous" },
|
||||
{ "V.8 CM", "E0 C1 45 13" },
|
||||
{ "Received level", "-12 dBm" },
|
||||
{ "Transmit modulation", "V.34" },
|
||||
{ "Transmit symbol rate", "3333 baud" },
|
||||
{ "First transmit rate", "33,600 bit/s" },
|
||||
{ "Last transmit rate", "28,800 bit/s" },
|
||||
{ "Error control", "V.42 LAPM" },
|
||||
{ "Compression", "V.44" },
|
||||
{ "Characters sent", "123,456" },
|
||||
{ "Why the call ended", "The other modem hung up" },
|
||||
{ "Key 9A", "1" },
|
||||
};
|
||||
for (size_t w = 0; w < sizeof(want) / sizeof(want[0]); w++) {
|
||||
int found = 0;
|
||||
for (int i = 0; i < dmc_diag_count(d); i++)
|
||||
if (!strcmp(dmc_diag_label(d, i), want[w][0])) {
|
||||
CHECK_STR(dmc_diag_value(d, i), want[w][1]);
|
||||
found = 1;
|
||||
}
|
||||
if (!found)
|
||||
fprintf(stderr, "no row %s\n", want[w][0]);
|
||||
CHECK(found);
|
||||
}
|
||||
CHECK_STR(dmc_diag_raw(d, 0x60), "41");
|
||||
CHECK(dmc_diag_raw(d, 0x61) == NULL);
|
||||
dmc_diag_free(d);
|
||||
}
|
||||
|
||||
static void test_vt(void)
|
||||
{
|
||||
dmc_vt *t = dmc_vt_new(20, 5, 100);
|
||||
const char *s = "ATI3\r\r\nD-Modem\r\n\r\nOK\r\n";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK(dmc_vt_changed(t));
|
||||
CHECK(!dmc_vt_changed(t));
|
||||
CHECK_STR(dmc_vt_text(t, 0), "ATI3");
|
||||
CHECK_STR(dmc_vt_text(t, 1), "D-Modem");
|
||||
CHECK_STR(dmc_vt_text(t, 3), "OK");
|
||||
CHECK(dmc_vt_cursor_row(t) == 4 && dmc_vt_cursor_col(t) == 0);
|
||||
/* scrolling into the scrollback */
|
||||
s = "a\r\nb\r\nc\r\n";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK(dmc_vt_history(t) == 3);
|
||||
CHECK_STR(dmc_vt_text(t, -3), "ATI3");
|
||||
CHECK_STR(dmc_vt_text(t, -1), "");
|
||||
CHECK_STR(dmc_vt_text(t, 0), "OK");
|
||||
/* the configurator's way: clear, move, colours, UTF-8 */
|
||||
s = "\x1b[0m\x1b[?25l\x1b[2J\x1b[2;3H\x1b[0;1;37;44m\xe2\x94\x8c"
|
||||
"Line\x1b[0;30;47m\xc3\xa9";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK(!dmc_vt_cursor_visible(t));
|
||||
CHECK(dmc_vt_char(t, 1, 2) == 0x250C);
|
||||
CHECK(dmc_vt_fg(t, 1, 2) == 7 && dmc_vt_bg(t, 1, 2) == 4);
|
||||
CHECK(dmc_vt_attr(t, 1, 2) == DMC_BOLD);
|
||||
CHECK(dmc_vt_char(t, 1, 7) == 0xE9);
|
||||
CHECK(dmc_vt_fg(t, 1, 7) == 0 && dmc_vt_bg(t, 1, 7) == 7);
|
||||
CHECK_STR(dmc_vt_text(t, 1), " \xe2\x94\x8cLine\xc3\xa9");
|
||||
/* the size probe: to the far corner and asked where */
|
||||
char r[32];
|
||||
s = "\x1b[999;999H\x1b[6n";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
int n = dmc_vt_reply(t, r, sizeof(r) - 1);
|
||||
r[n] = '\0';
|
||||
CHECK_STR(r, "\x1b[5;20R");
|
||||
/* and the UTF-8 probe: CR, é, asked again: column 2 */
|
||||
s = "\r\xc3\xa9\x1b[6n";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
n = dmc_vt_reply(t, r, sizeof(r) - 1);
|
||||
r[n] = '\0';
|
||||
CHECK_STR(r, "\x1b[5;2R");
|
||||
/* erase to the end of the line, insert, delete */
|
||||
s = "\x1b[3;1Habcdef\x1b[3;3H\x1b[K";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK_STR(dmc_vt_text(t, 2), "ab");
|
||||
s = "\x1b[3;1H\x1b[2@";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK_STR(dmc_vt_text(t, 2), " ab");
|
||||
s = "\x1b[3P";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK_STR(dmc_vt_text(t, 2), "b");
|
||||
/* a wrapped line */
|
||||
s = "\x1b[4;1H01234567890123456789X";
|
||||
dmc_vt_feed(t, s, (int)strlen(s));
|
||||
CHECK_STR(dmc_vt_text(t, 3), "01234567890123456789");
|
||||
CHECK_STR(dmc_vt_text(t, 4), "X");
|
||||
/* keys */
|
||||
n = dmc_vt_key(t, DMC_KEY_F2, r, sizeof(r));
|
||||
CHECK(n == 3 && !memcmp(r, "\x1bOQ", 3));
|
||||
n = dmc_vt_key(t, DMC_KEY_UP, r, sizeof(r));
|
||||
CHECK(n == 3 && !memcmp(r, "\x1b[A", 3));
|
||||
/* resized */
|
||||
dmc_vt_resize(t, 80, 24);
|
||||
CHECK(dmc_vt_cols(t) == 80 && dmc_vt_rows(t) == 24);
|
||||
CHECK_STR(dmc_vt_text(t, 3), "01234567890123456789");
|
||||
CHECK(dmc_vt_palette(4) == 0x0000AA);
|
||||
dmc_vt_free(t);
|
||||
}
|
||||
|
||||
static void test_daemon(void)
|
||||
{
|
||||
char b[256];
|
||||
CHECK(dmc_daemon_ready("Use `/dev/ttyDM0' as modem device, Ctrl+C "
|
||||
"for termination.", b, sizeof(b)));
|
||||
CHECK_STR(b, "/dev/ttyDM0");
|
||||
CHECK(dmc_daemon_ready("Use `/dev/pts/3' as modem device, Ctrl+C for "
|
||||
"termination.", b, sizeof(b)));
|
||||
CHECK_STR(b, "/dev/pts/3");
|
||||
CHECK(dmc_daemon_ready("Use TCP 127.0.0.1:2323 as the modem, Ctrl+C "
|
||||
"for termination.", b, sizeof(b)));
|
||||
CHECK_STR(b, "TCP 127.0.0.1:2323");
|
||||
CHECK(!dmc_daemon_ready("modem `dmodem0' created. TTY is `/dev/pts/3'",
|
||||
b, sizeof(b)));
|
||||
CHECK(dmc_daemon_error("error: cannot create PTY."));
|
||||
CHECK(!dmc_daemon_error("13:21:22.774 sip: SIP on 127.0.0.1:5060"));
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *dir = argc > 1 ? argv[1] : ".";
|
||||
CHECK(dmc_version() == DMC_VERSION);
|
||||
test_command();
|
||||
test_call();
|
||||
test_unsolicited();
|
||||
test_typed();
|
||||
test_model(dir);
|
||||
test_diag(dir);
|
||||
test_vt();
|
||||
test_daemon();
|
||||
printf("%d checks, %d failed\n", checks, failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
AT!M␍
|
||||
model 1 73
|
||||
setting country pick B5 B5 +GCI=%s Line Country +GCI: the line's settings and tones
|
||||
choice 02 algeria ALGERIA
|
||||
choice 07 argentina ARGENTINA
|
||||
choice 09 australia AUSTRALIA
|
||||
choice 0A austria AUSTRIA
|
||||
choice 0C bahrein BAHREIN
|
||||
choice 0F belgium BELGIUM
|
||||
choice 16 brazil BRAZIL
|
||||
choice 1A brunei BRUNEI
|
||||
choice 1B bulgaria BULGARIA
|
||||
choice 20 canada CANADA
|
||||
choice 25 chile CHILE
|
||||
choice 26 china CHINA
|
||||
choice 100 ctr21europe CTR21EUROPE
|
||||
choice 2D cyprus CYPRUS
|
||||
choice 2E czech-republic CZECH_REPUBLIC
|
||||
choice 31 denmark DENMARK
|
||||
choice 36 egypt EGYPT
|
||||
choice 101 estonia ESTONIA
|
||||
choice 3C finland FINLAND
|
||||
choice 3D france FRANCE
|
||||
choice 42 germany GERMANY
|
||||
choice 46 greece GREECE
|
||||
choice 50 hong-kong HONG_KONG
|
||||
choice 51 hungary HUNGARY
|
||||
choice 52 iceland ICELAND
|
||||
choice 53 india INDIA
|
||||
choice 54 indonesia INDONESIA
|
||||
choice 57 ireland IRELAND
|
||||
choice 58 israel ISRAEL
|
||||
choice 59 italy ITALY
|
||||
choice 00 japan JAPAN
|
||||
choice 5E jordan JORDAN
|
||||
choice 61 korea KOREA
|
||||
choice 62 kuwait KUWAIT
|
||||
choice 103 latvia LATVIA
|
||||
choice 64 lebanon LEBANON
|
||||
choice 104 lithuania LITHUANIA
|
||||
choice 69 luxembourg LUXEMBOURG
|
||||
choice 6C malaysia MALAYSIA
|
||||
choice 70 malta MALTA
|
||||
choice 73 mexico MEXICO
|
||||
choice 77 morocco MOROCCO
|
||||
choice 7B netherlands NETHERLANDS
|
||||
choice 7E new-zealand NEW_ZEALAND
|
||||
choice 82 norway NORWAY
|
||||
choice 83 oman OMAN
|
||||
choice 84 pakistan PAKISTAN
|
||||
choice 88 peru PERU
|
||||
choice 89 philippines PHILIPPINES
|
||||
choice 8A poland POLAND
|
||||
choice 8B portugal PORTUGAL
|
||||
choice 8E romania ROMANIA
|
||||
choice B8 russia RUSSIA
|
||||
choice 98 saudiarabia SAUDIARABIA
|
||||
choice 9C singapore SINGAPORE
|
||||
choice C5 slovakia SLOVAKIA
|
||||
choice C6 slovenia SLOVENIA
|
||||
choice 9F southafrica SOUTHAFRICA
|
||||
choice 107 southkorea SOUTHKOREA
|
||||
choice A0 spain SPAIN
|
||||
choice A1 srilanka SRILANKA
|
||||
choice A5 sweden SWEDEN
|
||||
choice A6 switzerland SWITZERLAND
|
||||
choice 108 taiwan TAIWAN
|
||||
choice A9 thailand THAILAND
|
||||
choice AD tunisia TUNISIA
|
||||
choice AE turkey TURKEY
|
||||
choice B3 uae UAE
|
||||
choice B4 uk UK
|
||||
choice B7 uruguay URUGUAY
|
||||
choice B5 usa USA
|
||||
choice BC vietnam VIETNAM
|
||||
setting dial-mode pick T T %s Line Dialling T tone, P pulse
|
||||
choice T tone Tone
|
||||
choice P pulse Pulse
|
||||
setting pulse-ratio pick 0 0 &P%s Line Pulse make/break &P (S28): kept; the country sets the pulses
|
||||
choice 0 0 &P0
|
||||
choice 1 1 &P1
|
||||
choice 2 2 &P2
|
||||
choice 3 3 &P3
|
||||
setting line-type pick 0 0 &L%s Line Line type &L (S47): a dialled line, or a leased one
|
||||
choice 0 dialup Dial-up
|
||||
choice 1 leased-2wire Leased 2-wire
|
||||
choice 2 leased-4wire Leased 4-wire
|
||||
setting call-progress pick 4 4 X%s Line Result codes and tones X (S56): CONNECT's rate, dial tone, busy
|
||||
choice 0 basic X0 basic
|
||||
choice 1 rate X1 rate
|
||||
choice 2 dial-tone X2 dial tone
|
||||
choice 3 busy X3 busy
|
||||
choice 4 full X4 all
|
||||
setting modulation pick 92 92 +MS=%s Modulation Modulation +MS: the highest modulation tried
|
||||
choice 21 v21 V21
|
||||
choice 22 v22 V22
|
||||
choice 23 v23 V23
|
||||
choice 26 v26 V26
|
||||
choice 126 v26ter V26ter
|
||||
choice 226 v26bis V26bis
|
||||
choice 27 v27ter V27ter
|
||||
choice 29 v29 V29
|
||||
choice 229 v29fastpos V29FastPOS
|
||||
choice 122 v22bis V22bis
|
||||
choice 32 v32 V32
|
||||
choice 132 v32bis V32bis
|
||||
choice 232 v32terbo V32terbo
|
||||
choice 168 hst HST
|
||||
choice 128 vfc VFC
|
||||
choice 61 v61 V61
|
||||
choice 33 v33 V33
|
||||
choice 34 v34 V34
|
||||
choice 103 bell103 Bell103
|
||||
choice 18 v18 V18
|
||||
choice 45 baudot Baudot
|
||||
choice 110 edt EDT
|
||||
choice 118 dtmf DTMF
|
||||
choice 121 v21text V21text
|
||||
choice 123 v23text V23text
|
||||
choice 203 bell103text Bell103text
|
||||
choice 5 contactid ContactID
|
||||
choice 12 sms SMS
|
||||
choice 212 bell212 Bell212
|
||||
choice 201 bell201 Bell201
|
||||
choice 202 bell202 Bell202
|
||||
choice 208 bell208 Bell208
|
||||
choice 56 k56flex K56Flex
|
||||
choice 90 v90 V90
|
||||
choice 91 v91 V91
|
||||
choice 92 v92 V92
|
||||
choice 150 vcvm VCVM
|
||||
choice 200 vwb VWB
|
||||
choice 255 pep PEP
|
||||
choice 64 clear CLEAR
|
||||
setting automode pick 1 1 +MS=,%s Modulation Automode +MS, N: fall back to slower modulations
|
||||
choice 0 off Off
|
||||
choice 1 on On
|
||||
setting min-rate number 300 300 300 56000 +MS=,,%s Modulation Lowest rate (bit/s) +MS: hang up rather than go below it
|
||||
setting max-rate number 56000 56000 300 56000 +MS=,,,%s Modulation Highest rate (bit/s) +MS: the fastest the modem tries
|
||||
setting error-control pick 3 3 \N%s Error control Error correction \N (S103): V.42, MNP or none
|
||||
choice 0 normal Normal (none)
|
||||
choice 1 direct Direct (none)
|
||||
choice 2 reliable Reliable
|
||||
choice 3 auto-reliable Auto-reliable
|
||||
choice 4 lapm V.42 LAPM only
|
||||
choice 5 mnp MNP only
|
||||
setting compression pick 3 3 %%C%s Error control Compression %C (S104): needs error correction
|
||||
choice 0 off None
|
||||
choice 1 mnp5 MNP 5
|
||||
choice 2 v42bis-v44 V.42bis or V.44
|
||||
choice 3 auto Either
|
||||
setting mnp-block pick 3 3 \A%s Error control MNP block size \A (S105): MNP's longest block
|
||||
choice 0 64 64 octets
|
||||
choice 1 128 128 octets
|
||||
choice 2 192 192 octets
|
||||
choice 3 256 256 octets
|
||||
setting line-quality pick 0 0 %%E%s Error control Line quality monitor %E (S39): kept
|
||||
choice 0 0 %E0
|
||||
choice 1 1 %E1
|
||||
choice 2 2 %E2
|
||||
setting echo pick 1 1 E%s Terminal Command echo E (S13): the modem echoes what you type
|
||||
choice 0 off Off
|
||||
choice 1 on On
|
||||
setting quiet pick 0 0 Q%s Terminal Result codes Q (S14): OK, CONNECT and the others shown or not
|
||||
choice 0 shown Shown
|
||||
choice 1 hidden Hidden
|
||||
setting verbose pick 1 1 V%s Terminal Result code form V (S15): words or numbers
|
||||
choice 0 numeric Numbers
|
||||
choice 1 words Words
|
||||
setting connect-lines number 0 0 0 7 &A%s Terminal Lines before CONNECT &A (S70): 1 modulation, 2 protocol, 4 rate
|
||||
setting connect-protocol pick 0 0 \V%s Terminal Protocol in CONNECT \V (S106): CONNECT 33600/LAPM
|
||||
choice 0 off Off
|
||||
choice 1 on On
|
||||
choice 2 on2 On (\V2)
|
||||
setting connect-rate pick 0 0 &E%s Terminal CONNECT rate source &E (S71): kept
|
||||
choice 0 0 &E0
|
||||
choice 1 1 &E1
|
||||
setting dcd pick 0 0 &C%s Terminal DCD &C (S60): kept
|
||||
choice 0 always-on Always on
|
||||
choice 1 carrier Follows carrier
|
||||
setting flow-control pick 0 0 &H%s Terminal Flow control &H (S62): as #UD reports it
|
||||
choice 0 none None
|
||||
choice 1 rts-cts RTS/CTS
|
||||
choice 2 xon-xoff XON/XOFF
|
||||
choice 3 both Both
|
||||
setting y number 0 0 0 3 Y%s Terminal Y setting Y (S161): kept
|
||||
setting speaker pick 1 1 M%s Speaker Speaker M (S29)
|
||||
choice 0 off Off
|
||||
choice 1 until-connect On until CONNECT
|
||||
choice 2 always Always on
|
||||
choice 3 answer-only On after dialling until CONNECT
|
||||
setting volume pick 3 3 L%s Speaker Speaker volume L (S30)
|
||||
choice 0 lowest Lowest
|
||||
choice 1 low Low
|
||||
choice 2 medium Medium
|
||||
choice 3 high High
|
||||
setting mode pick 0 0 +FCLASS=%s Fax and voice Mode +FCLASS: data, fax or voice
|
||||
choice 0 data Data
|
||||
choice 1 fax1 Fax class 1
|
||||
choice 1.0 fax1.0 Fax class 1.0
|
||||
choice 8 voice Voice
|
||||
setting caller-id pick 0 0 #CID=%s Fax and voice Caller ID #CID: shown after the first RING
|
||||
choice 0 off Off
|
||||
choice 1 formatted Formatted
|
||||
choice 2 raw Unformatted
|
||||
setting modem-on-hold pick 0 0 +PMH=%s Fax and voice V.92 modem-on-hold +PMH: granted or refused
|
||||
choice 0 on Granted
|
||||
choice 1 off Refused
|
||||
setting modem-on-hold-time number 5 5 0 13 +PMHT=%s Fax and voice Modem-on-hold time code +PMHT: the longest hold granted (V.92's code)
|
||||
setting auto-answer number 0 0 0 255 S0=%s Timers Rings before answering S0: 0 never answers by itself
|
||||
setting dial-tone-wait number 2 2 0 255 S6=%s Timers Dial tone wait (s) S6: seconds to wait for a dial tone
|
||||
setting carrier-wait number 60 60 0 255 S7=%s Timers Carrier wait (s) S7: seconds to wait for the other modem
|
||||
setting comma-pause number 2 2 0 255 S8=%s Timers Comma pause (s) S8: a ',' in the number waits this long
|
||||
setting carrier-detect-time number 6 6 0 255 S9=%s Timers Carrier detect (0.1 s) S9: the carrier must last this long
|
||||
setting carrier-loss-time number 7 7 0 255 S10=%s Timers Carrier loss (0.1 s) S10: hang up after the carrier is gone this long
|
||||
setting dtmf-duration number 100 100 0 255 S11=%s Timers DTMF tone length (ms) S11: each digit's tone and the gap after it
|
||||
setting flash-time number 50 50 0 255 S24=%s Timers Hook flash (10 ms) S24: how long a hook flash lasts
|
||||
setting answer-delay number 2 2 0 255 S92=%s Timers Answer delay (s) S92: from ATA to the answer tone
|
||||
setting test-timer number 0 0 0 255 S18=%s Timers Test timer (s) S18: how long an AT&T test runs, 0 until AT&T0
|
||||
setting simulated-carrier number 0 0 0 1 S48=%s Timers Simulated carrier (V.13) S48: 1 sends V.13's simulated carrier
|
||||
setting fast-connect number 0 0 0 3 S49=%s Timers Fast connect (bits) S49: 1 the short V.22 handshake, 2 with HDLC flags
|
||||
setting fast-answer-tone number 0 0 0 255 S50=%s Timers Fast answer tone (10 ms) S50: the fast connect answer tone, 0 for 400 ms
|
||||
setting escape-char number 43 43 0 255 S2=%s Characters Escape character S2: the +++ escape's character (43 is '+')
|
||||
setting escape-guard number 50 50 0 255 S12=%s Characters Escape guard time (20 ms) S12: the quiet before and after +++
|
||||
setting cr-char number 13 13 0 127 S3=%s Characters Line end character S3: ends a command line (13 is CR)
|
||||
setting lf-char number 10 10 0 127 S4=%s Characters Line feed character S4: follows S3 in responses (10 is LF)
|
||||
setting bs-char number 8 8 0 127 S5=%s Characters Backspace character S5: erases a character (8 is BS)
|
||||
setting ifc text 2,2 2,2 +IFC=%s Extended DTE flow control +IFC=(0-3),(0-2)
|
||||
setting icf text 3,3 3,3 +ICF=%s Extended DTE character framing +ICF=(1-6),(0-3)
|
||||
setting ipr text 0 0 +IPR=%s Extended DTE rate +IPR=(0,300,1200,2400,4800,9600,19200,38400,57600,115200,230400,460800,921600)
|
||||
setting ilrr text 0 0 +ILRR=%s Extended Local rate reporting +ILRR=(0,1)
|
||||
setting idsr text 0 0 +IDSR=%s Extended DSR control +IDSR=(0,1)
|
||||
setting ilsd text 0 0 +ILSD=%s Extended Line signal detect +ILSD=(0,1)
|
||||
setting mr text 0 0 +MR=%s Extended Modulation reporting +MR=(0,1)
|
||||
setting er text 0 0 +ER=%s Extended Error control reporting +ER=(0,1)
|
||||
setting dr text 0 0 +DR=%s Extended Compression reporting +DR=(0,1)
|
||||
setting es text 3,0,2 3,0,2 +ES=%s Extended Error control (V.250) +ES=(0-4,6),(0-4),(0-6,8)
|
||||
setting esa text 0,0,0,0,0,0,255,255 0,0,0,0,0,0,255,255 +ESA=%s Extended V.80 synchronous access +ESA=(0-2),(0,1),(0,1),(0),(0-2),(0),(0-255),(0-255)
|
||||
setting itf text 383,128,0 383,128,0 +ITF=%s Extended V.80 transmit buffer +ITF=(1-4095),(0-4094),(0-500)
|
||||
setting a8e text 1,1,0,0 1,1,0,0 +A8E=%s Extended V.8 and V.8 bis +A8E=(1),(1),(0),(0,1)
|
||||
setting dsvd text 0 0 +DSVD=%s Extended DSVD (V.70) offered +DSVD=(0,1)
|
||||
setting asvd text 0 0 +ASVD=%s Extended ASVD (V.61) offered +ASVD=(0,1)
|
||||
setting ds text 3,0,2048,34 3,0,2048,34 +DS=%s Extended V.42bis compression +DS=(0-3),(0,1),(512-65535),(6-250)
|
||||
setting ds44 text 3,0,0,4096,4096,255,255,12288,12288 3,0,0,4096,4096,255,255,12288,12288 +DS44=%s Extended V.44 compression +DS44=(0-3),(0,1),(0,1),(256-65535),(256-65535),(32-255),(32-255),(512-65535),(512-65535)
|
||||
setting dsz text 1,1 1,1 +DSZ=%s Extended zstd compression +DSZ=(0,1),(0,1)
|
||||
setting b2 text 0 0 +B2=%s Extended Clear channel link layer +B2=(0,5,7,9)
|
||||
setting cbst text 0,0,0 0,0,0 +CBST=%s Extended Bearer service +CBST=(0,65,66,68,70,71,75,79,80,81,83),(0,1),(0,1)
|
||||
setting crc text 0 0 +CRC=%s Extended Cellular result codes +CRC=(0,1)
|
||||
setting pcw text 2 2 +PCW=%s Extended V.92 call waiting +PCW=(0-2)
|
||||
setting pig text 1 1 +PIG=%s Extended V.92 PCM upstream +PIG=(0,1)
|
||||
setting faa text 0 0 +FAA=%s Extended Adaptive answer +FAA=(0,1)
|
||||
setting fpr text 0 0 +FPR=%s Extended Fax DTE rate +FPR=(0,1,2,4,8,10,18)
|
||||
setting sec text 0 0 -SEC=%s Extended MNP 10EC -SEC=(0,1),(0-30)
|
||||
setting cvm text 63,8000,0 63,8000,0 +CVM=%s Extended V.cvm +CVM=(0-63),(8000,16000),(0,1)
|
||||
OK
|
||||
@@ -0,0 +1,81 @@
|
||||
# Design
|
||||
|
||||
## One library, three native shells
|
||||
|
||||
The apps share everything that is not drawing. `core/` is libdmodemctl, a
|
||||
small C library with no I/O and no threads ("sans-I/O"): each app opens the
|
||||
modem in its own way, hands the bytes it reads to `dmc_feed()`, writes what
|
||||
`dmc_output()` gives it, and calls `dmc_poll()` from a 50 ms timer. That
|
||||
keeps it easy to call from C (GTK), C++ (Win32) and Swift, and easy to test
|
||||
(`core/test`, run by CI with ASan and UBSan).
|
||||
|
||||
| Part | What it does |
|
||||
| --- | --- |
|
||||
| `dmc_session` | The AT conversation: a queue of commands and their responses, the call's state from the result codes (RING, CONNECT, NO CARRIER), caller ID, the escape (`+++` with its guard times) and hanging up, and the byte stream for the terminal |
|
||||
| `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_daemon_*` | Reading what dmodemd prints when it starts: the device it made, or its error |
|
||||
|
||||
## Where the settings come from
|
||||
|
||||
dmodemd's core has one settings model (`Config::model`), which already
|
||||
drives its configurators (AT!CF, AT!CT, AT!C). AT!M prints that model as
|
||||
tab-separated lines: each setting's key, kind (pick, number or text),
|
||||
value, default, range, AT form, group, label and help, then each choice.
|
||||
The Settings page builds its controls from it, so a setting added to the
|
||||
modem shows in every app with no change here. A change is checked by the
|
||||
library, sent as its AT command, and kept once the modem says OK.
|
||||
|
||||
The modem keeps no stored profile, so the page shows AT!R's init string
|
||||
and its **Keep** button saves it in the app's line settings, to be sent
|
||||
each time the modem opens.
|
||||
|
||||
## The same screens everywhere
|
||||
|
||||
Each app has the same five 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 |
|
||||
| Terminal | The AT console; the buttons **Full-screen setup** (AT!CF) and **Command-line setup** (AT!CT) |
|
||||
| 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 |
|
||||
|
||||
The terminal sends Backspace as BS (0x08), the modem's S5: it does not take
|
||||
DEL. Colours are the brand's: background `#0a0f1c`, text `#e8f0ff`.
|
||||
|
||||
## Starting dmodemd
|
||||
|
||||
| | Linux | macOS | Windows |
|
||||
| --- | --- | --- | --- |
|
||||
| Started with | GSubprocess | Process | CreateProcess |
|
||||
| Its DTE | a pty (it prints "Use `/dev/pts/N' as modem device") | a pty | `--tcp 127.0.0.1:port` |
|
||||
| Settings kept in | `~/.config/dmodem-gui/settings.ini` (mode 0600) | user defaults, the SIP password in the keychain | `%APPDATA%\D-Modem\dmodem.ini` |
|
||||
|
||||
The SIP account goes to dmodemd in its environment (`SIP_LOGIN`,
|
||||
`SIP_T38`, `SIP_V152`, `SIP_V150`, `SIP_SRTP`); the country, USB modem and
|
||||
debug level as flags. On Linux and macOS the pty is made in the user's
|
||||
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.
|
||||
|
||||
## Windows 95 and later
|
||||
|
||||
The Windows app is plain Win32 in C++98, so that one binary runs from
|
||||
Windows 95 to Windows 11:
|
||||
|
||||
- ANSI APIs, with UTF-8 from the library converted by hand (no `CP_UTF8`
|
||||
on 9x); the terminal draws with `ExtTextOutW`, which 9x has.
|
||||
- The Windows 95 common controls (tabs, list views, the status bar),
|
||||
Winsock 1.1 (`wsock32`, `WSAAsyncSelect`) and the 4.0 `OPENFILENAME`.
|
||||
- No `SetHandleInformation` (NT only): the pipe from dmodemd is made
|
||||
non-inheritable with `DuplicateHandle`.
|
||||
- Built by Open Watcom 2.0 (`windows/build-watcom.sh`: `runtime
|
||||
windows=4.0`, the static C library), as CI does; MinGW and MSVC build the
|
||||
same code with CMake.
|
||||
|
||||
dmodemd itself needs Windows 7 or later. On Windows 9x and NT 4 the app
|
||||
defaults to a COM port, and can reach a dmodemd on another machine over TCP.
|
||||
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
@@ -0,0 +1,20 @@
|
||||
# The Linux (and BSD) app: GTK 4, libadwaita and VTE over libdmodemctl.
|
||||
add_executable(dmodem-gui
|
||||
src/main.c
|
||||
src/window.c
|
||||
src/modem.c
|
||||
src/config.c
|
||||
src/settings.c
|
||||
src/stats.c)
|
||||
target_link_libraries(dmodem-gui PRIVATE dmodemctl PkgConfig::GTK)
|
||||
target_compile_options(dmodem-gui PRIVATE -Wall -Wextra -Wno-unused-parameter)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS dmodem-gui RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
install(FILES data/io.github.d_modem.DModem.desktop
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
|
||||
install(FILES data/io.github.d_modem.DModem.metainfo.xml
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/metainfo)
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/assets/dmodem.svg
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps
|
||||
RENAME io.github.d_modem.DModem.svg)
|
||||
@@ -0,0 +1,11 @@
|
||||
[Desktop Entry]
|
||||
Name=D-Modem
|
||||
GenericName=Softmodem
|
||||
Comment=Dial up over SIP, a USB modem or a softmodem codec
|
||||
Exec=dmodem-gui
|
||||
Icon=io.github.d_modem.DModem
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Categories=Network;Dialup;GTK;
|
||||
Keywords=modem;dial-up;V.92;fax;SIP;AT;
|
||||
StartupNotify=true
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<component type="desktop-application">
|
||||
<id>io.github.d_modem.DModem</id>
|
||||
<metadata_license>CC0-1.0</metadata_license>
|
||||
<project_license>BSD-3-Clause</project_license>
|
||||
<name>D-Modem</name>
|
||||
<summary>The front panel of the open V.92 softmodem</summary>
|
||||
<description>
|
||||
<p>D-Modem is an open softmodem: V.92, V.90, V.34 and the older
|
||||
modulations, fax and voice, over a SIP call, a USB modem or a
|
||||
softmodem codec. This app starts it, dials and answers, changes its
|
||||
settings, shows each call's statistics and gives you a terminal on
|
||||
it, while your own programs (pppd, minicom, efax) use its device.</p>
|
||||
</description>
|
||||
<launchable type="desktop-id">io.github.d_modem.DModem.desktop</launchable>
|
||||
<url type="homepage">https://github.com/D-Modem/gui</url>
|
||||
<developer id="io.github.d_modem">
|
||||
<name>The D-Modem Authors</name>
|
||||
</developer>
|
||||
<content_rating type="oars-1.1"/>
|
||||
<releases>
|
||||
<release version="1.0.0" date="2026-11-06"/>
|
||||
</releases>
|
||||
</component>
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* app.h - the Linux app (GTK 4, libadwaita, VTE): what its parts share
|
||||
*/
|
||||
#ifndef DMODEM_GUI_APP_H
|
||||
#define DMODEM_GUI_APP_H
|
||||
|
||||
#include <adwaita.h>
|
||||
#include <vte/vte.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
|
||||
#define APP_ID "io.github.d_modem.DModem"
|
||||
|
||||
/* the line settings, kept in ~/.config/dmodem-gui/settings.ini */
|
||||
typedef struct Config {
|
||||
/* "sip", "usb", "alsa", or "device" (a modem that already runs) */
|
||||
char *line;
|
||||
char *sip_user, *sip_password, *sip_server;
|
||||
gboolean listen, t38, v152, v150;
|
||||
char *srtp; /* "", "no" or "require" */
|
||||
char *country; /* dmodemd -c's, "" for its default */
|
||||
char *usb, *alsa; /* --usb's (auto), -a's (hw:1) */
|
||||
char *device; /* the modem's device, "device" line */
|
||||
char *dmodemd; /* its path, "" to look for it */
|
||||
char *init; /* commands sent when the modem opens */
|
||||
int debug; /* dmodemd -d */
|
||||
} Config;
|
||||
|
||||
typedef struct App App;
|
||||
|
||||
/* a command's response */
|
||||
typedef void (*ResponseFn)(App *a, const dmc_event *ev, gpointer data);
|
||||
|
||||
struct App {
|
||||
AdwApplication *gapp;
|
||||
GtkWindow *window;
|
||||
AdwToastOverlay *toasts;
|
||||
Config cfg;
|
||||
|
||||
/* the modem */
|
||||
dmc_session *s;
|
||||
GSubprocess *proc;
|
||||
GCancellable *cancel;
|
||||
char *device; /* the DTE's path */
|
||||
int fd;
|
||||
guint fd_watch, tick;
|
||||
GByteArray *pending; /* written when the DTE takes it */
|
||||
GHashTable *waiting; /* tag -> struct Waiting */
|
||||
int last_state;
|
||||
|
||||
/* the pages' widgets */
|
||||
AdwViewStack *stack;
|
||||
GtkWidget *status_icon, *status_title, *status_detail;
|
||||
GtkWidget *number, *dial_btn, *answer_btn, *hangup_btn;
|
||||
GtkWidget *run_row, *run_btn, *device_row, *copy_btn;
|
||||
VteTerminal *term;
|
||||
GtkWidget *term_buttons;
|
||||
AdwPreferencesPage *settings_page;
|
||||
GPtrArray *settings_groups;
|
||||
GPtrArray *setting_rows; /* by the setting's index */
|
||||
int settings_gen; /* a new model: older answers ignored */
|
||||
GtkWidget *settings_status, *init_row;
|
||||
dmc_model *model;
|
||||
gboolean settings_quiet; /* (rows set by the app, not the user) */
|
||||
AdwPreferencesGroup *stats_group;
|
||||
GPtrArray *stats_rows;
|
||||
GtkWidget *stats_report, *stats_empty;
|
||||
GtkTextBuffer *log;
|
||||
};
|
||||
|
||||
/* config.c */
|
||||
void config_load(Config *c);
|
||||
void config_save(const Config *c);
|
||||
void config_free(Config *c);
|
||||
/* "SIP: alice@sip.example.com" and the like */
|
||||
char *config_summary(const Config *c);
|
||||
/* the line settings dialog */
|
||||
void prefs_show(App *a);
|
||||
|
||||
/* modem.c */
|
||||
void modem_start(App *a);
|
||||
void modem_stop(App *a);
|
||||
gboolean modem_running(App *a);
|
||||
/* bytes typed in the terminal */
|
||||
void modem_type(App *a, const char *data, gsize n);
|
||||
/* a command; fn (may be NULL) gets its response */
|
||||
int modem_command(App *a, const char *cmd, int flags, ResponseFn fn,
|
||||
gpointer data);
|
||||
/* the session's output, terminal bytes and events handled now */
|
||||
void modem_pump(App *a);
|
||||
void app_log(App *a, const char *line);
|
||||
|
||||
/* window.c */
|
||||
void window_build(App *a);
|
||||
void window_state(App *a);
|
||||
void window_toast(App *a, const char *text);
|
||||
/* the modem's events (the session's DMC_EV_*) */
|
||||
void window_event(App *a, const dmc_event *ev);
|
||||
void window_opened(App *a);
|
||||
void window_closed(App *a);
|
||||
|
||||
/* settings.c */
|
||||
GtkWidget *settings_page_new(App *a);
|
||||
void settings_load(App *a);
|
||||
void settings_clear(App *a);
|
||||
void settings_sensitive(App *a, gboolean on);
|
||||
|
||||
/* stats.c */
|
||||
GtkWidget *stats_page_new(App *a);
|
||||
void stats_refresh(App *a);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,316 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* config.c - the line settings: kept, and the dialog that changes them
|
||||
*
|
||||
* They are a key file only the user may read (the SIP password is in
|
||||
* it), ~/.config/dmodem-gui/settings.ini.
|
||||
*/
|
||||
#include <glib/gstdio.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
static char *path(void)
|
||||
{
|
||||
return g_build_filename(g_get_user_config_dir(), "dmodem-gui",
|
||||
"settings.ini", NULL);
|
||||
}
|
||||
|
||||
static char *get_s(GKeyFile *k, const char *key, const char *def)
|
||||
{
|
||||
char *v = g_key_file_get_string(k, "line", key, NULL);
|
||||
return v ? v : g_strdup(def);
|
||||
}
|
||||
|
||||
static gboolean get_b(GKeyFile *k, const char *key, gboolean def)
|
||||
{
|
||||
GError *e = NULL;
|
||||
gboolean v = g_key_file_get_boolean(k, "line", key, &e);
|
||||
if (e) {
|
||||
g_error_free(e);
|
||||
return def;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
void config_load(Config *c)
|
||||
{
|
||||
GKeyFile *k = g_key_file_new();
|
||||
char *p = path();
|
||||
g_key_file_load_from_file(k, p, G_KEY_FILE_NONE, NULL);
|
||||
g_free(p);
|
||||
c->line = get_s(k, "line", "sip");
|
||||
c->sip_user = get_s(k, "sip-user", "");
|
||||
c->sip_password = get_s(k, "sip-password", "");
|
||||
c->sip_server = get_s(k, "sip-server", "");
|
||||
c->listen = get_b(k, "listen", FALSE);
|
||||
c->t38 = get_b(k, "t38", TRUE);
|
||||
c->v152 = get_b(k, "v152", TRUE);
|
||||
c->v150 = get_b(k, "v150", FALSE);
|
||||
c->srtp = get_s(k, "srtp", "");
|
||||
c->country = get_s(k, "country", "");
|
||||
c->usb = get_s(k, "usb", "auto");
|
||||
c->alsa = get_s(k, "alsa", "hw:1");
|
||||
c->device = get_s(k, "device", "/dev/ttyDM0");
|
||||
c->dmodemd = get_s(k, "dmodemd", "");
|
||||
c->init = get_s(k, "init", "");
|
||||
c->debug = g_key_file_get_integer(k, "line", "debug", NULL);
|
||||
g_key_file_unref(k);
|
||||
}
|
||||
|
||||
void config_save(const Config *c)
|
||||
{
|
||||
GKeyFile *k = g_key_file_new();
|
||||
g_key_file_set_string(k, "line", "line", c->line);
|
||||
g_key_file_set_string(k, "line", "sip-user", c->sip_user);
|
||||
g_key_file_set_string(k, "line", "sip-password", c->sip_password);
|
||||
g_key_file_set_string(k, "line", "sip-server", c->sip_server);
|
||||
g_key_file_set_boolean(k, "line", "listen", c->listen);
|
||||
g_key_file_set_boolean(k, "line", "t38", c->t38);
|
||||
g_key_file_set_boolean(k, "line", "v152", c->v152);
|
||||
g_key_file_set_boolean(k, "line", "v150", c->v150);
|
||||
g_key_file_set_string(k, "line", "srtp", c->srtp);
|
||||
g_key_file_set_string(k, "line", "country", c->country);
|
||||
g_key_file_set_string(k, "line", "usb", c->usb);
|
||||
g_key_file_set_string(k, "line", "alsa", c->alsa);
|
||||
g_key_file_set_string(k, "line", "device", c->device);
|
||||
g_key_file_set_string(k, "line", "dmodemd", c->dmodemd);
|
||||
g_key_file_set_string(k, "line", "init", c->init);
|
||||
g_key_file_set_integer(k, "line", "debug", c->debug);
|
||||
char *p = path();
|
||||
char *dir = g_path_get_dirname(p);
|
||||
g_mkdir_with_parents(dir, 0700);
|
||||
GError *e = NULL;
|
||||
if (!g_key_file_save_to_file(k, p, &e)) {
|
||||
g_warning("%s: %s", p, e->message);
|
||||
g_error_free(e);
|
||||
}
|
||||
g_chmod(p, 0600);
|
||||
g_free(dir);
|
||||
g_free(p);
|
||||
g_key_file_unref(k);
|
||||
}
|
||||
|
||||
void config_free(Config *c)
|
||||
{
|
||||
g_free(c->line);
|
||||
g_free(c->sip_user);
|
||||
g_free(c->sip_password);
|
||||
g_free(c->sip_server);
|
||||
g_free(c->srtp);
|
||||
g_free(c->country);
|
||||
g_free(c->usb);
|
||||
g_free(c->alsa);
|
||||
g_free(c->device);
|
||||
g_free(c->dmodemd);
|
||||
g_free(c->init);
|
||||
}
|
||||
|
||||
char *config_summary(const Config *c)
|
||||
{
|
||||
if (!g_strcmp0(c->line, "usb"))
|
||||
return g_strdup_printf("USB modem (%s)", c->usb);
|
||||
if (!g_strcmp0(c->line, "alsa"))
|
||||
return g_strdup_printf("Softmodem codec %s", c->alsa);
|
||||
if (!g_strcmp0(c->line, "device"))
|
||||
return g_strdup_printf("The modem at %s", c->device);
|
||||
if (!*c->sip_user || !*c->sip_server)
|
||||
return g_strdup("SIP account not set up");
|
||||
return g_strdup_printf("SIP: %s@%s%s", c->sip_user, c->sip_server,
|
||||
c->listen ? ", taking calls" : "");
|
||||
}
|
||||
|
||||
/*
|
||||
* the dialog
|
||||
*/
|
||||
|
||||
static const char *const lines[] = { "sip", "usb", "alsa", "device", NULL };
|
||||
static const char *const line_labels[] = {
|
||||
"SIP account", "USB modem", "Softmodem codec (ALSA)",
|
||||
"A modem that already runs", NULL
|
||||
};
|
||||
static const char *const srtps[] = { "", "no", "require", NULL };
|
||||
static const char *const srtp_labels[] = {
|
||||
"When the other end offers it", "Never", "Always (refuse plain RTP)",
|
||||
NULL
|
||||
};
|
||||
|
||||
typedef struct Prefs {
|
||||
App *a;
|
||||
AdwComboRow *line, *srtp;
|
||||
AdwEntryRow *user, *server, *country, *usb, *alsa, *device, *dmodemd,
|
||||
*init;
|
||||
AdwPasswordEntryRow *password;
|
||||
AdwSwitchRow *listen, *t38, *v152, *v150;
|
||||
AdwSpinRow *debug;
|
||||
AdwPreferencesGroup *sip, *usb_g, *alsa_g, *device_g;
|
||||
} Prefs;
|
||||
|
||||
static int index_of(const char *const *v, const char *s)
|
||||
{
|
||||
for (int i = 0; v[i]; i++)
|
||||
if (!g_strcmp0(v[i], s))
|
||||
return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void show_groups(Prefs *p)
|
||||
{
|
||||
const char *l = lines[adw_combo_row_get_selected(p->line)];
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->sip), !g_strcmp0(l, "sip"));
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->usb_g), !g_strcmp0(l, "usb"));
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->alsa_g), !g_strcmp0(l, "alsa"));
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->device_g),
|
||||
!g_strcmp0(l, "device"));
|
||||
}
|
||||
|
||||
static void line_changed(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
(void)o;
|
||||
(void)ps;
|
||||
show_groups(data);
|
||||
}
|
||||
|
||||
static AdwEntryRow *entry(AdwPreferencesGroup *g, const char *title,
|
||||
const char *value)
|
||||
{
|
||||
GtkWidget *r = adw_entry_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r), title);
|
||||
gtk_editable_set_text(GTK_EDITABLE(r), value);
|
||||
adw_preferences_group_add(g, r);
|
||||
return ADW_ENTRY_ROW(r);
|
||||
}
|
||||
|
||||
static AdwSwitchRow *toggle(AdwPreferencesGroup *g, const char *title,
|
||||
const char *sub, gboolean on)
|
||||
{
|
||||
GtkWidget *r = adw_switch_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r), title);
|
||||
if (sub)
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(r), sub);
|
||||
adw_switch_row_set_active(ADW_SWITCH_ROW(r), on);
|
||||
adw_preferences_group_add(g, r);
|
||||
return ADW_SWITCH_ROW(r);
|
||||
}
|
||||
|
||||
static AdwComboRow *combo(AdwPreferencesGroup *g, const char *title,
|
||||
const char *const *labels, int sel)
|
||||
{
|
||||
GtkWidget *r = adw_combo_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r), title);
|
||||
GtkStringList *m = gtk_string_list_new((const char *const *)labels);
|
||||
adw_combo_row_set_model(ADW_COMBO_ROW(r), G_LIST_MODEL(m));
|
||||
g_object_unref(m);
|
||||
adw_combo_row_set_selected(ADW_COMBO_ROW(r), (guint)sel);
|
||||
adw_preferences_group_add(g, r);
|
||||
return ADW_COMBO_ROW(r);
|
||||
}
|
||||
|
||||
static AdwPreferencesGroup *group(AdwPreferencesPage *page, const char *title,
|
||||
const char *desc)
|
||||
{
|
||||
GtkWidget *g = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(g), title);
|
||||
if (desc)
|
||||
adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(g),
|
||||
desc);
|
||||
adw_preferences_page_add(page, ADW_PREFERENCES_GROUP(g));
|
||||
return ADW_PREFERENCES_GROUP(g);
|
||||
}
|
||||
|
||||
static char *text_of(AdwEntryRow *r)
|
||||
{
|
||||
return g_strstrip(g_strdup(gtk_editable_get_text(GTK_EDITABLE(r))));
|
||||
}
|
||||
|
||||
static void closed(AdwDialog *d, gpointer data)
|
||||
{
|
||||
(void)d;
|
||||
Prefs *p = data;
|
||||
Config *c = &p->a->cfg;
|
||||
config_free(c);
|
||||
c->line = g_strdup(lines[adw_combo_row_get_selected(p->line)]);
|
||||
c->sip_user = text_of(p->user);
|
||||
c->sip_password = g_strdup(gtk_editable_get_text(GTK_EDITABLE(p->password)));
|
||||
c->sip_server = text_of(p->server);
|
||||
c->listen = adw_switch_row_get_active(p->listen);
|
||||
c->t38 = adw_switch_row_get_active(p->t38);
|
||||
c->v152 = adw_switch_row_get_active(p->v152);
|
||||
c->v150 = adw_switch_row_get_active(p->v150);
|
||||
c->srtp = g_strdup(srtps[adw_combo_row_get_selected(p->srtp)]);
|
||||
c->country = text_of(p->country);
|
||||
c->usb = text_of(p->usb);
|
||||
c->alsa = text_of(p->alsa);
|
||||
c->device = text_of(p->device);
|
||||
c->dmodemd = text_of(p->dmodemd);
|
||||
c->init = text_of(p->init);
|
||||
c->debug = (int)adw_spin_row_get_value(p->debug);
|
||||
config_save(c);
|
||||
window_state(p->a);
|
||||
g_free(p);
|
||||
}
|
||||
|
||||
void prefs_show(App *a)
|
||||
{
|
||||
Config *c = &a->cfg;
|
||||
Prefs *p = g_new0(Prefs, 1);
|
||||
p->a = a;
|
||||
AdwDialog *d = ADW_DIALOG(adw_preferences_dialog_new());
|
||||
adw_dialog_set_title(d, "Line");
|
||||
AdwPreferencesPage *page = ADW_PREFERENCES_PAGE(adw_preferences_page_new());
|
||||
adw_preferences_page_set_title(page, "Line");
|
||||
adw_preferences_page_set_icon_name(page, "network-wired-symbolic");
|
||||
|
||||
AdwPreferencesGroup *g = group(page, "The modem's line",
|
||||
"Where dmodemd's calls go. Changes take effect the next time "
|
||||
"the modem starts.");
|
||||
p->line = combo(g, "Line", line_labels, index_of(lines, c->line));
|
||||
p->country = entry(g, "Country (dmodemd -c, empty for the USA)",
|
||||
c->country);
|
||||
|
||||
p->sip = group(page, "SIP account", "Calls go to sip:<number>@server.");
|
||||
p->user = entry(p->sip, "User name", c->sip_user);
|
||||
GtkWidget *pw = adw_password_entry_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(pw), "Password");
|
||||
gtk_editable_set_text(GTK_EDITABLE(pw), c->sip_password);
|
||||
adw_preferences_group_add(p->sip, pw);
|
||||
p->password = ADW_PASSWORD_ENTRY_ROW(pw);
|
||||
p->server = entry(p->sip, "Server (host or host:port)", c->sip_server);
|
||||
p->listen = toggle(p->sip, "Take calls", "Register, so calls to the "
|
||||
"account ring the modem", c->listen);
|
||||
p->t38 = toggle(p->sip, "Fax over T.38", NULL, c->t38);
|
||||
p->v152 = toggle(p->sip, "Mark calls as modem data (V.152)", NULL,
|
||||
c->v152);
|
||||
p->v150 = toggle(p->sip, "Modem relay (V.150.1)", NULL, c->v150);
|
||||
p->srtp = combo(p->sip, "Encrypted media (SRTP)", srtp_labels,
|
||||
index_of(srtps, c->srtp));
|
||||
|
||||
p->usb_g = group(page, "USB modem", "A SmartUSB56, a pico-serial "
|
||||
"Line or WB, an Agere or an Apple USB modem.");
|
||||
p->usb = entry(p->usb_g, "Device (auto, or bus:address)", c->usb);
|
||||
p->alsa_g = group(page, "Softmodem codec", "An AC'97 or HD-audio "
|
||||
"modem codec through ALSA (aplay -l lists it).");
|
||||
p->alsa = entry(p->alsa_g, "ALSA device", c->alsa);
|
||||
p->device_g = group(page, "A modem that already runs",
|
||||
"dmodemd started as a service, or any modem's "
|
||||
"serial port.");
|
||||
p->device = entry(p->device_g, "Device", c->device);
|
||||
|
||||
AdwPreferencesGroup *adv = group(page, "Advanced", NULL);
|
||||
p->init = entry(adv, "Commands when the modem opens", c->init);
|
||||
p->dmodemd = entry(adv, "dmodemd (empty to look for it)", c->dmodemd);
|
||||
GtkWidget *dbg = adw_spin_row_new_with_range(0, 9, 1);
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(dbg),
|
||||
"Debug messages (dmodemd -d)");
|
||||
adw_spin_row_set_value(ADW_SPIN_ROW(dbg), c->debug);
|
||||
adw_preferences_group_add(adv, dbg);
|
||||
p->debug = ADW_SPIN_ROW(dbg);
|
||||
|
||||
show_groups(p);
|
||||
g_signal_connect(p->line, "notify::selected", G_CALLBACK(line_changed),
|
||||
p);
|
||||
adw_preferences_dialog_add(ADW_PREFERENCES_DIALOG(d), page);
|
||||
g_signal_connect(d, "closed", G_CALLBACK(closed), p);
|
||||
adw_dialog_present(d, GTK_WIDGET(a->window));
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* main.c - D-Modem for Linux and the BSDs: GTK 4 and libadwaita over
|
||||
* libdmodemctl
|
||||
*/
|
||||
#include "app.h"
|
||||
|
||||
void modem_init(App *a);
|
||||
|
||||
static void activate(GApplication *g, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
if (a->window) {
|
||||
gtk_window_present(a->window);
|
||||
return;
|
||||
}
|
||||
window_build(a);
|
||||
gtk_window_present(a->window);
|
||||
/* a modem that runs already, or one this app starts */
|
||||
if (!g_strcmp0(a->cfg.line, "device") ||
|
||||
(!g_strcmp0(a->cfg.line, "sip") && *a->cfg.sip_user))
|
||||
modem_start(a);
|
||||
(void)g;
|
||||
}
|
||||
|
||||
static void shutdown(GApplication *g, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)g;
|
||||
if (modem_running(a))
|
||||
modem_stop(a);
|
||||
g_cancellable_cancel(a->cancel);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
App a = { 0 };
|
||||
config_load(&a.cfg);
|
||||
modem_init(&a);
|
||||
a.gapp = adw_application_new(APP_ID, G_APPLICATION_DEFAULT_FLAGS);
|
||||
g_signal_connect(a.gapp, "activate", G_CALLBACK(activate), &a);
|
||||
g_signal_connect(a.gapp, "shutdown", G_CALLBACK(shutdown), &a);
|
||||
int r = g_application_run(G_APPLICATION(a.gapp), argc, argv);
|
||||
g_object_unref(a.gapp);
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* modem.c - dmodemd started and stopped, its pty opened, and the bytes
|
||||
* between the pty, libdmodemctl's session and the terminal
|
||||
*
|
||||
* dmodemd runs as the user: it makes its pty and says where it is
|
||||
* ("Use `/dev/pts/3' as modem device"), and the app opens that. With
|
||||
* the "device" line nothing is started and the given device is opened.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <grp.h>
|
||||
#include <signal.h>
|
||||
#include <string.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <glib-unix.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
typedef struct Waiting {
|
||||
ResponseFn fn;
|
||||
gpointer data;
|
||||
} Waiting;
|
||||
|
||||
#define LOG_LINES 5000
|
||||
|
||||
void app_log(App *a, const char *line)
|
||||
{
|
||||
GtkTextIter end;
|
||||
gtk_text_buffer_get_end_iter(a->log, &end);
|
||||
gtk_text_buffer_insert(a->log, &end, line, -1);
|
||||
gtk_text_buffer_insert(a->log, &end, "\n", 1);
|
||||
int n = gtk_text_buffer_get_line_count(a->log);
|
||||
if (n > LOG_LINES) {
|
||||
GtkTextIter s, e;
|
||||
gtk_text_buffer_get_start_iter(a->log, &s);
|
||||
gtk_text_buffer_get_iter_at_line(a->log, &e, n - LOG_LINES);
|
||||
gtk_text_buffer_delete(a->log, &s, &e);
|
||||
}
|
||||
}
|
||||
|
||||
static int64_t now_ms(void)
|
||||
{
|
||||
return g_get_monotonic_time() / 1000;
|
||||
}
|
||||
|
||||
static void flush(App *a)
|
||||
{
|
||||
while (a->fd >= 0 && a->pending->len) {
|
||||
ssize_t n = write(a->fd, a->pending->data, a->pending->len);
|
||||
if (n > 0) {
|
||||
g_byte_array_remove_range(a->pending, 0, (guint)n);
|
||||
continue;
|
||||
}
|
||||
if (n < 0 && errno == EINTR)
|
||||
continue;
|
||||
break; /* EAGAIN: the next tick */
|
||||
}
|
||||
}
|
||||
|
||||
void modem_pump(App *a)
|
||||
{
|
||||
char buf[4096];
|
||||
int n;
|
||||
dmc_poll(a->s, now_ms());
|
||||
while ((n = dmc_output(a->s, buf, sizeof(buf))) > 0)
|
||||
g_byte_array_append(a->pending, (guint8 *)buf, (guint)n);
|
||||
flush(a);
|
||||
while ((n = dmc_terminal(a->s, buf, sizeof(buf))) > 0)
|
||||
vte_terminal_feed(a->term, buf, n);
|
||||
dmc_event ev;
|
||||
while (dmc_next_event(a->s, &ev)) {
|
||||
if (ev.type == DMC_EV_RESPONSE) {
|
||||
Waiting *w = g_hash_table_lookup(a->waiting,
|
||||
GINT_TO_POINTER(ev.tag));
|
||||
if (w) {
|
||||
Waiting copy = *w;
|
||||
g_hash_table_remove(a->waiting,
|
||||
GINT_TO_POINTER(ev.tag));
|
||||
if (copy.fn)
|
||||
copy.fn(a, &ev, copy.data);
|
||||
}
|
||||
} else {
|
||||
window_event(a, &ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static gboolean tick(gpointer data)
|
||||
{
|
||||
modem_pump(data);
|
||||
return G_SOURCE_CONTINUE;
|
||||
}
|
||||
|
||||
static void close_dte(App *a)
|
||||
{
|
||||
if (a->fd_watch) {
|
||||
g_source_remove(a->fd_watch);
|
||||
a->fd_watch = 0;
|
||||
}
|
||||
if (a->fd >= 0) {
|
||||
close(a->fd);
|
||||
a->fd = -1;
|
||||
}
|
||||
g_byte_array_set_size(a->pending, 0);
|
||||
g_hash_table_remove_all(a->waiting);
|
||||
if (dmc_state(a->s) != DMC_CLOSED) {
|
||||
dmc_close(a->s);
|
||||
modem_pump(a);
|
||||
window_closed(a);
|
||||
}
|
||||
}
|
||||
|
||||
static gboolean readable(gint fd, GIOCondition cond, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
char buf[4096];
|
||||
(void)cond;
|
||||
for (;;) {
|
||||
ssize_t n = read(fd, buf, sizeof(buf));
|
||||
if (n > 0) {
|
||||
dmc_feed(a->s, buf, (int)n);
|
||||
continue;
|
||||
}
|
||||
if (n < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (n < 0 && errno == EAGAIN)
|
||||
break;
|
||||
/* EOF, or EIO when dmodemd closed its end */
|
||||
a->fd_watch = 0;
|
||||
app_log(a, "The modem's device closed.");
|
||||
close_dte(a);
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
modem_pump(a);
|
||||
return G_SOURCE_CONTINUE;
|
||||
}
|
||||
|
||||
static gboolean open_dte(App *a, const char *path)
|
||||
{
|
||||
int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
char *m = g_strdup_printf("Can't open %s: %s", path,
|
||||
g_strerror(errno));
|
||||
app_log(a, m);
|
||||
window_toast(a, m);
|
||||
g_free(m);
|
||||
return FALSE;
|
||||
}
|
||||
struct termios t;
|
||||
if (!tcgetattr(fd, &t)) {
|
||||
cfmakeraw(&t);
|
||||
cfsetispeed(&t, B115200);
|
||||
cfsetospeed(&t, B115200);
|
||||
t.c_cflag |= CLOCAL | CREAD;
|
||||
tcsetattr(fd, TCSANOW, &t);
|
||||
}
|
||||
a->fd = fd;
|
||||
g_free(a->device);
|
||||
a->device = g_strdup(path);
|
||||
a->fd_watch = g_unix_fd_add(fd, G_IO_IN | G_IO_HUP | G_IO_ERR,
|
||||
readable, a);
|
||||
dmc_open(a->s, now_ms());
|
||||
window_opened(a);
|
||||
/* the user's own commands first */
|
||||
if (*a->cfg.init)
|
||||
modem_command(a, a->cfg.init, 0, NULL, NULL);
|
||||
modem_pump(a);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/*
|
||||
* dmodemd
|
||||
*/
|
||||
|
||||
static char *find_dmodemd(const Config *c)
|
||||
{
|
||||
if (*c->dmodemd)
|
||||
return g_strdup(c->dmodemd);
|
||||
char *p = g_find_program_in_path("dmodemd");
|
||||
if (p)
|
||||
return p;
|
||||
static const char *const places[] = {
|
||||
"/usr/local/sbin/dmodemd", "/usr/sbin/dmodemd",
|
||||
"/usr/local/bin/dmodemd", "/app/bin/dmodemd", NULL
|
||||
};
|
||||
for (int i = 0; places[i]; i++)
|
||||
if (g_file_test(places[i], G_FILE_TEST_IS_EXECUTABLE))
|
||||
return g_strdup(places[i]);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
typedef struct Reader {
|
||||
App *a;
|
||||
GDataInputStream *in;
|
||||
} Reader;
|
||||
|
||||
static void read_line(Reader *r);
|
||||
|
||||
static void line_read(GObject *src, GAsyncResult *res, gpointer data)
|
||||
{
|
||||
Reader *r = data;
|
||||
gsize len;
|
||||
GError *e = NULL;
|
||||
char *line = g_data_input_stream_read_line_finish_utf8(
|
||||
G_DATA_INPUT_STREAM(src), res, &len, &e);
|
||||
if (!line) {
|
||||
/* the end of dmodemd's output (or cancelled: the app may be
|
||||
gone, so nothing of it is touched) */
|
||||
if (e)
|
||||
g_error_free(e);
|
||||
g_object_unref(r->in);
|
||||
g_free(r);
|
||||
return;
|
||||
}
|
||||
App *a = r->a;
|
||||
app_log(a, line);
|
||||
char dev[512];
|
||||
if (dmc_daemon_ready(line, dev, sizeof(dev)) && a->fd < 0)
|
||||
open_dte(a, dev);
|
||||
else if (dmc_daemon_error(line) && a->fd < 0 &&
|
||||
!strstr(line, "group") && !strstr(line, "symbolic link"))
|
||||
window_toast(a, line + 7);
|
||||
g_free(line);
|
||||
read_line(r);
|
||||
}
|
||||
|
||||
static void read_line(Reader *r)
|
||||
{
|
||||
g_data_input_stream_read_line_async(r->in, G_PRIORITY_DEFAULT,
|
||||
r->a->cancel, line_read, r);
|
||||
}
|
||||
|
||||
static void watch(App *a, GInputStream *s)
|
||||
{
|
||||
Reader *r = g_new0(Reader, 1);
|
||||
r->a = a;
|
||||
r->in = g_data_input_stream_new(s);
|
||||
read_line(r);
|
||||
}
|
||||
|
||||
static void exited(GObject *src, GAsyncResult *res, gpointer data)
|
||||
{
|
||||
GSubprocess *p = G_SUBPROCESS(src);
|
||||
GError *e = NULL;
|
||||
if (!g_subprocess_wait_finish(p, res, &e)) {
|
||||
/* cancelled: the app is closing */
|
||||
g_error_free(e);
|
||||
g_object_unref(p);
|
||||
return;
|
||||
}
|
||||
App *a = data;
|
||||
char *m;
|
||||
if (g_subprocess_get_if_signaled(p))
|
||||
m = g_strdup_printf("dmodemd stopped (signal %d).",
|
||||
g_subprocess_get_term_sig(p));
|
||||
else
|
||||
m = g_strdup_printf("dmodemd stopped (exit status %d).",
|
||||
g_subprocess_get_exit_status(p));
|
||||
app_log(a, m);
|
||||
if (a->proc == p) {
|
||||
g_clear_object(&a->proc);
|
||||
close_dte(a);
|
||||
if (!g_subprocess_get_if_signaled(p) ||
|
||||
g_subprocess_get_term_sig(p) != SIGTERM)
|
||||
window_toast(a, m);
|
||||
}
|
||||
g_free(m);
|
||||
g_object_unref(p);
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
static void setenv_if(GSubprocessLauncher *l, const char *name,
|
||||
gboolean set, const char *value)
|
||||
{
|
||||
if (set)
|
||||
g_subprocess_launcher_setenv(l, name, value, TRUE);
|
||||
}
|
||||
|
||||
void modem_start(App *a)
|
||||
{
|
||||
Config *c = &a->cfg;
|
||||
if (modem_running(a))
|
||||
return;
|
||||
if (!g_strcmp0(c->line, "device")) {
|
||||
open_dte(a, c->device);
|
||||
window_state(a);
|
||||
return;
|
||||
}
|
||||
char *exe = find_dmodemd(c);
|
||||
if (!exe) {
|
||||
window_toast(a, "dmodemd was not found: install D-Modem, or "
|
||||
"set its path in the line settings");
|
||||
return;
|
||||
}
|
||||
if (!g_strcmp0(c->line, "sip") &&
|
||||
(!*c->sip_user || !*c->sip_server)) {
|
||||
window_toast(a, "Set up the SIP account first");
|
||||
prefs_show(a);
|
||||
g_free(exe);
|
||||
return;
|
||||
}
|
||||
GPtrArray *argv = g_ptr_array_new_with_free_func(g_free);
|
||||
g_ptr_array_add(argv, exe);
|
||||
if (*c->country) {
|
||||
g_ptr_array_add(argv, g_strdup("-c"));
|
||||
g_ptr_array_add(argv, g_strdup(c->country));
|
||||
}
|
||||
/* (the pty in the user's own group: the default, dialout, would
|
||||
need root) */
|
||||
struct group *gr = getgrgid(getgid());
|
||||
if (gr) {
|
||||
g_ptr_array_add(argv, g_strdup("-g"));
|
||||
g_ptr_array_add(argv, g_strdup(gr->gr_name));
|
||||
}
|
||||
if (c->debug > 0)
|
||||
g_ptr_array_add(argv, g_strdup_printf("-d%d", c->debug));
|
||||
if (!g_strcmp0(c->line, "usb")) {
|
||||
g_ptr_array_add(argv, g_strdup_printf("--usb=%s", c->usb));
|
||||
} else if (!g_strcmp0(c->line, "alsa")) {
|
||||
g_ptr_array_add(argv, g_strdup("-a"));
|
||||
g_ptr_array_add(argv, g_strdup(c->alsa));
|
||||
} else if (c->listen) {
|
||||
g_ptr_array_add(argv, g_strdup("-L"));
|
||||
}
|
||||
g_ptr_array_add(argv, NULL);
|
||||
|
||||
GSubprocessLauncher *l = g_subprocess_launcher_new(
|
||||
G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_PIPE);
|
||||
if (!g_strcmp0(c->line, "sip")) {
|
||||
char *login = g_strdup_printf("%s:%s@%s", c->sip_user,
|
||||
c->sip_password, c->sip_server);
|
||||
g_subprocess_launcher_setenv(l, "SIP_LOGIN", login, TRUE);
|
||||
g_free(login);
|
||||
}
|
||||
setenv_if(l, "SIP_T38", !c->t38, "no");
|
||||
setenv_if(l, "SIP_V152", !c->v152, "no");
|
||||
setenv_if(l, "SIP_V150", c->v150, "yes");
|
||||
setenv_if(l, "SIP_SRTP", *c->srtp, c->srtp);
|
||||
/* its log files where the user may write them */
|
||||
char *dir = g_build_filename(g_get_user_cache_dir(), "dmodem-gui", NULL);
|
||||
g_mkdir_with_parents(dir, 0700);
|
||||
g_subprocess_launcher_set_cwd(l, dir);
|
||||
g_free(dir);
|
||||
|
||||
GError *e = NULL;
|
||||
a->proc = g_subprocess_launcher_spawnv(l, (const char *const *)argv->pdata,
|
||||
&e);
|
||||
g_object_unref(l);
|
||||
char *shown = g_strjoinv(" ", (char **)argv->pdata);
|
||||
g_ptr_array_unref(argv);
|
||||
if (!a->proc) {
|
||||
char *m = g_strdup_printf("Can't start dmodemd: %s", e->message);
|
||||
window_toast(a, m);
|
||||
app_log(a, m);
|
||||
g_free(m);
|
||||
g_error_free(e);
|
||||
g_free(shown);
|
||||
window_state(a);
|
||||
return;
|
||||
}
|
||||
char *m = g_strdup_printf("$ %s", shown);
|
||||
app_log(a, m);
|
||||
g_free(m);
|
||||
g_free(shown);
|
||||
watch(a, g_subprocess_get_stderr_pipe(a->proc));
|
||||
watch(a, g_subprocess_get_stdout_pipe(a->proc));
|
||||
g_subprocess_wait_async(g_object_ref(a->proc), a->cancel, exited, a);
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
void modem_stop(App *a)
|
||||
{
|
||||
if (a->proc) {
|
||||
/* hang up first, so the call ends cleanly */
|
||||
if (a->fd >= 0)
|
||||
dmc_hangup(a->s);
|
||||
modem_pump(a);
|
||||
close_dte(a);
|
||||
g_subprocess_send_signal(a->proc, SIGTERM);
|
||||
} else {
|
||||
close_dte(a);
|
||||
}
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
gboolean modem_running(App *a)
|
||||
{
|
||||
return a->proc != NULL || a->fd >= 0;
|
||||
}
|
||||
|
||||
void modem_type(App *a, const char *data, gsize n)
|
||||
{
|
||||
if (a->fd < 0)
|
||||
return;
|
||||
dmc_type(a->s, data, (int)n);
|
||||
modem_pump(a);
|
||||
}
|
||||
|
||||
int modem_command(App *a, const char *cmd, int flags, ResponseFn fn,
|
||||
gpointer data)
|
||||
{
|
||||
int tag = dmc_command(a->s, cmd, flags, 0);
|
||||
if (tag > 0) {
|
||||
Waiting *w = g_new0(Waiting, 1);
|
||||
w->fn = fn;
|
||||
w->data = data;
|
||||
g_hash_table_insert(a->waiting, GINT_TO_POINTER(tag), w);
|
||||
modem_pump(a);
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
/* the ticks the session's timers need */
|
||||
void modem_init(App *a);
|
||||
void modem_init(App *a)
|
||||
{
|
||||
a->s = dmc_session_new();
|
||||
a->fd = -1;
|
||||
a->pending = g_byte_array_new();
|
||||
a->waiting = g_hash_table_new_full(g_direct_hash, g_direct_equal,
|
||||
NULL, g_free);
|
||||
a->cancel = g_cancellable_new();
|
||||
a->tick = g_timeout_add(50, tick, a);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* settings.c - the Settings page: the modem's own settings (AT!M), one
|
||||
* row each, grouped as the configurators group them
|
||||
*
|
||||
* A change runs the setting's command at once, as the configurators do;
|
||||
* a value the modem refuses is put back. AT!R's init string, the
|
||||
* commands that set what differs from the defaults, can be kept as the
|
||||
* commands the app sends when the modem opens.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
typedef struct Row {
|
||||
App *a;
|
||||
int i; /* the setting's index in the model */
|
||||
GtkWidget *w;
|
||||
} Row;
|
||||
|
||||
static void set_row(App *a, Row *r, const char *value);
|
||||
static void mark(App *a, Row *r);
|
||||
|
||||
/* a change sent to the modem */
|
||||
typedef struct Change {
|
||||
int gen, i;
|
||||
char *value;
|
||||
} Change;
|
||||
|
||||
static void applied(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
Change *c = data;
|
||||
if (a->model && c->gen == a->settings_gen) {
|
||||
Row *r = g_ptr_array_index(a->setting_rows, (guint)c->i);
|
||||
if (ev->ok) {
|
||||
dmc_setting_set(a->model, c->i, c->value);
|
||||
mark(a, r);
|
||||
} else {
|
||||
char *m = g_strdup_printf("The modem refused %s",
|
||||
dmc_setting_label(a->model, c->i));
|
||||
window_toast(a, m);
|
||||
g_free(m);
|
||||
set_row(a, r, dmc_setting_value(a->model, c->i));
|
||||
}
|
||||
/* the country sets other settings' defaults too */
|
||||
if (ev->ok && !strcmp(dmc_setting_key(a->model, c->i),
|
||||
"country"))
|
||||
settings_load(a);
|
||||
}
|
||||
g_free(c->value);
|
||||
g_free(c);
|
||||
}
|
||||
|
||||
static void apply(Row *r, const char *value)
|
||||
{
|
||||
App *a = r->a;
|
||||
if (a->settings_quiet || !a->model)
|
||||
return;
|
||||
if (!strcmp(value, dmc_setting_value(a->model, r->i)))
|
||||
return;
|
||||
const char *why = dmc_setting_check(a->model, r->i, value);
|
||||
if (*why) {
|
||||
window_toast(a, why);
|
||||
set_row(a, r, dmc_setting_value(a->model, r->i));
|
||||
return;
|
||||
}
|
||||
Change *c = g_new0(Change, 1);
|
||||
c->gen = a->settings_gen;
|
||||
c->i = r->i;
|
||||
c->value = g_strdup(value);
|
||||
const char *cmd = dmc_setting_command(a->model, r->i, value);
|
||||
if (modem_command(a, cmd, 0, applied, c) < 0) {
|
||||
window_toast(a, "The modem is busy");
|
||||
g_free(c->value);
|
||||
g_free(c);
|
||||
set_row(a, r, dmc_setting_value(a->model, r->i));
|
||||
}
|
||||
}
|
||||
|
||||
static void picked(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
(void)ps;
|
||||
Row *r = data;
|
||||
guint sel = adw_combo_row_get_selected(ADW_COMBO_ROW(o));
|
||||
if (sel == GTK_INVALID_LIST_POSITION || !r->a->model)
|
||||
return;
|
||||
apply(r, dmc_choice_value(r->a->model, r->i, (int)sel));
|
||||
}
|
||||
|
||||
static void spun(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
(void)ps;
|
||||
Row *r = data;
|
||||
char v[32];
|
||||
g_snprintf(v, sizeof(v), "%.0f", adw_spin_row_get_value(ADW_SPIN_ROW(o)));
|
||||
apply(r, v);
|
||||
}
|
||||
|
||||
static void entered(AdwEntryRow *e, gpointer data)
|
||||
{
|
||||
apply(data, gtk_editable_get_text(GTK_EDITABLE(e)));
|
||||
}
|
||||
|
||||
static void set_row(App *a, Row *r, const char *value)
|
||||
{
|
||||
a->settings_quiet = TRUE;
|
||||
switch (dmc_setting_kind(a->model, r->i)) {
|
||||
case DMC_PICK: {
|
||||
int c = dmc_setting_choice_of(a->model, r->i, value);
|
||||
adw_combo_row_set_selected(ADW_COMBO_ROW(r->w),
|
||||
c < 0 ? GTK_INVALID_LIST_POSITION :
|
||||
(guint)c);
|
||||
break;
|
||||
}
|
||||
case DMC_NUMBER:
|
||||
adw_spin_row_set_value(ADW_SPIN_ROW(r->w), atof(value));
|
||||
break;
|
||||
default:
|
||||
gtk_editable_set_text(GTK_EDITABLE(r->w), value);
|
||||
break;
|
||||
}
|
||||
a->settings_quiet = FALSE;
|
||||
}
|
||||
|
||||
/* a row shows when its value is not the default */
|
||||
static void mark(App *a, Row *r)
|
||||
{
|
||||
gboolean changed = strcmp(dmc_setting_value(a->model, r->i),
|
||||
dmc_setting_default(a->model, r->i)) != 0;
|
||||
if (changed)
|
||||
gtk_widget_add_css_class(r->w, "accent");
|
||||
else
|
||||
gtk_widget_remove_css_class(r->w, "accent");
|
||||
}
|
||||
|
||||
static GtkWidget *row_for(App *a, int i)
|
||||
{
|
||||
dmc_model *m = a->model;
|
||||
Row *r = g_new0(Row, 1);
|
||||
r->a = a;
|
||||
r->i = i;
|
||||
switch (dmc_setting_kind(m, i)) {
|
||||
case DMC_PICK: {
|
||||
GtkStringList *l = gtk_string_list_new(NULL);
|
||||
for (int c = 0; c < dmc_setting_choices(m, i); c++)
|
||||
gtk_string_list_append(l, dmc_choice_label(m, i, c));
|
||||
r->w = adw_combo_row_new();
|
||||
adw_combo_row_set_model(ADW_COMBO_ROW(r->w), G_LIST_MODEL(l));
|
||||
g_object_unref(l);
|
||||
if (dmc_setting_choices(m, i) > 12)
|
||||
adw_combo_row_set_enable_search(ADW_COMBO_ROW(r->w), TRUE);
|
||||
set_row(a, r, dmc_setting_value(m, i));
|
||||
g_signal_connect(r->w, "notify::selected", G_CALLBACK(picked), r);
|
||||
break;
|
||||
}
|
||||
case DMC_NUMBER:
|
||||
r->w = adw_spin_row_new_with_range((double)dmc_setting_lo(m, i),
|
||||
(double)dmc_setting_hi(m, i), 1);
|
||||
set_row(a, r, dmc_setting_value(m, i));
|
||||
g_signal_connect(r->w, "notify::value", G_CALLBACK(spun), r);
|
||||
break;
|
||||
default:
|
||||
r->w = adw_entry_row_new();
|
||||
adw_entry_row_set_show_apply_button(ADW_ENTRY_ROW(r->w), TRUE);
|
||||
set_row(a, r, dmc_setting_value(m, i));
|
||||
g_signal_connect(r->w, "apply", G_CALLBACK(entered), r);
|
||||
break;
|
||||
}
|
||||
adw_preferences_row_set_use_markup(ADW_PREFERENCES_ROW(r->w), FALSE);
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r->w),
|
||||
dmc_setting_label(m, i));
|
||||
if (ADW_IS_ACTION_ROW(r->w))
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(r->w),
|
||||
dmc_setting_help(m, i));
|
||||
else
|
||||
gtk_widget_set_tooltip_text(r->w, dmc_setting_help(m, i));
|
||||
g_object_set_data_full(G_OBJECT(r->w), "row", r, g_free);
|
||||
g_ptr_array_add(a->setting_rows, r);
|
||||
mark(a, r);
|
||||
return r->w;
|
||||
}
|
||||
|
||||
void settings_clear(App *a)
|
||||
{
|
||||
for (guint g = 0; a->settings_groups && g < a->settings_groups->len; g++)
|
||||
adw_preferences_page_remove(a->settings_page,
|
||||
g_ptr_array_index(a->settings_groups, g));
|
||||
if (a->settings_groups)
|
||||
g_ptr_array_set_size(a->settings_groups, 0);
|
||||
if (a->setting_rows)
|
||||
g_ptr_array_set_size(a->setting_rows, 0);
|
||||
a->settings_gen++;
|
||||
dmc_model_free(a->model);
|
||||
a->model = NULL;
|
||||
gtk_label_set_text(GTK_LABEL(a->settings_status),
|
||||
"Start the modem to see its settings.");
|
||||
gtk_widget_set_visible(a->settings_status, TRUE);
|
||||
}
|
||||
|
||||
static void got_init(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
return;
|
||||
/* AT!R's lines, as one line of commands */
|
||||
GString *s = g_string_new(NULL);
|
||||
char **lines = g_strsplit(ev->text, "\n", -1);
|
||||
for (int i = 0; lines[i]; i++) {
|
||||
char *l = g_strstrip(lines[i]);
|
||||
if (!*l || !g_ascii_strcasecmp(l, "AT"))
|
||||
continue;
|
||||
if (s->len) {
|
||||
/* (the next line's commands after this one's) */
|
||||
g_string_append(s, l + 2);
|
||||
} else {
|
||||
g_string_append(s, l);
|
||||
}
|
||||
}
|
||||
g_strfreev(lines);
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(a->init_row),
|
||||
s->len ? s->str : "AT (all at their defaults)");
|
||||
g_object_set_data_full(G_OBJECT(a->init_row), "init",
|
||||
g_string_free(s, FALSE), g_free);
|
||||
}
|
||||
|
||||
static void got_model(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok) {
|
||||
gtk_label_set_text(GTK_LABEL(a->settings_status),
|
||||
"This modem does not list its settings "
|
||||
"(AT!M): update D-Modem, or use the "
|
||||
"Terminal's setup screen.");
|
||||
return;
|
||||
}
|
||||
dmc_model *m = dmc_model_parse(ev->text);
|
||||
if (!m) {
|
||||
gtk_label_set_text(GTK_LABEL(a->settings_status),
|
||||
"The modem's settings list was not readable.");
|
||||
return;
|
||||
}
|
||||
settings_clear(a);
|
||||
a->model = m;
|
||||
gtk_widget_set_visible(a->settings_status, FALSE);
|
||||
for (int g = 0; g < dmc_model_groups(m); g++) {
|
||||
const char *name = dmc_model_group(m, g);
|
||||
GtkWidget *grp = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(grp), name);
|
||||
for (int i = 0; i < dmc_model_count(m); i++)
|
||||
if (!strcmp(dmc_setting_group(m, i), name))
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(grp),
|
||||
row_for(a, i));
|
||||
adw_preferences_page_add(a->settings_page,
|
||||
ADW_PREFERENCES_GROUP(grp));
|
||||
g_ptr_array_add(a->settings_groups, grp);
|
||||
}
|
||||
modem_command(a, "AT!R", DMC_QUIET, got_init, NULL);
|
||||
settings_sensitive(a, dmc_state(a->s) == DMC_IDLE);
|
||||
}
|
||||
|
||||
void settings_load(App *a)
|
||||
{
|
||||
if (dmc_state(a->s) == DMC_CLOSED)
|
||||
return;
|
||||
modem_command(a, "AT!M", DMC_QUIET, got_model, NULL);
|
||||
}
|
||||
|
||||
void settings_sensitive(App *a, gboolean on)
|
||||
{
|
||||
for (guint g = 0; a->settings_groups && g < a->settings_groups->len; g++)
|
||||
gtk_widget_set_sensitive(g_ptr_array_index(a->settings_groups, g),
|
||||
on);
|
||||
}
|
||||
|
||||
static void reload(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
settings_load(data);
|
||||
}
|
||||
|
||||
static void reset_done(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
window_toast(a, "The modem refused ATZ");
|
||||
settings_load(a);
|
||||
}
|
||||
|
||||
static void reset(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
modem_command(a, "ATZ", 0, reset_done, NULL);
|
||||
}
|
||||
|
||||
static void keep_init(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
const char *init = g_object_get_data(G_OBJECT(a->init_row), "init");
|
||||
g_free(a->cfg.init);
|
||||
a->cfg.init = g_strdup(init ? init : "");
|
||||
config_save(&a->cfg);
|
||||
window_toast(a, *a->cfg.init ? "Sent each time the modem opens" :
|
||||
"Nothing to send: every setting is at its default");
|
||||
}
|
||||
|
||||
GtkWidget *settings_page_new(App *a)
|
||||
{
|
||||
a->settings_groups = g_ptr_array_new();
|
||||
a->setting_rows = g_ptr_array_new();
|
||||
a->settings_page = ADW_PREFERENCES_PAGE(adw_preferences_page_new());
|
||||
|
||||
GtkWidget *top = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(top), "The modem's settings");
|
||||
adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(top),
|
||||
"Changes take effect at once. The modem keeps no stored "
|
||||
"profile, so keep the init string to have them each time.");
|
||||
GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
|
||||
GtkWidget *b = gtk_button_new_from_icon_name("view-refresh-symbolic");
|
||||
gtk_widget_set_tooltip_text(b, "Read the settings again");
|
||||
gtk_widget_add_css_class(b, "flat");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(reload), a);
|
||||
gtk_box_append(GTK_BOX(bar), b);
|
||||
b = gtk_button_new_with_label("Defaults");
|
||||
gtk_widget_set_tooltip_text(b, "Every setting back to its default (ATZ)");
|
||||
gtk_widget_add_css_class(b, "flat");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(reset), a);
|
||||
gtk_box_append(GTK_BOX(bar), b);
|
||||
adw_preferences_group_set_header_suffix(ADW_PREFERENCES_GROUP(top), bar);
|
||||
|
||||
a->init_row = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(a->init_row),
|
||||
"Init string");
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(a->init_row), "");
|
||||
adw_action_row_set_subtitle_selectable(ADW_ACTION_ROW(a->init_row), TRUE);
|
||||
gtk_widget_add_css_class(a->init_row, "property");
|
||||
b = gtk_button_new_with_label("Keep");
|
||||
gtk_widget_set_tooltip_text(b, "Send it each time the modem opens");
|
||||
gtk_widget_set_valign(b, GTK_ALIGN_CENTER);
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(keep_init), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(a->init_row), b);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(top), a->init_row);
|
||||
a->settings_status = gtk_label_new("");
|
||||
gtk_label_set_wrap(GTK_LABEL(a->settings_status), TRUE);
|
||||
gtk_widget_add_css_class(a->settings_status, "dim-label");
|
||||
gtk_widget_set_margin_top(a->settings_status, 12);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(top), a->settings_status);
|
||||
adw_preferences_page_add(a->settings_page, ADW_PREFERENCES_GROUP(top));
|
||||
settings_clear(a);
|
||||
return GTK_WIDGET(a->settings_page);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* stats.c - the Call Stats page: the last call's statistics (AT#UD, as
|
||||
* labelled rows) and the modem's own report of it (ATI11)
|
||||
*/
|
||||
#include "app.h"
|
||||
|
||||
static void got_report(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
gtk_label_set_text(GTK_LABEL(a->stats_report),
|
||||
ev->ok ? ev->text : "");
|
||||
}
|
||||
|
||||
static void got_diag(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
for (guint i = 0; i < a->stats_rows->len; i++)
|
||||
adw_preferences_group_remove(a->stats_group,
|
||||
g_ptr_array_index(a->stats_rows, i));
|
||||
g_ptr_array_set_size(a->stats_rows, 0);
|
||||
if (!ev->ok) {
|
||||
gtk_widget_set_visible(a->stats_empty, TRUE);
|
||||
return;
|
||||
}
|
||||
dmc_diag *d = dmc_diag_parse(ev->text);
|
||||
gboolean call = dmc_diag_has_call(d);
|
||||
gtk_widget_set_visible(a->stats_empty, !call);
|
||||
for (int i = 0; call && i < dmc_diag_count(d); i++) {
|
||||
if (dmc_diag_key(d, i) == 0)
|
||||
continue; /* the report's version */
|
||||
GtkWidget *r = adw_action_row_new();
|
||||
adw_preferences_row_set_use_markup(ADW_PREFERENCES_ROW(r), FALSE);
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r),
|
||||
dmc_diag_label(d, i));
|
||||
GtkWidget *v = gtk_label_new(dmc_diag_value(d, i));
|
||||
gtk_label_set_selectable(GTK_LABEL(v), TRUE);
|
||||
gtk_widget_add_css_class(v, "dim-label");
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(r), v);
|
||||
adw_preferences_group_add(a->stats_group, r);
|
||||
g_ptr_array_add(a->stats_rows, r);
|
||||
}
|
||||
dmc_diag_free(d);
|
||||
}
|
||||
|
||||
void stats_refresh(App *a)
|
||||
{
|
||||
int st = dmc_state(a->s);
|
||||
if (st == DMC_CLOSED || st == DMC_ONLINE)
|
||||
return;
|
||||
modem_command(a, "AT#UD", DMC_QUIET, got_diag, NULL);
|
||||
modem_command(a, "ATI11", DMC_QUIET, got_report, NULL);
|
||||
}
|
||||
|
||||
static void refresh(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
stats_refresh(data);
|
||||
}
|
||||
|
||||
GtkWidget *stats_page_new(App *a)
|
||||
{
|
||||
a->stats_rows = g_ptr_array_new();
|
||||
GtkWidget *page = adw_preferences_page_new();
|
||||
GtkWidget *g = adw_preferences_group_new();
|
||||
a->stats_group = ADW_PREFERENCES_GROUP(g);
|
||||
adw_preferences_group_set_title(a->stats_group, "Last call");
|
||||
adw_preferences_group_set_description(a->stats_group,
|
||||
"As the modem reports it (AT#UD), after each call; during "
|
||||
"one, escape to command mode to see it live.");
|
||||
GtkWidget *b = gtk_button_new_from_icon_name("view-refresh-symbolic");
|
||||
gtk_widget_set_tooltip_text(b, "Read them again");
|
||||
gtk_widget_add_css_class(b, "flat");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(refresh), a);
|
||||
adw_preferences_group_set_header_suffix(a->stats_group, b);
|
||||
a->stats_empty = gtk_label_new("No call yet.");
|
||||
gtk_widget_add_css_class(a->stats_empty, "dim-label");
|
||||
adw_preferences_group_add(a->stats_group, a->stats_empty);
|
||||
adw_preferences_page_add(ADW_PREFERENCES_PAGE(page), a->stats_group);
|
||||
|
||||
GtkWidget *rg = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(rg),
|
||||
"The modem's report (ATI11)");
|
||||
a->stats_report = gtk_label_new("");
|
||||
gtk_label_set_selectable(GTK_LABEL(a->stats_report), TRUE);
|
||||
gtk_label_set_xalign(GTK_LABEL(a->stats_report), 0);
|
||||
gtk_widget_add_css_class(a->stats_report, "monospace");
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(rg), a->stats_report);
|
||||
adw_preferences_page_add(ADW_PREFERENCES_PAGE(page),
|
||||
ADW_PREFERENCES_GROUP(rg));
|
||||
return page;
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* window.c - the main window: the Modem, Terminal, Settings, Call and
|
||||
* Log pages, the same pages as the Windows and macOS apps
|
||||
* (docs/design.md)
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
void window_toast(App *a, const char *text)
|
||||
{
|
||||
AdwToast *t = adw_toast_new(text);
|
||||
adw_toast_set_timeout(t, 4);
|
||||
adw_toast_overlay_add_toast(a->toasts, t);
|
||||
}
|
||||
|
||||
static const char *state_icon(int state)
|
||||
{
|
||||
switch (state) {
|
||||
case DMC_RINGING:
|
||||
return "call-incoming-symbolic";
|
||||
case DMC_DIALING:
|
||||
case DMC_ANSWERING:
|
||||
return "call-outgoing-symbolic";
|
||||
case DMC_ONLINE:
|
||||
case DMC_ONLINE_COMMAND:
|
||||
return "network-transmit-receive-symbolic";
|
||||
case DMC_CONFIGURATOR:
|
||||
return "preferences-system-symbolic";
|
||||
default:
|
||||
return "call-start-symbolic";
|
||||
}
|
||||
}
|
||||
|
||||
/* the Modem page and the buttons as the state is now */
|
||||
void window_state(App *a)
|
||||
{
|
||||
int st = dmc_state(a->s);
|
||||
gboolean running = modem_running(a);
|
||||
gtk_image_set_from_icon_name(GTK_IMAGE(a->status_icon),
|
||||
running ? state_icon(st) :
|
||||
"network-offline-symbolic");
|
||||
const char *title = running && st == DMC_CLOSED ? "Starting" :
|
||||
dmc_state_name(st);
|
||||
gtk_label_set_text(GTK_LABEL(a->status_title), title);
|
||||
char *detail = NULL;
|
||||
if (st == DMC_ONLINE || st == DMC_ONLINE_COMMAND ||
|
||||
st == DMC_HANGING_UP)
|
||||
detail = g_strdup(dmc_connect_text(a->s));
|
||||
else if (st == DMC_RINGING && *dmc_caller_number(a->s))
|
||||
detail = g_strdup_printf("%s %s", dmc_caller_number(a->s),
|
||||
dmc_caller_name(a->s));
|
||||
else
|
||||
detail = config_summary(&a->cfg);
|
||||
gtk_label_set_text(GTK_LABEL(a->status_detail), detail);
|
||||
g_free(detail);
|
||||
|
||||
gboolean open = st != DMC_CLOSED;
|
||||
gtk_widget_set_sensitive(a->dial_btn, open && st == DMC_IDLE);
|
||||
gtk_widget_set_sensitive(a->number, open);
|
||||
gtk_widget_set_sensitive(a->answer_btn, st == DMC_RINGING);
|
||||
gtk_widget_set_sensitive(a->hangup_btn,
|
||||
st == DMC_DIALING || st == DMC_ANSWERING ||
|
||||
st == DMC_ONLINE || st == DMC_ONLINE_COMMAND ||
|
||||
st == DMC_RINGING);
|
||||
gtk_button_set_label(GTK_BUTTON(a->run_btn), running ? "Stop" : "Start");
|
||||
if (running)
|
||||
gtk_widget_remove_css_class(a->run_btn, "suggested-action");
|
||||
else
|
||||
gtk_widget_add_css_class(a->run_btn, "suggested-action");
|
||||
char *sum = config_summary(&a->cfg);
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(a->run_row), sum);
|
||||
g_free(sum);
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(a->device_row),
|
||||
a->fd >= 0 && a->device ? a->device :
|
||||
"Not running");
|
||||
gtk_widget_set_sensitive(a->copy_btn, a->fd >= 0);
|
||||
gtk_widget_set_sensitive(a->term_buttons, st == DMC_IDLE);
|
||||
settings_sensitive(a, st == DMC_IDLE);
|
||||
}
|
||||
|
||||
void window_opened(App *a)
|
||||
{
|
||||
window_state(a);
|
||||
settings_load(a);
|
||||
stats_refresh(a);
|
||||
}
|
||||
|
||||
void window_closed(App *a)
|
||||
{
|
||||
settings_clear(a);
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
void window_event(App *a, const dmc_event *ev)
|
||||
{
|
||||
switch (ev->type) {
|
||||
case DMC_EV_STATE: {
|
||||
int was = a->last_state;
|
||||
a->last_state = ev->state;
|
||||
window_state(a);
|
||||
/* a call over: its statistics */
|
||||
if (ev->state == DMC_IDLE &&
|
||||
(was == DMC_ONLINE || was == DMC_ONLINE_COMMAND ||
|
||||
was == DMC_HANGING_UP || was == DMC_DIALING ||
|
||||
was == DMC_ANSWERING))
|
||||
stats_refresh(a);
|
||||
/* a configurator over: the settings it changed */
|
||||
if (ev->state == DMC_IDLE && was == DMC_CONFIGURATOR)
|
||||
settings_load(a);
|
||||
break;
|
||||
}
|
||||
case DMC_EV_RESULT:
|
||||
if (!strcmp(ev->result, "RING")) {
|
||||
if (!gtk_window_is_active(a->window)) {
|
||||
GNotification *n = g_notification_new("Incoming call");
|
||||
const char *who = dmc_caller_number(a->s);
|
||||
g_notification_set_body(n, *who ? who :
|
||||
"The modem is ringing");
|
||||
g_application_send_notification(
|
||||
G_APPLICATION(a->gapp), "ring", n);
|
||||
g_object_unref(n);
|
||||
}
|
||||
} else if (ev->result[0]) {
|
||||
window_toast(a, ev->result);
|
||||
}
|
||||
break;
|
||||
case DMC_EV_CALLER:
|
||||
window_state(a);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* the Modem page
|
||||
*/
|
||||
|
||||
static void dialled(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
window_toast(a, ev->result);
|
||||
}
|
||||
|
||||
static void dial(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
const char *n = gtk_editable_get_text(GTK_EDITABLE(a->number));
|
||||
if (!*n) {
|
||||
window_toast(a, "Enter a number to dial");
|
||||
return;
|
||||
}
|
||||
char *cmd = g_strdup_printf("ATD%s", n);
|
||||
modem_command(a, cmd, 0, dialled, NULL);
|
||||
g_free(cmd);
|
||||
}
|
||||
|
||||
static void answer(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
modem_command(a, "ATA", 0, dialled, NULL);
|
||||
}
|
||||
|
||||
static void hangup(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
dmc_hangup(a->s);
|
||||
modem_pump(a);
|
||||
}
|
||||
|
||||
static void run(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
if (modem_running(a))
|
||||
modem_stop(a);
|
||||
else
|
||||
modem_start(a);
|
||||
}
|
||||
|
||||
static void copy_device(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
if (!a->device)
|
||||
return;
|
||||
gdk_clipboard_set_text(gtk_widget_get_clipboard(w), a->device);
|
||||
window_toast(a, "Copied");
|
||||
}
|
||||
|
||||
static void line_settings(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
prefs_show(data);
|
||||
}
|
||||
|
||||
static GtkWidget *modem_page(App *a)
|
||||
{
|
||||
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 24);
|
||||
gtk_widget_set_margin_top(box, 24);
|
||||
gtk_widget_set_margin_bottom(box, 24);
|
||||
gtk_widget_set_margin_start(box, 12);
|
||||
gtk_widget_set_margin_end(box, 12);
|
||||
|
||||
/* the state, large */
|
||||
a->status_icon = gtk_image_new_from_icon_name("network-offline-symbolic");
|
||||
gtk_image_set_pixel_size(GTK_IMAGE(a->status_icon), 96);
|
||||
gtk_widget_add_css_class(a->status_icon, "dim-label");
|
||||
gtk_box_append(GTK_BOX(box), a->status_icon);
|
||||
a->status_title = gtk_label_new("Not connected");
|
||||
gtk_widget_add_css_class(a->status_title, "title-1");
|
||||
gtk_box_append(GTK_BOX(box), a->status_title);
|
||||
a->status_detail = gtk_label_new("");
|
||||
gtk_label_set_wrap(GTK_LABEL(a->status_detail), TRUE);
|
||||
gtk_widget_add_css_class(a->status_detail, "dim-label");
|
||||
gtk_box_append(GTK_BOX(box), a->status_detail);
|
||||
|
||||
/* the call */
|
||||
GtkWidget *call = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(call), "Call");
|
||||
a->number = adw_entry_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(a->number),
|
||||
"Number to dial");
|
||||
gtk_editable_set_text(GTK_EDITABLE(a->number), "");
|
||||
a->dial_btn = gtk_button_new_with_label("Dial");
|
||||
gtk_widget_set_valign(a->dial_btn, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(a->dial_btn, "suggested-action");
|
||||
adw_entry_row_add_suffix(ADW_ENTRY_ROW(a->number), a->dial_btn);
|
||||
g_signal_connect(a->dial_btn, "clicked", G_CALLBACK(dial), a);
|
||||
g_signal_connect(a->number, "entry-activated", G_CALLBACK(dial), a);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(call), a->number);
|
||||
|
||||
GtkWidget *calls = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(calls), "Answer or hang up");
|
||||
a->answer_btn = gtk_button_new_with_label("Answer");
|
||||
gtk_widget_set_valign(a->answer_btn, GTK_ALIGN_CENTER);
|
||||
g_signal_connect(a->answer_btn, "clicked", G_CALLBACK(answer), a);
|
||||
a->hangup_btn = gtk_button_new_with_label("Hang Up");
|
||||
gtk_widget_set_valign(a->hangup_btn, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(a->hangup_btn, "destructive-action");
|
||||
g_signal_connect(a->hangup_btn, "clicked", G_CALLBACK(hangup), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(calls), a->answer_btn);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(calls), a->hangup_btn);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(call), calls);
|
||||
gtk_box_append(GTK_BOX(box), call);
|
||||
|
||||
/* the modem */
|
||||
GtkWidget *mg = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(mg), "Modem");
|
||||
GtkWidget *line_btn = gtk_button_new_from_icon_name("emblem-system-symbolic");
|
||||
gtk_widget_set_tooltip_text(line_btn, "Line settings");
|
||||
gtk_widget_add_css_class(line_btn, "flat");
|
||||
g_signal_connect(line_btn, "clicked", G_CALLBACK(line_settings), a);
|
||||
adw_preferences_group_set_header_suffix(ADW_PREFERENCES_GROUP(mg),
|
||||
line_btn);
|
||||
a->run_row = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(a->run_row), "dmodemd");
|
||||
a->run_btn = gtk_button_new_with_label("Start");
|
||||
gtk_widget_set_valign(a->run_btn, GTK_ALIGN_CENTER);
|
||||
g_signal_connect(a->run_btn, "clicked", G_CALLBACK(run), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(a->run_row), a->run_btn);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), a->run_row);
|
||||
a->device_row = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(a->device_row),
|
||||
"Device");
|
||||
a->copy_btn = gtk_button_new_from_icon_name("edit-copy-symbolic");
|
||||
gtk_widget_set_tooltip_text(a->copy_btn, "Copy the device's path");
|
||||
gtk_widget_set_valign(a->copy_btn, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(a->copy_btn, "flat");
|
||||
g_signal_connect(a->copy_btn, "clicked", G_CALLBACK(copy_device), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(a->device_row), a->copy_btn);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), a->device_row);
|
||||
gtk_box_append(GTK_BOX(box), mg);
|
||||
|
||||
GtkWidget *clamp = adw_clamp_new();
|
||||
adw_clamp_set_maximum_size(ADW_CLAMP(clamp), 560);
|
||||
adw_clamp_set_child(ADW_CLAMP(clamp), box);
|
||||
GtkWidget *scroll = gtk_scrolled_window_new();
|
||||
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
|
||||
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
|
||||
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scroll), clamp);
|
||||
return scroll;
|
||||
}
|
||||
|
||||
/*
|
||||
* the Terminal page
|
||||
*/
|
||||
|
||||
static void committed(VteTerminal *t, char *text, guint size, gpointer data)
|
||||
{
|
||||
(void)t;
|
||||
modem_type(data, text, size);
|
||||
}
|
||||
|
||||
static void typed_command(App *a, const char *cmd)
|
||||
{
|
||||
if (dmc_state(a->s) != DMC_IDLE)
|
||||
return;
|
||||
modem_type(a, cmd, strlen(cmd));
|
||||
gtk_widget_grab_focus(GTK_WIDGET(a->term));
|
||||
}
|
||||
|
||||
static void setup_screen(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
typed_command(data, "AT!CF\r");
|
||||
}
|
||||
|
||||
static void setup_cli(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
typed_command(data, "AT!CT\r");
|
||||
}
|
||||
|
||||
static void clear_term(GtkWidget *w, gpointer data)
|
||||
{
|
||||
(void)w;
|
||||
App *a = data;
|
||||
vte_terminal_reset(a->term, TRUE, TRUE);
|
||||
}
|
||||
|
||||
static GtkWidget *terminal_page(App *a)
|
||||
{
|
||||
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);
|
||||
a->term_buttons = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
|
||||
GtkWidget *b = gtk_button_new_with_label("Full-Screen Setup");
|
||||
gtk_widget_set_tooltip_text(b, "The modem's own setup screen (AT!CF)");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(setup_screen), a);
|
||||
gtk_box_append(GTK_BOX(a->term_buttons), b);
|
||||
b = gtk_button_new_with_label("Command-Line Setup");
|
||||
gtk_widget_set_tooltip_text(b, "The modem's IOS-style command line "
|
||||
"(AT!CT)");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(setup_cli), a);
|
||||
gtk_box_append(GTK_BOX(a->term_buttons), b);
|
||||
gtk_box_append(GTK_BOX(bar), a->term_buttons);
|
||||
GtkWidget *spacer = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
|
||||
gtk_widget_set_hexpand(spacer, TRUE);
|
||||
gtk_box_append(GTK_BOX(bar), spacer);
|
||||
b = gtk_button_new_from_icon_name("edit-clear-all-symbolic");
|
||||
gtk_widget_set_tooltip_text(b, "Clear");
|
||||
gtk_widget_add_css_class(b, "flat");
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(clear_term), a);
|
||||
gtk_box_append(GTK_BOX(bar), b);
|
||||
gtk_box_append(GTK_BOX(box), bar);
|
||||
|
||||
a->term = VTE_TERMINAL(vte_terminal_new());
|
||||
vte_terminal_set_scrollback_lines(a->term, 5000);
|
||||
vte_terminal_set_size(a->term, 80, 25);
|
||||
/* (the modem takes S5, a backspace, not DEL) */
|
||||
vte_terminal_set_backspace_binding(a->term, VTE_ERASE_ASCII_BACKSPACE);
|
||||
PangoFontDescription *f = pango_font_description_from_string("Monospace 11");
|
||||
vte_terminal_set_font(a->term, f);
|
||||
pango_font_description_free(f);
|
||||
/* the brand's colours */
|
||||
GdkRGBA fg, bg;
|
||||
gdk_rgba_parse(&fg, "#e8f0ff");
|
||||
gdk_rgba_parse(&bg, "#0a0f1c");
|
||||
vte_terminal_set_colors(a->term, &fg, &bg, NULL, 0);
|
||||
gtk_widget_set_vexpand(GTK_WIDGET(a->term), TRUE);
|
||||
gtk_widget_set_hexpand(GTK_WIDGET(a->term), TRUE);
|
||||
g_signal_connect(a->term, "commit", G_CALLBACK(committed), a);
|
||||
GtkWidget *scroll = gtk_scrolled_window_new();
|
||||
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scroll),
|
||||
GTK_WIDGET(a->term));
|
||||
gtk_widget_set_vexpand(scroll, TRUE);
|
||||
gtk_box_append(GTK_BOX(box), scroll);
|
||||
return box;
|
||||
}
|
||||
|
||||
/*
|
||||
* the Log page
|
||||
*/
|
||||
|
||||
static GtkWidget *log_page(App *a)
|
||||
{
|
||||
GtkWidget *view = gtk_text_view_new();
|
||||
gtk_text_view_set_editable(GTK_TEXT_VIEW(view), FALSE);
|
||||
gtk_text_view_set_monospace(GTK_TEXT_VIEW(view), TRUE);
|
||||
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(view), GTK_WRAP_WORD_CHAR);
|
||||
gtk_text_view_set_left_margin(GTK_TEXT_VIEW(view), 12);
|
||||
gtk_text_view_set_top_margin(GTK_TEXT_VIEW(view), 12);
|
||||
a->log = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));
|
||||
GtkWidget *scroll = gtk_scrolled_window_new();
|
||||
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scroll), view);
|
||||
return scroll;
|
||||
}
|
||||
|
||||
/*
|
||||
* the window
|
||||
*/
|
||||
|
||||
static void about(GSimpleAction *act, GVariant *v, gpointer data)
|
||||
{
|
||||
(void)act;
|
||||
(void)v;
|
||||
App *a = data;
|
||||
AdwDialog *d = adw_about_dialog_new();
|
||||
adw_about_dialog_set_application_name(ADW_ABOUT_DIALOG(d), "D-Modem");
|
||||
adw_about_dialog_set_application_icon(ADW_ABOUT_DIALOG(d), APP_ID);
|
||||
adw_about_dialog_set_developer_name(ADW_ABOUT_DIALOG(d),
|
||||
"The D-Modem Authors");
|
||||
adw_about_dialog_set_version(ADW_ABOUT_DIALOG(d), "1.0.0");
|
||||
adw_about_dialog_set_comments(ADW_ABOUT_DIALOG(d),
|
||||
"The front panel of D-Modem, the open V.92 softmodem.");
|
||||
adw_about_dialog_set_website(ADW_ABOUT_DIALOG(d),
|
||||
"https://github.com/D-Modem/gui");
|
||||
adw_about_dialog_set_license_type(ADW_ABOUT_DIALOG(d),
|
||||
GTK_LICENSE_BSD_3);
|
||||
adw_dialog_present(d, GTK_WIDGET(a->window));
|
||||
}
|
||||
|
||||
static void line_action(GSimpleAction *act, GVariant *v, gpointer data)
|
||||
{
|
||||
(void)act;
|
||||
(void)v;
|
||||
prefs_show(data);
|
||||
}
|
||||
|
||||
void window_build(App *a)
|
||||
{
|
||||
AdwApplicationWindow *w = ADW_APPLICATION_WINDOW(
|
||||
adw_application_window_new(GTK_APPLICATION(a->gapp)));
|
||||
a->window = GTK_WINDOW(w);
|
||||
gtk_window_set_title(a->window, "D-Modem");
|
||||
gtk_window_set_default_size(a->window, 860, 680);
|
||||
|
||||
const GActionEntry actions[] = {
|
||||
{ "about", about, NULL, NULL, NULL, { 0 } },
|
||||
{ "line", line_action, NULL, NULL, NULL, { 0 } },
|
||||
};
|
||||
g_action_map_add_action_entries(G_ACTION_MAP(w), actions,
|
||||
G_N_ELEMENTS(actions), a);
|
||||
|
||||
a->stack = ADW_VIEW_STACK(adw_view_stack_new());
|
||||
adw_view_stack_add_titled_with_icon(a->stack, modem_page(a), "modem",
|
||||
"Modem", "call-start-symbolic");
|
||||
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, settings_page_new(a),
|
||||
"settings", "Settings",
|
||||
"preferences-system-symbolic");
|
||||
adw_view_stack_add_titled_with_icon(a->stack, stats_page_new(a),
|
||||
"call", "Call Stats",
|
||||
"utilities-system-monitor-symbolic");
|
||||
adw_view_stack_add_titled_with_icon(a->stack, log_page(a), "log",
|
||||
"Log", "text-x-generic-symbolic");
|
||||
|
||||
GtkWidget *header = adw_header_bar_new();
|
||||
GtkWidget *sw = adw_view_switcher_new();
|
||||
adw_view_switcher_set_stack(ADW_VIEW_SWITCHER(sw), a->stack);
|
||||
adw_view_switcher_set_policy(ADW_VIEW_SWITCHER(sw),
|
||||
ADW_VIEW_SWITCHER_POLICY_WIDE);
|
||||
adw_header_bar_set_title_widget(ADW_HEADER_BAR(header), sw);
|
||||
GMenu *menu = g_menu_new();
|
||||
g_menu_append(menu, "Line Settings", "win.line");
|
||||
g_menu_append(menu, "About D-Modem", "win.about");
|
||||
GtkWidget *mb = gtk_menu_button_new();
|
||||
gtk_menu_button_set_icon_name(GTK_MENU_BUTTON(mb), "open-menu-symbolic");
|
||||
gtk_menu_button_set_menu_model(GTK_MENU_BUTTON(mb), G_MENU_MODEL(menu));
|
||||
g_object_unref(menu);
|
||||
adw_header_bar_pack_end(ADW_HEADER_BAR(header), mb);
|
||||
|
||||
GtkWidget *tv = adw_toolbar_view_new();
|
||||
adw_toolbar_view_add_top_bar(ADW_TOOLBAR_VIEW(tv), header);
|
||||
a->toasts = ADW_TOAST_OVERLAY(adw_toast_overlay_new());
|
||||
adw_toast_overlay_set_child(a->toasts, GTK_WIDGET(a->stack));
|
||||
adw_toolbar_view_set_content(ADW_TOOLBAR_VIEW(tv), GTK_WIDGET(a->toasts));
|
||||
adw_application_window_set_content(w, tv);
|
||||
/* (a page to open on: screenshots and the docs) */
|
||||
const char *page = g_getenv("DMODEM_GUI_PAGE");
|
||||
if (page)
|
||||
adw_view_stack_set_visible_child_name(a->stack, page);
|
||||
window_state(a);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "16x16",
|
||||
"scale": "1x",
|
||||
"filename": "icon_16x16.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "16x16",
|
||||
"scale": "2x",
|
||||
"filename": "icon_16x16@2x.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "32x32",
|
||||
"scale": "1x",
|
||||
"filename": "icon_32x32.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "32x32",
|
||||
"scale": "2x",
|
||||
"filename": "icon_32x32@2x.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "128x128",
|
||||
"scale": "1x",
|
||||
"filename": "icon_128x128.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "128x128",
|
||||
"scale": "2x",
|
||||
"filename": "icon_128x128@2x.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "256x256",
|
||||
"scale": "1x",
|
||||
"filename": "icon_256x256.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "256x256",
|
||||
"scale": "2x",
|
||||
"filename": "icon_256x256@2x.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "512x512",
|
||||
"scale": "1x",
|
||||
"filename": "icon_512x512.png"
|
||||
},
|
||||
{
|
||||
"idiom": "mac",
|
||||
"size": "512x512",
|
||||
"scale": "2x",
|
||||
"filename": "icon_512x512@2x.png"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"version": 1,
|
||||
"author": "xcode"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 538 B |
|
After Width: | Height: | Size: 978 B |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 978 B |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 29 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* Bridging.h - libdmodemctl, for Swift
|
||||
*/
|
||||
#include "dmodemctl.h"
|
||||
@@ -0,0 +1,306 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// ContentView.swift - the window: its pages (Modem, Terminal, Settings,
|
||||
// Call Stats, Log) in a sidebar
|
||||
|
||||
import SwiftUI
|
||||
|
||||
enum Page: String, CaseIterable, Identifiable {
|
||||
case modem = "Modem", terminal = "Terminal", settings = "Settings"
|
||||
case stats = "Call Stats", log = "Log"
|
||||
var id: String { rawValue }
|
||||
var icon: String {
|
||||
switch self {
|
||||
case .modem: return "phone.connection"
|
||||
case .terminal: return "terminal"
|
||||
case .settings: return "slider.horizontal.3"
|
||||
case .stats: return "chart.bar"
|
||||
case .log: return "doc.plaintext"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
@State private var page: Page? = Page(rawValue: ProcessInfo.processInfo.environment["DMODEM_GUI_PAGE"] ?? "") ?? .modem
|
||||
|
||||
var body: some View {
|
||||
NavigationSplitView {
|
||||
List(Page.allCases, selection: $page) { p in
|
||||
Label(p.rawValue, systemImage: p.icon).tag(p)
|
||||
}
|
||||
.navigationSplitViewColumnWidth(170)
|
||||
} detail: {
|
||||
Group {
|
||||
switch page ?? .modem {
|
||||
case .modem: ModemPage()
|
||||
case .terminal: TerminalPane()
|
||||
case .settings: SettingsPage()
|
||||
case .stats: StatsPage()
|
||||
case .log: LogPage()
|
||||
}
|
||||
}
|
||||
.navigationTitle(page?.rawValue ?? "D-Modem")
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button(modem.running ? "Stop" : "Start") {
|
||||
modem.running ? modem.stop() : modem.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
.overlay(alignment: .bottom) {
|
||||
if let t = modem.toast {
|
||||
Text(t)
|
||||
.padding(.horizontal, 14).padding(.vertical, 8)
|
||||
.background(.regularMaterial, in: Capsule())
|
||||
.padding(16)
|
||||
.transition(.opacity)
|
||||
.task(id: t) {
|
||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||
if modem.toast == t { modem.toast = nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
.animation(.default, value: modem.toast)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Modem
|
||||
|
||||
struct ModemPage: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
@State private var number = ""
|
||||
|
||||
private var icon: String {
|
||||
guard modem.running else { return "phone.down" }
|
||||
switch modem.state {
|
||||
case Int(DMC_RINGING): return "phone.arrow.down.left"
|
||||
case Int(DMC_DIALING), Int(DMC_ANSWERING): return "phone.arrow.up.right"
|
||||
case Int(DMC_ONLINE), Int(DMC_ONLINE_COMMAND): return "arrow.up.arrow.down"
|
||||
case Int(DMC_CONFIGURATOR): return "gearshape"
|
||||
default: return "phone"
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
HStack(spacing: 16) {
|
||||
Image(systemName: icon)
|
||||
.font(.system(size: 36))
|
||||
.frame(width: 56)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(modem.stateName).font(.title.bold())
|
||||
Text(modem.detail).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
Section("Call") {
|
||||
HStack {
|
||||
TextField("Number", text: $number)
|
||||
.onSubmit { if modem.isIdle { modem.dial(number) } }
|
||||
Button("Dial") { modem.dial(number) }
|
||||
.disabled(!modem.isIdle)
|
||||
}
|
||||
.disabled(!modem.isOpen)
|
||||
HStack {
|
||||
Button("Answer") { modem.answer() }
|
||||
.disabled(modem.state != Int(DMC_RINGING))
|
||||
Button("Hang Up", role: .destructive) { modem.hangUp() }
|
||||
.disabled(!modem.canHangUp)
|
||||
}
|
||||
}
|
||||
Section("Line") {
|
||||
LabeledContent("Line", value: modem.config.summary)
|
||||
LabeledContent("Modem device") {
|
||||
HStack {
|
||||
Text(modem.device.isEmpty ? "Not running" : modem.device)
|
||||
.textSelection(.enabled)
|
||||
if !modem.device.isEmpty {
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(modem.device, forType: .string)
|
||||
} label: { Image(systemName: "doc.on.doc") }
|
||||
.buttonStyle(.borderless)
|
||||
.help("Copy, for another program to use the modem")
|
||||
}
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
if #available(macOS 14, *) {
|
||||
SettingsLink { Text("Line Settings…") }
|
||||
} else {
|
||||
Button("Line Settings…") {
|
||||
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
Button(modem.running ? "Stop" : "Start") {
|
||||
modem.running ? modem.stop() : modem.start()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Settings
|
||||
|
||||
struct SettingsPage: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
LabeledContent("Init string") {
|
||||
HStack {
|
||||
Text(modem.initString.isEmpty ? "AT (all at their defaults)" : modem.initString)
|
||||
.font(.body.monospaced())
|
||||
.textSelection(.enabled)
|
||||
Button("Keep") { modem.keepInit() }
|
||||
.help("Send it each time the modem opens")
|
||||
}
|
||||
}
|
||||
} header: {
|
||||
HStack {
|
||||
Text("The modem's settings")
|
||||
Spacer()
|
||||
Button { modem.loadSettings() } label: { Image(systemName: "arrow.clockwise") }
|
||||
.buttonStyle(.borderless)
|
||||
.help("Read the settings again")
|
||||
Button("Defaults") { modem.resetSettings() }
|
||||
.buttonStyle(.borderless)
|
||||
.help("Every setting back to its default (ATZ)")
|
||||
}
|
||||
} footer: {
|
||||
Text("Changes take effect at once. The modem keeps no stored profile, so keep the init string to have them each time.")
|
||||
}
|
||||
.disabled(!modem.isIdle)
|
||||
|
||||
if !modem.settingsNote.isEmpty {
|
||||
Text(modem.settingsNote).foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(modem.groups, id: \.self) { g in
|
||||
Section(g) {
|
||||
ForEach(modem.settings.filter { $0.group == g }) { s in
|
||||
SettingRow(s: s)
|
||||
}
|
||||
}
|
||||
.disabled(!modem.isIdle)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
}
|
||||
|
||||
struct SettingRow: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
let s: Setting
|
||||
@State private var text = ""
|
||||
|
||||
private var title: some View {
|
||||
Text(s.label).fontWeight(s.changed ? .semibold : .regular)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
switch s.kind {
|
||||
case Int(DMC_PICK):
|
||||
Picker(selection: Binding(get: { s.value }, set: { modem.apply(s.index, $0) })) {
|
||||
ForEach(s.choices, id: \.value) { Text($0.label).tag($0.value) }
|
||||
if !s.choices.contains(where: { $0.value == s.value }) {
|
||||
Text(s.value).tag(s.value)
|
||||
}
|
||||
} label: { title }
|
||||
case Int(DMC_NUMBER):
|
||||
LabeledContent {
|
||||
HStack {
|
||||
TextField("", text: $text)
|
||||
.frame(width: 80)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.onSubmit { modem.apply(s.index, text) }
|
||||
Stepper("", value: Binding(
|
||||
get: { Int(s.value) ?? s.lo },
|
||||
set: { modem.apply(s.index, String($0)) }),
|
||||
in: s.lo...max(s.lo, s.hi))
|
||||
.labelsHidden()
|
||||
}
|
||||
} label: { title }
|
||||
default:
|
||||
LabeledContent {
|
||||
TextField("", text: $text)
|
||||
.onSubmit { modem.apply(s.index, text) }
|
||||
} label: { title }
|
||||
}
|
||||
}
|
||||
.help(s.help)
|
||||
.onAppear { text = s.value }
|
||||
.onChange(of: s.value) { text = $0 }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Call Stats
|
||||
|
||||
struct StatsPage: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack {
|
||||
Text("The last call, as the modem reports it (AT#UD), after each call.")
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button { modem.refreshStats() } label: { Image(systemName: "arrow.clockwise") }
|
||||
.disabled(!modem.isIdle)
|
||||
.help("Ask the modem again")
|
||||
}
|
||||
.padding(12)
|
||||
if !modem.diagNote.isEmpty {
|
||||
Text(modem.diagNote).foregroundStyle(.secondary).padding(.horizontal, 12)
|
||||
}
|
||||
Table(modem.diag) {
|
||||
TableColumn("Statistic", value: \.label)
|
||||
TableColumn("Value") { r in Text(r.value).textSelection(.enabled) }
|
||||
}
|
||||
.frame(minHeight: 180)
|
||||
Text("The modem's report (ATI11)").font(.headline).padding(12)
|
||||
ScrollView {
|
||||
Text(modem.report.isEmpty ? " " : modem.report)
|
||||
.font(.body.monospaced())
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(12)
|
||||
}
|
||||
.frame(minHeight: 120)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Log
|
||||
|
||||
struct LogPage: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 1) {
|
||||
ForEach(Array(modem.log.enumerated()), id: \.offset) { i, line in
|
||||
Text(line).font(.callout.monospaced()).id(i)
|
||||
}
|
||||
}
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(12)
|
||||
}
|
||||
.onChange(of: modem.log.count) { n in
|
||||
if n > 0 { proxy.scrollTo(n - 1, anchor: .bottom) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// DModemApp.swift - the app: its window, menus and the line settings
|
||||
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct DModemApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
@StateObject private var modem = Modem()
|
||||
|
||||
var body: some Scene {
|
||||
Window("D-Modem", id: "main") {
|
||||
ContentView()
|
||||
.environmentObject(modem)
|
||||
.frame(minWidth: 760, minHeight: 520)
|
||||
.onAppear { delegate.modem = modem }
|
||||
}
|
||||
.commands {
|
||||
CommandMenu("Modem") {
|
||||
Button(modem.running ? "Stop" : "Start") {
|
||||
modem.running ? modem.stop() : modem.start()
|
||||
}
|
||||
.keyboardShortcut("r")
|
||||
Divider()
|
||||
Button("Answer") { modem.answer() }
|
||||
.disabled(modem.state != Int(DMC_RINGING))
|
||||
Button("Hang Up") { modem.hangUp() }
|
||||
.keyboardShortcut(".")
|
||||
.disabled(!modem.canHangUp)
|
||||
}
|
||||
}
|
||||
Settings {
|
||||
LineSettingsView()
|
||||
.environmentObject(modem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
weak var modem: Modem?
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
modem?.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// LineConfig.swift - the line settings: where dmodemd's calls go, kept in
|
||||
// the user defaults (the SIP password in the keychain)
|
||||
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
enum LineKind: String, CaseIterable, Identifiable {
|
||||
case sip, usb, device
|
||||
var id: String { rawValue }
|
||||
var label: String {
|
||||
switch self {
|
||||
case .sip: return "SIP account"
|
||||
case .usb: return "USB modem"
|
||||
case .device: return "A modem that already runs"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LineConfig {
|
||||
var line: LineKind = .sip
|
||||
var sipUser = ""
|
||||
var sipPassword = ""
|
||||
var sipServer = ""
|
||||
var listen = false
|
||||
var t38 = true
|
||||
var v152 = true
|
||||
var v150 = false
|
||||
var srtp = "" // "", "no" or "require"
|
||||
var country = ""
|
||||
var usb = "auto"
|
||||
var device = "/dev/ttyDM0"
|
||||
var dmodemd = "" // its path, "" to look for it
|
||||
var initString = "" // commands sent when the modem opens
|
||||
var debug = 0
|
||||
|
||||
private static let defaults = UserDefaults.standard
|
||||
|
||||
static func load() -> LineConfig {
|
||||
var c = LineConfig()
|
||||
let d = defaults
|
||||
c.line = LineKind(rawValue: d.string(forKey: "line") ?? "") ?? .sip
|
||||
c.sipUser = d.string(forKey: "sipUser") ?? ""
|
||||
c.sipServer = d.string(forKey: "sipServer") ?? ""
|
||||
c.listen = d.bool(forKey: "listen")
|
||||
c.t38 = d.object(forKey: "t38") as? Bool ?? true
|
||||
c.v152 = d.object(forKey: "v152") as? Bool ?? true
|
||||
c.v150 = d.bool(forKey: "v150")
|
||||
c.srtp = d.string(forKey: "srtp") ?? ""
|
||||
c.country = d.string(forKey: "country") ?? ""
|
||||
c.usb = d.string(forKey: "usb") ?? "auto"
|
||||
c.device = d.string(forKey: "device") ?? "/dev/ttyDM0"
|
||||
c.dmodemd = d.string(forKey: "dmodemd") ?? ""
|
||||
c.initString = d.string(forKey: "init") ?? ""
|
||||
c.debug = d.integer(forKey: "debug")
|
||||
c.sipPassword = Keychain.password(for: c.sipUser, server: c.sipServer) ?? ""
|
||||
return c
|
||||
}
|
||||
|
||||
func save() {
|
||||
let d = LineConfig.defaults
|
||||
d.set(line.rawValue, forKey: "line")
|
||||
d.set(sipUser, forKey: "sipUser")
|
||||
d.set(sipServer, forKey: "sipServer")
|
||||
d.set(listen, forKey: "listen")
|
||||
d.set(t38, forKey: "t38")
|
||||
d.set(v152, forKey: "v152")
|
||||
d.set(v150, forKey: "v150")
|
||||
d.set(srtp, forKey: "srtp")
|
||||
d.set(country, forKey: "country")
|
||||
d.set(usb, forKey: "usb")
|
||||
d.set(device, forKey: "device")
|
||||
d.set(dmodemd, forKey: "dmodemd")
|
||||
d.set(initString, forKey: "init")
|
||||
d.set(debug, forKey: "debug")
|
||||
Keychain.setPassword(sipPassword, for: sipUser, server: sipServer)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
switch line {
|
||||
case .usb: return "USB modem (\(usb))"
|
||||
case .device: return "The modem at \(device)"
|
||||
case .sip:
|
||||
if sipUser.isEmpty || sipServer.isEmpty { return "SIP account not set up" }
|
||||
return "SIP: \(sipUser)@\(sipServer)" + (listen ? ", taking calls" : "")
|
||||
}
|
||||
}
|
||||
|
||||
var isSetUp: Bool {
|
||||
line != .sip || (!sipUser.isEmpty && !sipServer.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// The SIP password, as an internet password in the login keychain.
|
||||
enum Keychain {
|
||||
private static func query(_ user: String, _ server: String) -> [String: Any] {
|
||||
[kSecClass as String: kSecClassInternetPassword,
|
||||
kSecAttrServer as String: server,
|
||||
kSecAttrAccount as String: user]
|
||||
}
|
||||
|
||||
static func password(for user: String, server: String) -> String? {
|
||||
guard !user.isEmpty, !server.isEmpty else { return nil }
|
||||
var q = query(user, server)
|
||||
q[kSecReturnData as String] = true
|
||||
q[kSecMatchLimit as String] = kSecMatchLimitOne
|
||||
var out: CFTypeRef?
|
||||
guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess,
|
||||
let data = out as? Data else { return nil }
|
||||
return String(data: data, encoding: .utf8)
|
||||
}
|
||||
|
||||
static func setPassword(_ password: String, for user: String, server: String) {
|
||||
guard !user.isEmpty, !server.isEmpty else { return }
|
||||
let q = query(user, server)
|
||||
SecItemDelete(q as CFDictionary)
|
||||
guard !password.isEmpty else { return }
|
||||
var add = q
|
||||
add[kSecValueData as String] = Data(password.utf8)
|
||||
add[kSecAttrLabel as String] = "D-Modem SIP account"
|
||||
SecItemAdd(add as CFDictionary, nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// LineSettingsView.swift - the line settings (D-Modem > Settings):
|
||||
// where the modem's calls go
|
||||
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct LineSettingsView: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
@State private var c = LineConfig()
|
||||
@State private var loaded = false
|
||||
@State private var choosing = false
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Picker("Line", selection: $c.line) {
|
||||
ForEach(LineKind.allCases) { Text($0.label).tag($0) }
|
||||
}
|
||||
.pickerStyle(.radioGroup)
|
||||
|
||||
switch c.line {
|
||||
case .sip:
|
||||
Section("SIP account") {
|
||||
TextField("User", text: $c.sipUser)
|
||||
SecureField("Password", text: $c.sipPassword)
|
||||
TextField("Server", text: $c.sipServer, prompt: Text("sip.example.net"))
|
||||
Toggle("Take incoming calls", isOn: $c.listen)
|
||||
}
|
||||
Section("Calls") {
|
||||
Toggle("Fax over T.38", isOn: $c.t38)
|
||||
Toggle("Modem over V.152", isOn: $c.v152)
|
||||
Toggle("Modem relay (V.150.1)", isOn: $c.v150)
|
||||
Picker("Encryption (SRTP)", selection: $c.srtp) {
|
||||
Text("When offered").tag("")
|
||||
Text("Never").tag("no")
|
||||
Text("Required").tag("require")
|
||||
}
|
||||
}
|
||||
case .usb:
|
||||
Section("USB modem") {
|
||||
TextField("Modem", text: $c.usb, prompt: Text("auto"))
|
||||
Text("“auto” takes the first USB voice modem found.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
case .device:
|
||||
Section("The modem's device") {
|
||||
TextField("Device", text: $c.device, prompt: Text("/dev/ttyDM0"))
|
||||
Text("A D-Modem that already runs, as a service or by hand.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
Section("The modem") {
|
||||
TextField("Country", text: $c.country, prompt: Text("as the modem's default"))
|
||||
TextField("Init string", text: $c.initString, prompt: Text("sent each time it opens"))
|
||||
.font(.body.monospaced())
|
||||
if c.line != .device {
|
||||
HStack {
|
||||
TextField("dmodemd", text: $c.dmodemd, prompt: Text("looked for"))
|
||||
Button("Choose…") { choosing = true }
|
||||
}
|
||||
Stepper("Debug level: \(c.debug)", value: $c.debug, in: 0...5)
|
||||
}
|
||||
}
|
||||
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Save") {
|
||||
modem.saveConfig(c)
|
||||
if modem.running { modem.say("The new settings apply when the modem starts again") }
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.frame(width: 480)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.onAppear {
|
||||
if !loaded {
|
||||
c = modem.config
|
||||
loaded = true
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $choosing, allowedContentTypes: [.unixExecutable, .item]) { r in
|
||||
if case .success(let url) = r { c.dmodemd = url.path }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// Modem.swift - dmodemd started and stopped, its pty opened, and the
|
||||
// bytes between the pty, libdmodemctl's session and the terminal screen
|
||||
//
|
||||
// dmodemd runs as the user: it makes its pty and says where it is ("Use
|
||||
// `/dev/ttys003' as modem device"), and the app opens that. With the
|
||||
// "device" line nothing is started and the given device is opened.
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
|
||||
/// A C string from the library, "" for none.
|
||||
func cstr(_ p: UnsafePointer<CChar>?) -> String {
|
||||
p.map { String(cString: $0) } ?? ""
|
||||
}
|
||||
|
||||
/// What a command of the app's got back.
|
||||
struct Response {
|
||||
var ok: Bool
|
||||
var text: String // its lines, apart by "\n"
|
||||
var result: String // OK, ERROR, CONNECT..., timeout
|
||||
}
|
||||
|
||||
/// A choice of a setting's
|
||||
struct Choice: Hashable {
|
||||
var value: String
|
||||
var label: String
|
||||
}
|
||||
|
||||
/// One of the modem's settings (AT!M), as the Settings page shows it.
|
||||
struct Setting: Identifiable {
|
||||
var index: Int
|
||||
var key: String
|
||||
var kind: Int
|
||||
var value: String
|
||||
var defaultValue: String
|
||||
var lo: Int
|
||||
var hi: Int
|
||||
var group: String
|
||||
var label: String
|
||||
var help: String
|
||||
var choices: [Choice]
|
||||
var id: String { key }
|
||||
var changed: Bool { value != defaultValue }
|
||||
}
|
||||
|
||||
/// A row of the last call's statistics (AT#UD).
|
||||
struct DiagRow: Identifiable {
|
||||
var id: Int
|
||||
var label: String
|
||||
var value: String
|
||||
}
|
||||
|
||||
final class Modem: ObservableObject {
|
||||
@Published var config = LineConfig.load()
|
||||
@Published private(set) var state = Int(DMC_CLOSED)
|
||||
@Published private(set) var running = false
|
||||
@Published private(set) var device = ""
|
||||
@Published private(set) var log: [String] = []
|
||||
@Published var toast: String?
|
||||
|
||||
@Published private(set) var settings: [Setting] = []
|
||||
@Published private(set) var groups: [String] = []
|
||||
@Published private(set) var settingsNote = "Start the modem to see its settings."
|
||||
@Published private(set) var initString = ""
|
||||
|
||||
@Published private(set) var diag: [DiagRow] = []
|
||||
@Published private(set) var diagNote = "Start the modem to see the last call's statistics."
|
||||
@Published private(set) var report = ""
|
||||
|
||||
/// bumped when the terminal screen changed, to draw it again
|
||||
@Published private(set) var screenVersion = 0
|
||||
|
||||
let session: OpaquePointer
|
||||
let vt: OpaquePointer
|
||||
|
||||
private var process: Process?
|
||||
private var fd: Int32 = -1
|
||||
private var source: DispatchSourceRead?
|
||||
private var pending: [UInt8] = []
|
||||
private var waiting: [Int32: (Response) -> Void] = [:]
|
||||
private var timer: Timer?
|
||||
private var model: OpaquePointer?
|
||||
private var modelGen = 0
|
||||
private var lastState = Int(DMC_CLOSED)
|
||||
|
||||
init() {
|
||||
session = dmc_session_new()
|
||||
vt = dmc_vt_new(80, 24, 2000)
|
||||
let t = Timer(timeInterval: 0.05, repeats: true) { [weak self] _ in
|
||||
self?.pump()
|
||||
}
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
timer = t
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
dmc_model_free(model)
|
||||
dmc_vt_free(vt)
|
||||
dmc_session_free(session)
|
||||
}
|
||||
|
||||
// MARK: - what the pages use
|
||||
|
||||
var stateName: String {
|
||||
running && state == Int(DMC_CLOSED) ? "Starting" : cstr(dmc_state_name(Int32(state)))
|
||||
}
|
||||
|
||||
var detail: String {
|
||||
switch state {
|
||||
case Int(DMC_ONLINE), Int(DMC_ONLINE_COMMAND), Int(DMC_HANGING_UP):
|
||||
return cstr(dmc_connect_text(session))
|
||||
case Int(DMC_RINGING):
|
||||
let n = cstr(dmc_caller_number(session))
|
||||
if !n.isEmpty { return n + " " + cstr(dmc_caller_name(session)) }
|
||||
return config.summary
|
||||
default:
|
||||
return config.summary
|
||||
}
|
||||
}
|
||||
|
||||
var isOpen: Bool { state != Int(DMC_CLOSED) }
|
||||
var isIdle: Bool { state == Int(DMC_IDLE) }
|
||||
var canHangUp: Bool {
|
||||
[DMC_DIALING, DMC_ANSWERING, DMC_ONLINE, DMC_ONLINE_COMMAND, DMC_RINGING]
|
||||
.map { Int($0) }.contains(state)
|
||||
}
|
||||
|
||||
func say(_ text: String) {
|
||||
toast = text
|
||||
}
|
||||
|
||||
func addLog(_ line: String) {
|
||||
log.append(line)
|
||||
if log.count > 5000 { log.removeFirst(log.count - 5000) }
|
||||
}
|
||||
|
||||
// MARK: - commands
|
||||
|
||||
@discardableResult
|
||||
func command(_ cmd: String, quiet: Bool = false,
|
||||
_ done: ((Response) -> Void)? = nil) -> Int32 {
|
||||
let tag = dmc_command(session, cmd, quiet ? Int32(DMC_QUIET) : 0, 0)
|
||||
if tag > 0 {
|
||||
waiting[tag] = done ?? { _ in }
|
||||
pump()
|
||||
}
|
||||
return tag
|
||||
}
|
||||
|
||||
func dial(_ number: String) {
|
||||
let n = number.trimmingCharacters(in: .whitespaces)
|
||||
guard !n.isEmpty else { return say("Enter a number to dial") }
|
||||
command("ATD" + n) { [weak self] r in
|
||||
if !r.ok { self?.say(r.result) }
|
||||
}
|
||||
}
|
||||
|
||||
func answer() {
|
||||
if dmc_answer(session) > 0 { pump() }
|
||||
}
|
||||
|
||||
func hangUp() {
|
||||
dmc_hangup(session)
|
||||
pump()
|
||||
}
|
||||
|
||||
/// bytes typed in the terminal
|
||||
func type(_ bytes: [UInt8]) {
|
||||
guard fd >= 0, !bytes.isEmpty else { return }
|
||||
bytes.withUnsafeBufferPointer { b in
|
||||
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
|
||||
dmc_type(session, $0, Int32(b.count))
|
||||
}
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
func type(_ text: String) { type(Array(text.utf8)) }
|
||||
|
||||
func key(_ k: Int) {
|
||||
var buf = [CChar](repeating: 0, count: 16)
|
||||
let n = dmc_vt_key(vt, Int32(k), &buf, Int32(buf.count))
|
||||
if n > 0 { type(buf[0..<Int(n)].map { UInt8(bitPattern: $0) }) }
|
||||
}
|
||||
|
||||
func clearScreen() {
|
||||
dmc_vt_reset(vt)
|
||||
screenVersion += 1
|
||||
}
|
||||
|
||||
// MARK: - the bytes
|
||||
|
||||
private static func now() -> Int64 {
|
||||
Int64(DispatchTime.now().uptimeNanoseconds / 1_000_000)
|
||||
}
|
||||
|
||||
func pump() {
|
||||
dmc_poll(session, Modem.now())
|
||||
var buf = [CChar](repeating: 0, count: 4096)
|
||||
var n: Int32
|
||||
while true {
|
||||
n = dmc_output(session, &buf, Int32(buf.count))
|
||||
if n <= 0 { break }
|
||||
pending.append(contentsOf: buf[0..<Int(n)].map { UInt8(bitPattern: $0) })
|
||||
}
|
||||
flush()
|
||||
var fed = false
|
||||
while true {
|
||||
n = dmc_terminal(session, &buf, Int32(buf.count))
|
||||
if n <= 0 { break }
|
||||
dmc_vt_feed(vt, buf, n)
|
||||
fed = true
|
||||
}
|
||||
if fed {
|
||||
// the screen's answers (where the cursor is), as if typed
|
||||
var reply = [CChar](repeating: 0, count: 256)
|
||||
while true {
|
||||
let k = dmc_vt_reply(vt, &reply, Int32(reply.count))
|
||||
if k <= 0 { break }
|
||||
dmc_type(session, reply, k)
|
||||
}
|
||||
}
|
||||
if dmc_vt_changed(vt) != 0 { screenVersion += 1 }
|
||||
var ev = dmc_event()
|
||||
while dmc_next_event(session, &ev) != 0 {
|
||||
let type = Int(ev.type)
|
||||
if type == Int(DMC_EV_RESPONSE) {
|
||||
let r = Response(ok: ev.ok != 0, text: cstr(ev.text),
|
||||
result: cstr(ev.result))
|
||||
if let fn = waiting.removeValue(forKey: ev.tag) { fn(r) }
|
||||
} else {
|
||||
event(type, state: Int(ev.state), result: cstr(ev.result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func flush() {
|
||||
while fd >= 0 && !pending.isEmpty {
|
||||
let n = pending.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
|
||||
if n > 0 {
|
||||
pending.removeFirst(n)
|
||||
continue
|
||||
}
|
||||
if n < 0 && errno == EINTR { continue }
|
||||
break // EAGAIN: the next tick
|
||||
}
|
||||
}
|
||||
|
||||
private func event(_ type: Int, state st: Int, result: String) {
|
||||
switch type {
|
||||
case Int(DMC_EV_STATE):
|
||||
let was = lastState
|
||||
lastState = st
|
||||
state = st
|
||||
let calls = [DMC_ONLINE, DMC_ONLINE_COMMAND, DMC_HANGING_UP,
|
||||
DMC_DIALING, DMC_ANSWERING].map { Int($0) }
|
||||
// a call over: its statistics
|
||||
if st == Int(DMC_IDLE) && calls.contains(was) { refreshStats() }
|
||||
// a configurator over: the settings it changed
|
||||
if st == Int(DMC_IDLE) && was == Int(DMC_CONFIGURATOR) { loadSettings() }
|
||||
case Int(DMC_EV_RESULT):
|
||||
if result == "RING" {
|
||||
ring()
|
||||
} else if !result.isEmpty {
|
||||
say(result)
|
||||
}
|
||||
case Int(DMC_EV_CALLER):
|
||||
objectWillChange.send()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func ring() {
|
||||
guard !NSApp.isActive else { return }
|
||||
NSApp.requestUserAttention(.informationalRequest)
|
||||
let c = UNMutableNotificationContent()
|
||||
c.title = "Incoming call"
|
||||
let who = cstr(dmc_caller_number(session))
|
||||
c.body = who.isEmpty ? "The modem is ringing" : who
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.requestAuthorization(options: [.alert, .sound]) { ok, _ in
|
||||
guard ok else { return }
|
||||
center.add(UNNotificationRequest(identifier: "ring", content: c, trigger: nil))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - the device
|
||||
|
||||
private func openDevice(_ path: String) -> Bool {
|
||||
let f = Darwin.open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC)
|
||||
if f < 0 {
|
||||
let m = "Can't open \(path): \(String(cString: strerror(errno)))"
|
||||
addLog(m)
|
||||
say(m)
|
||||
return false
|
||||
}
|
||||
var t = termios()
|
||||
if tcgetattr(f, &t) == 0 {
|
||||
cfmakeraw(&t)
|
||||
cfsetspeed(&t, speed_t(B115200))
|
||||
t.c_cflag |= tcflag_t(CLOCAL | CREAD)
|
||||
tcsetattr(f, TCSANOW, &t)
|
||||
}
|
||||
fd = f
|
||||
device = path
|
||||
let s = DispatchSource.makeReadSource(fileDescriptor: f, queue: .main)
|
||||
s.setEventHandler { [weak self] in self?.readable() }
|
||||
s.resume()
|
||||
source = s
|
||||
dmc_open(session, Modem.now())
|
||||
state = Int(dmc_state(session))
|
||||
lastState = state
|
||||
// the user's own commands first
|
||||
if !config.initString.isEmpty { command(config.initString) }
|
||||
loadSettings()
|
||||
refreshStats()
|
||||
pump()
|
||||
return true
|
||||
}
|
||||
|
||||
private func readable() {
|
||||
var buf = [CChar](repeating: 0, count: 4096)
|
||||
while fd >= 0 {
|
||||
let n = Darwin.read(fd, &buf, buf.count)
|
||||
if n > 0 {
|
||||
dmc_feed(session, buf, Int32(n))
|
||||
continue
|
||||
}
|
||||
if n < 0 && errno == EINTR { continue }
|
||||
if n < 0 && errno == EAGAIN { break }
|
||||
// EOF, or EIO when dmodemd closed its end
|
||||
addLog("The modem's device closed.")
|
||||
closeDevice()
|
||||
return
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
private func closeDevice() {
|
||||
source?.cancel()
|
||||
source = nil
|
||||
if fd >= 0 {
|
||||
Darwin.close(fd)
|
||||
fd = -1
|
||||
}
|
||||
device = ""
|
||||
pending.removeAll()
|
||||
waiting.removeAll()
|
||||
if dmc_state(session) != Int32(DMC_CLOSED) {
|
||||
dmc_close(session)
|
||||
pump()
|
||||
}
|
||||
state = Int(DMC_CLOSED)
|
||||
lastState = state
|
||||
clearSettings()
|
||||
running = process != nil
|
||||
}
|
||||
|
||||
// MARK: - dmodemd
|
||||
|
||||
private func findDmodemd() -> String? {
|
||||
if !config.dmodemd.isEmpty { return config.dmodemd }
|
||||
var places = ["/opt/homebrew/sbin/dmodemd", "/opt/homebrew/bin/dmodemd",
|
||||
"/usr/local/sbin/dmodemd", "/usr/local/bin/dmodemd"]
|
||||
if let inApp = Bundle.main.url(forAuxiliaryExecutable: "dmodemd") {
|
||||
places.insert(inApp.path, at: 0)
|
||||
}
|
||||
for dir in (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":") {
|
||||
places.append(dir + "/dmodemd")
|
||||
}
|
||||
return places.first { FileManager.default.isExecutableFile(atPath: $0) }
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard !running else { return }
|
||||
let c = config
|
||||
if c.line == .device {
|
||||
running = openDevice(c.device)
|
||||
return
|
||||
}
|
||||
guard let exe = findDmodemd() else {
|
||||
return say("dmodemd was not found: install D-Modem, or set its path in the line settings")
|
||||
}
|
||||
if !c.isSetUp {
|
||||
say("Set up the SIP account first")
|
||||
if !NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) {
|
||||
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
var args: [String] = []
|
||||
if !c.country.isEmpty { args += ["-c", c.country] }
|
||||
// (the pty in the user's own group: the default would need root)
|
||||
if let g = getgrgid(getgid()) { args += ["-g", String(cString: g.pointee.gr_name)] }
|
||||
if c.debug > 0 { args.append("-d\(c.debug)") }
|
||||
if c.line == .usb {
|
||||
args.append("--usb=\(c.usb)")
|
||||
} else if c.listen {
|
||||
args.append("-L")
|
||||
}
|
||||
var env = ProcessInfo.processInfo.environment
|
||||
if c.line == .sip {
|
||||
env["SIP_LOGIN"] = "\(c.sipUser):\(c.sipPassword)@\(c.sipServer)"
|
||||
}
|
||||
if !c.t38 { env["SIP_T38"] = "no" }
|
||||
if !c.v152 { env["SIP_V152"] = "no" }
|
||||
if c.v150 { env["SIP_V150"] = "yes" }
|
||||
if !c.srtp.isEmpty { env["SIP_SRTP"] = c.srtp }
|
||||
|
||||
let p = Process()
|
||||
p.executableURL = URL(fileURLWithPath: exe)
|
||||
p.arguments = args
|
||||
p.environment = env
|
||||
// its log files where the user may write them
|
||||
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("D-Modem")
|
||||
try? FileManager.default.createDirectory(at: caches, withIntermediateDirectories: true)
|
||||
p.currentDirectoryURL = caches
|
||||
let out = Pipe()
|
||||
p.standardOutput = out
|
||||
p.standardError = out
|
||||
p.standardInput = FileHandle.nullDevice
|
||||
var partial = Data()
|
||||
out.fileHandleForReading.readabilityHandler = { [weak self] h in
|
||||
let d = h.availableData
|
||||
if d.isEmpty {
|
||||
h.readabilityHandler = nil
|
||||
return
|
||||
}
|
||||
partial.append(d)
|
||||
var lines: [String] = []
|
||||
while let nl = partial.firstIndex(of: 0x0A) {
|
||||
lines.append(String(decoding: partial[partial.startIndex..<nl], as: UTF8.self))
|
||||
partial.removeSubrange(partial.startIndex...nl)
|
||||
}
|
||||
if lines.isEmpty { return }
|
||||
DispatchQueue.main.async { lines.forEach { self?.daemonLine($0) } }
|
||||
}
|
||||
p.terminationHandler = { [weak self] q in
|
||||
DispatchQueue.main.async { self?.exited(q) }
|
||||
}
|
||||
do {
|
||||
try p.run()
|
||||
} catch {
|
||||
let m = "Can't start dmodemd: \(error.localizedDescription)"
|
||||
addLog(m)
|
||||
return say(m)
|
||||
}
|
||||
process = p
|
||||
running = true
|
||||
addLog("$ " + ([exe] + args).joined(separator: " "))
|
||||
}
|
||||
|
||||
private func daemonLine(_ raw: String) {
|
||||
let line = raw.trimmingCharacters(in: CharacterSet(charactersIn: "\r"))
|
||||
addLog(line)
|
||||
var dev = [CChar](repeating: 0, count: 512)
|
||||
if dmc_daemon_ready(line, &dev, Int32(dev.count)) != 0 && fd < 0 {
|
||||
_ = openDevice(String(cString: dev))
|
||||
} else if dmc_daemon_error(line) != 0 && fd < 0 &&
|
||||
!line.contains("group") && !line.contains("symbolic link") {
|
||||
say(String(line.dropFirst(7)))
|
||||
}
|
||||
}
|
||||
|
||||
private func exited(_ p: Process) {
|
||||
let m = p.terminationReason == .uncaughtSignal
|
||||
? "dmodemd stopped (signal \(p.terminationStatus))."
|
||||
: "dmodemd stopped (exit status \(p.terminationStatus))."
|
||||
addLog(m)
|
||||
guard p === process else { return }
|
||||
process = nil
|
||||
closeDevice()
|
||||
running = false
|
||||
if !(p.terminationReason == .uncaughtSignal && p.terminationStatus == SIGTERM) {
|
||||
say(m)
|
||||
}
|
||||
}
|
||||
|
||||
func stop() {
|
||||
if fd >= 0 && process != nil {
|
||||
// hang up first, so the call ends cleanly
|
||||
dmc_hangup(session)
|
||||
pump()
|
||||
}
|
||||
closeDevice()
|
||||
process?.terminate()
|
||||
running = process != nil
|
||||
}
|
||||
|
||||
func saveConfig(_ c: LineConfig) {
|
||||
config = c
|
||||
c.save()
|
||||
}
|
||||
|
||||
// MARK: - the settings (AT!M)
|
||||
|
||||
private func clearSettings() {
|
||||
modelGen += 1
|
||||
dmc_model_free(model)
|
||||
model = nil
|
||||
settings = []
|
||||
groups = []
|
||||
initString = ""
|
||||
settingsNote = "Start the modem to see its settings."
|
||||
}
|
||||
|
||||
private func snapshot(_ i: Int) -> Setting {
|
||||
let m = model, n = Int32(i)
|
||||
var choices: [Choice] = []
|
||||
for c in 0..<dmc_setting_choices(m, n) {
|
||||
choices.append(Choice(value: cstr(dmc_choice_value(m, n, c)),
|
||||
label: cstr(dmc_choice_label(m, n, c))))
|
||||
}
|
||||
return Setting(index: i, key: cstr(dmc_setting_key(m, n)),
|
||||
kind: Int(dmc_setting_kind(m, n)),
|
||||
value: cstr(dmc_setting_value(m, n)),
|
||||
defaultValue: cstr(dmc_setting_default(m, n)),
|
||||
lo: Int(dmc_setting_lo(m, n)), hi: Int(dmc_setting_hi(m, n)),
|
||||
group: cstr(dmc_setting_group(m, n)),
|
||||
label: cstr(dmc_setting_label(m, n)),
|
||||
help: cstr(dmc_setting_help(m, n)), choices: choices)
|
||||
}
|
||||
|
||||
func loadSettings() {
|
||||
guard isOpen else { return }
|
||||
command("AT!M", quiet: true) { [weak self] r in
|
||||
guard let self else { return }
|
||||
guard r.ok else {
|
||||
self.settingsNote = "This modem does not list its settings (AT!M): update D-Modem, or use the Terminal's setup screen."
|
||||
return
|
||||
}
|
||||
guard let m = dmc_model_parse(r.text) else {
|
||||
self.settingsNote = "The modem's settings list was not readable."
|
||||
return
|
||||
}
|
||||
self.clearSettings()
|
||||
self.model = m
|
||||
self.groups = (0..<dmc_model_groups(m)).map { cstr(dmc_model_group(m, $0)) }
|
||||
self.settings = (0..<Int(dmc_model_count(m))).map { self.snapshot($0) }
|
||||
self.settingsNote = ""
|
||||
self.command("AT!R", quiet: true) { [weak self] r in
|
||||
if r.ok { self?.initString = Modem.initLine(r.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AT!R's lines, as one line of commands
|
||||
static func initLine(_ text: String) -> String {
|
||||
var s = ""
|
||||
for raw in text.split(separator: "\n") {
|
||||
let l = raw.trimmingCharacters(in: .whitespaces)
|
||||
if l.isEmpty || l.uppercased() == "AT" { continue }
|
||||
s += s.isEmpty ? l : String(l.dropFirst(2))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
/// setting i set to value: checked, sent, and kept after the OK
|
||||
func apply(_ i: Int, _ value: String) {
|
||||
guard let m = model, i < settings.count, settings[i].value != value else { return }
|
||||
let why = cstr(dmc_setting_check(m, Int32(i), value))
|
||||
if !why.isEmpty {
|
||||
objectWillChange.send() // the control back as it was
|
||||
return say(why)
|
||||
}
|
||||
let gen = modelGen
|
||||
let cmd = cstr(dmc_setting_command(m, Int32(i), value))
|
||||
let tag = command(cmd) { [weak self] r in
|
||||
guard let self, gen == self.modelGen, let m = self.model else { return }
|
||||
if r.ok {
|
||||
dmc_setting_set(m, Int32(i), value)
|
||||
self.settings[i] = self.snapshot(i)
|
||||
self.command("AT!R", quiet: true) { [weak self] r in
|
||||
if r.ok { self?.initString = Modem.initLine(r.text) }
|
||||
}
|
||||
} else {
|
||||
self.objectWillChange.send()
|
||||
self.say("The modem refused \(cmd)")
|
||||
}
|
||||
}
|
||||
if tag < 0 {
|
||||
objectWillChange.send()
|
||||
say("The modem is busy")
|
||||
}
|
||||
}
|
||||
|
||||
func resetSettings() {
|
||||
command("ATZ") { [weak self] r in
|
||||
if !r.ok { self?.say("The modem refused ATZ") }
|
||||
self?.loadSettings()
|
||||
}
|
||||
}
|
||||
|
||||
func keepInit() {
|
||||
var c = config
|
||||
c.initString = initString
|
||||
saveConfig(c)
|
||||
say(initString.isEmpty ? "Nothing to send: every setting is at its default"
|
||||
: "Sent each time the modem opens")
|
||||
}
|
||||
|
||||
// MARK: - the call's statistics
|
||||
|
||||
func refreshStats() {
|
||||
guard isOpen else { return }
|
||||
command("AT#UD", quiet: true) { [weak self] r in
|
||||
guard let self else { return }
|
||||
let d = dmc_diag_parse(r.ok ? r.text : "")
|
||||
defer { dmc_diag_free(d) }
|
||||
self.diag = (0..<dmc_diag_count(d)).map {
|
||||
DiagRow(id: Int(dmc_diag_key(d, $0)), label: cstr(dmc_diag_label(d, $0)),
|
||||
value: cstr(dmc_diag_value(d, $0)))
|
||||
}
|
||||
self.diagNote = !r.ok ? "This modem does not report statistics (AT#UD)."
|
||||
: dmc_diag_has_call(d) == 0 ? "No call yet." : ""
|
||||
}
|
||||
command("ATI11", quiet: true) { [weak self] r in
|
||||
self?.report = r.ok ? r.text : ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
// Copyright (c) 2026, D-Modem
|
||||
//
|
||||
// TerminalView.swift - the modem's console and its full-screen setup:
|
||||
// libdmodemctl's terminal screen (dmc_vt), drawn cell by cell
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
struct TerminalPane: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Button("Full-screen setup") { modem.type("AT!CF\r") }
|
||||
.help("The configurator in screens and menus (AT!CF)")
|
||||
Button("Command-line setup") { modem.type("AT!CT\r") }
|
||||
.help("The configurator as commands, Cisco style (AT!CT)")
|
||||
Spacer()
|
||||
Button("Clear") { modem.clearScreen() }
|
||||
}
|
||||
.disabled(!modem.isIdle)
|
||||
.padding(8)
|
||||
TerminalView(modem: modem, version: modem.screenVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TerminalView: NSViewRepresentable {
|
||||
let modem: Modem
|
||||
let version: Int
|
||||
|
||||
func makeNSView(context: Context) -> TerminalNSView {
|
||||
let v = TerminalNSView()
|
||||
v.modem = modem
|
||||
return v
|
||||
}
|
||||
|
||||
func updateNSView(_ v: TerminalNSView, context: Context) {
|
||||
v.modem = modem
|
||||
v.needsDisplay = true
|
||||
}
|
||||
}
|
||||
|
||||
final class TerminalNSView: NSView {
|
||||
weak var modem: Modem?
|
||||
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)
|
||||
private var scroll = 0 // rows up into the scrollback
|
||||
|
||||
static let background = NSColor(srgbRed: 0x0a / 255, green: 0x0f / 255, blue: 0x1c / 255, alpha: 1)
|
||||
static let foreground = NSColor(srgbRed: 0xe8 / 255, green: 0xf0 / 255, blue: 0xff / 255, alpha: 1)
|
||||
|
||||
override init(frame: NSRect) {
|
||||
super.init(frame: frame)
|
||||
let w = ("M" as NSString).size(withAttributes: [.font: font]).width
|
||||
cell = NSSize(width: ceil(w), height: ceil(font.ascender - font.descender + font.leading))
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) { fatalError("not used") }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
override var acceptsFirstResponder: Bool { true }
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
window?.makeFirstResponder(self)
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
window?.makeFirstResponder(self)
|
||||
}
|
||||
|
||||
override func setFrameSize(_ size: NSSize) {
|
||||
super.setFrameSize(size)
|
||||
guard let vt = modem?.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)) {
|
||||
dmc_vt_resize(vt, Int32(cols), Int32(rows))
|
||||
}
|
||||
}
|
||||
|
||||
private func colour(_ c: Int32, _ fallback: NSColor) -> NSColor {
|
||||
guard c >= 0 && c < 16 else { return fallback }
|
||||
let rgb = dmc_vt_palette(c)
|
||||
return NSColor(srgbRed: CGFloat((rgb >> 16) & 0xff) / 255,
|
||||
green: CGFloat((rgb >> 8) & 0xff) / 255,
|
||||
blue: CGFloat(rgb & 0xff) / 255, alpha: 1)
|
||||
}
|
||||
|
||||
override func draw(_ dirty: NSRect) {
|
||||
Self.background.setFill()
|
||||
bounds.fill()
|
||||
guard let vt = modem?.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
|
||||
for y in 0..<rows {
|
||||
let row = Int32(y - scroll)
|
||||
var x = 0
|
||||
while x < cols {
|
||||
let fg = dmc_vt_fg(vt, row, Int32(x)), bg = dmc_vt_bg(vt, row, Int32(x))
|
||||
let at = Int(dmc_vt_attr(vt, row, Int32(x)))
|
||||
var text = ""
|
||||
var n = 0
|
||||
while x + n < cols &&
|
||||
dmc_vt_fg(vt, row, Int32(x + n)) == fg &&
|
||||
dmc_vt_bg(vt, row, Int32(x + n)) == bg &&
|
||||
Int(dmc_vt_attr(vt, row, Int32(x + n))) == at {
|
||||
let c = dmc_vt_char(vt, row, Int32(x + n))
|
||||
text.unicodeScalars.append(Unicode.Scalar(c) ?? "?")
|
||||
n += 1
|
||||
}
|
||||
// bold as the bright colours, as a PC's text mode
|
||||
let f = fg >= 0 && fg < 8 && at & Int(DMC_BOLD) != 0 ? fg + 8 : fg
|
||||
var fc = colour(f, Self.foreground), bc = colour(bg, Self.background)
|
||||
if at & Int(DMC_REVERSE) != 0 { swap(&fc, &bc) }
|
||||
let r = NSRect(x: ox + CGFloat(x) * cell.width, y: oy + CGFloat(y) * cell.height,
|
||||
width: CGFloat(n) * cell.width, height: cell.height)
|
||||
if bc != Self.background {
|
||||
bc.setFill()
|
||||
r.fill()
|
||||
}
|
||||
var attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: at & Int(DMC_BOLD) != 0 ? bold : font, .foregroundColor: fc]
|
||||
if at & Int(DMC_UNDERLINE) != 0 {
|
||||
attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue
|
||||
}
|
||||
// each character in its cell, whatever the font
|
||||
for (i, ch) in text.enumerated() where ch != " " {
|
||||
(String(ch) as NSString).draw(
|
||||
at: NSPoint(x: r.minX + CGFloat(i) * cell.width, y: r.minY),
|
||||
withAttributes: attrs)
|
||||
}
|
||||
if at & Int(DMC_UNDERLINE) != 0 && text.allSatisfy({ $0 == " " }) {
|
||||
fc.setFill()
|
||||
NSRect(x: r.minX, y: r.maxY - 1, width: r.width, height: 1).fill()
|
||||
}
|
||||
x += n
|
||||
}
|
||||
}
|
||||
if dmc_vt_cursor_visible(vt) != 0 && scroll == 0 {
|
||||
let r = NSRect(x: ox + CGFloat(dmc_vt_cursor_col(vt)) * cell.width,
|
||||
y: oy + CGFloat(dmc_vt_cursor_row(vt)) * cell.height,
|
||||
width: cell.width, height: cell.height)
|
||||
Self.foreground.withAlphaComponent(window?.firstResponder === self ? 0.7 : 0.3).setFill()
|
||||
r.fill(using: .sourceOver)
|
||||
}
|
||||
}
|
||||
|
||||
override func scrollWheel(with event: NSEvent) {
|
||||
guard let vt = modem?.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
|
||||
}
|
||||
|
||||
// MARK: - keys
|
||||
|
||||
override func keyDown(with event: NSEvent) {
|
||||
guard let modem else { return }
|
||||
scroll = 0
|
||||
let mods = event.modifierFlags
|
||||
if mods.contains(.command) {
|
||||
super.keyDown(with: event)
|
||||
return
|
||||
}
|
||||
if let k = special(event) {
|
||||
modem.key(k)
|
||||
return
|
||||
}
|
||||
guard var s = event.characters, !s.isEmpty else { return }
|
||||
// Option as Meta: ESC and the key
|
||||
if mods.contains(.option), let plain = event.charactersIgnoringModifiers {
|
||||
s = "\u{1b}" + plain
|
||||
}
|
||||
modem.type(s)
|
||||
}
|
||||
|
||||
private func special(_ e: NSEvent) -> Int? {
|
||||
switch Int(e.keyCode) {
|
||||
case 36, 76: return Int(DMC_KEY_ENTER)
|
||||
case 51: return Int(DMC_KEY_BACKSPACE)
|
||||
case 53: return Int(DMC_KEY_ESCAPE)
|
||||
case 48: return e.modifierFlags.contains(.shift) ? Int(DMC_KEY_BACKTAB) : Int(DMC_KEY_TAB)
|
||||
default: break
|
||||
}
|
||||
guard let c = e.charactersIgnoringModifiers?.unicodeScalars.first else { return nil }
|
||||
switch Int(c.value) {
|
||||
case NSUpArrowFunctionKey: return Int(DMC_KEY_UP)
|
||||
case NSDownArrowFunctionKey: return Int(DMC_KEY_DOWN)
|
||||
case NSLeftArrowFunctionKey: return Int(DMC_KEY_LEFT)
|
||||
case NSRightArrowFunctionKey: return Int(DMC_KEY_RIGHT)
|
||||
case NSHomeFunctionKey: return Int(DMC_KEY_HOME)
|
||||
case NSEndFunctionKey: return Int(DMC_KEY_END)
|
||||
case NSPageUpFunctionKey: return Int(DMC_KEY_PGUP)
|
||||
case NSPageDownFunctionKey: return Int(DMC_KEY_PGDN)
|
||||
case NSInsertFunctionKey, NSHelpFunctionKey: return Int(DMC_KEY_INSERT)
|
||||
case NSDeleteFunctionKey: return Int(DMC_KEY_DELETE)
|
||||
case NSF1FunctionKey...NSF10FunctionKey:
|
||||
return Int(DMC_KEY_F1) + Int(c.value) - NSF1FunctionKey
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
@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")
|
||||
.replacingOccurrences(of: "\n", with: "\r"))
|
||||
}
|
||||
|
||||
override func menu(for event: NSEvent) -> NSMenu? {
|
||||
let m = NSMenu()
|
||||
m.addItem(withTitle: "Paste", action: #selector(paste(_:)), keyEquivalent: "")
|
||||
return m
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# The macOS app's Xcode project, made by XcodeGen:
|
||||
# brew install xcodegen && cd macos && xcodegen
|
||||
# xcodebuild -project DModem.xcodeproj -scheme DModem build
|
||||
name: DModem
|
||||
options:
|
||||
bundleIdPrefix: io.github.d-modem
|
||||
deploymentTarget:
|
||||
macOS: "13.0"
|
||||
targets:
|
||||
DModem:
|
||||
type: application
|
||||
platform: macOS
|
||||
sources:
|
||||
- path: DModem
|
||||
- path: ../core/src
|
||||
buildPhase: sources
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_NAME: D-Modem
|
||||
PRODUCT_BUNDLE_IDENTIFIER: io.github.d-modem.DModem
|
||||
MARKETING_VERSION: "1.0.0"
|
||||
CURRENT_PROJECT_VERSION: "1"
|
||||
HEADER_SEARCH_PATHS: $(SRCROOT)/../core/include
|
||||
SWIFT_OBJC_BRIDGING_HEADER: DModem/Bridging.h
|
||||
SWIFT_VERSION: "5.0"
|
||||
GCC_C_LANGUAGE_STANDARD: c11
|
||||
GENERATE_INFOPLIST_FILE: YES
|
||||
INFOPLIST_KEY_CFBundleDisplayName: D-Modem
|
||||
INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.utilities
|
||||
INFOPLIST_KEY_NSHumanReadableCopyright: Copyright (c) 2026, D-Modem. BSD 3-Clause.
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
CODE_SIGN_IDENTITY: "-"
|
||||
ENABLE_HARDENED_RUNTIME: YES
|
||||
# dmodemd runs as a child process and the modem's pty is opened:
|
||||
# no sandbox
|
||||
ENABLE_APP_SANDBOX: NO
|
||||
@@ -0,0 +1,20 @@
|
||||
// Renders assets/dmodem.svg (D-Modem/brand's app icon on a tile) to the
|
||||
// PNGs the apps' icons are made from, with Playwright's Chromium:
|
||||
// node tools/icons.js && python3 tools/icons.py
|
||||
const { chromium } = require('playwright');
|
||||
const fs = require('fs'), path = require('path');
|
||||
const root = path.join(__dirname, '..');
|
||||
const svg = fs.readFileSync(path.join(root, 'assets', 'dmodem.svg'), 'utf8');
|
||||
const out = path.join(root, 'build', 'icons');
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
for (const size of [16, 32, 48, 64, 128, 256, 512, 1024]) {
|
||||
const page = await browser.newPage({ viewport: { width: size, height: size } });
|
||||
const s = svg.replace(/width="\d+" height="\d+"/, `width="${size}" height="${size}"`);
|
||||
await page.setContent(`<html><body style="margin:0;background:transparent">${s}</body></html>`);
|
||||
await page.screenshot({ path: path.join(out, `${size}.png`), omitBackground: true });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
})();
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Makes the apps' icon files from tools/icons.js's PNGs (build/icons):
|
||||
|
||||
windows/res/dmodem.ico 16, 32 and 48 in 256 colours (Windows 9x) and
|
||||
in 32-bit colour with alpha (XP on), 256 as PNG
|
||||
macos/.../AppIcon.appiconset the sizes an Asset Catalog wants
|
||||
|
||||
The .ico is written by hand: Windows 95 reads only BMP entries."""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(__file__), '..')
|
||||
SRC = os.path.join(ROOT, 'build', 'icons')
|
||||
|
||||
|
||||
def png(size):
|
||||
return Image.open(os.path.join(SRC, f'{size}.png')).convert('RGBA')
|
||||
|
||||
|
||||
def and_mask(img):
|
||||
w, h = img.size
|
||||
stride = ((w + 31) // 32) * 4
|
||||
rows = []
|
||||
for y in range(h - 1, -1, -1):
|
||||
bits = bytearray(stride)
|
||||
for x in range(w):
|
||||
if img.getpixel((x, y))[3] < 128:
|
||||
bits[x // 8] |= 0x80 >> (x % 8)
|
||||
rows.append(bytes(bits))
|
||||
return b''.join(rows)
|
||||
|
||||
|
||||
def dib_32(img):
|
||||
w, h = img.size
|
||||
header = struct.pack('<IiiHHIIiiII', 40, w, h * 2, 1, 32, 0, 0, 0, 0, 0, 0)
|
||||
px = bytearray()
|
||||
for y in range(h - 1, -1, -1):
|
||||
for x in range(w):
|
||||
r, g, b, a = img.getpixel((x, y))
|
||||
px += bytes((b, g, r, a))
|
||||
return header + bytes(px) + and_mask(img)
|
||||
|
||||
|
||||
def dib_8(img):
|
||||
w, h = img.size
|
||||
# 255 colours of the opaque pixels, on black where it is clear
|
||||
flat = Image.new('RGB', img.size, (0, 0, 0))
|
||||
flat.paste(img, mask=img.split()[3])
|
||||
q = flat.quantize(colors=256, method=Image.Quantize.MEDIANCUT)
|
||||
pal = q.getpalette()[:256 * 3]
|
||||
pal += [0] * (256 * 3 - len(pal))
|
||||
header = struct.pack('<IiiHHIIiiII', 40, w, h * 2, 1, 8, 0, 0, 0, 0, 256, 0)
|
||||
table = bytearray()
|
||||
for i in range(256):
|
||||
r, g, b = pal[i * 3:i * 3 + 3]
|
||||
table += bytes((b, g, r, 0))
|
||||
stride = (w + 3) & ~3
|
||||
px = bytearray()
|
||||
for y in range(h - 1, -1, -1):
|
||||
row = bytes(q.getpixel((x, y)) for x in range(w))
|
||||
px += row + bytes(stride - w)
|
||||
return header + bytes(table) + bytes(px) + and_mask(img)
|
||||
|
||||
|
||||
def ico(path):
|
||||
entries = []
|
||||
for size in (16, 32, 48):
|
||||
img = png(size)
|
||||
entries.append((size, 8, 256, dib_8(img)))
|
||||
for size in (16, 32, 48):
|
||||
entries.append((size, 32, 0, dib_32(png(size))))
|
||||
b = io.BytesIO()
|
||||
png(256).save(b, 'PNG')
|
||||
entries.append((256, 32, 0, b.getvalue()))
|
||||
head = struct.pack('<HHH', 0, 1, len(entries))
|
||||
offset = 6 + 16 * len(entries)
|
||||
dirs, data = b'', b''
|
||||
for size, bpp, colours, blob in entries:
|
||||
dirs += struct.pack('<BBBBHHII', size % 256, size % 256,
|
||||
colours % 256, 0, 1, bpp, len(blob), offset)
|
||||
offset += len(blob)
|
||||
data += blob
|
||||
with open(path, 'wb') as f:
|
||||
f.write(head + dirs + data)
|
||||
|
||||
|
||||
def appiconset(dir):
|
||||
os.makedirs(dir, exist_ok=True)
|
||||
images = []
|
||||
for pt in (16, 32, 128, 256, 512):
|
||||
for scale in (1, 2):
|
||||
px = pt * scale
|
||||
name = f'icon_{pt}x{pt}{"@2x" if scale == 2 else ""}.png'
|
||||
png(px).save(os.path.join(dir, name))
|
||||
images.append({'idiom': 'mac', 'size': f'{pt}x{pt}',
|
||||
'scale': f'{scale}x', 'filename': name})
|
||||
with open(os.path.join(dir, 'Contents.json'), 'w') as f:
|
||||
json.dump({'images': images, 'info': {'version': 1, 'author': 'xcode'}},
|
||||
f, indent=2)
|
||||
f.write('\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ico(os.path.join(ROOT, 'windows', 'res', 'dmodem.ico'))
|
||||
appiconset(os.path.join(ROOT, 'macos', 'DModem', 'Assets.xcassets',
|
||||
'AppIcon.appiconset'))
|
||||
@@ -0,0 +1,22 @@
|
||||
# The Windows app with MinGW or MSVC (the Windows 95 build is Open
|
||||
# Watcom's: build-watcom.sh). ANSI, for the same code to build with both.
|
||||
enable_language(CXX)
|
||||
enable_language(RC)
|
||||
add_executable(dmodem WIN32
|
||||
src/main.cpp
|
||||
src/link.cpp
|
||||
src/pages.cpp
|
||||
src/term.cpp
|
||||
src/settings.cpp
|
||||
src/config.cpp
|
||||
res/app.rc)
|
||||
target_include_directories(dmodem PRIVATE src)
|
||||
target_link_libraries(dmodem PRIVATE dmodemctl comctl32 wsock32 comdlg32 gdi32)
|
||||
if(MSVC)
|
||||
target_compile_definitions(dmodem PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
# (a manifest of our own in app.rc)
|
||||
target_link_options(dmodem PRIVATE /MANIFEST:NO)
|
||||
else()
|
||||
target_compile_options(dmodem PRIVATE -Wall -Wextra -Wno-unused-parameter)
|
||||
target_link_options(dmodem PRIVATE -static)
|
||||
endif()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Builds dmodem.exe with Open Watcom 2.0, for Windows 95 and later:
|
||||
# ANSI Win32, the Windows 95 common controls, Winsock 1.1, the static
|
||||
# Watcom C library. WATCOM must name Open Watcom's directory, and its
|
||||
# binaries be on the PATH (on Linux, $WATCOM/binl64 or binl).
|
||||
#
|
||||
# windows/build-watcom.sh [the output directory, build/watcom]
|
||||
set -eu
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
root=$(dirname "$here")
|
||||
out=${1:-$root/build/watcom}
|
||||
mkdir -p "$out"
|
||||
cd "$out"
|
||||
|
||||
: "${WATCOM:?set WATCOM to Open Watcom's directory}"
|
||||
inc="-i=$WATCOM/h -i=$WATCOM/h/nt -i=$root/core/include -i=$root/core/src"
|
||||
# 386 code, the stack calling convention's names as Win32's, C99
|
||||
copts="-q -bt=nt -bm -3r -ox -w4 -zq -za99 $inc"
|
||||
cppopts="-q -bt=nt -bm -3r -ox -w4 -zq -xs $inc -i=$here/src"
|
||||
|
||||
# every file compiled, so that one run shows all the errors
|
||||
objs=""
|
||||
failed=0
|
||||
for f in "$root"/core/src/*.c; do
|
||||
o=$(basename "$f" .c).obj
|
||||
wcc386 $copts -fo="$o" "$f" || failed=1
|
||||
objs="$objs $o"
|
||||
done
|
||||
for f in "$here"/src/*.cpp; do
|
||||
o=$(basename "$f" .cpp).obj
|
||||
wpp386 $cppopts -fo="$o" "$f" || failed=1
|
||||
objs="$objs $o"
|
||||
done
|
||||
[ $failed = 0 ] || exit 1
|
||||
wrc -q -r -bt=nt -i="$WATCOM/h/nt" -i="$here/src" -i="$here/res" \
|
||||
-fo=app.res "$here/res/app.rc"
|
||||
|
||||
{
|
||||
echo "system nt_win"
|
||||
echo "name dmodem.exe"
|
||||
echo "option quiet"
|
||||
echo "option stack=256k"
|
||||
# Windows 95 and NT 4 take a subsystem version of 4.0
|
||||
echo "runtime windows=4.0"
|
||||
for o in $objs; do echo "file $o"; done
|
||||
echo "library comctl32.lib, wsock32.lib, comdlg32.lib"
|
||||
echo "option resource=app.res"
|
||||
} > dmodem.lnk
|
||||
wlink @dmodem.lnk
|
||||
ls -l dmodem.exe
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="DModem.Gui" type="win32"/>
|
||||
<description>D-Modem</description>
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*"/>
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* app.rc - the Windows app's icon, menu and dialogs (MS Shell Dlg: MS
|
||||
* Sans Serif on Windows 9x, Tahoma or Segoe UI later)
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include "../src/resource.h"
|
||||
|
||||
IDI_APP ICON "dmodem.ico"
|
||||
|
||||
/* visual styles from Windows XP on (Windows 9x ignores it) */
|
||||
1 24 "app.manifest"
|
||||
|
||||
IDR_MENU MENU
|
||||
BEGIN
|
||||
POPUP "&Modem"
|
||||
BEGIN
|
||||
MENUITEM "&Start or Stop", IDM_START
|
||||
MENUITEM "&Line Settings...", IDM_LINE
|
||||
MENUITEM SEPARATOR
|
||||
MENUITEM "E&xit", IDM_EXIT
|
||||
END
|
||||
POPUP "&Help"
|
||||
BEGIN
|
||||
MENUITEM "&About D-Modem", IDM_ABOUT
|
||||
END
|
||||
END
|
||||
|
||||
IDD_LINE DIALOG 0, 0, 300, 286
|
||||
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Line Settings"
|
||||
FONT 8, "MS Shell Dlg"
|
||||
BEGIN
|
||||
AUTORADIOBUTTON "Start &dmodemd on this computer (Windows 7 or later)", IDC_L_DMODEMD, 8, 8, 284, 10, WS_GROUP | WS_TABSTOP
|
||||
LTEXT "SIP &user:", -1, 20, 24, 60, 8
|
||||
EDITTEXT IDC_L_USER, 84, 22, 120, 12, ES_AUTOHSCROLL
|
||||
LTEXT "&Password:", -1, 20, 40, 60, 8
|
||||
EDITTEXT IDC_L_PASSWORD, 84, 38, 120, 12, ES_AUTOHSCROLL | ES_PASSWORD
|
||||
LTEXT "Ser&ver:", -1, 20, 56, 60, 8
|
||||
EDITTEXT IDC_L_SERVER, 84, 54, 208, 12, ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "Take &calls (register with the server)", IDC_L_LISTEN, 20, 72, 200, 10, WS_TABSTOP
|
||||
AUTOCHECKBOX "Fax over &T.38", IDC_L_T38, 20, 84, 120, 10, WS_TABSTOP
|
||||
AUTOCHECKBOX "Mark calls as modem data (V.15&2)", IDC_L_V152, 140, 84, 152, 10, WS_TABSTOP
|
||||
AUTOCHECKBOX "Modem relay (V.15&0.1)", IDC_L_V150, 20, 96, 120, 10, WS_TABSTOP
|
||||
LTEXT "C&ountry:", -1, 20, 112, 60, 8
|
||||
EDITTEXT IDC_L_COUNTRY, 84, 110, 80, 12, ES_AUTOHSCROLL
|
||||
LTEXT "(empty for the USA)", -1, 170, 112, 120, 8
|
||||
LTEXT "USB &modem:", -1, 20, 128, 60, 8
|
||||
EDITTEXT IDC_L_USB, 84, 126, 80, 12, ES_AUTOHSCROLL
|
||||
LTEXT "(auto, or empty for SIP)", -1, 170, 128, 120, 8
|
||||
LTEXT "dmodemd.e&xe:", -1, 20, 144, 60, 8
|
||||
EDITTEXT IDC_L_PATH, 84, 142, 152, 12, ES_AUTOHSCROLL
|
||||
PUSHBUTTON "&Browse...", IDC_L_BROWSE, 240, 141, 52, 14
|
||||
AUTORADIOBUTTON "dmodemd on &another computer, or as a service (TCP)", IDC_L_TCP, 8, 164, 284, 10, WS_TABSTOP
|
||||
LTEXT "&Address:", -1, 20, 180, 60, 8
|
||||
EDITTEXT IDC_L_ADDRESS, 84, 178, 120, 12, ES_AUTOHSCROLL
|
||||
AUTORADIOBUTTON "A modem on a &serial port", IDC_L_COM, 8, 198, 284, 10, WS_TABSTOP
|
||||
LTEXT "P&ort:", -1, 20, 214, 60, 8
|
||||
COMBOBOX IDC_L_PORT, 84, 212, 80, 120, CBS_DROPDOWN | WS_VSCROLL | WS_TABSTOP
|
||||
LTEXT "Commands when the modem &opens:", -1, 8, 236, 140, 8
|
||||
EDITTEXT IDC_L_INIT, 8, 246, 284, 12, ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "OK", IDOK, 186, 266, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 242, 266, 50, 14
|
||||
END
|
||||
|
||||
IDD_SETTING DIALOG 0, 0, 240, 110
|
||||
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Change Setting"
|
||||
FONT 8, "MS Shell Dlg"
|
||||
BEGIN
|
||||
LTEXT "", IDC_S_LABEL, 8, 8, 224, 8
|
||||
LTEXT "", IDC_S_HELP, 8, 20, 224, 20
|
||||
COMBOBOX IDC_S_LIST, 8, 44, 224, 140, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
|
||||
EDITTEXT IDC_S_EDIT, 8, 44, 224, 12, ES_AUTOHSCROLL
|
||||
LTEXT "", IDC_S_RANGE, 8, 62, 224, 8
|
||||
LTEXT "", IDC_S_DEFAULT, 8, 74, 224, 8
|
||||
DEFPUSHBUTTON "OK", IDOK, 126, 90, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 182, 90, 50, 14
|
||||
END
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,0,0
|
||||
PRODUCTVERSION 1,0,0,0
|
||||
FILEOS 0x4
|
||||
FILETYPE 0x1
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "D-Modem\0"
|
||||
VALUE "FileDescription", "D-Modem\0"
|
||||
VALUE "FileVersion", "1.0.0\0"
|
||||
VALUE "LegalCopyright", "Copyright (c) 2026, D-Modem. BSD 3-Clause.\0"
|
||||
VALUE "ProductName", "D-Modem\0"
|
||||
VALUE "ProductVersion", "1.0.0\0"
|
||||
VALUE "OriginalFilename", "dmodem.exe\0"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* app.h - the Windows app: plain Win32 in C++98, ANSI, the common
|
||||
* controls of Windows 95, so the one .exe runs on Windows 95,
|
||||
* 98 and ME and on NT 4 through Windows 11. Built with Open
|
||||
* Watcom (windows/build-watcom.sh), or MinGW or MSVC (CMake).
|
||||
*
|
||||
* The modem is reached one of three ways (Link):
|
||||
* - dmodemd started by the app on this PC (Windows 7 and later, as
|
||||
* dmodemd needs), its DTE a TCP socket on 127.0.0.1;
|
||||
* - a TCP address: dmodemd as a service, or on another computer;
|
||||
* - a COM port: a modem's serial port, a pico-serial, or dmodemd's
|
||||
* --com through a com0com pair.
|
||||
*/
|
||||
#ifndef DMODEM_WIN_APP_H
|
||||
#define DMODEM_WIN_APP_H
|
||||
|
||||
#ifndef WINVER
|
||||
#define WINVER 0x0400
|
||||
#endif
|
||||
#ifndef _WIN32_WINNT
|
||||
#define _WIN32_WINNT 0x0400
|
||||
#endif
|
||||
#ifndef _WIN32_IE
|
||||
#define _WIN32_IE 0x0300
|
||||
#endif
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <winsock.h>
|
||||
#include <commctrl.h>
|
||||
|
||||
#include "dmodemctl.h"
|
||||
|
||||
/* (older headers, Open Watcom's among them, without the 64-bit names) */
|
||||
#ifndef GWLP_USERDATA
|
||||
#define GWLP_USERDATA GWL_USERDATA
|
||||
#define GetWindowLongPtr GetWindowLong
|
||||
#define SetWindowLongPtr SetWindowLong
|
||||
#define GWLP_WNDPROC GWL_WNDPROC
|
||||
#endif
|
||||
|
||||
/* the line settings, kept in dmodem.ini */
|
||||
enum LineKind { LINE_DMODEMD = 0, LINE_TCP, LINE_COM };
|
||||
|
||||
struct Config {
|
||||
int line; /* LineKind */
|
||||
char sip_user[128], sip_password[128], sip_server[256];
|
||||
int listen, t38, v152, v150;
|
||||
char country[64];
|
||||
char usb[64]; /* --usb, "" for a SIP line */
|
||||
char dmodemd[MAX_PATH]; /* dmodemd.exe, "" next to the app */
|
||||
char tcp[256]; /* host:port */
|
||||
char com[32]; /* COM1 */
|
||||
char init[256]; /* commands when the modem opens */
|
||||
};
|
||||
|
||||
void config_load(Config *c);
|
||||
void config_save(const Config *c);
|
||||
/* "SIP: alice@sip.example.com" and the like, into out */
|
||||
void config_summary(const Config *c, char *out, int n);
|
||||
/* the Line Settings dialog: true if changed */
|
||||
bool line_dialog(HWND owner, Config *c);
|
||||
|
||||
/* a command's response */
|
||||
typedef void (*ResponseFn)(const dmc_event *ev, void *data);
|
||||
|
||||
/* the app's state */
|
||||
struct App {
|
||||
HINSTANCE inst;
|
||||
HWND main, tabs;
|
||||
HWND pages[5];
|
||||
HFONT font, bold_font, big_font, mono_font;
|
||||
Config cfg;
|
||||
dmc_session *s;
|
||||
int last_state;
|
||||
char device[256]; /* what the modem is at, for people */
|
||||
};
|
||||
|
||||
extern App app;
|
||||
|
||||
/* link.cpp: the modem's connection */
|
||||
void link_start();
|
||||
void link_stop();
|
||||
bool link_running();
|
||||
bool link_open(); /* the DTE is open */
|
||||
/* the session's output written, input read, events handled */
|
||||
void link_pump();
|
||||
/* socket messages (WM_APP_SOCKET) */
|
||||
void link_socket(WPARAM w, LPARAM l);
|
||||
void link_type(const char *data, int n);
|
||||
int link_command(const char *cmd, int flags, ResponseFn fn, void *data);
|
||||
|
||||
#define WM_APP_SOCKET (WM_APP + 1)
|
||||
#define TIMER_PUMP 1
|
||||
|
||||
/* main.cpp */
|
||||
void app_log(const char *line);
|
||||
void app_message(const char *text); /* the status bar's */
|
||||
/* the modem's events, the state */
|
||||
void app_event(const dmc_event *ev);
|
||||
void app_state();
|
||||
void app_opened();
|
||||
void app_closed();
|
||||
|
||||
/* pages.cpp: a page (a plain child window whose controls' commands go
|
||||
to fn), and the Modem, Call Stats and Log pages */
|
||||
typedef void (*CommandFn)(HWND page, int id, int code);
|
||||
HWND page_new(HWND parent, CommandFn fn);
|
||||
HWND modem_page_new(HWND parent);
|
||||
void modem_page_state();
|
||||
void modem_page_layout(HWND page, int w, int h);
|
||||
HWND stats_page_new(HWND parent);
|
||||
void stats_page_layout(HWND page, int w, int h);
|
||||
void stats_refresh();
|
||||
HWND log_page_new(HWND parent);
|
||||
void log_page_layout(HWND page, int w, int h);
|
||||
void log_append(const char *line);
|
||||
|
||||
/* term.cpp: the Terminal page */
|
||||
HWND term_page_new(HWND parent);
|
||||
void term_page_layout(HWND page, int w, int h);
|
||||
void term_feed(const char *data, int n);
|
||||
void term_state();
|
||||
|
||||
/* settings.cpp: the Settings page */
|
||||
HWND settings_page_new(HWND parent);
|
||||
void settings_page_layout(HWND page, int w, int h);
|
||||
void settings_load();
|
||||
void settings_clear();
|
||||
void settings_state();
|
||||
|
||||
/* util */
|
||||
/* UTF-8 to the ANSI code page (Windows 9x has few W functions) */
|
||||
void to_ansi(const char *utf8, char *out, int n);
|
||||
/* a code point to UTF-8: how many bytes */
|
||||
int utf8_encode(unsigned long c, char *out);
|
||||
HWND make_child(const char *cls, const char *text, DWORD style, HWND parent,
|
||||
int id, DWORD ex = 0);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* config.cpp - the line settings, kept in dmodem.ini (in
|
||||
* %APPDATA%\D-Modem, or beside the app where there is no
|
||||
* APPDATA, as on Windows 9x), and the Line Settings dialog
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
#include <commdlg.h>
|
||||
#include "resource.h"
|
||||
|
||||
#ifndef OPENFILENAME_SIZE_VERSION_400
|
||||
#define OPENFILENAME_SIZE_VERSION_400 76
|
||||
#endif
|
||||
|
||||
static void ini_path(char *out, int n)
|
||||
{
|
||||
char dir[MAX_PATH];
|
||||
DWORD k = GetEnvironmentVariable("APPDATA", dir, sizeof(dir));
|
||||
if (k > 0 && k < sizeof(dir)) {
|
||||
strcat(dir, "\\D-Modem");
|
||||
CreateDirectory(dir, NULL);
|
||||
_snprintf(out, n, "%s\\dmodem.ini", dir);
|
||||
} else {
|
||||
GetModuleFileName(NULL, out, n);
|
||||
char *slash = strrchr(out, '\\');
|
||||
if (slash)
|
||||
strcpy(slash + 1, "dmodem.ini");
|
||||
}
|
||||
out[n - 1] = '\0';
|
||||
}
|
||||
|
||||
static void get(const char *ini, const char *key, const char *def, char *out,
|
||||
int n)
|
||||
{
|
||||
GetPrivateProfileString("line", key, def, out, n, ini);
|
||||
}
|
||||
|
||||
static int get_i(const char *ini, const char *key, int def)
|
||||
{
|
||||
return (int)GetPrivateProfileInt("line", key, def, ini);
|
||||
}
|
||||
|
||||
static void put(const char *ini, const char *key, const char *v)
|
||||
{
|
||||
WritePrivateProfileString("line", key, v, ini);
|
||||
}
|
||||
|
||||
static void put_i(const char *ini, const char *key, int v)
|
||||
{
|
||||
char b[16];
|
||||
_snprintf(b, sizeof(b), "%d", v);
|
||||
b[sizeof(b) - 1] = '\0';
|
||||
put(ini, key, b);
|
||||
}
|
||||
|
||||
void config_load(Config *c)
|
||||
{
|
||||
char ini[MAX_PATH];
|
||||
ini_path(ini, sizeof(ini));
|
||||
memset(c, 0, sizeof(*c));
|
||||
/* (Windows 9x and NT 4 can't run dmodemd: a COM port by default) */
|
||||
OSVERSIONINFO v;
|
||||
memset(&v, 0, sizeof(v));
|
||||
v.dwOSVersionInfoSize = sizeof(v);
|
||||
GetVersionEx(&v);
|
||||
bool old = v.dwPlatformId != VER_PLATFORM_WIN32_NT || v.dwMajorVersion < 6;
|
||||
c->line = get_i(ini, "line", old ? LINE_COM : LINE_DMODEMD);
|
||||
get(ini, "sip-user", "", c->sip_user, sizeof(c->sip_user));
|
||||
get(ini, "sip-password", "", c->sip_password, sizeof(c->sip_password));
|
||||
get(ini, "sip-server", "", c->sip_server, sizeof(c->sip_server));
|
||||
c->listen = get_i(ini, "listen", 0);
|
||||
c->t38 = get_i(ini, "t38", 1);
|
||||
c->v152 = get_i(ini, "v152", 1);
|
||||
c->v150 = get_i(ini, "v150", 0);
|
||||
get(ini, "country", "", c->country, sizeof(c->country));
|
||||
get(ini, "usb", "", c->usb, sizeof(c->usb));
|
||||
get(ini, "dmodemd", "", c->dmodemd, sizeof(c->dmodemd));
|
||||
get(ini, "tcp", "127.0.0.1:2323", c->tcp, sizeof(c->tcp));
|
||||
get(ini, "com", "COM1", c->com, sizeof(c->com));
|
||||
get(ini, "init", "", c->init, sizeof(c->init));
|
||||
}
|
||||
|
||||
void config_save(const Config *c)
|
||||
{
|
||||
char ini[MAX_PATH];
|
||||
ini_path(ini, sizeof(ini));
|
||||
put_i(ini, "line", c->line);
|
||||
put(ini, "sip-user", c->sip_user);
|
||||
put(ini, "sip-password", c->sip_password);
|
||||
put(ini, "sip-server", c->sip_server);
|
||||
put_i(ini, "listen", c->listen);
|
||||
put_i(ini, "t38", c->t38);
|
||||
put_i(ini, "v152", c->v152);
|
||||
put_i(ini, "v150", c->v150);
|
||||
put(ini, "country", c->country);
|
||||
put(ini, "usb", c->usb);
|
||||
put(ini, "dmodemd", c->dmodemd);
|
||||
put(ini, "tcp", c->tcp);
|
||||
put(ini, "com", c->com);
|
||||
put(ini, "init", c->init);
|
||||
}
|
||||
|
||||
void config_summary(const Config *c, char *out, int n)
|
||||
{
|
||||
switch (c->line) {
|
||||
case LINE_TCP:
|
||||
_snprintf(out, n, "dmodemd at %s", c->tcp);
|
||||
break;
|
||||
case LINE_COM:
|
||||
_snprintf(out, n, "The modem on %s", c->com);
|
||||
break;
|
||||
default:
|
||||
if (c->usb[0])
|
||||
_snprintf(out, n, "dmodemd: USB modem (%s)", c->usb);
|
||||
else if (!c->sip_user[0] || !c->sip_server[0])
|
||||
_snprintf(out, n, "dmodemd: SIP account not set up");
|
||||
else
|
||||
_snprintf(out, n, "dmodemd: SIP %s@%s%s", c->sip_user,
|
||||
c->sip_server, c->listen ? ", taking calls" : "");
|
||||
break;
|
||||
}
|
||||
out[n - 1] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* the dialog
|
||||
*/
|
||||
|
||||
static Config *editing;
|
||||
|
||||
static void enable(HWND d)
|
||||
{
|
||||
bool here = IsDlgButtonChecked(d, IDC_L_DMODEMD) == BST_CHECKED;
|
||||
bool tcp = IsDlgButtonChecked(d, IDC_L_TCP) == BST_CHECKED;
|
||||
bool com = IsDlgButtonChecked(d, IDC_L_COM) == BST_CHECKED;
|
||||
static const int dmodemd_ids[] = {
|
||||
IDC_L_USER, IDC_L_PASSWORD, IDC_L_SERVER, IDC_L_LISTEN,
|
||||
IDC_L_T38, IDC_L_V152, IDC_L_V150, IDC_L_COUNTRY, IDC_L_USB,
|
||||
IDC_L_PATH, IDC_L_BROWSE, 0
|
||||
};
|
||||
for (int i = 0; dmodemd_ids[i]; i++)
|
||||
EnableWindow(GetDlgItem(d, dmodemd_ids[i]), here);
|
||||
EnableWindow(GetDlgItem(d, IDC_L_ADDRESS), tcp);
|
||||
EnableWindow(GetDlgItem(d, IDC_L_PORT), com);
|
||||
}
|
||||
|
||||
static void check(HWND d, int id, int on)
|
||||
{
|
||||
CheckDlgButton(d, id, on ? BST_CHECKED : BST_UNCHECKED);
|
||||
}
|
||||
|
||||
static int checked(HWND d, int id)
|
||||
{
|
||||
return IsDlgButtonChecked(d, id) == BST_CHECKED;
|
||||
}
|
||||
|
||||
static void browse(HWND d)
|
||||
{
|
||||
char file[MAX_PATH] = "dmodemd.exe";
|
||||
OPENFILENAME o;
|
||||
memset(&o, 0, sizeof(o));
|
||||
/* (the size Windows 95 and NT 4 know) */
|
||||
o.lStructSize = OPENFILENAME_SIZE_VERSION_400;
|
||||
o.hwndOwner = d;
|
||||
o.lpstrFilter = "dmodemd.exe\0dmodemd.exe\0Programs\0*.exe\0";
|
||||
o.lpstrFile = file;
|
||||
o.nMaxFile = sizeof(file);
|
||||
o.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
|
||||
if (GetOpenFileName(&o))
|
||||
SetDlgItemText(d, IDC_L_PATH, file);
|
||||
}
|
||||
|
||||
static BOOL CALLBACK line_proc(HWND d, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
(void)lp;
|
||||
Config *c = editing;
|
||||
switch (m) {
|
||||
case WM_INITDIALOG: {
|
||||
check(d, IDC_L_DMODEMD, c->line == LINE_DMODEMD);
|
||||
check(d, IDC_L_TCP, c->line == LINE_TCP);
|
||||
check(d, IDC_L_COM, c->line == LINE_COM);
|
||||
SetDlgItemText(d, IDC_L_USER, c->sip_user);
|
||||
SetDlgItemText(d, IDC_L_PASSWORD, c->sip_password);
|
||||
SetDlgItemText(d, IDC_L_SERVER, c->sip_server);
|
||||
check(d, IDC_L_LISTEN, c->listen);
|
||||
check(d, IDC_L_T38, c->t38);
|
||||
check(d, IDC_L_V152, c->v152);
|
||||
check(d, IDC_L_V150, c->v150);
|
||||
SetDlgItemText(d, IDC_L_COUNTRY, c->country);
|
||||
SetDlgItemText(d, IDC_L_USB, c->usb);
|
||||
SetDlgItemText(d, IDC_L_PATH, c->dmodemd);
|
||||
SetDlgItemText(d, IDC_L_ADDRESS, c->tcp);
|
||||
HWND port = GetDlgItem(d, IDC_L_PORT);
|
||||
for (int i = 1; i <= 16; i++) {
|
||||
char n[8];
|
||||
_snprintf(n, sizeof(n), "COM%d", i);
|
||||
n[sizeof(n) - 1] = '\0';
|
||||
SendMessage(port, CB_ADDSTRING, 0, (LPARAM)n);
|
||||
}
|
||||
SetWindowText(port, c->com);
|
||||
SetDlgItemText(d, IDC_L_INIT, c->init);
|
||||
enable(d);
|
||||
return TRUE;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
switch (LOWORD(wp)) {
|
||||
case IDC_L_DMODEMD:
|
||||
case IDC_L_TCP:
|
||||
case IDC_L_COM:
|
||||
enable(d);
|
||||
return TRUE;
|
||||
case IDC_L_BROWSE:
|
||||
browse(d);
|
||||
return TRUE;
|
||||
case IDOK:
|
||||
c->line = checked(d, IDC_L_TCP) ? LINE_TCP :
|
||||
checked(d, IDC_L_COM) ? LINE_COM : LINE_DMODEMD;
|
||||
GetDlgItemText(d, IDC_L_USER, c->sip_user, sizeof(c->sip_user));
|
||||
GetDlgItemText(d, IDC_L_PASSWORD, c->sip_password,
|
||||
sizeof(c->sip_password));
|
||||
GetDlgItemText(d, IDC_L_SERVER, c->sip_server,
|
||||
sizeof(c->sip_server));
|
||||
c->listen = checked(d, IDC_L_LISTEN);
|
||||
c->t38 = checked(d, IDC_L_T38);
|
||||
c->v152 = checked(d, IDC_L_V152);
|
||||
c->v150 = checked(d, IDC_L_V150);
|
||||
GetDlgItemText(d, IDC_L_COUNTRY, c->country, sizeof(c->country));
|
||||
GetDlgItemText(d, IDC_L_USB, c->usb, sizeof(c->usb));
|
||||
GetDlgItemText(d, IDC_L_PATH, c->dmodemd, sizeof(c->dmodemd));
|
||||
GetDlgItemText(d, IDC_L_ADDRESS, c->tcp, sizeof(c->tcp));
|
||||
GetDlgItemText(d, IDC_L_PORT, c->com, sizeof(c->com));
|
||||
GetDlgItemText(d, IDC_L_INIT, c->init, sizeof(c->init));
|
||||
EndDialog(d, IDOK);
|
||||
return TRUE;
|
||||
case IDCANCEL:
|
||||
EndDialog(d, IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
bool line_dialog(HWND owner, Config *c)
|
||||
{
|
||||
Config copy = *c;
|
||||
editing = ©
|
||||
if (DialogBox(app.inst, MAKEINTRESOURCE(IDD_LINE), owner,
|
||||
(DLGPROC)line_proc) != IDOK)
|
||||
return false;
|
||||
*c = copy;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* link.cpp - the modem's connection: dmodemd started here (its DTE a
|
||||
* TCP socket on 127.0.0.1), a TCP address, or a COM port;
|
||||
* and the bytes between it, the session and the terminal
|
||||
*
|
||||
* Only what Windows 95 has: Winsock 1.1 (WSAAsyncSelect), anonymous
|
||||
* pipes read with PeekNamedPipe, and a COM port read on the timer.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
/* the commands that wait for their responses */
|
||||
struct Waiting {
|
||||
int tag;
|
||||
ResponseFn fn;
|
||||
void *data;
|
||||
Waiting *next;
|
||||
};
|
||||
|
||||
static Waiting *waiting;
|
||||
static SOCKET sock = INVALID_SOCKET;
|
||||
static int sock_ready; /* connected */
|
||||
static HANDLE com = INVALID_HANDLE_VALUE;
|
||||
static HANDLE proc, proc_out; /* dmodemd, its stdout and stderr */
|
||||
static char proc_line[1024];
|
||||
static int proc_n;
|
||||
static char port_out[8192]; /* what the DTE has yet to take */
|
||||
static int port_out_n;
|
||||
static DWORD start_tick;
|
||||
static int connect_tries;
|
||||
|
||||
static int64_t now_ms()
|
||||
{
|
||||
return (int64_t)GetTickCount();
|
||||
}
|
||||
|
||||
bool link_open()
|
||||
{
|
||||
return (sock != INVALID_SOCKET && sock_ready) ||
|
||||
com != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
bool link_running()
|
||||
{
|
||||
return proc != NULL || sock != INVALID_SOCKET ||
|
||||
com != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
static void opened(const char *what)
|
||||
{
|
||||
_snprintf(app.device, sizeof(app.device), "%s", what);
|
||||
app.device[sizeof(app.device) - 1] = '\0';
|
||||
dmc_open(app.s, now_ms());
|
||||
if (app.cfg.init[0])
|
||||
link_command(app.cfg.init, 0, NULL, NULL);
|
||||
app_opened();
|
||||
link_pump();
|
||||
}
|
||||
|
||||
static void close_port()
|
||||
{
|
||||
if (sock != INVALID_SOCKET) {
|
||||
closesocket(sock);
|
||||
sock = INVALID_SOCKET;
|
||||
}
|
||||
sock_ready = 0;
|
||||
if (com != INVALID_HANDLE_VALUE) {
|
||||
CloseHandle(com);
|
||||
com = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
port_out_n = 0;
|
||||
while (waiting) {
|
||||
Waiting *w = waiting;
|
||||
waiting = w->next;
|
||||
free(w);
|
||||
}
|
||||
if (dmc_state(app.s) != DMC_CLOSED) {
|
||||
dmc_close(app.s);
|
||||
dmc_event ev;
|
||||
while (dmc_next_event(app.s, &ev))
|
||||
;
|
||||
app_closed();
|
||||
}
|
||||
}
|
||||
|
||||
/* host:port, its address */
|
||||
static bool address(const char *spec, sockaddr_in *sa)
|
||||
{
|
||||
char host[256];
|
||||
strncpy(host, spec, sizeof(host) - 1);
|
||||
host[sizeof(host) - 1] = '\0';
|
||||
char *colon = strrchr(host, ':');
|
||||
int port = 2323;
|
||||
if (colon) {
|
||||
*colon = '\0';
|
||||
port = atoi(colon + 1);
|
||||
}
|
||||
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)
|
||||
return false;
|
||||
memcpy(&sa->sin_addr, h->h_addr, sizeof(sa->sin_addr));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool open_tcp(const char *spec)
|
||||
{
|
||||
sockaddr_in sa;
|
||||
if (!address(spec, &sa)) {
|
||||
char m[300];
|
||||
_snprintf(m, sizeof(m), "Can't find %s", spec);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
app_log(m);
|
||||
return false;
|
||||
}
|
||||
sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sock == INVALID_SOCKET)
|
||||
return false;
|
||||
WSAAsyncSelect(sock, app.main, WM_APP_SOCKET,
|
||||
FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE);
|
||||
connect(sock, (sockaddr *)&sa, sizeof(sa));
|
||||
if (spec != app.device)
|
||||
_snprintf(app.device, sizeof(app.device), "%s", spec);
|
||||
app.device[sizeof(app.device) - 1] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool open_com(const char *name)
|
||||
{
|
||||
char path[64];
|
||||
_snprintf(path, sizeof(path), "\\\\.\\%s", name);
|
||||
path[sizeof(path) - 1] = '\0';
|
||||
com = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
|
||||
OPEN_EXISTING, 0, NULL);
|
||||
if (com == INVALID_HANDLE_VALUE) {
|
||||
char m[128];
|
||||
_snprintf(m, sizeof(m), "Can't open %s (error %lu)", name,
|
||||
(unsigned long)GetLastError());
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
app_log(m);
|
||||
return false;
|
||||
}
|
||||
DCB dcb;
|
||||
memset(&dcb, 0, sizeof(dcb));
|
||||
dcb.DCBlength = sizeof(dcb);
|
||||
GetCommState(com, &dcb);
|
||||
dcb.BaudRate = CBR_115200;
|
||||
dcb.ByteSize = 8;
|
||||
dcb.Parity = NOPARITY;
|
||||
dcb.StopBits = ONESTOPBIT;
|
||||
dcb.fBinary = TRUE;
|
||||
dcb.fDtrControl = DTR_CONTROL_ENABLE;
|
||||
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
|
||||
dcb.fOutxCtsFlow = TRUE;
|
||||
SetCommState(com, &dcb);
|
||||
/* reads return at once with what there is */
|
||||
COMMTIMEOUTS t;
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.ReadIntervalTimeout = MAXDWORD;
|
||||
t.WriteTotalTimeoutConstant = 1000;
|
||||
SetCommTimeouts(com, &t);
|
||||
opened(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* dmodemd.exe: the configured one, or next to this app */
|
||||
static void dmodemd_path(char *out, int n)
|
||||
{
|
||||
if (app.cfg.dmodemd[0]) {
|
||||
_snprintf(out, n, "%s", app.cfg.dmodemd);
|
||||
out[n - 1] = '\0';
|
||||
return;
|
||||
}
|
||||
GetModuleFileName(NULL, out, n);
|
||||
char *slash = strrchr(out, '\\');
|
||||
if (slash)
|
||||
strcpy(slash + 1, "dmodemd.exe");
|
||||
}
|
||||
|
||||
/* an environment block: ours, and these */
|
||||
static char *environment(const char *const *add)
|
||||
{
|
||||
char *env = GetEnvironmentStrings();
|
||||
int n = 0;
|
||||
while (env[n])
|
||||
n += (int)strlen(env + n) + 1;
|
||||
int extra = 0;
|
||||
for (int i = 0; add[i]; i++)
|
||||
extra += (int)strlen(add[i]) + 1;
|
||||
char *block = (char *)malloc(n + extra + 2);
|
||||
int o = 0;
|
||||
for (int i = 0; add[i]; i++) {
|
||||
strcpy(block + o, add[i]);
|
||||
o += (int)strlen(add[i]) + 1;
|
||||
}
|
||||
/* (ours, but for those set here) */
|
||||
for (int p = 0; env[p]; p += (int)strlen(env + p) + 1) {
|
||||
bool dup = false;
|
||||
for (int i = 0; add[i]; i++) {
|
||||
const char *eq = strchr(add[i], '=');
|
||||
if (eq && !_strnicmp(env + p, add[i], eq - add[i] + 1))
|
||||
dup = true;
|
||||
}
|
||||
if (!dup) {
|
||||
strcpy(block + o, env + p);
|
||||
o += (int)strlen(env + p) + 1;
|
||||
}
|
||||
}
|
||||
block[o] = '\0';
|
||||
FreeEnvironmentStrings(env);
|
||||
return block;
|
||||
}
|
||||
|
||||
static bool start_dmodemd()
|
||||
{
|
||||
Config &c = app.cfg;
|
||||
if (!c.usb[0] && (!c.sip_user[0] || !c.sip_server[0])) {
|
||||
app_message("Set up the SIP account first (Modem, Line Settings)");
|
||||
return false;
|
||||
}
|
||||
char exe[MAX_PATH];
|
||||
dmodemd_path(exe, sizeof(exe));
|
||||
if (GetFileAttributes(exe) == (DWORD)-1) {
|
||||
char m[MAX_PATH + 64];
|
||||
_snprintf(m, sizeof(m), "dmodemd.exe was not found (%s)", exe);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
app_log(m);
|
||||
return false;
|
||||
}
|
||||
/* a port of our own on 127.0.0.1 */
|
||||
int port = 23000 + (int)(GetCurrentProcessId() % 1000);
|
||||
char cmd[1024];
|
||||
int o = _snprintf(cmd, sizeof(cmd), "\"%s\" --tcp 127.0.0.1:%d", exe,
|
||||
port);
|
||||
if (c.country[0])
|
||||
o += _snprintf(cmd + o, sizeof(cmd) - o, " -c %s", c.country);
|
||||
if (c.usb[0])
|
||||
o += _snprintf(cmd + o, sizeof(cmd) - o, " --usb=%s", c.usb);
|
||||
else if (c.listen)
|
||||
o += _snprintf(cmd + o, sizeof(cmd) - o, " -L");
|
||||
cmd[sizeof(cmd) - 1] = '\0';
|
||||
|
||||
char login[600];
|
||||
_snprintf(login, sizeof(login), "SIP_LOGIN=%s:%s@%s", c.sip_user,
|
||||
c.sip_password, c.sip_server);
|
||||
login[sizeof(login) - 1] = '\0';
|
||||
const char *add[6];
|
||||
int k = 0;
|
||||
if (!c.usb[0])
|
||||
add[k++] = login;
|
||||
if (!c.t38)
|
||||
add[k++] = "SIP_T38=no";
|
||||
if (!c.v152)
|
||||
add[k++] = "SIP_V152=no";
|
||||
if (c.v150)
|
||||
add[k++] = "SIP_V150=yes";
|
||||
add[k] = NULL;
|
||||
char *env = environment(add);
|
||||
|
||||
SECURITY_ATTRIBUTES sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.nLength = sizeof(sa);
|
||||
sa.bInheritHandle = TRUE;
|
||||
HANDLE rd, wr;
|
||||
if (!CreatePipe(&rd, &wr, &sa, 0)) {
|
||||
free(env);
|
||||
return false;
|
||||
}
|
||||
/* our end not inherited (DuplicateHandle, as Windows 95 has no
|
||||
SetHandleInformation) */
|
||||
HANDLE rd2;
|
||||
if (DuplicateHandle(GetCurrentProcess(), rd, GetCurrentProcess(), &rd2,
|
||||
0, FALSE, DUPLICATE_SAME_ACCESS)) {
|
||||
CloseHandle(rd);
|
||||
rd = rd2;
|
||||
}
|
||||
STARTUPINFO si;
|
||||
memset(&si, 0, sizeof(si));
|
||||
si.cb = sizeof(si);
|
||||
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
|
||||
si.wShowWindow = SW_HIDE;
|
||||
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
|
||||
si.hStdOutput = wr;
|
||||
si.hStdError = wr;
|
||||
PROCESS_INFORMATION pi;
|
||||
BOOL ok = CreateProcess(NULL, cmd, NULL, NULL, TRUE,
|
||||
CREATE_NO_WINDOW, env, NULL, &si, &pi);
|
||||
free(env);
|
||||
CloseHandle(wr);
|
||||
char m[1100];
|
||||
if (!ok) {
|
||||
CloseHandle(rd);
|
||||
_snprintf(m, sizeof(m), "Can't start dmodemd (error %lu)",
|
||||
(unsigned long)GetLastError());
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
app_log(m);
|
||||
return false;
|
||||
}
|
||||
_snprintf(m, sizeof(m), "> %s", cmd);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_log(m);
|
||||
CloseHandle(pi.hThread);
|
||||
proc = pi.hProcess;
|
||||
proc_out = rd;
|
||||
proc_n = 0;
|
||||
start_tick = GetTickCount();
|
||||
connect_tries = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void link_start()
|
||||
{
|
||||
if (link_running())
|
||||
return;
|
||||
bool ok = false;
|
||||
switch (app.cfg.line) {
|
||||
case LINE_TCP:
|
||||
ok = open_tcp(app.cfg.tcp);
|
||||
break;
|
||||
case LINE_COM:
|
||||
ok = open_com(app.cfg.com);
|
||||
break;
|
||||
default:
|
||||
ok = start_dmodemd();
|
||||
break;
|
||||
}
|
||||
(void)ok;
|
||||
app_state();
|
||||
}
|
||||
|
||||
void link_stop()
|
||||
{
|
||||
if (link_open()) {
|
||||
dmc_hangup(app.s);
|
||||
link_pump();
|
||||
}
|
||||
close_port();
|
||||
if (proc) {
|
||||
/* dmodemd has no window to close: it is ended */
|
||||
TerminateProcess(proc, 0);
|
||||
CloseHandle(proc);
|
||||
proc = NULL;
|
||||
}
|
||||
if (proc_out) {
|
||||
CloseHandle(proc_out);
|
||||
proc_out = NULL;
|
||||
}
|
||||
app_state();
|
||||
}
|
||||
|
||||
/* dmodemd's output, a line at a time */
|
||||
static void proc_read()
|
||||
{
|
||||
DWORD avail = 0;
|
||||
while (proc_out && PeekNamedPipe(proc_out, NULL, 0, NULL, &avail, NULL) &&
|
||||
avail) {
|
||||
char buf[512];
|
||||
DWORD n = 0;
|
||||
if (!ReadFile(proc_out, buf, avail < sizeof(buf) ? avail :
|
||||
sizeof(buf), &n, NULL) || !n)
|
||||
break;
|
||||
for (DWORD i = 0; i < n; i++) {
|
||||
char ch = buf[i];
|
||||
if (ch == '\r')
|
||||
continue;
|
||||
if (ch != '\n' && proc_n < (int)sizeof(proc_line) - 1) {
|
||||
proc_line[proc_n++] = ch;
|
||||
continue;
|
||||
}
|
||||
if (ch != '\n')
|
||||
continue;
|
||||
proc_line[proc_n] = '\0';
|
||||
proc_n = 0;
|
||||
app_log(proc_line);
|
||||
char dev[256];
|
||||
if (dmc_daemon_ready(proc_line, dev, sizeof(dev)) &&
|
||||
!link_open() && sock == INVALID_SOCKET) {
|
||||
/* "TCP 127.0.0.1:23001" */
|
||||
const char *a = strncmp(dev, "TCP ", 4) ? dev :
|
||||
dev + 4;
|
||||
open_tcp(a);
|
||||
} else if (dmc_daemon_error(proc_line) && !link_open()) {
|
||||
app_message(proc_line + 7);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (proc && WaitForSingleObject(proc, 0) == WAIT_OBJECT_0) {
|
||||
DWORD code = 0;
|
||||
GetExitCodeProcess(proc, &code);
|
||||
char m[64];
|
||||
_snprintf(m, sizeof(m), "dmodemd stopped (exit status %ld)",
|
||||
(long)code);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_log(m);
|
||||
app_message(m);
|
||||
CloseHandle(proc);
|
||||
proc = NULL;
|
||||
close_port();
|
||||
if (proc_out) {
|
||||
CloseHandle(proc_out);
|
||||
proc_out = NULL;
|
||||
}
|
||||
app_state();
|
||||
}
|
||||
}
|
||||
|
||||
static void port_write()
|
||||
{
|
||||
int sent = 0;
|
||||
while (sent < port_out_n) {
|
||||
int n = 0;
|
||||
if (sock != INVALID_SOCKET && sock_ready) {
|
||||
n = send(sock, port_out + sent, port_out_n - sent, 0);
|
||||
if (n == SOCKET_ERROR)
|
||||
n = 0;
|
||||
} else if (com != INVALID_HANDLE_VALUE) {
|
||||
DWORD w = 0;
|
||||
if (!WriteFile(com, port_out + sent, port_out_n - sent,
|
||||
&w, NULL))
|
||||
w = 0;
|
||||
n = (int)w;
|
||||
}
|
||||
if (n <= 0)
|
||||
break;
|
||||
sent += n;
|
||||
}
|
||||
memmove(port_out, port_out + sent, port_out_n - sent);
|
||||
port_out_n -= sent;
|
||||
}
|
||||
|
||||
static void port_read()
|
||||
{
|
||||
char buf[4096];
|
||||
if (com != INVALID_HANDLE_VALUE) {
|
||||
DWORD n = 0;
|
||||
while (ReadFile(com, buf, sizeof(buf), &n, NULL) && n > 0)
|
||||
dmc_feed(app.s, buf, (int)n);
|
||||
}
|
||||
}
|
||||
|
||||
void link_socket(WPARAM w, LPARAM l)
|
||||
{
|
||||
if ((SOCKET)w != sock)
|
||||
return;
|
||||
int ev = WSAGETSELECTEVENT(l), err = WSAGETSELECTERROR(l);
|
||||
if (ev == FD_CONNECT) {
|
||||
if (err) {
|
||||
closesocket(sock);
|
||||
sock = INVALID_SOCKET;
|
||||
/* dmodemd may not listen yet: try again for a while */
|
||||
if (proc && connect_tries++ < 20) {
|
||||
Sleep(100);
|
||||
open_tcp(app.device);
|
||||
return;
|
||||
}
|
||||
char m[300];
|
||||
_snprintf(m, sizeof(m), "Can't connect to %s (error %d)",
|
||||
app.device, err);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
app_log(m);
|
||||
app_state();
|
||||
return;
|
||||
}
|
||||
sock_ready = 1;
|
||||
char what[300];
|
||||
_snprintf(what, sizeof(what), "%s (TCP)", app.device);
|
||||
what[sizeof(what) - 1] = '\0';
|
||||
opened(what);
|
||||
} else if (ev == FD_READ) {
|
||||
char buf[4096];
|
||||
int n = recv(sock, buf, sizeof(buf), 0);
|
||||
if (n > 0)
|
||||
dmc_feed(app.s, buf, n);
|
||||
link_pump();
|
||||
} else if (ev == FD_WRITE) {
|
||||
port_write();
|
||||
} else if (ev == FD_CLOSE) {
|
||||
app_log("The modem closed the connection.");
|
||||
close_port();
|
||||
app_state();
|
||||
}
|
||||
}
|
||||
|
||||
void link_pump()
|
||||
{
|
||||
if (proc_out)
|
||||
proc_read();
|
||||
if (!link_open())
|
||||
return;
|
||||
port_read();
|
||||
dmc_poll(app.s, now_ms());
|
||||
char buf[4096];
|
||||
int n;
|
||||
while ((n = dmc_output(app.s, buf, sizeof(buf))) > 0) {
|
||||
if (port_out_n + n > (int)sizeof(port_out))
|
||||
n = (int)sizeof(port_out) - port_out_n;
|
||||
memcpy(port_out + port_out_n, buf, n);
|
||||
port_out_n += n;
|
||||
}
|
||||
port_write();
|
||||
while ((n = dmc_terminal(app.s, buf, sizeof(buf))) > 0)
|
||||
term_feed(buf, n);
|
||||
dmc_event ev;
|
||||
while (dmc_next_event(app.s, &ev)) {
|
||||
if (ev.type != DMC_EV_RESPONSE) {
|
||||
app_event(&ev);
|
||||
continue;
|
||||
}
|
||||
Waiting **p = &waiting;
|
||||
while (*p && (*p)->tag != ev.tag)
|
||||
p = &(*p)->next;
|
||||
if (*p) {
|
||||
Waiting *w = *p;
|
||||
*p = w->next;
|
||||
if (w->fn)
|
||||
w->fn(&ev, w->data);
|
||||
free(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void link_type(const char *data, int n)
|
||||
{
|
||||
if (!link_open())
|
||||
return;
|
||||
dmc_type(app.s, data, n);
|
||||
link_pump();
|
||||
}
|
||||
|
||||
int link_command(const char *cmd, int flags, ResponseFn fn, void *data)
|
||||
{
|
||||
int tag = dmc_command(app.s, cmd, flags, 0);
|
||||
if (tag > 0) {
|
||||
Waiting *w = (Waiting *)calloc(1, sizeof(Waiting));
|
||||
w->tag = tag;
|
||||
w->fn = fn;
|
||||
w->data = data;
|
||||
w->next = waiting;
|
||||
waiting = w;
|
||||
link_pump();
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* main.cpp - the main window: a tab for each page (Modem, Terminal,
|
||||
* Settings, Call Stats, Log, as the macOS and Linux apps
|
||||
* have them) and a status bar
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
#include "resource.h"
|
||||
|
||||
App app;
|
||||
|
||||
static HWND status_bar;
|
||||
|
||||
enum { PAGE_MODEM, PAGE_TERM, PAGE_SETTINGS, PAGE_STATS, PAGE_LOG, PAGES };
|
||||
static const char *const page_names[PAGES] = {
|
||||
"Modem", "Terminal", "Settings", "Call Stats", "Log"
|
||||
};
|
||||
|
||||
HWND make_child(const char *cls, const char *text, DWORD style, HWND parent,
|
||||
int id, DWORD ex)
|
||||
{
|
||||
HWND w = CreateWindowEx(ex, cls, text, WS_CHILD | WS_VISIBLE | style,
|
||||
0, 0, 10, 10, parent, (HMENU)(INT_PTR)id,
|
||||
app.inst, NULL);
|
||||
SendMessage(w, WM_SETFONT, (WPARAM)app.font, TRUE);
|
||||
return w;
|
||||
}
|
||||
|
||||
int utf8_encode(unsigned long c, char *o)
|
||||
{
|
||||
if (c < 0x80) {
|
||||
o[0] = (char)c;
|
||||
return 1;
|
||||
}
|
||||
if (c < 0x800) {
|
||||
o[0] = (char)(0xC0 | (c >> 6));
|
||||
o[1] = (char)(0x80 | (c & 0x3F));
|
||||
return 2;
|
||||
}
|
||||
if (c < 0x10000) {
|
||||
o[0] = (char)(0xE0 | (c >> 12));
|
||||
o[1] = (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
o[2] = (char)(0x80 | (c & 0x3F));
|
||||
return 3;
|
||||
}
|
||||
o[0] = (char)(0xF0 | (c >> 18));
|
||||
o[1] = (char)(0x80 | ((c >> 12) & 0x3F));
|
||||
o[2] = (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
o[3] = (char)(0x80 | (c & 0x3F));
|
||||
return 4;
|
||||
}
|
||||
|
||||
/* (by hand: Windows 95 has no CP_UTF8) */
|
||||
void to_ansi(const char *s, char *out, int n)
|
||||
{
|
||||
int o = 0;
|
||||
const unsigned char *p = (const unsigned char *)s;
|
||||
while (*p && o + 2 < n) {
|
||||
unsigned long c = *p++;
|
||||
int more = 0;
|
||||
if (c >= 0xF0) {
|
||||
c &= 0x07;
|
||||
more = 3;
|
||||
} else if (c >= 0xE0) {
|
||||
c &= 0x0F;
|
||||
more = 2;
|
||||
} else if (c >= 0xC0) {
|
||||
c &= 0x1F;
|
||||
more = 1;
|
||||
}
|
||||
while (more-- && (*p & 0xC0) == 0x80)
|
||||
c = (c << 6) | (*p++ & 0x3F);
|
||||
if (c < 0x80) {
|
||||
out[o++] = (char)c;
|
||||
continue;
|
||||
}
|
||||
WCHAR w = c < 0x10000 ? (WCHAR)c : (WCHAR)'?';
|
||||
char mb[8];
|
||||
BOOL lossy = FALSE;
|
||||
int k = WideCharToMultiByte(CP_ACP, 0, &w, 1, mb, sizeof(mb),
|
||||
NULL, &lossy);
|
||||
if (k <= 0 || lossy) {
|
||||
out[o++] = '?';
|
||||
continue;
|
||||
}
|
||||
for (int i = 0; i < k && o + 1 < n; i++)
|
||||
out[o++] = mb[i];
|
||||
}
|
||||
out[o] = '\0';
|
||||
}
|
||||
|
||||
void app_message(const char *text)
|
||||
{
|
||||
char a[512];
|
||||
to_ansi(text, a, sizeof(a));
|
||||
SendMessage(status_bar, SB_SETTEXT, 0, (LPARAM)a);
|
||||
}
|
||||
|
||||
void app_log(const char *line)
|
||||
{
|
||||
log_append(line);
|
||||
}
|
||||
|
||||
void app_state()
|
||||
{
|
||||
char t[160];
|
||||
int st = dmc_state(app.s);
|
||||
if (link_running() && st == DMC_CLOSED)
|
||||
strcpy(t, "Starting");
|
||||
else
|
||||
_snprintf(t, sizeof(t), "%s", dmc_state_name(st));
|
||||
t[sizeof(t) - 1] = '\0';
|
||||
SendMessage(status_bar, SB_SETTEXT, 1, (LPARAM)t);
|
||||
modem_page_state();
|
||||
term_state();
|
||||
settings_state();
|
||||
}
|
||||
|
||||
void app_opened()
|
||||
{
|
||||
app_state();
|
||||
settings_load();
|
||||
stats_refresh();
|
||||
}
|
||||
|
||||
void app_closed()
|
||||
{
|
||||
settings_clear();
|
||||
app_state();
|
||||
}
|
||||
|
||||
void app_event(const dmc_event *ev)
|
||||
{
|
||||
switch (ev->type) {
|
||||
case DMC_EV_STATE: {
|
||||
int was = app.last_state;
|
||||
app.last_state = ev->state;
|
||||
app_state();
|
||||
if (ev->state == DMC_IDLE &&
|
||||
(was == DMC_ONLINE || was == DMC_ONLINE_COMMAND ||
|
||||
was == DMC_HANGING_UP || was == DMC_DIALING ||
|
||||
was == DMC_ANSWERING))
|
||||
stats_refresh();
|
||||
if (ev->state == DMC_IDLE && was == DMC_CONFIGURATOR)
|
||||
settings_load();
|
||||
break;
|
||||
}
|
||||
case DMC_EV_RESULT:
|
||||
if (!strcmp(ev->result, "RING")) {
|
||||
app_message("Ringing");
|
||||
if (GetForegroundWindow() != app.main)
|
||||
FlashWindow(app.main, TRUE);
|
||||
} else if (ev->result[0]) {
|
||||
app_message(ev->result);
|
||||
}
|
||||
break;
|
||||
case DMC_EV_CALLER:
|
||||
app_state();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void show_page(int i)
|
||||
{
|
||||
for (int p = 0; p < PAGES; p++)
|
||||
ShowWindow(app.pages[p], p == i ? SW_SHOW : SW_HIDE);
|
||||
if (i == PAGE_TERM)
|
||||
SetFocus(GetWindow(app.pages[i], GW_CHILD));
|
||||
}
|
||||
|
||||
static void layout()
|
||||
{
|
||||
RECT r;
|
||||
GetClientRect(app.main, &r);
|
||||
SendMessage(status_bar, WM_SIZE, 0, 0);
|
||||
RECT sb;
|
||||
GetWindowRect(status_bar, &sb);
|
||||
int sbh = sb.bottom - sb.top;
|
||||
int parts[2] = { r.right - 200, -1 };
|
||||
SendMessage(status_bar, SB_SETPARTS, 2, (LPARAM)parts);
|
||||
MoveWindow(app.tabs, 4, 4, r.right - 8, r.bottom - sbh - 8, TRUE);
|
||||
RECT in = { 0, 0, r.right - 8, r.bottom - sbh - 8 };
|
||||
TabCtrl_AdjustRect(app.tabs, FALSE, &in);
|
||||
int x = in.left + 4, y = in.top + 4;
|
||||
int w = in.right - in.left, h = in.bottom - in.top;
|
||||
for (int p = 0; p < PAGES; p++)
|
||||
MoveWindow(app.pages[p], x, y, w, h, TRUE);
|
||||
modem_page_layout(app.pages[PAGE_MODEM], w, h);
|
||||
term_page_layout(app.pages[PAGE_TERM], 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);
|
||||
}
|
||||
|
||||
static void about()
|
||||
{
|
||||
MessageBox(app.main,
|
||||
"D-Modem 1.0.0\r\n\r\n"
|
||||
"The front panel of D-Modem, the open V.92 softmodem.\r\n"
|
||||
"https://github.com/D-Modem/gui\r\n\r\n"
|
||||
"Copyright (c) 2026, D-Modem. BSD 3-Clause License.",
|
||||
"About D-Modem", MB_OK | MB_ICONINFORMATION);
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
switch (m) {
|
||||
case WM_CREATE: {
|
||||
app.main = w;
|
||||
status_bar = CreateStatusWindow(WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP,
|
||||
"", w, IDC_STATUS);
|
||||
app.tabs = make_child(WC_TABCONTROL, "", WS_CLIPSIBLINGS, w,
|
||||
IDC_TABS);
|
||||
for (int p = 0; p < PAGES; p++) {
|
||||
TCITEM it;
|
||||
memset(&it, 0, sizeof(it));
|
||||
it.mask = TCIF_TEXT;
|
||||
it.pszText = (char *)page_names[p];
|
||||
TabCtrl_InsertItem(app.tabs, p, &it);
|
||||
}
|
||||
app.pages[PAGE_MODEM] = modem_page_new(w);
|
||||
app.pages[PAGE_TERM] = term_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);
|
||||
for (int p = 0; p < PAGES; p++)
|
||||
SetWindowPos(app.pages[p], HWND_TOP, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE);
|
||||
show_page(PAGE_MODEM);
|
||||
SetTimer(w, TIMER_PUMP, 50, NULL);
|
||||
app_state();
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE:
|
||||
layout();
|
||||
return 0;
|
||||
case WM_GETMINMAXINFO: {
|
||||
MINMAXINFO *mm = (MINMAXINFO *)lp;
|
||||
mm->ptMinTrackSize.x = 560;
|
||||
mm->ptMinTrackSize.y = 420;
|
||||
return 0;
|
||||
}
|
||||
case WM_NOTIFY: {
|
||||
NMHDR *n = (NMHDR *)lp;
|
||||
if (n->hwndFrom == app.tabs && n->code == TCN_SELCHANGE)
|
||||
show_page(TabCtrl_GetCurSel(app.tabs));
|
||||
break;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
switch (LOWORD(wp)) {
|
||||
case IDM_LINE:
|
||||
if (line_dialog(w, &app.cfg)) {
|
||||
config_save(&app.cfg);
|
||||
app_state();
|
||||
}
|
||||
return 0;
|
||||
case IDM_START:
|
||||
if (link_running())
|
||||
link_stop();
|
||||
else
|
||||
link_start();
|
||||
return 0;
|
||||
case IDM_EXIT:
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
case IDM_ABOUT:
|
||||
about();
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_TIMER:
|
||||
if (wp == TIMER_PUMP)
|
||||
link_pump();
|
||||
return 0;
|
||||
case WM_APP_SOCKET:
|
||||
link_socket(wp, lp);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
KillTimer(w, TIMER_PUMP);
|
||||
if (link_running())
|
||||
link_stop();
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProc(w, m, wp, lp);
|
||||
}
|
||||
|
||||
static HFONT font(const char *face, int points, int weight)
|
||||
{
|
||||
HDC dc = GetDC(NULL);
|
||||
int h = -MulDiv(points, GetDeviceCaps(dc, LOGPIXELSY), 72);
|
||||
ReleaseDC(NULL, dc);
|
||||
return CreateFont(h, 0, 0, 0, weight, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
|
||||
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
|
||||
FIXED_PITCH | FF_MODERN, face);
|
||||
}
|
||||
|
||||
int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmd, int show)
|
||||
{
|
||||
(void)prev;
|
||||
(void)cmd;
|
||||
app.inst = inst;
|
||||
InitCommonControls();
|
||||
WSADATA wsa;
|
||||
WSAStartup(MAKEWORD(1, 1), &wsa);
|
||||
|
||||
/* the system's dialog font (MS Sans Serif on 9x, Tahoma or Segoe
|
||||
UI later), bold and large versions of it, and a terminal font */
|
||||
NONCLIENTMETRICS ncm;
|
||||
memset(&ncm, 0, sizeof(ncm));
|
||||
ncm.cbSize = sizeof(ncm);
|
||||
if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0))
|
||||
app.font = CreateFontIndirect(&ncm.lfMessageFont);
|
||||
else
|
||||
app.font = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
|
||||
LOGFONT lf;
|
||||
GetObject(app.font, sizeof(lf), &lf);
|
||||
lf.lfWeight = FW_BOLD;
|
||||
app.bold_font = CreateFontIndirect(&lf);
|
||||
lf.lfHeight = lf.lfHeight * 2;
|
||||
app.big_font = CreateFontIndirect(&lf);
|
||||
app.mono_font = font("Lucida Console", 10, FW_NORMAL);
|
||||
if (!app.mono_font)
|
||||
app.mono_font = font("Courier New", 10, FW_NORMAL);
|
||||
|
||||
config_load(&app.cfg);
|
||||
app.s = dmc_session_new();
|
||||
|
||||
WNDCLASS wc;
|
||||
memset(&wc, 0, sizeof(wc));
|
||||
wc.lpfnWndProc = main_proc;
|
||||
wc.hInstance = inst;
|
||||
wc.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_APP));
|
||||
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
|
||||
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
|
||||
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU);
|
||||
wc.lpszClassName = "DModemMain";
|
||||
if (!RegisterClass(&wc))
|
||||
return 1;
|
||||
HWND w = CreateWindowEx(0, "DModemMain", "D-Modem",
|
||||
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, 720, 560, NULL,
|
||||
NULL, inst, NULL);
|
||||
if (!w)
|
||||
return 1;
|
||||
ShowWindow(w, show);
|
||||
UpdateWindow(w);
|
||||
/* a modem that is set up starts at once */
|
||||
if (app.cfg.line != LINE_DMODEMD || app.cfg.sip_user[0] ||
|
||||
app.cfg.usb[0])
|
||||
link_start();
|
||||
|
||||
MSG msg;
|
||||
while (GetMessage(&msg, NULL, 0, 0) > 0) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
}
|
||||
dmc_session_free(app.s);
|
||||
WSACleanup();
|
||||
return (int)msg.wParam;
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* pages.cpp - the Modem, Call Stats and Log pages
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
#include "resource.h"
|
||||
|
||||
|
||||
static LRESULT CALLBACK page_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (m == WM_COMMAND) {
|
||||
CommandFn fn = (CommandFn)GetWindowLongPtr(w, GWLP_USERDATA);
|
||||
if (fn)
|
||||
fn(w, LOWORD(wp), HIWORD(wp));
|
||||
return 0;
|
||||
}
|
||||
if (m == WM_NOTIFY || m == WM_CTLCOLORSTATIC || m == WM_DRAWITEM)
|
||||
return SendMessage(GetParent(w), m, wp, lp);
|
||||
return DefWindowProc(w, m, wp, lp);
|
||||
}
|
||||
|
||||
HWND page_new(HWND parent, CommandFn fn)
|
||||
{
|
||||
static bool registered;
|
||||
if (!registered) {
|
||||
WNDCLASS wc;
|
||||
memset(&wc, 0, sizeof(wc));
|
||||
wc.lpfnWndProc = page_proc;
|
||||
wc.hInstance = app.inst;
|
||||
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
|
||||
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
|
||||
wc.lpszClassName = "DModemPage";
|
||||
RegisterClass(&wc);
|
||||
registered = true;
|
||||
}
|
||||
/* (no WS_CLIPCHILDREN: a group box paints only its frame, so the
|
||||
page paints behind it) */
|
||||
HWND w = CreateWindowEx(WS_EX_CONTROLPARENT, "DModemPage", "",
|
||||
WS_CHILD, 0, 0, 10, 10, parent,
|
||||
NULL, app.inst, NULL);
|
||||
SetWindowLongPtr(w, GWLP_USERDATA, (LONG_PTR)fn);
|
||||
return w;
|
||||
}
|
||||
|
||||
static void set_text(HWND page, int id, const char *utf8)
|
||||
{
|
||||
char a[512];
|
||||
to_ansi(utf8, a, sizeof(a));
|
||||
SetDlgItemText(page, id, a);
|
||||
}
|
||||
|
||||
/*
|
||||
* the Modem page
|
||||
*/
|
||||
|
||||
static HWND modem;
|
||||
|
||||
void modem_page_state()
|
||||
{
|
||||
if (!modem)
|
||||
return;
|
||||
int st = dmc_state(app.s);
|
||||
bool running = link_running();
|
||||
set_text(modem, IDC_STATE, running && st == DMC_CLOSED ? "Starting" :
|
||||
dmc_state_name(st));
|
||||
char d[400];
|
||||
if (st == DMC_ONLINE || st == DMC_ONLINE_COMMAND || st == DMC_HANGING_UP)
|
||||
_snprintf(d, sizeof(d), "%s", dmc_connect_text(app.s));
|
||||
else if (st == DMC_RINGING && dmc_caller_number(app.s)[0])
|
||||
_snprintf(d, sizeof(d), "%s %s", dmc_caller_number(app.s),
|
||||
dmc_caller_name(app.s));
|
||||
else
|
||||
d[0] = '\0';
|
||||
d[sizeof(d) - 1] = '\0';
|
||||
set_text(modem, IDC_DETAIL, d);
|
||||
char sum[400];
|
||||
config_summary(&app.cfg, sum, sizeof(sum));
|
||||
set_text(modem, IDC_SUMMARY, sum);
|
||||
char dev[300];
|
||||
_snprintf(dev, sizeof(dev), "Device: %s", link_open() ? app.device :
|
||||
"not connected");
|
||||
dev[sizeof(dev) - 1] = '\0';
|
||||
set_text(modem, IDC_DEVICE, dev);
|
||||
SetDlgItemText(modem, IDC_RUN, running ? "&Stop" : "&Start");
|
||||
bool open = st != DMC_CLOSED;
|
||||
EnableWindow(GetDlgItem(modem, IDC_NUMBER), open);
|
||||
EnableWindow(GetDlgItem(modem, IDC_DIAL), st == DMC_IDLE);
|
||||
EnableWindow(GetDlgItem(modem, IDC_ANSWER), st == DMC_RINGING);
|
||||
EnableWindow(GetDlgItem(modem, IDC_HANGUP),
|
||||
st == DMC_DIALING || st == DMC_ANSWERING ||
|
||||
st == DMC_ONLINE || st == DMC_ONLINE_COMMAND ||
|
||||
st == DMC_RINGING);
|
||||
}
|
||||
|
||||
static void dialled(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
app_message(ev->result);
|
||||
}
|
||||
|
||||
static void modem_command(HWND page, int id, int code)
|
||||
{
|
||||
(void)code;
|
||||
switch (id) {
|
||||
case IDC_DIAL: {
|
||||
char n[128], cmd[140];
|
||||
GetDlgItemText(page, IDC_NUMBER, n, sizeof(n));
|
||||
if (!n[0]) {
|
||||
app_message("Enter a number to dial");
|
||||
return;
|
||||
}
|
||||
_snprintf(cmd, sizeof(cmd), "ATD%s", n);
|
||||
cmd[sizeof(cmd) - 1] = '\0';
|
||||
link_command(cmd, 0, dialled, NULL);
|
||||
break;
|
||||
}
|
||||
case IDC_ANSWER:
|
||||
link_command("ATA", 0, dialled, NULL);
|
||||
break;
|
||||
case IDC_HANGUP:
|
||||
dmc_hangup(app.s);
|
||||
link_pump();
|
||||
break;
|
||||
case IDC_RUN:
|
||||
SendMessage(app.main, WM_COMMAND, IDM_START, 0);
|
||||
break;
|
||||
case IDC_LINEBTN:
|
||||
SendMessage(app.main, WM_COMMAND, IDM_LINE, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
HWND modem_page_new(HWND parent)
|
||||
{
|
||||
modem = page_new(parent, modem_command);
|
||||
HWND st = make_child("STATIC", "Not connected", SS_LEFT, modem, IDC_STATE);
|
||||
SendMessage(st, WM_SETFONT, (WPARAM)app.big_font, TRUE);
|
||||
make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, modem, IDC_DETAIL);
|
||||
make_child("BUTTON", "Call", BS_GROUPBOX, modem, IDC_CALLBOX);
|
||||
make_child("STATIC", "&Number:", SS_LEFT, modem, IDC_NUMLABEL);
|
||||
make_child("EDIT", "", WS_TABSTOP | ES_AUTOHSCROLL, modem, IDC_NUMBER,
|
||||
WS_EX_CLIENTEDGE);
|
||||
make_child("BUTTON", "&Dial", WS_TABSTOP | BS_DEFPUSHBUTTON, modem,
|
||||
IDC_DIAL);
|
||||
make_child("BUTTON", "&Answer", WS_TABSTOP, modem, IDC_ANSWER);
|
||||
make_child("BUTTON", "&Hang Up", WS_TABSTOP, modem, IDC_HANGUP);
|
||||
make_child("BUTTON", "Modem", BS_GROUPBOX, modem, IDC_MODEMBOX);
|
||||
make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, modem, IDC_SUMMARY);
|
||||
make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, modem, IDC_DEVICE);
|
||||
make_child("BUTTON", "&Start", WS_TABSTOP, modem, IDC_RUN);
|
||||
make_child("BUTTON", "&Line Settings...", WS_TABSTOP, modem,
|
||||
IDC_LINEBTN);
|
||||
return modem;
|
||||
}
|
||||
|
||||
static void place(HWND page, int id, int x, int y, int w, int h)
|
||||
{
|
||||
MoveWindow(GetDlgItem(page, id), x, y, w, h, TRUE);
|
||||
}
|
||||
|
||||
void modem_page_layout(HWND page, int w, int h)
|
||||
{
|
||||
(void)h;
|
||||
int m = 12, bw = 90, bh = 24, x = m, y = m;
|
||||
int inner = w - 2 * m;
|
||||
if (inner > 560)
|
||||
inner = 560;
|
||||
place(page, IDC_STATE, x, y, inner, 40);
|
||||
y += 44;
|
||||
place(page, IDC_DETAIL, x, y, inner, 20);
|
||||
y += 32;
|
||||
place(page, IDC_CALLBOX, x, y, inner, 96);
|
||||
place(page, IDC_NUMLABEL, x + 12, y + 28, 60, 20);
|
||||
place(page, IDC_NUMBER, x + 76, y + 24, inner - 76 - bw - 24, bh);
|
||||
place(page, IDC_DIAL, x + inner - bw - 12, y + 24, bw, bh);
|
||||
place(page, IDC_ANSWER, x + inner - 2 * bw - 18, y + 60, bw, bh);
|
||||
place(page, IDC_HANGUP, x + inner - bw - 12, y + 60, bw, bh);
|
||||
y += 108;
|
||||
place(page, IDC_MODEMBOX, x, y, inner, 104);
|
||||
place(page, IDC_SUMMARY, x + 12, y + 24, inner - bw - 36, 20);
|
||||
place(page, IDC_DEVICE, x + 12, y + 48, inner - bw - 36, 20);
|
||||
place(page, IDC_RUN, x + inner - bw - 12, y + 22, bw, bh);
|
||||
place(page, IDC_LINEBTN, x + inner - 130 - 12, y + 66, 130, bh);
|
||||
}
|
||||
|
||||
/*
|
||||
* the Call Stats page
|
||||
*/
|
||||
|
||||
static HWND stats;
|
||||
|
||||
static void got_report(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
/* the edit control wants CR LF */
|
||||
char a[4096], b[8192];
|
||||
to_ansi(ev->ok ? ev->text : "", a, sizeof(a));
|
||||
int o = 0;
|
||||
for (int i = 0; a[i] && o + 2 < (int)sizeof(b); i++) {
|
||||
if (a[i] == '\n')
|
||||
b[o++] = '\r';
|
||||
b[o++] = a[i];
|
||||
}
|
||||
b[o] = '\0';
|
||||
SetDlgItemText(stats, IDC_REPORT, b);
|
||||
}
|
||||
|
||||
static void got_diag(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
HWND lv = GetDlgItem(stats, IDC_STATS);
|
||||
ListView_DeleteAllItems(lv);
|
||||
dmc_diag *d = dmc_diag_parse(ev->ok ? ev->text : "");
|
||||
if (!dmc_diag_has_call(d)) {
|
||||
LVITEM it;
|
||||
memset(&it, 0, sizeof(it));
|
||||
it.mask = LVIF_TEXT;
|
||||
it.pszText = (char *)"No call yet";
|
||||
ListView_InsertItem(lv, &it);
|
||||
}
|
||||
for (int i = 0, row = 0; dmc_diag_has_call(d) && i < dmc_diag_count(d);
|
||||
i++) {
|
||||
if (dmc_diag_key(d, i) == 0)
|
||||
continue;
|
||||
char label[128], value[256];
|
||||
to_ansi(dmc_diag_label(d, i), label, sizeof(label));
|
||||
to_ansi(dmc_diag_value(d, i), value, sizeof(value));
|
||||
LVITEM it;
|
||||
memset(&it, 0, sizeof(it));
|
||||
it.mask = LVIF_TEXT;
|
||||
it.iItem = row;
|
||||
it.pszText = label;
|
||||
ListView_InsertItem(lv, &it);
|
||||
ListView_SetItemText(lv, row, 1, value);
|
||||
row++;
|
||||
}
|
||||
dmc_diag_free(d);
|
||||
}
|
||||
|
||||
void stats_refresh()
|
||||
{
|
||||
int st = dmc_state(app.s);
|
||||
if (st == DMC_CLOSED || st == DMC_ONLINE)
|
||||
return;
|
||||
link_command("AT#UD", DMC_QUIET, got_diag, NULL);
|
||||
link_command("ATI11", DMC_QUIET, got_report, NULL);
|
||||
}
|
||||
|
||||
static void stats_command(HWND page, int id, int code)
|
||||
{
|
||||
(void)page;
|
||||
(void)code;
|
||||
if (id == IDC_REFRESH)
|
||||
stats_refresh();
|
||||
}
|
||||
|
||||
HWND stats_page_new(HWND parent)
|
||||
{
|
||||
stats = page_new(parent, stats_command);
|
||||
HWND lv = make_child(WC_LISTVIEW, "", WS_TABSTOP | LVS_REPORT |
|
||||
LVS_SINGLESEL | LVS_NOSORTHEADER, stats, IDC_STATS,
|
||||
WS_EX_CLIENTEDGE);
|
||||
ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
|
||||
LVCOLUMN c;
|
||||
memset(&c, 0, sizeof(c));
|
||||
c.mask = LVCF_TEXT | LVCF_WIDTH;
|
||||
c.pszText = (char *)"Last call";
|
||||
c.cx = 200;
|
||||
ListView_InsertColumn(lv, 0, &c);
|
||||
c.pszText = (char *)"Value";
|
||||
c.cx = 220;
|
||||
ListView_InsertColumn(lv, 1, &c);
|
||||
HWND r = make_child("EDIT", "", WS_TABSTOP | WS_VSCROLL | ES_MULTILINE |
|
||||
ES_READONLY | ES_AUTOVSCROLL, stats, IDC_REPORT,
|
||||
WS_EX_CLIENTEDGE);
|
||||
SendMessage(r, WM_SETFONT, (WPARAM)app.mono_font, TRUE);
|
||||
make_child("BUTTON", "&Refresh", WS_TABSTOP, stats, IDC_REFRESH);
|
||||
return stats;
|
||||
}
|
||||
|
||||
void stats_page_layout(HWND page, int w, int h)
|
||||
{
|
||||
int m = 8, bh = 24;
|
||||
int lvw = (w - 3 * m) / 2;
|
||||
place(page, IDC_STATS, m, m, lvw, h - 3 * m - bh);
|
||||
place(page, IDC_REPORT, 2 * m + lvw, m, w - 3 * m - lvw, h - 3 * m - bh);
|
||||
place(page, IDC_REFRESH, m, h - m - bh, 90, bh);
|
||||
}
|
||||
|
||||
/*
|
||||
* the Log page
|
||||
*/
|
||||
|
||||
static HWND logp;
|
||||
|
||||
void log_append(const char *line)
|
||||
{
|
||||
if (!logp)
|
||||
return;
|
||||
HWND e = GetDlgItem(logp, IDC_LOG);
|
||||
char a[1100];
|
||||
to_ansi(line, a, sizeof(a) - 2);
|
||||
strcat(a, "\r\n");
|
||||
/* (Windows 9x's edit controls hold 64K) */
|
||||
int n = GetWindowTextLength(e);
|
||||
if (n > 48000) {
|
||||
SendMessage(e, EM_SETSEL, 0, 16000);
|
||||
SendMessage(e, EM_REPLACESEL, FALSE, (LPARAM)"");
|
||||
n = GetWindowTextLength(e);
|
||||
}
|
||||
SendMessage(e, EM_SETSEL, n, n);
|
||||
SendMessage(e, EM_REPLACESEL, FALSE, (LPARAM)a);
|
||||
}
|
||||
|
||||
static void log_command(HWND page, int id, int code)
|
||||
{
|
||||
(void)page;
|
||||
(void)id;
|
||||
(void)code;
|
||||
}
|
||||
|
||||
HWND log_page_new(HWND parent)
|
||||
{
|
||||
logp = page_new(parent, log_command);
|
||||
HWND e = make_child("EDIT", "", WS_VSCROLL | WS_HSCROLL | ES_MULTILINE |
|
||||
ES_READONLY | ES_AUTOVSCROLL | ES_AUTOHSCROLL, logp,
|
||||
IDC_LOG, WS_EX_CLIENTEDGE);
|
||||
SendMessage(e, WM_SETFONT, (WPARAM)app.mono_font, TRUE);
|
||||
SendMessage(e, EM_LIMITTEXT, 60000, 0);
|
||||
return logp;
|
||||
}
|
||||
|
||||
void log_page_layout(HWND page, int w, int h)
|
||||
{
|
||||
place(page, IDC_LOG, 8, 8, w - 16, h - 16);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* resource.h - the Windows app's resource and control ids
|
||||
*/
|
||||
#ifndef DMODEM_WIN_RESOURCE_H
|
||||
#define DMODEM_WIN_RESOURCE_H
|
||||
|
||||
#define IDI_APP 1
|
||||
#define IDR_MENU 100
|
||||
|
||||
#define IDM_LINE 200
|
||||
#define IDM_START 201
|
||||
#define IDM_EXIT 202
|
||||
#define IDM_ABOUT 203
|
||||
|
||||
#define IDC_STATUS 300
|
||||
#define IDC_TABS 301
|
||||
|
||||
/* the Modem page */
|
||||
#define IDC_STATE 400
|
||||
#define IDC_DETAIL 401
|
||||
#define IDC_NUMBER 402
|
||||
#define IDC_DIAL 403
|
||||
#define IDC_ANSWER 404
|
||||
#define IDC_HANGUP 405
|
||||
#define IDC_RUN 406
|
||||
#define IDC_SUMMARY 407
|
||||
#define IDC_DEVICE 408
|
||||
#define IDC_LINEBTN 409
|
||||
#define IDC_CALLBOX 410
|
||||
#define IDC_MODEMBOX 411
|
||||
#define IDC_NUMLABEL 412
|
||||
|
||||
/* the Terminal page */
|
||||
#define IDC_TERM 500
|
||||
#define IDC_SETUP_CF 501
|
||||
#define IDC_SETUP_CT 502
|
||||
#define IDC_CLEAR 503
|
||||
|
||||
/* the Settings page */
|
||||
#define IDC_GROUPS 600
|
||||
#define IDC_SETTINGS 601
|
||||
#define IDC_SETTING_HELP 602
|
||||
#define IDC_RELOAD 603
|
||||
#define IDC_DEFAULTS 604
|
||||
#define IDC_INIT 605
|
||||
#define IDC_KEEP 606
|
||||
#define IDC_CHANGE 607
|
||||
|
||||
/* the Call Stats page */
|
||||
#define IDC_STATS 700
|
||||
#define IDC_REPORT 701
|
||||
#define IDC_REFRESH 702
|
||||
|
||||
/* the Log page */
|
||||
#define IDC_LOG 800
|
||||
|
||||
/* the Line Settings dialog */
|
||||
#define IDD_LINE 900
|
||||
#define IDC_L_DMODEMD 901
|
||||
#define IDC_L_TCP 902
|
||||
#define IDC_L_COM 903
|
||||
#define IDC_L_USER 904
|
||||
#define IDC_L_PASSWORD 905
|
||||
#define IDC_L_SERVER 906
|
||||
#define IDC_L_LISTEN 907
|
||||
#define IDC_L_T38 908
|
||||
#define IDC_L_V152 909
|
||||
#define IDC_L_V150 910
|
||||
#define IDC_L_COUNTRY 911
|
||||
#define IDC_L_USB 912
|
||||
#define IDC_L_PATH 913
|
||||
#define IDC_L_BROWSE 914
|
||||
#define IDC_L_ADDRESS 915
|
||||
#define IDC_L_PORT 916
|
||||
#define IDC_L_INIT 917
|
||||
|
||||
/* the Change Setting dialog */
|
||||
#define IDD_SETTING 950
|
||||
#define IDC_S_LABEL 951
|
||||
#define IDC_S_HELP 952
|
||||
#define IDC_S_LIST 953
|
||||
#define IDC_S_EDIT 954
|
||||
#define IDC_S_RANGE 955
|
||||
#define IDC_S_DEFAULT 956
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,426 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* settings.cpp - the Settings page: the modem's settings (AT!M), its
|
||||
* groups on the left and their settings on the right;
|
||||
* Change (or a double click) opens a dialog for the
|
||||
* value, which the modem takes at once
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
#include "resource.h"
|
||||
|
||||
static HWND page;
|
||||
static dmc_model *model;
|
||||
static int group = -1;
|
||||
static int gen; /* a new model: older answers ignored */
|
||||
static char init_string[512];
|
||||
|
||||
/* the settings of the group shown, by row */
|
||||
static int rows[256], n_rows;
|
||||
|
||||
static void set_ansi(HWND w, const char *utf8)
|
||||
{
|
||||
char a[1024];
|
||||
to_ansi(utf8, a, sizeof(a));
|
||||
SetWindowText(w, a);
|
||||
}
|
||||
|
||||
/* a setting's value as people read it */
|
||||
static void shown(int i, const char *v, char *out, int n)
|
||||
{
|
||||
int c = dmc_setting_kind(model, i) == DMC_PICK ?
|
||||
dmc_setting_choice_of(model, i, v) : -1;
|
||||
to_ansi(c >= 0 ? dmc_choice_label(model, i, c) : v, out, n);
|
||||
}
|
||||
|
||||
static void fill_settings()
|
||||
{
|
||||
HWND lv = GetDlgItem(page, IDC_SETTINGS);
|
||||
SendMessage(lv, WM_SETREDRAW, FALSE, 0);
|
||||
ListView_DeleteAllItems(lv);
|
||||
n_rows = 0;
|
||||
const char *g = dmc_model_group(model, group);
|
||||
for (int i = 0; model && i < dmc_model_count(model) && n_rows < 256; i++) {
|
||||
if (strcmp(dmc_setting_group(model, i), g))
|
||||
continue;
|
||||
char label[160], value[160], def[160];
|
||||
to_ansi(dmc_setting_label(model, i), label, sizeof(label));
|
||||
shown(i, dmc_setting_value(model, i), value, sizeof(value));
|
||||
shown(i, dmc_setting_default(model, i), def, sizeof(def));
|
||||
/* a changed one marked, as the configurators mark them */
|
||||
if (strcmp(dmc_setting_value(model, i),
|
||||
dmc_setting_default(model, i))) {
|
||||
char t[170];
|
||||
_snprintf(t, sizeof(t), "* %s", label);
|
||||
t[sizeof(t) - 1] = '\0';
|
||||
strcpy(label, t);
|
||||
}
|
||||
LVITEM it;
|
||||
memset(&it, 0, sizeof(it));
|
||||
it.mask = LVIF_TEXT;
|
||||
it.iItem = n_rows;
|
||||
it.pszText = label;
|
||||
ListView_InsertItem(lv, &it);
|
||||
ListView_SetItemText(lv, n_rows, 1, value);
|
||||
ListView_SetItemText(lv, n_rows, 2, def);
|
||||
rows[n_rows++] = i;
|
||||
}
|
||||
SendMessage(lv, WM_SETREDRAW, TRUE, 0);
|
||||
InvalidateRect(lv, NULL, TRUE);
|
||||
SetDlgItemText(page, IDC_SETTING_HELP, "");
|
||||
}
|
||||
|
||||
static void fill_groups()
|
||||
{
|
||||
HWND lb = GetDlgItem(page, IDC_GROUPS);
|
||||
SendMessage(lb, LB_RESETCONTENT, 0, 0);
|
||||
for (int g = 0; model && g < dmc_model_groups(model); g++) {
|
||||
char a[128];
|
||||
to_ansi(dmc_model_group(model, g), a, sizeof(a));
|
||||
SendMessage(lb, LB_ADDSTRING, 0, (LPARAM)a);
|
||||
}
|
||||
if (group < 0 || group >= dmc_model_groups(model))
|
||||
group = 0;
|
||||
SendMessage(lb, LB_SETCURSEL, group, 0);
|
||||
fill_settings();
|
||||
}
|
||||
|
||||
void settings_clear()
|
||||
{
|
||||
dmc_model_free(model);
|
||||
model = NULL;
|
||||
gen++;
|
||||
if (!page)
|
||||
return;
|
||||
SendDlgItemMessage(page, IDC_GROUPS, LB_RESETCONTENT, 0, 0);
|
||||
ListView_DeleteAllItems(GetDlgItem(page, IDC_SETTINGS));
|
||||
SetDlgItemText(page, IDC_SETTING_HELP, "Start the modem to see its settings.");
|
||||
SetDlgItemText(page, IDC_INIT, "");
|
||||
}
|
||||
|
||||
static void got_init(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
return;
|
||||
/* AT!R's lines as one line of commands */
|
||||
init_string[0] = '\0';
|
||||
const char *p = ev->text;
|
||||
while (*p) {
|
||||
const char *e = strchr(p, '\n');
|
||||
int n = e ? (int)(e - p) : (int)strlen(p);
|
||||
char line[256];
|
||||
if (n > 255)
|
||||
n = 255;
|
||||
memcpy(line, p, n);
|
||||
line[n] = '\0';
|
||||
if (n > 2 && _stricmp(line, "AT")) {
|
||||
const char *cmds = init_string[0] ? line + 2 : line;
|
||||
if (strlen(init_string) + strlen(cmds) < sizeof(init_string))
|
||||
strcat(init_string, cmds);
|
||||
}
|
||||
p += e ? n + 1 : n;
|
||||
}
|
||||
SetDlgItemText(page, IDC_INIT, init_string[0] ? init_string :
|
||||
"AT (all at their defaults)");
|
||||
}
|
||||
|
||||
static void got_model(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
dmc_model *m = ev->ok ? dmc_model_parse(ev->text) : NULL;
|
||||
if (!m) {
|
||||
SetDlgItemText(page, IDC_SETTING_HELP, ev->ok ?
|
||||
"The modem's settings list was not readable." :
|
||||
"This modem does not list its settings (AT!M): "
|
||||
"update D-Modem, or use the Terminal's setup "
|
||||
"screen.");
|
||||
return;
|
||||
}
|
||||
dmc_model_free(model);
|
||||
model = m;
|
||||
gen++;
|
||||
fill_groups();
|
||||
link_command("AT!R", DMC_QUIET, got_init, NULL);
|
||||
settings_state();
|
||||
}
|
||||
|
||||
void settings_load()
|
||||
{
|
||||
if (dmc_state(app.s) == DMC_CLOSED)
|
||||
return;
|
||||
link_command("AT!M", DMC_QUIET, got_model, NULL);
|
||||
}
|
||||
|
||||
void settings_state()
|
||||
{
|
||||
if (!page)
|
||||
return;
|
||||
bool idle = dmc_state(app.s) == DMC_IDLE && model;
|
||||
EnableWindow(GetDlgItem(page, IDC_CHANGE), idle);
|
||||
EnableWindow(GetDlgItem(page, IDC_DEFAULTS), idle);
|
||||
EnableWindow(GetDlgItem(page, IDC_RELOAD),
|
||||
dmc_state(app.s) != DMC_CLOSED);
|
||||
}
|
||||
|
||||
/*
|
||||
* the Change dialog
|
||||
*/
|
||||
|
||||
struct Change {
|
||||
int gen, i;
|
||||
char value[256];
|
||||
};
|
||||
|
||||
static Change editing;
|
||||
|
||||
static void applied(const dmc_event *ev, void *data)
|
||||
{
|
||||
Change *c = (Change *)data;
|
||||
if (model && c->gen == gen) {
|
||||
if (ev->ok) {
|
||||
dmc_setting_set(model, c->i, c->value);
|
||||
/* the country sets others' defaults: all again */
|
||||
if (!strcmp(dmc_setting_key(model, c->i), "country"))
|
||||
settings_load();
|
||||
else
|
||||
fill_settings();
|
||||
link_command("AT!R", DMC_QUIET, got_init, NULL);
|
||||
} else {
|
||||
char m[200], l[160];
|
||||
to_ansi(dmc_setting_label(model, c->i), l, sizeof(l));
|
||||
_snprintf(m, sizeof(m), "The modem refused %s", l);
|
||||
m[sizeof(m) - 1] = '\0';
|
||||
app_message(m);
|
||||
}
|
||||
}
|
||||
free(c);
|
||||
}
|
||||
|
||||
static BOOL CALLBACK change_proc(HWND d, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
(void)lp;
|
||||
int i = editing.i;
|
||||
switch (m) {
|
||||
case WM_INITDIALOG: {
|
||||
set_ansi(GetDlgItem(d, IDC_S_LABEL), dmc_setting_label(model, i));
|
||||
set_ansi(GetDlgItem(d, IDC_S_HELP), dmc_setting_help(model, i));
|
||||
char def[200], t[220];
|
||||
shown(i, dmc_setting_default(model, i), def, sizeof(def));
|
||||
_snprintf(t, sizeof(t), "Default: %s", def);
|
||||
t[sizeof(t) - 1] = '\0';
|
||||
SetDlgItemText(d, IDC_S_DEFAULT, t);
|
||||
int kind = dmc_setting_kind(model, i);
|
||||
HWND list = GetDlgItem(d, IDC_S_LIST), edit = GetDlgItem(d, IDC_S_EDIT);
|
||||
ShowWindow(list, kind == DMC_PICK ? SW_SHOW : SW_HIDE);
|
||||
ShowWindow(edit, kind == DMC_PICK ? SW_HIDE : SW_SHOW);
|
||||
if (kind == DMC_PICK) {
|
||||
for (int c = 0; c < dmc_setting_choices(model, i); c++) {
|
||||
char a[160];
|
||||
to_ansi(dmc_choice_label(model, i, c), a, sizeof(a));
|
||||
SendMessage(list, CB_ADDSTRING, 0, (LPARAM)a);
|
||||
}
|
||||
SendMessage(list, CB_SETCURSEL,
|
||||
dmc_setting_choice_of(model, i,
|
||||
dmc_setting_value(model, i)), 0);
|
||||
} else {
|
||||
SetWindowText(edit, dmc_setting_value(model, i));
|
||||
if (kind == DMC_NUMBER) {
|
||||
_snprintf(t, sizeof(t), "From %ld to %ld",
|
||||
dmc_setting_lo(model, i),
|
||||
dmc_setting_hi(model, i));
|
||||
t[sizeof(t) - 1] = '\0';
|
||||
SetDlgItemText(d, IDC_S_RANGE, t);
|
||||
} else {
|
||||
SetDlgItemText(d, IDC_S_RANGE,
|
||||
"Numbers apart by commas");
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if (LOWORD(wp) == IDOK) {
|
||||
const char *v;
|
||||
char text[256];
|
||||
if (dmc_setting_kind(model, i) == DMC_PICK) {
|
||||
int c = (int)SendDlgItemMessage(d, IDC_S_LIST,
|
||||
CB_GETCURSEL, 0, 0);
|
||||
v = dmc_choice_value(model, i, c);
|
||||
} else {
|
||||
GetDlgItemText(d, IDC_S_EDIT, text, sizeof(text));
|
||||
v = text;
|
||||
}
|
||||
const char *why = dmc_setting_check(model, i, v);
|
||||
if (*why) {
|
||||
MessageBox(d, why, "D-Modem", MB_OK | MB_ICONWARNING);
|
||||
return TRUE;
|
||||
}
|
||||
strncpy(editing.value, v, sizeof(editing.value) - 1);
|
||||
editing.value[sizeof(editing.value) - 1] = '\0';
|
||||
EndDialog(d, IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if (LOWORD(wp) == IDCANCEL) {
|
||||
EndDialog(d, IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static void change_selected()
|
||||
{
|
||||
if (!model || dmc_state(app.s) != DMC_IDLE)
|
||||
return;
|
||||
int r = ListView_GetNextItem(GetDlgItem(page, IDC_SETTINGS), -1,
|
||||
LVNI_SELECTED);
|
||||
if (r < 0 || r >= n_rows)
|
||||
return;
|
||||
memset(&editing, 0, sizeof(editing));
|
||||
editing.gen = gen;
|
||||
editing.i = rows[r];
|
||||
if (DialogBox(app.inst, MAKEINTRESOURCE(IDD_SETTING), app.main,
|
||||
(DLGPROC)change_proc) != IDOK)
|
||||
return;
|
||||
if (!strcmp(editing.value, dmc_setting_value(model, editing.i)))
|
||||
return;
|
||||
Change *c = (Change *)malloc(sizeof(Change));
|
||||
*c = editing;
|
||||
if (link_command(dmc_setting_command(model, c->i, c->value), 0, applied,
|
||||
c) < 0) {
|
||||
app_message("The modem is busy");
|
||||
free(c);
|
||||
}
|
||||
}
|
||||
|
||||
static void reset_done(const dmc_event *ev, void *data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok)
|
||||
app_message("The modem refused ATZ");
|
||||
settings_load();
|
||||
}
|
||||
|
||||
static void settings_command(HWND p, int id, int code)
|
||||
{
|
||||
(void)p;
|
||||
switch (id) {
|
||||
case IDC_GROUPS:
|
||||
if (code == LBN_SELCHANGE) {
|
||||
group = (int)SendDlgItemMessage(page, IDC_GROUPS,
|
||||
LB_GETCURSEL, 0, 0);
|
||||
fill_settings();
|
||||
}
|
||||
break;
|
||||
case IDC_CHANGE:
|
||||
change_selected();
|
||||
break;
|
||||
case IDC_RELOAD:
|
||||
settings_load();
|
||||
break;
|
||||
case IDC_DEFAULTS:
|
||||
if (MessageBox(app.main, "Put every setting back to its default "
|
||||
"(ATZ)?", "D-Modem", MB_OKCANCEL |
|
||||
MB_ICONQUESTION) == IDOK)
|
||||
link_command("ATZ", 0, reset_done, NULL);
|
||||
break;
|
||||
case IDC_KEEP:
|
||||
strncpy(app.cfg.init, init_string, sizeof(app.cfg.init) - 1);
|
||||
app.cfg.init[sizeof(app.cfg.init) - 1] = '\0';
|
||||
config_save(&app.cfg);
|
||||
app_message(init_string[0] ? "The init string is sent each time "
|
||||
"the modem opens" : "Nothing to keep: every setting "
|
||||
"is at its default");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* the list's notifications come through the main window */
|
||||
static WNDPROC list_old;
|
||||
|
||||
static LRESULT CALLBACK list_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (m == WM_KEYDOWN && wp == VK_RETURN) {
|
||||
change_selected();
|
||||
return 0;
|
||||
}
|
||||
if (m == WM_LBUTTONDBLCLK) {
|
||||
CallWindowProc(list_old, w, WM_LBUTTONDOWN, wp, lp);
|
||||
change_selected();
|
||||
return 0;
|
||||
}
|
||||
if (m == WM_GETDLGCODE && lp) {
|
||||
MSG *msg = (MSG *)lp;
|
||||
if (msg->message == WM_KEYDOWN && msg->wParam == VK_RETURN)
|
||||
return DLGC_WANTMESSAGE;
|
||||
}
|
||||
LRESULT r = CallWindowProc(list_old, w, m, wp, lp);
|
||||
/* (the selection's help) */
|
||||
if (m == WM_LBUTTONDOWN || m == WM_KEYUP) {
|
||||
int row = ListView_GetNextItem(w, -1, LVNI_SELECTED);
|
||||
if (model && row >= 0 && row < n_rows)
|
||||
set_ansi(GetDlgItem(page, IDC_SETTING_HELP),
|
||||
dmc_setting_help(model, rows[row]));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
HWND settings_page_new(HWND parent)
|
||||
{
|
||||
page = page_new(parent, settings_command);
|
||||
make_child("LISTBOX", "", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY |
|
||||
LBS_NOINTEGRALHEIGHT, page, IDC_GROUPS, WS_EX_CLIENTEDGE);
|
||||
HWND lv = make_child(WC_LISTVIEW, "", WS_TABSTOP | LVS_REPORT |
|
||||
LVS_SINGLESEL | LVS_SHOWSELALWAYS |
|
||||
LVS_NOSORTHEADER, page, IDC_SETTINGS,
|
||||
WS_EX_CLIENTEDGE);
|
||||
ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
|
||||
LVCOLUMN c;
|
||||
memset(&c, 0, sizeof(c));
|
||||
c.mask = LVCF_TEXT | LVCF_WIDTH;
|
||||
c.pszText = (char *)"Setting";
|
||||
c.cx = 200;
|
||||
ListView_InsertColumn(lv, 0, &c);
|
||||
c.pszText = (char *)"Value";
|
||||
c.cx = 140;
|
||||
ListView_InsertColumn(lv, 1, &c);
|
||||
c.pszText = (char *)"Default";
|
||||
c.cx = 110;
|
||||
ListView_InsertColumn(lv, 2, &c);
|
||||
list_old = (WNDPROC)SetWindowLongPtr(lv, GWLP_WNDPROC,
|
||||
(LONG_PTR)list_proc);
|
||||
make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, page, IDC_SETTING_HELP);
|
||||
make_child("BUTTON", "&Change...", WS_TABSTOP, page, IDC_CHANGE);
|
||||
make_child("BUTTON", "&Reload", WS_TABSTOP, page, IDC_RELOAD);
|
||||
make_child("BUTTON", "&Defaults", WS_TABSTOP, page, IDC_DEFAULTS);
|
||||
make_child("EDIT", "", WS_TABSTOP | ES_READONLY | ES_AUTOHSCROLL, page,
|
||||
IDC_INIT, WS_EX_CLIENTEDGE);
|
||||
make_child("BUTTON", "&Keep", WS_TABSTOP, page, IDC_KEEP);
|
||||
settings_clear();
|
||||
settings_state();
|
||||
return page;
|
||||
}
|
||||
|
||||
void settings_page_layout(HWND p, int w, int h)
|
||||
{
|
||||
int m = 8, bh = 24, gw = 130, bw = 90;
|
||||
int listh = h - 4 * m - 2 * bh - 36;
|
||||
MoveWindow(GetDlgItem(p, IDC_GROUPS), m, m, gw, listh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_SETTINGS), 2 * m + gw, m, w - 3 * m - gw,
|
||||
listh, TRUE);
|
||||
int y = m + listh + m;
|
||||
MoveWindow(GetDlgItem(p, IDC_SETTING_HELP), m, y, w - 2 * m, 32, TRUE);
|
||||
y += 36;
|
||||
MoveWindow(GetDlgItem(p, IDC_CHANGE), m, y, bw, bh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_RELOAD), 2 * m + bw, y, bw, bh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_DEFAULTS), 3 * m + 2 * bw, y, bw, bh, TRUE);
|
||||
y += bh + m;
|
||||
MoveWindow(GetDlgItem(p, IDC_INIT), m, y, w - 3 * m - bw, bh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_KEEP), w - m - bw, y, bw, bh, TRUE);
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
* Copyright (c) 2026, D-Modem
|
||||
*
|
||||
* term.cpp - the Terminal page: the modem's screen (libdmodemctl's
|
||||
* dmc_vt, drawn with GDI), with buttons for its full-screen
|
||||
* and command-line setup
|
||||
*
|
||||
* The text is drawn with ExtTextOutW, one of the few wide functions
|
||||
* Windows 95 has, so the configurator's box drawing shows on every
|
||||
* version. Keys go to the modem as a VT100's; the right button pastes.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
#include "resource.h"
|
||||
|
||||
|
||||
static HWND page, term;
|
||||
static dmc_vt *vt;
|
||||
static int cw = 8, ch = 16; /* a cell's size */
|
||||
static int scroll; /* 0 the screen, -n back in history */
|
||||
static bool focused;
|
||||
|
||||
/* the brand's background and text (D-Modem/brand: docs/palette.md) */
|
||||
static const COLORREF BG = RGB(0x0a, 0x0f, 0x1c), FG = RGB(0xe8, 0xf0, 0xff);
|
||||
|
||||
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()
|
||||
{
|
||||
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(vt) + dmc_vt_rows(vt) - 1;
|
||||
si.nPage = dmc_vt_rows(vt);
|
||||
si.nPos = dmc_vt_history(vt) + scroll;
|
||||
SetScrollInfo(term, SB_VERT, &si, TRUE);
|
||||
}
|
||||
|
||||
static void place_caret()
|
||||
{
|
||||
if (!focused)
|
||||
return;
|
||||
if (scroll == 0 && dmc_vt_cursor_visible(vt)) {
|
||||
SetCaretPos(dmc_vt_cursor_col(vt) * cw,
|
||||
dmc_vt_cursor_row(vt) * ch + ch - 2);
|
||||
ShowCaret(term);
|
||||
} else {
|
||||
HideCaret(term);
|
||||
}
|
||||
}
|
||||
|
||||
static void paint(HDC dc, RECT *area)
|
||||
{
|
||||
RECT r;
|
||||
GetClientRect(term, &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);
|
||||
int rows = dmc_vt_rows(vt), cols = dmc_vt_cols(vt);
|
||||
WCHAR text[512];
|
||||
for (int y = 0; y < rows; y++) {
|
||||
int row = y + 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)'?';
|
||||
n++;
|
||||
}
|
||||
/* bold as the bright colours, as a PC's text mode */
|
||||
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 t = fc;
|
||||
fc = bc;
|
||||
bc = t;
|
||||
}
|
||||
SetTextColor(mem, fc);
|
||||
SetBkColor(mem, bc);
|
||||
RECT cell = { x * cw, y * ch, (x + n) * cw, (y + 1) * ch };
|
||||
/* each character in its cell, whatever the font */
|
||||
INT dx[512];
|
||||
for (int i = 0; i < n; i++)
|
||||
dx[i] = cw;
|
||||
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()
|
||||
{
|
||||
HDC dc = GetDC(term);
|
||||
HGDIOBJ old = SelectObject(dc, app.mono_font);
|
||||
TEXTMETRIC tm;
|
||||
GetTextMetrics(dc, &tm);
|
||||
cw = tm.tmAveCharWidth > 0 ? tm.tmAveCharWidth : 8;
|
||||
ch = tm.tmHeight > 0 ? tm.tmHeight : 16;
|
||||
SelectObject(dc, old);
|
||||
ReleaseDC(term, dc);
|
||||
}
|
||||
|
||||
static void send_text(const char *s, int n)
|
||||
{
|
||||
link_type(s, n);
|
||||
}
|
||||
|
||||
/* a character the keyboard gave, in the ANSI code page, as UTF-8 */
|
||||
static void send_char(unsigned char c)
|
||||
{
|
||||
if (c < 0x80) {
|
||||
char b = (char)c;
|
||||
send_text(&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(o, utf8_encode(w, o));
|
||||
}
|
||||
|
||||
static void paste()
|
||||
{
|
||||
if (!OpenClipboard(term))
|
||||
return;
|
||||
HANDLE h = GetClipboardData(CF_TEXT);
|
||||
if (h) {
|
||||
const char *t = (const char *)GlobalLock(h);
|
||||
if (t) {
|
||||
for (const char *p = t; *p; p++) {
|
||||
/* a CR LF as the one CR a terminal sends */
|
||||
if (*p == '\n' && p > t && p[-1] == '\r')
|
||||
continue;
|
||||
send_char(*p == '\n' ? '\r' : (unsigned char)*p);
|
||||
}
|
||||
GlobalUnlock(h);
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
}
|
||||
|
||||
static void to_bottom()
|
||||
{
|
||||
if (scroll) {
|
||||
scroll = 0;
|
||||
update_scrollbar();
|
||||
InvalidateRect(term, NULL, FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK term_proc(HWND w, UINT m, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
switch (m) {
|
||||
case WM_GETDLGCODE:
|
||||
return DLGC_WANTALLKEYS | DLGC_WANTARROWS | DLGC_WANTCHARS |
|
||||
DLGC_WANTTAB;
|
||||
case WM_SETFOCUS:
|
||||
focused = true;
|
||||
CreateCaret(w, NULL, cw, 2);
|
||||
place_caret();
|
||||
return 0;
|
||||
case WM_KILLFOCUS:
|
||||
focused = false;
|
||||
DestroyCaret();
|
||||
return 0;
|
||||
case WM_LBUTTONDOWN:
|
||||
SetFocus(w);
|
||||
return 0;
|
||||
case WM_RBUTTONUP:
|
||||
paste();
|
||||
return 0;
|
||||
case WM_ERASEBKGND:
|
||||
return 1;
|
||||
case WM_PAINT: {
|
||||
PAINTSTRUCT ps;
|
||||
HDC dc = BeginPaint(w, &ps);
|
||||
paint(dc, &ps.rcPaint);
|
||||
EndPaint(w, &ps);
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE: {
|
||||
int cols = LOWORD(lp) / cw, rows = HIWORD(lp) / ch;
|
||||
if (cols < 20)
|
||||
cols = 20;
|
||||
if (rows < 5)
|
||||
rows = 5;
|
||||
if (cols > 160)
|
||||
cols = 160;
|
||||
if (rows > 66)
|
||||
rows = 66;
|
||||
dmc_vt_resize(vt, cols, rows);
|
||||
update_scrollbar();
|
||||
InvalidateRect(w, NULL, FALSE);
|
||||
return 0;
|
||||
}
|
||||
case WM_VSCROLL: {
|
||||
int hist = dmc_vt_history(vt), pos = hist + scroll;
|
||||
switch (LOWORD(wp)) {
|
||||
case SB_LINEUP: pos--; break;
|
||||
case SB_LINEDOWN: pos++; break;
|
||||
case SB_PAGEUP: pos -= dmc_vt_rows(vt); break;
|
||||
case SB_PAGEDOWN: pos += dmc_vt_rows(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;
|
||||
scroll = pos - hist;
|
||||
update_scrollbar();
|
||||
place_caret();
|
||||
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();
|
||||
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;
|
||||
char b[16];
|
||||
int n = dmc_vt_key(vt, key, b, sizeof(b));
|
||||
to_bottom();
|
||||
send_text(b, n);
|
||||
return 0;
|
||||
}
|
||||
case WM_SYSKEYDOWN:
|
||||
/* F10 is the configurator's menu, not Windows' */
|
||||
if (wp == VK_F10) {
|
||||
char b[16];
|
||||
int n = dmc_vt_key(vt, DMC_KEY_F10, b, sizeof(b));
|
||||
send_text(b, n);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_SYSCHAR:
|
||||
/* Alt and a letter: ESC and it, as a terminal sends them */
|
||||
if (wp >= 0x20 && wp < 0x7f) {
|
||||
char b[2] = { 0x1b, (char)wp };
|
||||
to_bottom();
|
||||
send_text(b, 2);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_CHAR:
|
||||
if (wp == '\t' && GetKeyState(VK_SHIFT) < 0)
|
||||
return 0; /* (Shift-Tab went as a key) */
|
||||
to_bottom();
|
||||
send_char((unsigned char)wp);
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProc(w, m, wp, lp);
|
||||
}
|
||||
|
||||
void term_feed(const char *data, int n)
|
||||
{
|
||||
if (!vt)
|
||||
return;
|
||||
int before = dmc_vt_history(vt);
|
||||
dmc_vt_feed(vt, data, n);
|
||||
/* (looking back: the view stays where it was) */
|
||||
if (scroll)
|
||||
scroll -= dmc_vt_history(vt) - before;
|
||||
char r[64];
|
||||
int k;
|
||||
while ((k = dmc_vt_reply(vt, r, sizeof(r))) > 0)
|
||||
send_text(r, k);
|
||||
update_scrollbar();
|
||||
place_caret();
|
||||
InvalidateRect(term, NULL, FALSE);
|
||||
}
|
||||
|
||||
void term_state()
|
||||
{
|
||||
if (!page)
|
||||
return;
|
||||
bool idle = dmc_state(app.s) == DMC_IDLE;
|
||||
EnableWindow(GetDlgItem(page, IDC_SETUP_CF), idle);
|
||||
EnableWindow(GetDlgItem(page, IDC_SETUP_CT), idle);
|
||||
}
|
||||
|
||||
static void typed_command(const char *cmd)
|
||||
{
|
||||
if (dmc_state(app.s) != DMC_IDLE)
|
||||
return;
|
||||
link_type(cmd, (int)strlen(cmd));
|
||||
SetFocus(term);
|
||||
}
|
||||
|
||||
static void term_command(HWND p, int id, int code)
|
||||
{
|
||||
(void)p;
|
||||
(void)code;
|
||||
switch (id) {
|
||||
case IDC_SETUP_CF:
|
||||
typed_command("AT!CF\r");
|
||||
break;
|
||||
case IDC_SETUP_CT:
|
||||
typed_command("AT!CT\r");
|
||||
break;
|
||||
case IDC_CLEAR:
|
||||
dmc_vt_reset(vt);
|
||||
scroll = 0;
|
||||
update_scrollbar();
|
||||
InvalidateRect(term, NULL, FALSE);
|
||||
SetFocus(term);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
HWND term_page_new(HWND parent)
|
||||
{
|
||||
WNDCLASS wc;
|
||||
memset(&wc, 0, sizeof(wc));
|
||||
wc.style = CS_HREDRAW | CS_VREDRAW;
|
||||
wc.lpfnWndProc = term_proc;
|
||||
wc.hInstance = app.inst;
|
||||
wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
|
||||
wc.lpszClassName = "DModemTerminal";
|
||||
RegisterClass(&wc);
|
||||
vt = dmc_vt_new(80, 25, 2000);
|
||||
page = page_new(parent, term_command);
|
||||
make_child("BUTTON", "&Full-Screen Setup", WS_TABSTOP, page, IDC_SETUP_CF);
|
||||
make_child("BUTTON", "&Command-Line Setup", WS_TABSTOP, page,
|
||||
IDC_SETUP_CT);
|
||||
make_child("BUTTON", "C&lear", WS_TABSTOP, page, IDC_CLEAR);
|
||||
term = make_child("DModemTerminal", "", WS_TABSTOP | WS_VSCROLL, page,
|
||||
IDC_TERM, WS_EX_CLIENTEDGE);
|
||||
measure();
|
||||
return page;
|
||||
}
|
||||
|
||||
void term_page_layout(HWND p, int w, int h)
|
||||
{
|
||||
int m = 8, bh = 24;
|
||||
MoveWindow(GetDlgItem(p, IDC_SETUP_CF), m, m, 140, bh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_SETUP_CT), m + 148, m, 150, bh, TRUE);
|
||||
MoveWindow(GetDlgItem(p, IDC_CLEAR), w - m - 80, m, 80, bh, TRUE);
|
||||
MoveWindow(term, m, 2 * m + bh, w - 2 * m, h - 3 * m - bh, TRUE);
|
||||
}
|
||||