Merge pull request #74 from D-Modem/claude/project-thread-0j0ur0
Make the Win32 app the only desktop GUI
No files matched your search
@@ -1,5 +1,6 @@
|
||||
# Builds and tests the three apps and the library they share, and the
|
||||
# Windows app for Linux and macOS (winport/)
|
||||
# Builds and tests the app (windows/) and the library that it uses
|
||||
# (core/, ssh/): on Windows 95 to Windows 11, and on Linux and macOS over
|
||||
# clang-retro MFC's portable Win32 layer (winport/)
|
||||
name: Build
|
||||
|
||||
# The nightly release (nightly.yml) takes its files from this
|
||||
@@ -15,19 +16,18 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux (GTK 4)
|
||||
# libdmodemctl (core/) and libdmodemssh (ssh/), with no app: the
|
||||
# tests, the tests with the sanitizers, and SSH against a real sshd
|
||||
core:
|
||||
name: Library and SSH tests (Linux)
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- 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 \
|
||||
libpulse-dev libsndfile1-dev libasound2-dev libusb-1.0-0-dev
|
||||
cmake ninja-build pkg-config
|
||||
- name: Build
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
@@ -62,14 +62,6 @@ jobs:
|
||||
DMODEM_SSH_TEST=127.0.0.1:2222:dmtest:Sesame-42 DMODEM_SSH_TEST_KEY="$RUNNER_TEMP/key" \
|
||||
DMODEM_SSH_TEST_PPK="$RUNNER_TEMP/key.ppk" DMODEM_SSH_TEST_AGENT="$RUNNER_TEMP/agent.sock" \
|
||||
build/ssh/dmodemssh_test
|
||||
- name: Package
|
||||
run: |
|
||||
DESTDIR="$PWD/pkg" cmake --install build --prefix /usr
|
||||
tar -C pkg -czf dmodem-gui-linux-x86_64.tar.gz usr
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmodem-linux
|
||||
path: dmodem-gui-linux-x86_64.tar.gz
|
||||
|
||||
# Both Windows builds use clang-retro (https://clang-retro.github.io/),
|
||||
# its toolchain package from its setup-toolchain action, on Linux
|
||||
@@ -195,7 +187,7 @@ jobs:
|
||||
- name: Build
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DDMODEM_GUI_LINUX=OFF -DDMODEM_GUI_WINPORT=ON -DCLANG_RETRO_MFC="$PWD/mfc" \
|
||||
-DDMODEM_GUI_WINPORT=ON -DCLANG_RETRO_MFC="$PWD/mfc" \
|
||||
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
|
||||
cmake --build build --target dmodem-win32
|
||||
- name: The built-in modem is in the app
|
||||
@@ -247,54 +239,13 @@ jobs:
|
||||
test "$(lipo -archs build/winport/dmodem-win32)" = "${{ matrix.arch }}"
|
||||
- name: The built-in modem is in the app
|
||||
run: nm build/winport/dmodem-win32 | grep -q dmodem_embed_start
|
||||
- name: Library tests
|
||||
run: |
|
||||
cmake --build build --target dmodemctl_test xfer_test -j"$(sysctl -n hw.ncpu)"
|
||||
ctest --test-dir build --output-on-failure -R '^(dmodemctl|xfer)$'
|
||||
- name: Package
|
||||
run: tar -C build/winport -czf dmodem-win32-macos-${{ matrix.arch }}.tar.gz dmodem-win32
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.artifact }}
|
||||
path: dmodem-win32-macos-${{ matrix.arch }}.tar.gz
|
||||
|
||||
# The built-in modem (external/D-Modem) is built by CMake, which
|
||||
# writes build/macos-embed.xcconfig for the Xcode project
|
||||
macos:
|
||||
name: macOS (SwiftUI)
|
||||
runs-on: macos-15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Library tests
|
||||
run: |
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0
|
||||
cmake --build build
|
||||
ctest --test-dir build --output-on-failure
|
||||
- name: Project
|
||||
run: |
|
||||
brew install xcodegen
|
||||
cd macos && xcodegen
|
||||
# (arm64 and x86_64: with no destination, xcodebuild builds for
|
||||
# the runner's Mac alone)
|
||||
- name: Build
|
||||
run: |
|
||||
cd macos
|
||||
xcodebuild -project DModem.xcodeproj -scheme DModem \
|
||||
-configuration Release -derivedDataPath ../build/xcode \
|
||||
-destination 'generic/platform=macOS' \
|
||||
ARCHS='arm64 x86_64' ONLY_ACTIVE_ARCH=NO \
|
||||
CODE_SIGN_IDENTITY=- build
|
||||
- name: The built-in modem is in the app, for each architecture
|
||||
run: |
|
||||
app=build/xcode/Build/Products/Release/D-Modem.app/Contents/MacOS/D-Modem
|
||||
lipo -archs "$app"
|
||||
for arch in arm64 x86_64; do
|
||||
lipo "$app" -verify_arch "$arch"
|
||||
nm -arch "$arch" "$app" | grep -q dmodem_embed_start
|
||||
done
|
||||
# (ditto keeps the bundle's symbolic links and executable bits)
|
||||
- name: Package
|
||||
run: ditto -c -k --keepParent build/xcode/Build/Products/Release/D-Modem.app D-Modem-macos.zip
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmodem-macos
|
||||
path: D-Modem-macos.zip
|
||||
@@ -1,9 +1,9 @@
|
||||
# D-Modem bump: moves the external/D-Modem submodule (the built-in
|
||||
# modem) to the latest main of D-Modem. It opens a pull request for the
|
||||
# change, or updates the open one. Build (build.yml) builds and tests
|
||||
# the apps in that pull request. The workflow merges the pull request
|
||||
# the app in that pull request. The workflow merges the pull request
|
||||
# when all of its checks pass. Build then runs on main, and the next
|
||||
# nightly release (nightly.yml) has the new apps.
|
||||
# nightly release (nightly.yml) has the new app.
|
||||
#
|
||||
# It starts:
|
||||
# - from D-Modem, when its main changes (a repository_dispatch event of
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
# Nightly: the "nightly" pre-release of the apps, from the artifacts of
|
||||
# Nightly: the "nightly" pre-release of the app, from the artifacts of
|
||||
# the newest complete run of build.yml on main. It does not build the
|
||||
# apps again. It runs each time a run of build.yml on main completes,
|
||||
# app again. It runs each time a run of build.yml on main completes,
|
||||
# and once a day. Each run updates the release in place and moves its
|
||||
# tag: a run that fails does not delete the release. When main has no
|
||||
# new commits, the run stops and the release does not change. A manual
|
||||
# run (Actions > Nightly > Run workflow) can publish again with "force".
|
||||
#
|
||||
# The files are not signed: Windows SmartScreen and macOS Gatekeeper
|
||||
# show a warning for them.
|
||||
# show a warning for them. The release has only the files of this
|
||||
# build: nightly-publish.sh removes the files that the build did not
|
||||
# make (for example the old Linux GTK app and the old macOS SwiftUI app).
|
||||
name: Nightly
|
||||
|
||||
on:
|
||||
@@ -70,8 +72,6 @@ jobs:
|
||||
take dmodem-windows-9x dmodem.exe dmodem-win9x.exe
|
||||
take dmodem-windows-98 dmodem.exe dmodem-win98.exe
|
||||
take dmodem-windows dmodem.exe dmodem-win7.exe
|
||||
take dmodem-linux dmodem-gui-linux-x86_64.tar.gz
|
||||
take dmodem-macos D-Modem-macos.zip
|
||||
take dmodem-win32-linux dmodem-win32-linux-x86_64.tar.gz
|
||||
take dmodem-win32-macos dmodem-win32-macos-arm64.tar.gz
|
||||
take dmodem-win32-macos-x86_64 dmodem-win32-macos-x86_64.tar.gz
|
||||
@@ -86,11 +86,9 @@ jobs:
|
||||
echo "| \`dmodem-win9x.exe\` | The Windows app with the modem built in, for Windows 95, 98, ME, NT 4.0 and later (no C runtime DLL; Windows 95 needs Winsock 2) |"
|
||||
echo "| \`dmodem-win98.exe\` | The Windows app with the modem built in, for Windows 98 SE, ME, 2000 and later (on msvcrt.dll) |"
|
||||
echo "| \`dmodem-win7.exe\` | The Windows app for Windows 7 and later, with the modem built in |"
|
||||
echo "| \`dmodem-gui-linux-x86_64.tar.gz\` | The Linux app (GTK 4), x86_64. It needs GTK 4, libadwaita, PulseAudio and libsndfile. Its files are in \`usr/\`: extract it into \`/\`, for example with \`sudo tar -xzf dmodem-gui-linux-x86_64.tar.gz -C /\` |"
|
||||
echo "| \`D-Modem-macos.zip\` | The macOS app (SwiftUI) with the modem built in, arm64 and x86_64, macOS 13 and later. Not notarized: right-click the app and select Open |"
|
||||
echo "| \`dmodem-win32-linux-x86_64.tar.gz\` | The Windows app on Linux (X11) with the modem built in, x86_64 |"
|
||||
echo "| \`dmodem-win32-macos-arm64.tar.gz\` | The Windows app on macOS with the modem built in, arm64 (Apple silicon) |"
|
||||
echo "| \`dmodem-win32-macos-x86_64.tar.gz\` | The Windows app on macOS with the modem built in, x86_64 (Intel Mac) |"
|
||||
echo "| \`dmodem-win32-linux-x86_64.tar.gz\` | The app on Linux (X11) with the modem built in, x86_64 |"
|
||||
echo "| \`dmodem-win32-macos-arm64.tar.gz\` | The app on macOS with the modem built in, arm64 (Apple silicon) |"
|
||||
echo "| \`dmodem-win32-macos-x86_64.tar.gz\` | The app on macOS with the modem built in, x86_64 (Intel Mac) |"
|
||||
echo "| \`SHA256SUMS\` | The SHA-256 of each file |"
|
||||
if [ -f missing ]; then
|
||||
echo
|
||||
|
||||
@@ -4,11 +4,6 @@ build-*/
|
||||
bin/
|
||||
obj/
|
||||
*.user
|
||||
.build/
|
||||
.swiftpm/
|
||||
*.xcodeproj/xcuserdata/
|
||||
DerivedData/
|
||||
.flatpak-builder/
|
||||
|
||||
# the site (brand's tools/site.sh): the theme it copies in, and the built site
|
||||
.site/
|
||||
|
||||
@@ -1,46 +1,38 @@
|
||||
# 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 clang-retro (cmake/clang-retro.cmake), MinGW or MSVC.
|
||||
# The macOS app (macos/) builds with Xcode and takes the core from here.
|
||||
# With DMODEM_GUI_WINPORT, the Windows app also builds for Linux and
|
||||
# macOS, over clang-retro MFC's portable Win32 layer (winport/).
|
||||
# With DMODEM_GUI_EMBED, the Linux app, the Windows app (Windows 95 and
|
||||
# later), the macOS app and the Windows app on Linux and macOS have the
|
||||
# modem in them (libdmodem_embed from the D-Modem submodule,
|
||||
# external/D-Modem): they need no dmodemd.
|
||||
# For the macOS app, CMake writes macos-embed.xcconfig
|
||||
# (cmake/MacosEmbed.cmake).
|
||||
# D-Modem's desktop app: the shared C core (libdmodemctl), and the
|
||||
# Win32 app (windows/). On Windows, it builds with clang-retro
|
||||
# (cmake/clang-retro.cmake), MinGW or MSVC. With DMODEM_GUI_WINPORT, the
|
||||
# same app builds for Linux and macOS, over clang-retro MFC's portable
|
||||
# Win32 layer (winport/). On Linux and macOS with no DMODEM_GUI_WINPORT,
|
||||
# only the core, libdmodemssh and their tests build.
|
||||
# With DMODEM_GUI_EMBED, the app (Windows 95 and later, and the app on
|
||||
# Linux and macOS) has the modem in it (libdmodem_embed from the D-Modem
|
||||
# submodule, external/D-Modem): it needs no dmodemd.
|
||||
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)
|
||||
option(DMODEM_GUI_SSH "Build libdmodemssh (libssh) for the Remote page" ON)
|
||||
option(DMODEM_GUI_WINPORT "Build the Windows app for Linux or macOS (winport/)" OFF)
|
||||
set(CLANG_RETRO_MFC "" CACHE PATH "A clang-retro MFC checkout, for DMODEM_GUI_WINPORT")
|
||||
|
||||
# the modem built in (docs/embedded-modem.md): the Linux, macOS and
|
||||
# Windows apps, and the Windows app on Linux and macOS (winport/), when
|
||||
# the submodule is there (git submodule update --init)
|
||||
# the modem built in (docs/embedded-modem.md): the app on Windows, and
|
||||
# the app on Linux and macOS (winport/), when the submodule is there
|
||||
# (git submodule update --init)
|
||||
set(DMODEM_GUI_DMODEM_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/D-Modem
|
||||
CACHE PATH "The D-Modem tree, for DMODEM_GUI_EMBED")
|
||||
# (all the Windows builds: clang-retro's win32-picolibc, the Windows 95
|
||||
# build, has libc++ for the modem's C++17, as win98 and win7 do)
|
||||
set(_embed_default OFF)
|
||||
if(EXISTS ${DMODEM_GUI_DMODEM_DIR}/CMakeLists.txt)
|
||||
if(UNIX AND NOT APPLE AND (DMODEM_GUI_LINUX OR DMODEM_GUI_WINPORT))
|
||||
set(_embed_default ON)
|
||||
elseif(APPLE)
|
||||
set(_embed_default ON)
|
||||
elseif(WIN32)
|
||||
if(WIN32 OR DMODEM_GUI_WINPORT)
|
||||
set(_embed_default ON)
|
||||
endif()
|
||||
endif()
|
||||
option(DMODEM_GUI_EMBED "Build the modem into the app (libdmodem_embed)"
|
||||
${_embed_default})
|
||||
if(DMODEM_GUI_EMBED AND (WIN32 OR APPLE OR DMODEM_GUI_LINUX OR DMODEM_GUI_WINPORT))
|
||||
if(DMODEM_GUI_EMBED AND (WIN32 OR DMODEM_GUI_WINPORT))
|
||||
if(NOT EXISTS ${DMODEM_GUI_DMODEM_DIR}/CMakeLists.txt)
|
||||
message(FATAL_ERROR "DMODEM_GUI_EMBED: no D-Modem in "
|
||||
"${DMODEM_GUI_DMODEM_DIR} (git submodule update --init)")
|
||||
@@ -98,20 +90,3 @@ if(WIN32)
|
||||
elseif(DMODEM_GUI_WINPORT)
|
||||
add_subdirectory(winport)
|
||||
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)
|
||||
endif()
|
||||
if(GTK_FOUND)
|
||||
add_subdirectory(linux)
|
||||
else()
|
||||
message(STATUS "gtk4 or libadwaita-1 not found: the Linux app is not built")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# the macOS app (Xcode): the built-in modem's libraries, for its project
|
||||
if(APPLE AND NOT DMODEM_GUI_WINPORT)
|
||||
include(cmake/MacosEmbed.cmake)
|
||||
endif()
|
||||
@@ -1,16 +1,15 @@
|
||||
<img src=".github/banner.png" alt="D-Modem/gui: D-Modem on the desktop" width="100%">
|
||||
|
||||
# D-Modem desktop apps
|
||||
# D-Modem desktop app
|
||||
|
||||
Native apps for D-Modem on Windows, macOS and Linux. The site of the apps is
|
||||
<https://d-modem.github.io/gui/>.
|
||||
The D-Modem desktop app is one Win32 app for Windows, macOS and Linux. The
|
||||
site of the app is <https://d-modem.github.io/gui/>.
|
||||
|
||||
The apps have the modem built in, so they need no dmodemd (refer to
|
||||
[The built-in modem](docs/embedded-modem.md)). Each app
|
||||
shows the modem as a desktop program. You can dial and answer from a window,
|
||||
change the settings without AT commands, and see the results of the last
|
||||
call. All three apps are thin native shells over one small C library,
|
||||
libdmodemctl. Thus they operate in the same way.
|
||||
The app has the modem built in, so it needs no dmodemd (refer to
|
||||
[The built-in modem](docs/embedded-modem.md)). The app shows the modem as a
|
||||
desktop program. You can dial and answer from a window, change the settings
|
||||
without AT commands, and see the results of the last call. The app is a
|
||||
thin Win32 shell over one small C library, libdmodemctl.
|
||||
|
||||
- **Modem**: the state of the call, dial, answer and hang up, and the line that the modem uses
|
||||
- **Phone**: voice calls through the sound card (dial, answer, keypad), and an
|
||||
@@ -18,54 +17,58 @@ libdmodemctl. Thus they operate in the same way.
|
||||
- **Terminal**: the AT console, and the setup screens of the modem (AT!CF, AT!CT)
|
||||
- **Remote**: log in to a server by SSH, Telnet or rlogin, in a separate terminal. SSH is built in, on libssh, and it uses the keys and the agent of OpenSSH and PuTTY
|
||||
- **Terminal types**: the terminal emulator of the D-Modem app, ported to C: xterm, DEC VT52 to VT525, ANSI-BBS, PETSCII, ATASCII, Viewdata, Minitel and Tektronix 4014, with sixel, ReGIS and Tektronix graphics
|
||||
- **The Windows app**: file transfers (ZMODEM, YMODEM, XMODEM and Kermit), copy and capture, and the ASCII Setup, Terminal Settings and Call menu of HyperTerminal. Refer to [Features](docs/features.md)
|
||||
- **HyperTerminal items**: file transfers (ZMODEM, YMODEM, XMODEM and Kermit), copy and capture, and the ASCII Setup, Terminal Settings and Call menu of HyperTerminal. Refer to [Features](docs/features.md)
|
||||
- **Settings**: each modem setting as a native control, from AT!M
|
||||
- **Call Stats**: the rate, modulation, error control and line figures of the last call (AT#UD, ATI11)
|
||||
- **Line settings**: a SIP account, a USB modem, or a modem that already runs (dmodemd, or a hardware modem such as the MultiTech MT9234MU)
|
||||
- **Windows 95 and later**: plain Win32, built with [clang-retro](https://clang-retro.github.io/). The modem is built in on each Windows. The app can also connect to a modem through TCP or a COM port
|
||||
- **The Windows app on Linux and macOS**: the same Win32 code, built over the portable Win32 layer of [clang-retro MFC](https://github.com/clang-retro/mfc). It has the built-in modem. It can also start dmodemd, or connect to a modem through TCP or a COM port. Refer to "The Windows app on Linux and macOS" in [Design](docs/design.md)
|
||||
|
||||
| | Windows | macOS | Linux |
|
||||
| --- | --- | --- | --- |
|
||||
| Toolkit | Win32, C++ | SwiftUI | GTK 4, libadwaita |
|
||||
| Runs on | Windows 95 and later | macOS 13 and later | GTK 4.10 and libadwaita 1.5 or later (Ubuntu 24.04, Fedora 40) |
|
||||
| Toolkit | Win32, C++ | Win32, over the Cocoa layer of [clang-retro MFC](https://github.com/clang-retro/mfc) | Win32, over the X11 and Wayland layer of clang-retro MFC |
|
||||
| Built with | [clang-retro](https://clang-retro.github.io/), MinGW or MSVC | clang | clang |
|
||||
| Runs on | Windows 95 and later | arm64 (Apple silicon) and x86_64 (Intel Mac) | x86_64 |
|
||||
|
||||
<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">
|
||||
The source code of the app is the same on each system. Refer to "The
|
||||
Windows app on Linux and macOS" in [Design](docs/design.md).
|
||||
|
||||
<img src="docs/images/linux-phone.png" width="49%" alt="The Linux app's Phone page"> <img src="docs/images/windows-phone.png" width="49%" alt="The Windows app's Phone page taking a message">
|
||||
<img src="docs/images/windows-settings.png" width="49%" alt="The Settings page of the app"> <img src="docs/images/windows-setup-screen.png" width="49%" alt="The Terminal of the app with the setup screen of the modem">
|
||||
|
||||
<img src="docs/images/windows-modem.png" width="49%" alt="The Modem page of the app"> <img src="docs/images/windows-phone.png" width="49%" alt="The Phone page of the app as it takes a message">
|
||||
|
||||
## Nightly builds
|
||||
|
||||
The [nightly release](https://github.com/D-Modem/gui/releases/tag/nightly)
|
||||
has the apps from the newest build of `main`. It has the Windows app (for
|
||||
Windows 95 and later, and for Windows 7 and later), the Linux app, the
|
||||
macOS app, and the Windows app for Linux and macOS. A workflow
|
||||
has the app from the newest build of `main`: for Windows 95 and later, for
|
||||
Windows 7 and later, for Linux, and for macOS. A workflow
|
||||
(`.github/workflows/nightly.yml`) replaces the release one time each day.
|
||||
When `main` has no new commits, the release does not change. When the
|
||||
main branch of D-Modem changes, a workflow moves the built-in modem to it
|
||||
and builds the apps again (refer to [Building](docs/building.md)).
|
||||
and builds the app again (refer to [Building](docs/building.md)).
|
||||
|
||||
These builds are not stable releases. The files are not signed. Thus
|
||||
Windows and macOS can show a warning before the app starts.
|
||||
|
||||
## Quick start
|
||||
|
||||
Linux:
|
||||
Linux (get [clang-retro MFC](https://github.com/clang-retro/mfc) first):
|
||||
|
||||
sudo apt install cmake libgtk-4-dev libadwaita-1-dev libpulse-dev \
|
||||
libsndfile1-dev
|
||||
cmake -S . -B build && cmake --build build && ./build/linux/dmodem-gui
|
||||
git submodule update --init
|
||||
sudo apt install cmake ninja-build clang llvm libx11-dev \
|
||||
libusb-1.0-0-dev libasound2-dev
|
||||
cmake -S . -B build -DDMODEM_GUI_WINPORT=ON -DCLANG_RETRO_MFC=/path/to/mfc \
|
||||
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
|
||||
cmake --build build --target dmodem-win32 && ./build/winport/dmodem-win32
|
||||
|
||||
For Windows (with clang-retro), macOS, and the Windows app on Linux and
|
||||
macOS, refer to [Building](docs/building.md).
|
||||
For Windows (with clang-retro) and macOS, refer to
|
||||
[Building](docs/building.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [The site](https://d-modem.github.io/gui/): the home page, the downloads and all the pages below
|
||||
- [Features](docs/features.md): each page and menu of the apps, with the details of the Windows app
|
||||
- [Building](docs/building.md): Linux, Windows with clang-retro, macOS, and the Windows app on Linux and macOS
|
||||
- [The built-in modem](docs/embedded-modem.md): the modem inside the Linux and Windows apps, with no dmodemd
|
||||
- [Design](docs/design.md): how the apps are built, what they share, hardware modems (the MultiTech MT9234MU), the Windows 9x notes, and the Windows app on Linux and macOS
|
||||
- [Features](docs/features.md): each page and menu of the app
|
||||
- [Building](docs/building.md): Windows with clang-retro, and the app on Linux and macOS
|
||||
- [The built-in modem](docs/embedded-modem.md): the modem inside the app, with no dmodemd
|
||||
- [Design](docs/design.md): how the app is built, hardware modems (the MultiTech MT9234MU), the Windows 9x notes, and the app on Linux and macOS
|
||||
- [libdmodemctl](core/include/dmodemctl.h): the API of the library
|
||||
- [Documentation style](docs/STYLE.md): the rules for ASD-STE100 Simplified Technical English
|
||||
|
||||
@@ -75,7 +78,7 @@ macOS, refer to [Building](docs/building.md).
|
||||
| --- | --- |
|
||||
| [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 |
|
||||
| [gui](https://github.com/D-Modem/gui) | D-Modem on the desktop: one Win32 app for Windows, macOS and Linux |
|
||||
| [hardware](https://github.com/D-Modem/hardware) | pico-serial: RP2040 serial adapters and phone-line USB sticks |
|
||||
| [login](https://github.com/D-Modem/login) | dmodem-login: the login, menu and LDAP provider for dial-up callers |
|
||||
| [bbs](https://github.com/D-Modem/bbs) | A bulletin board for telnet, SSH, TN3270 and modem callers |
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# The macOS app (macos/) builds with Xcode, not CMake. This file writes
|
||||
# ${CMAKE_BINARY_DIR}/macos-embed.xcconfig, which the Xcode project
|
||||
# (macos/project.yml) includes:
|
||||
# DMODEM_EMBED_HEADERS the directory of dmodem_embed.h
|
||||
# DMODEM_EMBED_LDFLAGS the static libraries of libdmodem_embed, all of
|
||||
# them, and the system libraries they need
|
||||
# DMODEM_EMBED_SWIFT DMODEM_GUI_EMBED, for Swift's #if
|
||||
# Without the built-in modem, the three values are empty.
|
||||
#
|
||||
# A small program, dmodem_embed_link, links the library. Its linker
|
||||
# launcher (macos-embed/link-capture.sh) keeps the link command that
|
||||
# CMake made, with all the libraries that the library needs. Then
|
||||
# macos-embed/xcconfig.cmake makes the file from that command.
|
||||
|
||||
set(_xcconfig ${CMAKE_BINARY_DIR}/macos-embed.xcconfig)
|
||||
if(DMODEM_GUI_EMBED AND TARGET dmodem_embed)
|
||||
if(CMAKE_VERSION VERSION_LESS 3.21)
|
||||
message(FATAL_ERROR "The built-in modem of the macOS app needs CMake 3.21 or later")
|
||||
endif()
|
||||
set(_dir ${CMAKE_CURRENT_LIST_DIR}/macos-embed)
|
||||
set(_cmd ${CMAKE_BINARY_DIR}/macos-embed.link)
|
||||
add_executable(dmodem_embed_link ${_dir}/main.c)
|
||||
target_link_libraries(dmodem_embed_link PRIVATE dmodem_embed)
|
||||
set_target_properties(dmodem_embed_link PROPERTIES
|
||||
LINKER_LANGUAGE CXX
|
||||
C_LINKER_LAUNCHER "${_dir}/link-capture.sh;${_cmd}"
|
||||
CXX_LINKER_LAUNCHER "${_dir}/link-capture.sh;${_cmd}")
|
||||
add_custom_command(TARGET dmodem_embed_link POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -DIN=${_cmd} -DOUT=${_xcconfig}
|
||||
-DHEADERS=${DMODEM_GUI_DMODEM_DIR}/frontend/embed
|
||||
-P ${_dir}/xcconfig.cmake
|
||||
VERBATIM)
|
||||
else()
|
||||
file(WRITE ${_xcconfig}
|
||||
"// Made by CMake (cmake/MacosEmbed.cmake): no built-in modem
|
||||
DMODEM_EMBED_HEADERS =
|
||||
DMODEM_EMBED_LDFLAGS =
|
||||
DMODEM_EMBED_SWIFT =
|
||||
")
|
||||
endif()
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Copyright (C) 2026 D-Modem Authors
|
||||
#
|
||||
# link-capture.sh - the linker launcher of dmodem_embed_link
|
||||
# (cmake/MacosEmbed.cmake). It writes the directory and the link
|
||||
# command, one argument on each line, to <file>. Then it runs the
|
||||
# command.
|
||||
#
|
||||
# Usage: link-capture.sh <file> <command> [<argument>...]
|
||||
|
||||
out=$1
|
||||
shift
|
||||
{
|
||||
pwd
|
||||
printf '%s\n' "$@"
|
||||
} > "$out"
|
||||
exec "$@"
|
||||
@@ -1,15 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* main.c - dmodem_embed_link (cmake/MacosEmbed.cmake): a program that
|
||||
* links libdmodem_embed, so that CMake gives the full link command of
|
||||
* the library
|
||||
*/
|
||||
#include "dmodem_embed.h"
|
||||
|
||||
/* Uses the library, so that the linker includes it. */
|
||||
int main(void)
|
||||
{
|
||||
return dmodem_embed_version() ? 0 : 1;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
# xcconfig.cmake - makes macos-embed.xcconfig from the link command that
|
||||
# link-capture.sh wrote (cmake/MacosEmbed.cmake). It keeps the static
|
||||
# libraries, the -l libraries and the frameworks of the command. A
|
||||
# relative path is made absolute from the directory of the command.
|
||||
#
|
||||
# Usage: cmake -DIN=<captured command> -DOUT=<xcconfig>
|
||||
# -DHEADERS=<directory of dmodem_embed.h> -P xcconfig.cmake
|
||||
|
||||
file(STRINGS ${IN} _args)
|
||||
list(POP_FRONT _args _dir)
|
||||
set(_ld "")
|
||||
set(_framework OFF)
|
||||
foreach(_a ${_args})
|
||||
if(_framework)
|
||||
string(APPEND _ld " -framework ${_a}")
|
||||
set(_framework OFF)
|
||||
elseif(_a STREQUAL "-framework")
|
||||
set(_framework ON)
|
||||
elseif(_a MATCHES "^-framework ")
|
||||
string(APPEND _ld " ${_a}")
|
||||
elseif(_a MATCHES "^-l" OR _a STREQUAL "-pthread")
|
||||
string(APPEND _ld " ${_a}")
|
||||
elseif(_a MATCHES "\\.a$")
|
||||
get_filename_component(_p "${_a}" ABSOLUTE BASE_DIR "${_dir}")
|
||||
string(APPEND _ld " \"${_p}\"")
|
||||
endif()
|
||||
endforeach()
|
||||
# (the modem is C++: the app, Swift and C, links libc++ for it)
|
||||
if(NOT _ld MATCHES " -lc\\+\\+")
|
||||
string(APPEND _ld " -lc++")
|
||||
endif()
|
||||
file(WRITE ${OUT}.new
|
||||
"// Made by CMake (cmake/MacosEmbed.cmake): the built-in modem
|
||||
DMODEM_EMBED_HEADERS = \"${HEADERS}\"
|
||||
DMODEM_EMBED_LDFLAGS =${_ld}
|
||||
DMODEM_EMBED_SWIFT = DMODEM_GUI_EMBED
|
||||
")
|
||||
# (the same file is not written again, so Xcode does not rebuild)
|
||||
file(COPY_FILE ${OUT}.new ${OUT} ONLY_IF_DIFFERENT)
|
||||
file(REMOVE ${OUT}.new)
|
||||
@@ -1,6 +1,6 @@
|
||||
# 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).
|
||||
# libdmodemctl: the part of the desktop app that does not draw, in plain
|
||||
# C with no dependencies. Static by default; a DLL for a P/Invoke caller
|
||||
# (-DDMODEMCTL_SHARED=ON).
|
||||
option(DMODEMCTL_SHARED "Build libdmodemctl as a shared library" OFF)
|
||||
|
||||
set(DMODEMCTL_SOURCES
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* dmodemctl.h - the part of D-Modem's desktop apps that is not drawing.
|
||||
* dmodemctl.h - the part of D-Modem's desktop app 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#
|
||||
* The Win32 app (on Windows, and on Linux and macOS over clang-retro
|
||||
* MFC's Win32 layer) is a thin shell over this small C library, so that
|
||||
* the app is only views. The library does no I/O of its own and
|
||||
* starts no threads: the app opens the modem's DTE (a TCP socket, a COM
|
||||
* port), 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, C++ (Win32), C#
|
||||
* (P/Invoke) and Swift.
|
||||
*
|
||||
* Its parts:
|
||||
@@ -250,8 +250,8 @@ DMC_API int dmc_wav_header(char *buf, int n);
|
||||
allocated (dmc_free() it); -1 if it is not one this reads. It reads
|
||||
WAV (PCM of 8, 16, 24 or 32 bits, 32 or 64-bit floats, A-law, mu-law,
|
||||
IMA and Microsoft ADPCM), AIFF and AIFF-C (PCM, floats, A-law,
|
||||
mu-law) and Sun/NeXT .au, of any rate and channels. (The apps read
|
||||
MP3, AAC, FLAC, Ogg and the like with their platforms' decoders.) */
|
||||
mu-law) and Sun/NeXT .au, of any rate and channels. (The app reads
|
||||
MP3 and the like with the ACM codecs.) */
|
||||
DMC_API int dmc_audio_decode(const char *data, int n, int16_t **pcm);
|
||||
/* (dmc_audio_decode's old name) */
|
||||
DMC_API int dmc_wav_decode(const char *data, int n, int16_t **pcm);
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
# Building
|
||||
|
||||
Linux:
|
||||
The app is one Win32 app (`windows/`). It builds for Windows, and for
|
||||
Linux and macOS over the portable Win32 layer of clang-retro MFC
|
||||
(`winport/`). The submodule `external/D-Modem` gives the built-in modem.
|
||||
Refer to [The built-in modem](embedded-modem.md).
|
||||
|
||||
git submodule update --init
|
||||
sudo apt install cmake libgtk-4-dev libadwaita-1-dev libpulse-dev \
|
||||
libsndfile1-dev libasound2-dev libusb-1.0-0-dev
|
||||
cmake -S . -B build && cmake --build build && ./build/linux/dmodem-gui
|
||||
## Windows
|
||||
|
||||
The submodule `external/D-Modem` gives the built-in modem. Refer to
|
||||
[The built-in modem](embedded-modem.md).
|
||||
|
||||
Windows: we build the Windows app with clang-retro. Get its toolchain
|
||||
We build the app for Windows with clang-retro. Get its toolchain
|
||||
package (`clang-dos-linux-x86_64.tar.xz` or `clang-dos-windows-x86_64.zip`,
|
||||
from the [nightly release](https://github.com/clang-retro/dos-sdk/releases/tag/nightly)).
|
||||
Then set `CLANG_DOS` to the directory of the package. Each build needs the
|
||||
@@ -36,14 +33,9 @@ submodule (`git submodule update --init`) for the built-in modem:
|
||||
The app is in `windows/dmodem.exe` of the build directory. MSVC
|
||||
(`cmake -S . -B build -A Win32`) and MinGW also build the same code.
|
||||
|
||||
macOS: first use `git submodule update --init`, then
|
||||
`cmake -S . -B build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build build`.
|
||||
This builds libssh (for SSH) and the built-in modem, and writes
|
||||
`build/macos-embed.xcconfig` for the Xcode project. CMake 3.21 or later
|
||||
is necessary for the built-in modem. Then use
|
||||
`brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`.
|
||||
## Linux and macOS
|
||||
|
||||
The Windows app on Linux or macOS: get [clang-retro MFC](https://github.com/clang-retro/mfc),
|
||||
Get [clang-retro MFC](https://github.com/clang-retro/mfc),
|
||||
clang and `llvm-rc` (on macOS, `brew install llvm`). For the built-in
|
||||
modem, get the D-Modem submodule (`git submodule update --init`). On
|
||||
Linux, also install `libusb-1.0-0-dev` and `libasound2-dev`. Then:
|
||||
@@ -52,11 +44,24 @@ Linux, also install `libusb-1.0-0-dev` and `libasound2-dev`. Then:
|
||||
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
|
||||
cmake --build build --target dmodem-win32 && ./build/winport/dmodem-win32
|
||||
|
||||
On Linux, `cmake --install build` installs the app, its desktop entry,
|
||||
its icon and the firmware of the MultiTech MT9234MU (`firmware/`).
|
||||
|
||||
On macOS, the app is for the architecture of the Mac. To build the app
|
||||
for an Intel Mac on a Mac with Apple silicon, add
|
||||
`-DCMAKE_OSX_ARCHITECTURES=x86_64` to the first command. Set one
|
||||
architecture only. The app cannot be a universal binary.
|
||||
|
||||
## The library only
|
||||
|
||||
With no `DMODEM_GUI_WINPORT`, a build on Linux or macOS makes only
|
||||
libdmodemctl, libdmodemssh and their tests. You do not need clang-retro
|
||||
MFC for this build:
|
||||
|
||||
cmake -S . -B build && cmake --build build && ctest --test-dir build
|
||||
|
||||
## Notes
|
||||
|
||||
The first CMake build downloads libssh and mbedTLS for SSH. This always
|
||||
occurs on Windows and macOS. Use `-DDMODEM_GUI_SSH=OFF` for a build with
|
||||
no SSH. On Linux, it occurs if the libssh of the system
|
||||
@@ -72,8 +77,9 @@ The workflow `.github/workflows/d-modem-bump.yml` keeps the submodule
|
||||
`external/D-Modem` on the main branch of D-Modem. It starts when the main
|
||||
branch of D-Modem changes, one time each day, or when you start it
|
||||
manually. It opens a pull request that moves the submodule. Build
|
||||
(`.github/workflows/build.yml`) builds and tests the apps in that pull
|
||||
request. The workflow merges the pull request when all checks pass. If a
|
||||
(`.github/workflows/build.yml`) builds and tests the app in that pull
|
||||
request. The workflow merges the pull request when all checks pass. Then
|
||||
Build runs on `main`, and the next nightly release has the new app. If a
|
||||
check fails, the pull request stays open for a person. The workflow needs
|
||||
a `DMODEM_BUMP_TOKEN` secret. The header of the workflow gives the
|
||||
necessary permissions.
|
||||
@@ -1,14 +1,17 @@
|
||||
# Design
|
||||
|
||||
## One library, three native shells
|
||||
## One library, one Win32 app
|
||||
|
||||
The apps share all the code that does not draw. `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. Then it gives the bytes that it reads to `dmc_feed()`,
|
||||
writes the data that `dmc_output()` gives it, and calls `dmc_poll()` from a
|
||||
50 ms timer. Thus the library is easy to call from C (GTK), C++ (Win32) and
|
||||
Swift. It is also easy to test (`core/test`, which CI runs with ASan and
|
||||
UBSan).
|
||||
The app is one Win32 app (`windows/`). The same source code builds for
|
||||
Windows, and for Linux and macOS over the portable Win32 layer of
|
||||
clang-retro MFC (refer to "The Windows app on Linux and macOS", below).
|
||||
|
||||
All the code that does not draw is in `core/`. `core/` is libdmodemctl, a
|
||||
small C library with no I/O and no threads ("sans-I/O"). The app opens the
|
||||
modem. Then it gives the bytes that it reads to `dmc_feed()`, writes the
|
||||
data that `dmc_output()` gives it, and calls `dmc_poll()` from a 50 ms
|
||||
timer. Thus the library is easy to call from C and C++. It is also easy to
|
||||
test (`core/test`, which CI runs with ASan and UBSan).
|
||||
|
||||
| Part | What it does |
|
||||
| --- | --- |
|
||||
@@ -16,7 +19,7 @@ UBSan).
|
||||
| `dmc_model` | The settings of the modem from AT!M, with the check of each setting and the command that sets it |
|
||||
| `dmc_path` | The connection path at the top of the Settings page: the terminal, the modem, the line and what the line reaches. For each step, its role, name, state and setting, from the line settings and the state of the session |
|
||||
| `dmc_diag` | The statistics of the last call from AT#UD, as labelled rows (with the V.58 code tables decoded) |
|
||||
| `dmc_vt` | The terminal emulator of the D-Modem app (`shared/.../terminal` of D-Modem/app), ported to C: each type of terminal that it emulates (see below). Each app draws it from its cells |
|
||||
| `dmc_vt` | The terminal emulator of the D-Modem app (`shared/.../terminal` of D-Modem/app), ported to C: each type of terminal that it emulates (see below). The app draws it from its cells |
|
||||
| `dmc_net` | Telnet (option negotiation, terminal type, window size) and rlogin (the handshake, and the window size on the urgent request of the server), for the Remote page |
|
||||
| `dmc_daemon_*` | It reads the text that dmodemd prints when it starts: the device that it made, or its error |
|
||||
|
||||
@@ -27,7 +30,7 @@ also controls its configurators (AT!CF, AT!CT, AT!C). AT!M prints that model
|
||||
as tab-separated lines. Each line has the key of a setting, its kind (pick,
|
||||
number or text), value, default, range, AT form, group, label and help, and
|
||||
then each choice. The Settings page builds its controls from this output.
|
||||
Thus, if a setting is added to the modem, it shows in each app without a
|
||||
Thus, if a setting is added to the modem, it shows in the app without a
|
||||
change here. The library checks a change and sends it as its AT command. The
|
||||
app keeps the change when the modem says OK.
|
||||
|
||||
@@ -35,9 +38,9 @@ The modem keeps no stored profile. Thus the page shows the init string of
|
||||
AT!R. Its **Keep** button saves the string in the line settings of the app.
|
||||
The app sends the string each time that the modem opens.
|
||||
|
||||
## The same screens everywhere
|
||||
## The pages
|
||||
|
||||
Each app has the same seven pages, with the same words:
|
||||
The app has seven pages:
|
||||
|
||||
| Page | Contents |
|
||||
| --- | --- |
|
||||
@@ -72,9 +75,8 @@ accent colour. A step that you must still set (no SIP account, no device) is
|
||||
red and its line is dashed, and the text below says what to set. When the
|
||||
modem starts, dials and is online, the steps light green as the call goes,
|
||||
and the text below shows the CONNECT line. `dmc_path` of libdmodemctl has the
|
||||
words, so the three apps show the same text. Each app draws them:
|
||||
`pathview.c`, `pathview.cpp` (GDI, with the Wingdings of Windows 95) and
|
||||
`PathView.swift`. The D-Modem app has the same picture at the top of its
|
||||
words. The app draws them in `pathview.cpp` (GDI, with the Wingdings of
|
||||
Windows 95). The D-Modem app has the same picture at the top of its
|
||||
Settings, with its own lines (Wi-Fi and Bluetooth to another phone, the
|
||||
mobile calls of the phone, external modems).
|
||||
|
||||
@@ -113,15 +115,14 @@ If the screen of a machine has its own size (40x25 for a C64), the library
|
||||
requests that size (`dmc_vt_requested_cols`). The view stretches its cells
|
||||
to fill the window, by whole pixels where they fit.
|
||||
|
||||
| | The view |
|
||||
| --- | --- |
|
||||
| Windows | `termview.cpp`: GDI, one row at a time into a DIB section (text by `ExtTextOutW`, glyphs and pictures by pixel). The view copies the section to the window (or stretches it, for the double width and height of DEC) |
|
||||
| Linux | `termview.c`: a GtkDrawingArea drawn with Cairo and Pango (the app does not use VTE now) |
|
||||
| macOS | `TerminalView.swift`: an NSView drawn with Core Graphics |
|
||||
The view is `termview.cpp`. It draws with GDI, one row at a time, into a
|
||||
DIB section (text by `ExtTextOutW`, glyphs and pictures by pixel). The
|
||||
view copies the section to the window (or stretches it, for the double
|
||||
width and height of DEC).
|
||||
|
||||
### Copy, capture and print (Windows app)
|
||||
### Copy, capture and print
|
||||
|
||||
The Windows terminal control (`termview.cpp`) keeps a selection. The
|
||||
The terminal control (`termview.cpp`) keeps a selection. The
|
||||
selection uses the rows of `dmc_vt_cell` (a row below 0 is in the
|
||||
scrollback). The selection moves up with its text when new lines push the
|
||||
text into the scrollback.
|
||||
@@ -248,7 +249,7 @@ protocols are:
|
||||
example `.zip`, `.gz` or `.jpg`), or a file whose first 64 KB do not
|
||||
become 5% smaller. When the other side does not use this mode, the
|
||||
transfer is normal ZMODEM. To stop zstd, set `dmc_xfer_options.no_zstd`
|
||||
(the Windows app: Transfer, ZMODEM Compression (zstd)).
|
||||
(in the app: Transfer, ZMODEM Compression (zstd)).
|
||||
`dmc_xfer_zstd` tells if the file now goes with zstd. The zstd encoder
|
||||
and decoder are in `core/src/zstd_codec.c`. They are a C port of the
|
||||
codec of the D-Modem app (`Zstd.kt`), and they do not use libzstd.
|
||||
@@ -283,7 +284,7 @@ other systems). The thread and the app use two queues with a lock:
|
||||
gets only as much as the line can send now. The queue holds 32 KB
|
||||
maximum, thus the thread waits when the line is slow.
|
||||
3. The notify function of `dmc_xfer_set_notify` tells the app when there
|
||||
are bytes to send. On Windows, it posts `WM_APP_XFER` to the window.
|
||||
are bytes to send. The app posts `WM_APP_XFER` to the window.
|
||||
4. `dmc_xfer_get_status` gives the file, the bytes, the size, the retries
|
||||
and the result.
|
||||
|
||||
@@ -299,7 +300,7 @@ ZRQINIT of sz, the ZRINIT of rz, and the Send-Init of kermit -s. When
|
||||
Automatic Receive is on, the app starts a receive, or it opens the Send
|
||||
File dialog for rz.
|
||||
|
||||
The Windows app (`windows/src/xfer.cpp`) has these parts:
|
||||
The app (`windows/src/xfer.cpp`) has these parts:
|
||||
|
||||
- The Transfer menu: Send File, Receive File, Automatic Receive and
|
||||
Cancel Transfer. The Terminal page also has Send and Receive buttons.
|
||||
@@ -317,31 +318,29 @@ with noise. It also does a test with `sz` and `rz` (lrzsz) and with
|
||||
C-Kermit on a pty, when they are installed. Set `DMODEM_XFER_INTEROP=1` to
|
||||
make these tests mandatory.
|
||||
|
||||
The Linux and macOS apps do not have a transfer UI at this time.
|
||||
## How the app starts dmodemd
|
||||
|
||||
## How the apps start 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 app starts dmodemd with `CreateProcess`. The DTE of dmodemd is a TCP
|
||||
socket (`--tcp 127.0.0.1:port`). The app keeps its settings in
|
||||
`dmodem.ini`: `%APPDATA%\D-Modem\dmodem.ini` on Windows,
|
||||
`~/.config/D-Modem/dmodem.ini` on Linux and
|
||||
`~/Library/Application Support/D-Modem/dmodem.ini` on macOS.
|
||||
|
||||
The app gives the SIP account to dmodemd in its environment (`SIP_LOGIN`,
|
||||
`SIP_T38`, `SIP_V152`, `SIP_V150`, `SIP_SRTP`). It gives the country, the
|
||||
USB modem and the debug level as flags. On Linux and macOS, the app makes
|
||||
the pty in the group of the user (`-g`). Thus dmodemd does not need root.
|
||||
USB modem and the debug level as flags.
|
||||
|
||||
Each app can also use a modem that already runs: a device path on Linux and
|
||||
macOS, or a TCP address or a COM port on Windows.
|
||||
The app can also use a modem that already runs: a TCP address or a COM
|
||||
port. On Linux and macOS, the layer changes a COM port name to a device
|
||||
(refer to "The Windows app on Linux and macOS", below).
|
||||
|
||||
The Linux, macOS and Windows apps do not start dmodemd by default. They run the
|
||||
modem in a thread (`libdmodem_embed`), and its DTE is a socket. Refer to
|
||||
The app does not start dmodemd by default. It runs the modem in a thread
|
||||
(`libdmodem_embed`), and its DTE is a socket. Refer to
|
||||
[The built-in modem](embedded-modem.md).
|
||||
|
||||
## Hardware modems: the MultiTech MT9234MU
|
||||
|
||||
The "device" line can also open a hardware modem. The apps send AT commands
|
||||
The COM port line can also open a hardware modem. The app sends AT commands
|
||||
to it and read its result codes, as they do with dmodemd. The Settings page
|
||||
needs `AT!M`, thus it operates only with dmodemd.
|
||||
|
||||
@@ -359,16 +358,16 @@ firmware into the chip each time you connect the modem.
|
||||
Linux does not include `mts_mt9234mu.fw` after June 2026. MultiTech gave no
|
||||
license that lets other persons distribute it, thus linux-firmware removed
|
||||
it. This repository includes the file, with a notice
|
||||
(`linux/firmware/README.md`). The AGPL-3.0 license does not apply to it.
|
||||
(`firmware/README.md`). The AGPL-3.0 license does not apply to it.
|
||||
`cmake --install` puts it in `share/dmodem-gui/firmware`, and
|
||||
`-DDMODEM_GUI_INSTALL_FIRMWARE=ON` also puts it in `/lib/firmware`. Else,
|
||||
copy it to `/lib/firmware` (for the MT9234ZBA-USB, as `mts_mt9234zba.fw`),
|
||||
then disconnect the modem and connect it again.
|
||||
|
||||
On Linux, the app finds the modem in sysfs (`linux/src/usbmodem.c`). The
|
||||
line settings show where the modem is, with a "Use" button. If the modem
|
||||
has no firmware, they show the command that copies the file. When the app opens the port of the
|
||||
modem, it sets RTS/CTS flow control (`CRTSCTS`). The modem uses `&K3` from
|
||||
Select the port of the modem in the Line Settings dialog, with hardware
|
||||
flow control (RTS/CTS). On Linux, give the port a COM name with
|
||||
`WINPORT_COMn` (for example `WINPORT_COM5=/dev/ttyUSB0`, refer to "The
|
||||
Windows app on Linux and macOS", below). The modem uses `&K3` from
|
||||
the factory.
|
||||
|
||||
Set the country of the line with `AT%T19,0,<code>` and `AT&F&W` in the
|
||||
@@ -386,8 +385,8 @@ We did not test this yet with a real MT9234MU.
|
||||
## Remote logins
|
||||
|
||||
The Remote page logs in to a server, next to the modem, in a separate
|
||||
terminal. Telnet and rlogin are a TCP connection that each app makes in its
|
||||
own way. The app uses `dmc_net` of libdmodemctl for the protocol (sans-I/O,
|
||||
terminal. Telnet and rlogin are a TCP connection that the app makes with
|
||||
Winsock. The app uses `dmc_net` of libdmodemctl for the protocol (sans-I/O,
|
||||
as the session). SSH is libdmodemssh (`ssh/`), the client of D-Modem on
|
||||
libssh 0.11. The Android and iOS apps use the same engine. Thus SSH is the
|
||||
same on all platforms, and you do not need to install anything:
|
||||
@@ -403,8 +402,8 @@ same on all platforms, and you do not need to install anything:
|
||||
`~/.ssh`, then keyboard-interactive or a password (three tries), in the
|
||||
dialogs of the app. The app reads `~/.ssh/config` (host aliases, users,
|
||||
ports).
|
||||
- Alternatively, you can select next to the server (the key menu on Linux,
|
||||
Login... on Windows, the key popover on macOS) one of these: the keys of
|
||||
- Alternatively, you can select with Login... next to the server one of
|
||||
these: the keys of
|
||||
the agent only, or a key file. The key file can be in the format of
|
||||
OpenSSH, PEM or the `.ppk` of PuTTY (versions 2 and 3). `ssh/src/ppk.c`
|
||||
reads `.ppk` files, with Argon2, the same with each libssh build. The app
|
||||
@@ -449,11 +448,11 @@ uses Winsock 1.1 (`wsock32`) for its sockets. `getaddrinfo` is the
|
||||
`WspiapiGetAddrInfo` of mingw-w64, which uses `gethostbyname` if Winsock 2
|
||||
is not there.
|
||||
|
||||
| | Telnet and rlogin | SSH | Kept in |
|
||||
| --- | --- | --- | --- |
|
||||
| Linux | GSocketClient, its socket on the main loop (G_IO_PRI for the urgent byte of rlogin) | libdmodemssh on a GThread, events by `g_main_context_invoke`, AdwAlertDialogs | `settings.ini`, `[remote]` |
|
||||
| Windows | Winsock 1.1, `WSAAsyncSelect` (FD_OOB for rlogin), on all Windows versions from 95 | libdmodemssh on a thread, posted events (`WM_APP_SSH`), the `.ssh` of the profile | `dmodem.ini`, `[remote]` |
|
||||
| macOS | a BSD socket on a dispatch source | libdmodemssh (`SSHConnection.swift`) on a thread, events on the main queue, SwiftUI alerts | UserDefaults |
|
||||
| | How the app does it |
|
||||
| --- | --- |
|
||||
| Telnet and rlogin | Winsock 1.1, `WSAAsyncSelect` (FD_OOB for rlogin), on all Windows versions from 95 |
|
||||
| SSH | libdmodemssh on a thread, posted events (`WM_APP_SSH`), the `.ssh` of the profile |
|
||||
| Kept in | `dmodem.ini`, `[remote]` |
|
||||
|
||||
The TERM of SSH and the terminal of rlogin come from the type of terminal
|
||||
(`xterm-256color`, `vt220`, `ansi`, `petscii` ...). The TERMINAL-TYPE of
|
||||
@@ -475,14 +474,15 @@ Voice uses the V.253 voice mode of dmodemd: `AT+FCLASS=8`, `AT+VSM=4` (G.711
|
||||
stream. libdmodemctl does all of this work. It does the DLE framing and its
|
||||
events (hangup, busy, dial tone, digits, caller ID), μ-law, the pacing of
|
||||
the stream by the clock that the app gives to `dmc_poll`, DTMF, and the
|
||||
answering machine. The apps only move 8 kHz 16-bit samples between the
|
||||
answering machine. The app only moves 8 kHz 16-bit samples between the
|
||||
library and the sound card (`dmc_voice_read`, `dmc_voice_write`):
|
||||
|
||||
| | Sound | Settings | Messages | Greeting files beyond the library's |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Linux | PulseAudio on the GLib main loop (or the Pulse server of PipeWire) | `settings.ini`, `[voice]` | `~/.local/share/dmodem-gui/voicemail` | libsndfile, if the build includes it: MP3, FLAC, Ogg Vorbis, Opus |
|
||||
| Windows | `waveOut` and `waveIn` with window callbacks (Windows 95 has them) | `dmodem.ini`, `[voice]` | `%APPDATA%\D-Modem\Voicemail`, or next to the exe | the ACM codecs of the system: MP3 and compressed WAVs (GSM 6.10 and the other installed codecs) |
|
||||
| macOS | AVAudioEngine, converted to 8 kHz | UserDefaults | `~/Library/Application Support/D-Modem/Voicemail` | AVAudioFile: MP3, AAC/M4A, FLAC, ALAC, CAF |
|
||||
| | How the app does it |
|
||||
| --- | --- |
|
||||
| Sound | `waveOut` and `waveIn` with window callbacks (Windows 95 has them). On Linux and macOS, the layer supplies them |
|
||||
| Settings | `dmodem.ini`, `[voice]` |
|
||||
| Messages | `Voicemail` in the settings folder (for example `%APPDATA%\D-Modem\Voicemail`), or next to the exe |
|
||||
| Greeting files beyond the library's | the ACM codecs: MP3 and compressed WAVs (GSM 6.10 and the other installed codecs) |
|
||||
|
||||
The answering machine is disabled until you enable it. When it is enabled,
|
||||
it answers after the selected number of rings (4 by default). It plays the
|
||||
@@ -494,8 +494,8 @@ The app deletes a message that is shorter than one second.
|
||||
You can record a greeting from the microphone, or select a sound file. The
|
||||
app converts the file to 8 kHz mono. The library itself reads WAV (8 to
|
||||
32-bit PCM, floats, A-law, μ-law, IMA and Microsoft ADPCM), AIFF and AIFF-C,
|
||||
and Sun/NeXT `.au` (`dmc_audio_decode`). Each app gives all other files to
|
||||
the decoders of the system, as the table shows. Pick Up changes a message
|
||||
and Sun/NeXT `.au` (`dmc_audio_decode`). The app gives all other files to
|
||||
the ACM codecs, as the table shows. Pick Up changes a message
|
||||
into a call while the caller leaves it. Listen plays the message while the
|
||||
caller leaves it. Messages stay on this computer.
|
||||
|
||||
@@ -565,7 +565,11 @@ code is the same as on Windows.
|
||||
`dmodem0.data` in the settings folder.
|
||||
- SSH uses `~/.ssh` and `/` in paths, because libssh uses POSIX paths
|
||||
on these systems.
|
||||
- The layer changes a COM port name to a device: `COM1` is `/dev/ttyS0`.
|
||||
- The layer changes a COM port name to a device. On Linux, `COM1` is
|
||||
`/dev/ttyS0`. On macOS, `COM1` is the first `/dev/cu.*` device (in
|
||||
alphabetical order, with no Bluetooth devices). To use another device,
|
||||
set the environment variable `WINPORT_COMn`. For example, with
|
||||
`WINPORT_COM5=/dev/ttyUSB0`, `COM5` is `/dev/ttyUSB0`.
|
||||
- CI builds the app on Linux, and on macOS for arm64 and x86_64. On Linux, `winport/test/smoke.sh`
|
||||
starts the app in Xvfb three times: with a TCP line, with a dmodemd
|
||||
that the app starts (`winport/test/dmodemd`, a test dmodemd), and with
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Download
|
||||
|
||||
The [nightly release](https://github.com/D-Modem/gui/releases/tag/nightly)
|
||||
has the apps from the newest build of `main`. A workflow
|
||||
has the app from the newest build of `main`. A workflow
|
||||
(`.github/workflows/nightly.yml`) replaces the release one time each day.
|
||||
When `main` has no new commits, the release does not change.
|
||||
|
||||
@@ -13,14 +13,12 @@ When `main` has no new commits, the release does not change.
|
||||
|
||||
| System | File | What it is |
|
||||
| --- | --- | --- |
|
||||
| Windows 95, 98, ME, NT 4.0 and later | [`dmodem-win9x.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win9x.exe) | The Windows app with the built-in modem. It needs no C runtime DLL. Windows 95 needs Winsock 2. |
|
||||
| Windows 98 SE, ME, 2000 and later | [`dmodem-win98.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win98.exe) | The Windows app with the built-in modem, on `msvcrt.dll`. |
|
||||
| Windows 7 and later | [`dmodem-win7.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win7.exe) | The Windows app with the built-in modem. |
|
||||
| macOS 13 and later | [`D-Modem-macos.zip`](https://github.com/D-Modem/gui/releases/download/nightly/D-Modem-macos.zip) | The macOS app (SwiftUI) with the built-in modem, for arm64 and x86_64. |
|
||||
| Linux, x86_64 | [`dmodem-gui-linux-x86_64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-gui-linux-x86_64.tar.gz) | The Linux app (GTK 4). |
|
||||
| Linux, x86_64 (X11) | [`dmodem-win32-linux-x86_64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-linux-x86_64.tar.gz) | The Windows app on Linux, with the built-in modem. |
|
||||
| macOS, arm64 (Apple silicon) | [`dmodem-win32-macos-arm64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-macos-arm64.tar.gz) | The Windows app on macOS, with the built-in modem. |
|
||||
| macOS, x86_64 (Intel Mac) | [`dmodem-win32-macos-x86_64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-macos-x86_64.tar.gz) | The Windows app on macOS, with the built-in modem. |
|
||||
| Windows 95, 98, ME, NT 4.0 and later | [`dmodem-win9x.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win9x.exe) | The app with the built-in modem. It needs no C runtime DLL. Windows 95 needs Winsock 2. |
|
||||
| Windows 98 SE, ME, 2000 and later | [`dmodem-win98.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win98.exe) | The app with the built-in modem, on `msvcrt.dll`. |
|
||||
| Windows 7 and later | [`dmodem-win7.exe`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win7.exe) | The app with the built-in modem. |
|
||||
| Linux, x86_64 (X11) | [`dmodem-win32-linux-x86_64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-linux-x86_64.tar.gz) | The app on Linux, with the built-in modem. |
|
||||
| macOS, arm64 (Apple silicon) | [`dmodem-win32-macos-arm64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-macos-arm64.tar.gz) | The app on macOS, with the built-in modem. |
|
||||
| macOS, x86_64 (Intel Mac) | [`dmodem-win32-macos-x86_64.tar.gz`](https://github.com/D-Modem/gui/releases/download/nightly/dmodem-win32-macos-x86_64.tar.gz) | The app on macOS, with the built-in modem. |
|
||||
| All | [`SHA256SUMS`](https://github.com/D-Modem/gui/releases/download/nightly/SHA256SUMS) | The SHA-256 of each file. |
|
||||
|
||||
If a file is not in the release, the newest build did not make it. The
|
||||
@@ -43,22 +41,22 @@ The result for the file must be `OK`.
|
||||
|
||||
## Install on macOS
|
||||
|
||||
1. Download `D-Modem-macos.zip`.
|
||||
2. Double-click the file to extract the app.
|
||||
3. Move the app to the **Applications** folder.
|
||||
4. Right-click the app, then select **Open**. The app is not notarized.
|
||||
Thus macOS shows a warning the first time.
|
||||
1. Download `dmodem-win32-macos-arm64.tar.gz` for a Mac with Apple
|
||||
silicon, or `dmodem-win32-macos-x86_64.tar.gz` for an Intel Mac.
|
||||
2. Extract the file. In a terminal, type
|
||||
`tar -xzf dmodem-win32-macos-arm64.tar.gz` (or the name of the x86_64
|
||||
file).
|
||||
3. Remove the quarantine attribute. Type
|
||||
`xattr -d com.apple.quarantine dmodem-win32`. The app is not notarized.
|
||||
4. Start the app. Type `./dmodem-win32`.
|
||||
|
||||
## Install on Linux
|
||||
|
||||
The Linux app needs GTK 4, libadwaita, PulseAudio and libsndfile.
|
||||
|
||||
1. Install the libraries. On Ubuntu 24.04, type
|
||||
`sudo apt install libgtk-4-1 libadwaita-1-0 libpulse0 libsndfile1`.
|
||||
2. Download `dmodem-gui-linux-x86_64.tar.gz`.
|
||||
3. Extract the file into `/`. Type
|
||||
`sudo tar -xzf dmodem-gui-linux-x86_64.tar.gz -C /`.
|
||||
4. Start the app from the menu of applications, or type `dmodem-gui`.
|
||||
`sudo apt install libx11-6 libusb-1.0-0 libasound2t64`.
|
||||
2. Download `dmodem-win32-linux-x86_64.tar.gz`.
|
||||
3. Extract the file. Type `tar -xzf dmodem-win32-linux-x86_64.tar.gz`.
|
||||
4. Start the app. Type `./dmodem-win32`.
|
||||
|
||||
## Build the app
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
# The built-in modem
|
||||
|
||||
The Linux app, the macOS app, the Windows app (Windows 98 SE and later)
|
||||
and the Windows app on Linux and macOS have the D-Modem modem in them.
|
||||
Thus, these apps do not need a separate `dmodemd`. This includes the
|
||||
Windows 95 build.
|
||||
The app has the D-Modem modem in it, on Windows (Windows 95 and later),
|
||||
on Linux and on macOS. Thus, the app does not need a separate `dmodemd`.
|
||||
|
||||
## What it does
|
||||
|
||||
@@ -24,39 +22,27 @@ app opens the device and starts no modem.
|
||||
|
||||
- There is no pty and no `/dev/ttyDM0` link. Other programs cannot use the
|
||||
built-in modem. To share the modem with other programs, start `dmodemd`.
|
||||
- The app does not need root (Linux), a pty (macOS) or a firewall
|
||||
- The app does not need root or a pty (Linux and macOS), or a firewall
|
||||
exception for a TCP port (Windows).
|
||||
- A USB modem needs a udev rule that lets the user open the device.
|
||||
- A softmodem codec needs the user in the `audio` group.
|
||||
- The modem keeps the measurements of the line in
|
||||
`~/.local/share/dmodem-gui/dmodem0.data` (Linux),
|
||||
`~/.config/D-Modem/dmodem0.data` (Linux),
|
||||
`~/Library/Application Support/D-Modem/dmodem0.data` (macOS), or
|
||||
`%APPDATA%\D-Modem\dmodem0.data` (Windows).
|
||||
- The **Log** page shows the log of the modem.
|
||||
|
||||
## How to use dmodemd
|
||||
|
||||
On Linux:
|
||||
|
||||
1. Open the line settings (the gear button on the Modem page).
|
||||
2. In **Advanced**, set **Built-in modem** to off.
|
||||
3. Optional: set the path of `dmodemd`.
|
||||
|
||||
On macOS:
|
||||
|
||||
1. Open the line settings (**D-Modem > Settings**).
|
||||
2. In **The modem**, set **Built-in modem** to off.
|
||||
3. Optional: set the path of `dmodemd`.
|
||||
|
||||
On Windows, the Line Settings dialog does not have this setting yet. Close
|
||||
the app, and add this line to the `[line]` section of
|
||||
`%APPDATA%\D-Modem\dmodem.ini` (Windows), `~/.config/D-Modem/dmodem.ini`
|
||||
(the Windows app on Linux) or
|
||||
`~/Library/Application Support/D-Modem/dmodem.ini` (the Windows app on
|
||||
macOS):
|
||||
The Line Settings dialog does not have this setting yet. Close the app,
|
||||
and add this line to the `[line]` section of the settings file:
|
||||
|
||||
builtin=0
|
||||
|
||||
The settings file is `%APPDATA%\D-Modem\dmodem.ini` (Windows),
|
||||
`~/.config/D-Modem/dmodem.ini` (Linux) or
|
||||
`~/Library/Application Support/D-Modem/dmodem.ini` (macOS).
|
||||
|
||||
The app then starts `dmodemd` as before.
|
||||
|
||||
## How to build it
|
||||
@@ -66,22 +52,15 @@ The D-Modem source is a git submodule in `external/D-Modem`. To get it:
|
||||
git submodule update --init
|
||||
|
||||
If the submodule is there, CMake builds the built-in modem
|
||||
(`DMODEM_GUI_EMBED`, on by default) for the Linux app, the macOS app, and
|
||||
the Windows app with the clang-retro configurations `win32-picolibc` (the
|
||||
Windows 95 build), `win98`, `winme`, `win7` and later, and for the Windows
|
||||
app on Linux and macOS (`DMODEM_GUI_WINPORT`). To build the app with no built-in
|
||||
(`DMODEM_GUI_EMBED`, on by default) for the app on Windows with the
|
||||
clang-retro configurations `win32-picolibc` (the Windows 95 build),
|
||||
`win98`, `winme`, `win7` and later, and for the app on Linux and macOS
|
||||
(`DMODEM_GUI_WINPORT`). To build the app with no built-in
|
||||
modem, use `-DDMODEM_GUI_EMBED=OFF`. For a USB line and an ALSA line, also
|
||||
install `libusb-1.0-0-dev` and `libasound2-dev`.
|
||||
|
||||
The first build downloads libre and Mbed TLS for the SIP line of the modem.
|
||||
|
||||
The macOS app builds with Xcode, not with CMake. CMake builds the
|
||||
libraries of the built-in modem, and writes `build/macos-embed.xcconfig`.
|
||||
This file gives Xcode the header path, the libraries and the Swift
|
||||
condition `DMODEM_GUI_EMBED`. The Xcode project (`macos/project.yml`)
|
||||
includes this file. Thus, do the CMake build before `xcodegen`. Refer to
|
||||
[Building](building.md).
|
||||
|
||||
## Licence
|
||||
|
||||
D-Modem and the GUI are both under the AGPL-3.0-only, or a commercial
|
||||
@@ -93,15 +72,13 @@ Windows and macOS, the build links libusb (LGPL-2.1) statically, as
|
||||
|
||||
## Status
|
||||
|
||||
| App | Status |
|
||||
| System | Status |
|
||||
| --- | --- |
|
||||
| Linux | Done. Tested: a call from the Dial button to another D-Modem connects at 62666 bit/s (V.91), and **Stop** hangs up. |
|
||||
| Windows 98 SE and later | Done (`win98` build). It builds, and its imports agree with Windows 98 SE. It is not tested on Windows or Wine yet. |
|
||||
| Windows 7 and later | Done (`win7` build). It builds. It is not tested on Windows or Wine yet. |
|
||||
| Windows 95, NT 4.0 and later | Done (`win32-picolibc` build). It builds, and its imports agree with Windows 95 and NT 4.0. It is not tested on Windows or Wine yet. Refer to "Windows 95" below. |
|
||||
| macOS | Done. CI builds it for arm64 and x86_64, and checks that the library is in the app for each architecture. It is not tested on a Mac yet. |
|
||||
| The Windows app on Linux | Done. CI builds it, checks that the library is in the app, and starts the built-in modem in Xvfb (`winport/test/smoke.sh`). |
|
||||
| The Windows app on macOS | Done (arm64 and x86_64). CI builds it for each architecture, and checks that the library is in the app. It is not tested on a Mac yet. |
|
||||
| Linux | Done. CI builds it, checks that the library is in the app, and starts the built-in modem in Xvfb (`winport/test/smoke.sh`). |
|
||||
| macOS | Done (arm64 and x86_64). CI builds it for each architecture, and checks that the library is in the app. It is not tested on a Mac yet. |
|
||||
|
||||
### Windows 95
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Features
|
||||
|
||||
This page gives the details of the pages and menus of the apps. The
|
||||
This page gives the details of the pages and menus of the app. The
|
||||
[README](../README.md) gives a summary.
|
||||
|
||||
- **Remote**: log in to a server by SSH, Telnet or rlogin, in a separate terminal. SSH is built in, on libssh: it uses the keys, agent, config and known hosts of OpenSSH. It can use or import the `.ppk` keys of PuTTY. It uses Pageant on Windows, and an ssh-agent on Linux and macOS. On Windows 95, SSH needs CryptoAPI (Windows 95 OSR2, or Internet Explorer 3 or later)
|
||||
@@ -10,8 +10,8 @@ This page gives the details of the pages and menus of the apps. The
|
||||
the Minitel and the Tektronix 4014. They have sixel, ReGIS and Tektronix
|
||||
graphics, and the font of each machine (the SyncTERM copies of their ROMs,
|
||||
LGPL-2.0-or-later: `core/licenses/syncterm-fonts-LGPL-2.0.txt`)
|
||||
- **File transfers** (Windows app): send and receive files on the modem line or on a Telnet, rlogin or SSH login. The protocols are the same as the D-Modem app: ZMODEM (with Automatic Receive when the remote side starts sz, rz or kermit -s, with Crash Recovery, and with zstd compression to the D-Modem BBS and app), YMODEM, YMODEM-G, XMODEM, XMODEM-1K, Kermit, Intel HEX, Motorola S-records and plain text. Use the Transfer menu, or the Send and Receive buttons of the Terminal page
|
||||
- **Copy and capture** (Windows app): select text with the mouse (Shift and the mouse when the remote side uses the mouse), then copy it. Paste to Host, Select All, Capture Text (to a file), Capture to Printer, and Print (the screen or the selection). Text that the remote side sends to its printer port goes to the printer. Use the Edit and Transfer menus, or click the right mouse button on the terminal
|
||||
- **ASCII Setup** (Windows app, Modem menu): the same items as HyperTerminal. For the data that you send: Enter sends CR LF, the local echo, and the line delay and character delay of a text file. For the data that you receive: an LF after each CR, 7-bit ASCII, and the wrap of long lines. The settings apply to the modem terminal and to the Remote terminal
|
||||
- **Terminal Settings** (Windows app, Modem menu): the same items as HyperTerminal, for the modem terminal and for the Remote terminal. They are what Backspace sends (Ctrl+H, Del, or Ctrl+H, Space, Ctrl+H), the function, arrow and Ctrl keys as terminal keys or Windows keys, the backscroll buffer lines, the font, the cursor, the Telnet terminal ID, and Exit program upon disconnecting. The status bar shows the connect timer during a call
|
||||
- **Call menu** (Windows app): Call (sessions with a name and a number, as the connection files of HyperTerminal), Wait for a Call (ATS0=1), Disconnect, and Send Break (Ctrl+Break: a COM port or a Telnet connection). Line Settings has the COM port settings: bits per second, data bits, parity, stop bits and flow control
|
||||
- **File transfers**: send and receive files on the modem line or on a Telnet, rlogin or SSH login. The protocols are the same as the D-Modem app: ZMODEM (with Automatic Receive when the remote side starts sz, rz or kermit -s, with Crash Recovery, and with zstd compression to the D-Modem BBS and app), YMODEM, YMODEM-G, XMODEM, XMODEM-1K, Kermit, Intel HEX, Motorola S-records and plain text. Use the Transfer menu, or the Send and Receive buttons of the Terminal page
|
||||
- **Copy and capture**: select text with the mouse (Shift and the mouse when the remote side uses the mouse), then copy it. Paste to Host, Select All, Capture Text (to a file), Capture to Printer, and Print (the screen or the selection). Text that the remote side sends to its printer port goes to the printer. Use the Edit and Transfer menus, or click the right mouse button on the terminal
|
||||
- **ASCII Setup** (Modem menu): the same items as HyperTerminal. For the data that you send: Enter sends CR LF, the local echo, and the line delay and character delay of a text file. For the data that you receive: an LF after each CR, 7-bit ASCII, and the wrap of long lines. The settings apply to the modem terminal and to the Remote terminal
|
||||
- **Terminal Settings** (Modem menu): the same items as HyperTerminal, for the modem terminal and for the Remote terminal. They are what Backspace sends (Ctrl+H, Del, or Ctrl+H, Space, Ctrl+H), the function, arrow and Ctrl keys as terminal keys or Windows keys, the backscroll buffer lines, the font, the cursor, the Telnet terminal ID, and Exit program upon disconnecting. The status bar shows the connect timer during a call
|
||||
- **Call menu**: Call (sessions with a name and a number, as the connection files of HyperTerminal), Wait for a Call (ATS0=1), Disconnect, and Send Break (Ctrl+Break: a COM port or a Telnet connection). Line Settings has the COM port settings: bits per second, data bits, parity, stop bits and flow control
|
||||
|
Before Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 43 KiB |
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: D-Modem desktop apps
|
||||
title: D-Modem desktop app
|
||||
hide:
|
||||
- navigation
|
||||
- toc
|
||||
@@ -9,12 +9,12 @@ hide:
|
||||
<img src="images/dmodem.svg" alt="">
|
||||
<div markdown>
|
||||
|
||||
# D-Modem desktop apps
|
||||
# D-Modem desktop app
|
||||
|
||||
**D-Modem on the desktop: a V.92 modem in a window, from Windows 95 to
|
||||
Windows 11, on macOS and on Linux.**
|
||||
|
||||
The apps have the modem built in. You do not need modem hardware or a
|
||||
The app has the modem built in. You do not need modem hardware or a
|
||||
separate `dmodemd`. Dial a BBS, a fax machine or an ISP from a SIP call,
|
||||
a USB modem or a hardware modem.
|
||||
|
||||
@@ -24,9 +24,9 @@ a USB modem or a hardware modem.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<img src="images/linux-settings.png" width="49%" alt="The Settings page of the Linux app"> <img src="images/windows-setup-screen.png" width="49%" alt="The Terminal of the Windows app with the setup screen of the modem">
|
||||
<img src="images/windows-settings.png" width="49%" alt="The Settings page of the app"> <img src="images/windows-setup-screen.png" width="49%" alt="The Terminal of the app with the setup screen of the modem">
|
||||
|
||||
## What the apps do
|
||||
## What the app does
|
||||
|
||||
<div class="grid cards" markdown>
|
||||
|
||||
@@ -78,25 +78,24 @@ a USB modem or a hardware modem.
|
||||
|
||||
[All the features](features.md){ .md-button }
|
||||
|
||||
<img src="images/linux-phone.png" width="49%" alt="The Phone page of the Linux app"> <img src="images/windows-phone.png" width="49%" alt="The Phone page of the Windows app as it takes a message">
|
||||
<img src="images/windows-modem.png" width="49%" alt="The Modem page of the app"> <img src="images/windows-phone.png" width="49%" alt="The Phone page of the app as it takes a message">
|
||||
|
||||
## Three native apps, one library
|
||||
## One Win32 app, one library
|
||||
|
||||
Each app uses the native toolkit of its system. All three apps are thin
|
||||
shells over one small C library, libdmodemctl. Thus they operate in the
|
||||
same way.
|
||||
The app is plain Win32, built with
|
||||
[clang-retro](https://clang-retro.github.io/). The same Win32 code also
|
||||
runs on Linux and macOS, over the portable Win32 layer of
|
||||
[clang-retro MFC](https://github.com/clang-retro/mfc). The app is a thin
|
||||
shell over one small C library, libdmodemctl. Thus it operates in the
|
||||
same way on each system.
|
||||
|
||||
| | Windows | macOS | Linux |
|
||||
| --- | --- | --- | --- |
|
||||
| Toolkit | Win32, C++ | SwiftUI | GTK 4, libadwaita |
|
||||
| Runs on | Windows 95 and later | macOS 13 and later | GTK 4.10 and libadwaita 1.5 or later (Ubuntu 24.04, Fedora 40) |
|
||||
| Toolkit | Win32, C++ | Win32, over the Cocoa layer of clang-retro MFC | Win32, over the X11 and Wayland layer of clang-retro MFC |
|
||||
| Runs on | Windows 95 and later | arm64 (Apple silicon) and x86_64 (Intel Mac) | x86_64 |
|
||||
| Built-in modem | Yes | Yes | Yes |
|
||||
|
||||
The Windows app is plain Win32, built with
|
||||
[clang-retro](https://clang-retro.github.io/). The same Win32 code also
|
||||
runs on Linux and macOS, over the portable Win32 layer of
|
||||
[clang-retro MFC](https://github.com/clang-retro/mfc). Refer to
|
||||
[Design](design.md).
|
||||
Refer to [Design](design.md).
|
||||
|
||||
## Start here
|
||||
|
||||
@@ -105,12 +104,12 @@ runs on Linux and macOS, over the portable Win32 layer of
|
||||
- **Build the app:** refer to [Building](building.md).
|
||||
- **Use the modem without dmodemd:** refer to
|
||||
[The built-in modem](embedded-modem.md).
|
||||
- **Learn how the apps are built:** refer to [Design](design.md) and to
|
||||
- **Learn how the app is built:** refer to [Design](design.md) and to
|
||||
the API of [libdmodemctl](https://github.com/D-Modem/gui/blob/main/core/include/dmodemctl.h).
|
||||
|
||||
## Part of the D-Modem suite
|
||||
|
||||
The desktop apps are one part of the [D-Modem suite](https://d-modem.github.io/).
|
||||
The desktop app is one part of the [D-Modem suite](https://d-modem.github.io/).
|
||||
The suite has the softmodem ([D-Modem](https://d-modem.github.io/D-Modem/)),
|
||||
the [app for Android and iOS](https://d-modem.github.io/app/), the
|
||||
[pico-serial boards](https://d-modem.github.io/hardware/), and the
|
||||
|
||||
@@ -12,8 +12,8 @@ same code.
|
||||
|
||||
To install it:
|
||||
|
||||
sudo cp linux/firmware/mts_mt9234mu.fw /lib/firmware/
|
||||
sudo cp linux/firmware/mts_mt9234mu.fw /lib/firmware/mts_mt9234zba.fw
|
||||
sudo cp firmware/mts_mt9234mu.fw /lib/firmware/
|
||||
sudo cp firmware/mts_mt9234mu.fw /lib/firmware/mts_mt9234zba.fw
|
||||
|
||||
Then disconnect the modem and connect it again. `cmake --install` puts the
|
||||
file in `share/dmodem-gui/firmware`. With `-DDMODEM_GUI_INSTALL_FIRMWARE=ON`,
|
||||
@@ -1,66 +0,0 @@
|
||||
# The Linux (and BSD) app: GTK 4 and libadwaita over libdmodemctl
|
||||
# (and libdmodemssh for the Remote page's SSH).
|
||||
add_executable(dmodem-gui
|
||||
src/main.c
|
||||
src/window.c
|
||||
src/modem.c
|
||||
src/config.c
|
||||
src/usbmodem.c
|
||||
src/settings.c
|
||||
src/pathview.c
|
||||
src/stats.c
|
||||
src/voice.c
|
||||
src/remote.c
|
||||
src/termview.c
|
||||
src/audio.c)
|
||||
target_link_libraries(dmodem-gui PRIVATE dmodemctl dmodemssh PkgConfig::GTK)
|
||||
# the modem built in (libdmodem_embed): no dmodemd to start
|
||||
if(DMODEM_GUI_EMBED AND TARGET dmodem_embed)
|
||||
target_link_libraries(dmodem-gui PRIVATE dmodem_embed)
|
||||
target_compile_definitions(dmodem-gui PRIVATE DMODEM_GUI_EMBED)
|
||||
set_target_properties(dmodem-gui PROPERTIES LINKER_LANGUAGE CXX)
|
||||
endif()
|
||||
# where the MT9234MU's firmware is installed, and where it is in the source
|
||||
include(GNUInstallDirs)
|
||||
target_compile_definitions(dmodem-gui PRIVATE
|
||||
DMODEM_FIRMWARE_DIR="${CMAKE_INSTALL_FULL_DATADIR}/dmodem-gui/firmware"
|
||||
DMODEM_FIRMWARE_SRC="${CMAKE_CURRENT_SOURCE_DIR}/firmware")
|
||||
# the sound of voice calls: PulseAudio's client (PipeWire serves it
|
||||
# too); without it the app has no sound
|
||||
pkg_check_modules(PULSE IMPORTED_TARGET libpulse-mainloop-glib)
|
||||
if(PULSE_FOUND)
|
||||
target_link_libraries(dmodem-gui PRIVATE PkgConfig::PULSE)
|
||||
target_compile_definitions(dmodem-gui PRIVATE HAVE_PULSE)
|
||||
else()
|
||||
message(STATUS "libpulse-mainloop-glib not found: the Linux app has no sound for voice calls")
|
||||
endif()
|
||||
# greetings from MP3, FLAC, Ogg and the like (WAV, AIFF and .au need
|
||||
# nothing more)
|
||||
pkg_check_modules(SNDFILE IMPORTED_TARGET sndfile)
|
||||
if(SNDFILE_FOUND)
|
||||
target_link_libraries(dmodem-gui PRIVATE PkgConfig::SNDFILE)
|
||||
target_compile_definitions(dmodem-gui PRIVATE HAVE_SNDFILE)
|
||||
else()
|
||||
message(STATUS "libsndfile not found: greetings are read from WAV, AIFF and .au files only")
|
||||
endif()
|
||||
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)
|
||||
# MultiTech's firmware for the MT9234MU (licence unknown: linux/firmware/README.md)
|
||||
install(FILES firmware/mts_mt9234mu.fw firmware/README.md
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/dmodem-gui/firmware)
|
||||
option(DMODEM_GUI_INSTALL_FIRMWARE
|
||||
"Also install mts_mt9234mu.fw (and mts_mt9234zba.fw) in /lib/firmware" OFF)
|
||||
if(DMODEM_GUI_INSTALL_FIRMWARE)
|
||||
install(FILES firmware/mts_mt9234mu.fw DESTINATION /lib/firmware)
|
||||
install(FILES firmware/mts_mt9234mu.fw DESTINATION /lib/firmware
|
||||
RENAME mts_mt9234zba.fw)
|
||||
endif()
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/assets/dmodem.svg
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps
|
||||
RENAME io.github.d_modem.DModem.svg)
|
||||
@@ -1,216 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* app.h - the Linux app (GTK 4, libadwaita): what its parts share
|
||||
*/
|
||||
#ifndef DMODEM_GUI_APP_H
|
||||
#define DMODEM_GUI_APP_H
|
||||
|
||||
#include <adwaita.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;
|
||||
/* SIP with no account (dmodemd's SIP_LOGIN=anonymous): nothing
|
||||
registered, SIP addresses (sip:user@host, user@host) dialled as
|
||||
they are, from "Anonymous" */
|
||||
gboolean sip_anonymous;
|
||||
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 */
|
||||
/* the modem built into the app (libdmodem_embed, DMODEM_GUI_EMBED)
|
||||
for the SIP, USB and ALSA lines; FALSE: dmodemd started */
|
||||
gboolean builtin;
|
||||
char *init; /* commands sent when the modem opens */
|
||||
int debug; /* dmodemd -d */
|
||||
/* the answering machine ([voice]): on, after how many RINGs, a
|
||||
message's longest (s) */
|
||||
gboolean voicemail;
|
||||
int vm_rings, vm_max;
|
||||
/* the Remote page's last login ([remote]): "SSH", "Telnet" or
|
||||
"rlogin", the server, its port (0: the protocol's), the user */
|
||||
char *remote_proto, *remote_host, *remote_user;
|
||||
/* how SSH logs in: "auto" (OpenSSH's keys and the agent), "agent"
|
||||
or "key" (remote_key's file: OpenSSH's, PEM or PuTTY's .ppk);
|
||||
the agent's socket ("": SSH_AUTH_SOCK's) */
|
||||
char *remote_auth, *remote_key, *remote_agent;
|
||||
/* the terminals' kinds (dmc_vt profiles' ids) */
|
||||
char *term_type, *remote_term;
|
||||
int remote_port;
|
||||
} 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;
|
||||
/* the modem built in (modem.c; a struct dmodem_embed), when it
|
||||
runs; its start's number, so that the news of an older start is
|
||||
ignored */
|
||||
void *embed;
|
||||
gboolean embed_running;
|
||||
guint embed_gen;
|
||||
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;
|
||||
GtkWidget *term, *term_type;
|
||||
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;
|
||||
|
||||
/* the Phone page (voice.c) */
|
||||
struct Voice *voice;
|
||||
};
|
||||
|
||||
/* 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 SIP line has what dmodemd needs: an account, or none (anonymous) */
|
||||
gboolean config_sip_ready(const Config *c);
|
||||
/* the line settings dialog */
|
||||
void prefs_show(App *a);
|
||||
|
||||
/* usbmodem.c: a MultiTech MT9234MU (or MT9234ZBA-USB) on USB, from
|
||||
sysfs */
|
||||
typedef struct UsbModem {
|
||||
char *name; /* "MultiTech MT9234MU" */
|
||||
char *tty; /* "/dev/ttyUSB0", or NULL if it has none */
|
||||
gboolean no_firmware; /* in the boot ROM: no firmware loaded */
|
||||
} UsbModem;
|
||||
/* the first one plugged in, or NULL */
|
||||
UsbModem *usbmodem_find(void);
|
||||
/* what it is and where, or what it needs, for the user */
|
||||
char *usbmodem_describe(const UsbModem *m);
|
||||
/* whether Linux has its firmware file (mts_mt9234mu.fw) */
|
||||
gboolean usbmodem_firmware_present(void);
|
||||
/* the copy of mts_mt9234mu.fw that comes with the app, or NULL */
|
||||
char *usbmodem_shipped_firmware(void);
|
||||
/* whether tty path is such a modem's */
|
||||
gboolean usbmodem_is(const char *path);
|
||||
void usbmodem_free(UsbModem *m);
|
||||
|
||||
/* 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);
|
||||
/* fn (may be NULL) gets the response of the session's command tag
|
||||
(dmc_voice_dial()'s and the like) */
|
||||
void modem_wait(App *a, int tag, 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);
|
||||
|
||||
/* voice.c: the Phone page, voice calls' audio, the answering machine
|
||||
and its messages */
|
||||
GtkWidget *voice_page_new(App *a);
|
||||
void voice_state(App *a);
|
||||
void voice_event(App *a, const dmc_event *ev);
|
||||
/* the answering machine's settings to the session */
|
||||
void voice_configure(App *a);
|
||||
|
||||
/* audio.c: the sound card, 8 kHz mono (PulseAudio, or PipeWire's) */
|
||||
/* the speaker's next samples: how many of n there were (the rest
|
||||
silence); the microphone's */
|
||||
typedef int (*AudioPull)(App *a, int16_t *pcm, int n);
|
||||
typedef void (*AudioPush)(App *a, const int16_t *pcm, int n);
|
||||
/* sound from pull and to push (either NULL for none): FALSE if there
|
||||
is no sound here */
|
||||
gboolean audio_start(App *a, AudioPull pull, AudioPush push);
|
||||
void audio_stop(App *a);
|
||||
gboolean audio_available(void);
|
||||
|
||||
|
||||
/* termview.c: a terminal widget of its own screen (dmc_vt), whose keys
|
||||
go to fn */
|
||||
typedef void (*TermTypedFn)(const char *data, int n, void *ctx);
|
||||
GtkWidget *termview_new(TermTypedFn fn, void *ctx);
|
||||
/* bytes from the far end */
|
||||
void termview_feed(GtkWidget *w, const char *data, int n);
|
||||
void termview_reset(GtkWidget *w);
|
||||
void termview_size(GtkWidget *w, int *cols, int *rows);
|
||||
/* what Backspace sends (DEL unless set) */
|
||||
void termview_set_backspace(GtkWidget *w, int code);
|
||||
/* the kind of terminal it is (dmc_vt_set_profile()'s id) */
|
||||
void termview_set_profile(GtkWidget *w, const char *id);
|
||||
const char *termview_profile(GtkWidget *w);
|
||||
void termview_focus(GtkWidget *w);
|
||||
/* a drop-down of the kinds of terminal, id chosen; the one chosen */
|
||||
GtkWidget *term_types_new(const char *id);
|
||||
const char *term_types_chosen(GtkWidget *d);
|
||||
|
||||
/* remote.c: the Remote page, a login by SSH, Telnet or rlogin */
|
||||
GtkWidget *remote_page_new(App *a);
|
||||
/* its connection ended (the app is quitting) */
|
||||
void remote_stop(App *a);
|
||||
|
||||
/* pathview.c: the connection path at the top of the Settings page, as
|
||||
the line settings and the modem are now */
|
||||
GtkWidget *pathview_new(App *a);
|
||||
void pathview_update(App *a);
|
||||
|
||||
/* stats.c */
|
||||
GtkWidget *stats_page_new(App *a);
|
||||
void stats_refresh(App *a);
|
||||
|
||||
#endif
|
||||
@@ -1,217 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* audio.c - the sound card for voice calls, greetings and messages:
|
||||
* PulseAudio (or PipeWire's pulse server) on GLib's main
|
||||
* loop, so that no thread is needed; 16-bit mono at 8 kHz,
|
||||
* the line's own rate, and the server converts
|
||||
*
|
||||
* Without libpulse the app builds all the same, with no sound.
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
#ifdef HAVE_PULSE
|
||||
|
||||
#include <pulse/glib-mainloop.h>
|
||||
#include <pulse/pulseaudio.h>
|
||||
|
||||
/* the speaker's and the microphone's buffers: 40 ms, 20 ms a read */
|
||||
#define PLAY_MS 40
|
||||
#define READ_MS 20
|
||||
|
||||
static struct {
|
||||
App *a;
|
||||
pa_glib_mainloop *loop;
|
||||
pa_context *ctx;
|
||||
pa_stream *play, *rec;
|
||||
AudioPull pull;
|
||||
AudioPush push;
|
||||
gboolean failed;
|
||||
} au;
|
||||
|
||||
static const pa_sample_spec spec = {
|
||||
PA_SAMPLE_S16NE, DMC_VOICE_RATE, 1
|
||||
};
|
||||
|
||||
static void writable(pa_stream *st, size_t bytes, void *data)
|
||||
{
|
||||
(void)data;
|
||||
while (bytes >= 2) {
|
||||
void *p = NULL;
|
||||
size_t n = bytes;
|
||||
if (pa_stream_begin_write(st, &p, &n) < 0 || !p)
|
||||
return;
|
||||
int want = (int)(n / 2), got = 0;
|
||||
if (au.pull)
|
||||
got = au.pull(au.a, p, want);
|
||||
if (got < want)
|
||||
memset((int16_t *)p + got, 0,
|
||||
(size_t)(want - got) * 2);
|
||||
pa_stream_write(st, p, (size_t)want * 2, NULL, 0,
|
||||
PA_SEEK_RELATIVE);
|
||||
bytes -= (size_t)want * 2;
|
||||
}
|
||||
}
|
||||
|
||||
static void readable(pa_stream *st, size_t bytes, void *data)
|
||||
{
|
||||
(void)bytes;
|
||||
(void)data;
|
||||
const void *p;
|
||||
size_t n;
|
||||
while (pa_stream_readable_size(st) > 0) {
|
||||
if (pa_stream_peek(st, &p, &n) < 0)
|
||||
return;
|
||||
if (!n)
|
||||
break;
|
||||
/* (a hole: none of it) */
|
||||
if (p && au.push)
|
||||
au.push(au.a, p, (int)(n / 2));
|
||||
pa_stream_drop(st);
|
||||
}
|
||||
}
|
||||
|
||||
static void streams_close(void)
|
||||
{
|
||||
if (au.play) {
|
||||
pa_stream_disconnect(au.play);
|
||||
pa_stream_unref(au.play);
|
||||
au.play = NULL;
|
||||
}
|
||||
if (au.rec) {
|
||||
pa_stream_disconnect(au.rec);
|
||||
pa_stream_unref(au.rec);
|
||||
au.rec = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static void streams_open(void)
|
||||
{
|
||||
pa_buffer_attr at;
|
||||
memset(&at, 0xff, sizeof(at));
|
||||
if (au.pull && !au.play) {
|
||||
au.play = pa_stream_new(au.ctx, "Voice call", &spec, NULL);
|
||||
pa_stream_set_write_callback(au.play, writable, NULL);
|
||||
at.tlength = (uint32_t)pa_usec_to_bytes(PLAY_MS * 1000, &spec);
|
||||
at.minreq = (uint32_t)pa_usec_to_bytes(READ_MS * 1000, &spec);
|
||||
pa_stream_connect_playback(au.play, NULL, &at,
|
||||
PA_STREAM_ADJUST_LATENCY, NULL,
|
||||
NULL);
|
||||
}
|
||||
memset(&at, 0xff, sizeof(at));
|
||||
if (au.push && !au.rec) {
|
||||
au.rec = pa_stream_new(au.ctx, "Voice call", &spec, NULL);
|
||||
pa_stream_set_read_callback(au.rec, readable, NULL);
|
||||
at.fragsize = (uint32_t)pa_usec_to_bytes(READ_MS * 1000, &spec);
|
||||
pa_stream_connect_record(au.rec, NULL, &at,
|
||||
PA_STREAM_ADJUST_LATENCY);
|
||||
}
|
||||
}
|
||||
|
||||
static gboolean unref_later(gpointer c)
|
||||
{
|
||||
pa_context_unref(c);
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
static void context_state(pa_context *c, void *data)
|
||||
{
|
||||
(void)data;
|
||||
switch (pa_context_get_state(c)) {
|
||||
case PA_CONTEXT_READY:
|
||||
streams_open();
|
||||
break;
|
||||
case PA_CONTEXT_FAILED:
|
||||
case PA_CONTEXT_TERMINATED:
|
||||
/* (a new context the next time; this one let go outside its
|
||||
own callback) */
|
||||
if (au.ctx != c)
|
||||
break;
|
||||
streams_close();
|
||||
au.ctx = NULL;
|
||||
pa_context_set_state_callback(c, NULL, NULL);
|
||||
g_idle_add(unref_later, c);
|
||||
if (au.a && (au.pull || au.push) && !au.failed) {
|
||||
au.failed = TRUE;
|
||||
window_toast(au.a, "No sound: the sound server is not "
|
||||
"running");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
gboolean audio_available(void)
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
gboolean audio_start(App *a, AudioPull pull, AudioPush push)
|
||||
{
|
||||
streams_close();
|
||||
au.a = a;
|
||||
au.pull = pull;
|
||||
au.push = push;
|
||||
au.failed = FALSE;
|
||||
if (!au.loop)
|
||||
au.loop = pa_glib_mainloop_new(NULL);
|
||||
if (!au.ctx) {
|
||||
pa_proplist *pl = pa_proplist_new();
|
||||
pa_proplist_sets(pl, PA_PROP_APPLICATION_ID, APP_ID);
|
||||
pa_proplist_sets(pl, PA_PROP_APPLICATION_ICON_NAME, APP_ID);
|
||||
pa_proplist_sets(pl, PA_PROP_MEDIA_ROLE, "phone");
|
||||
au.ctx = pa_context_new_with_proplist(
|
||||
pa_glib_mainloop_get_api(au.loop), "D-Modem", pl);
|
||||
pa_proplist_free(pl);
|
||||
pa_context_set_state_callback(au.ctx, context_state, NULL);
|
||||
if (pa_context_connect(au.ctx, NULL, PA_CONTEXT_NOFLAGS,
|
||||
NULL) < 0) {
|
||||
/* (its state callback may have let it go already) */
|
||||
if (au.ctx) {
|
||||
pa_context_set_state_callback(au.ctx, NULL,
|
||||
NULL);
|
||||
pa_context_unref(au.ctx);
|
||||
au.ctx = NULL;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if (pa_context_get_state(au.ctx) == PA_CONTEXT_READY)
|
||||
streams_open();
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void audio_stop(App *a)
|
||||
{
|
||||
(void)a;
|
||||
au.pull = NULL;
|
||||
au.push = NULL;
|
||||
streams_close();
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
gboolean audio_available(void)
|
||||
{
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
gboolean audio_start(App *a, AudioPull pull, AudioPush push)
|
||||
{
|
||||
(void)a;
|
||||
(void)pull;
|
||||
(void)push;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void audio_stop(App *a)
|
||||
{
|
||||
(void)a;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,455 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* 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->sip_anonymous = get_b(k, "sip-anonymous", FALSE);
|
||||
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->builtin = get_b(k, "builtin", TRUE);
|
||||
c->init = get_s(k, "init", "");
|
||||
c->debug = g_key_file_get_integer(k, "line", "debug", NULL);
|
||||
/* the answering machine: off until the user turns it on */
|
||||
GError *e = NULL;
|
||||
c->voicemail = g_key_file_get_boolean(k, "voice", "voicemail", NULL);
|
||||
c->vm_rings = g_key_file_get_integer(k, "voice", "rings", &e);
|
||||
if (e || c->vm_rings < 1)
|
||||
c->vm_rings = 4;
|
||||
g_clear_error(&e);
|
||||
c->vm_max = g_key_file_get_integer(k, "voice", "max-seconds", &e);
|
||||
if (e || c->vm_max < 10)
|
||||
c->vm_max = 120;
|
||||
g_clear_error(&e);
|
||||
c->remote_proto = g_key_file_get_string(k, "remote", "protocol", NULL);
|
||||
if (!c->remote_proto)
|
||||
c->remote_proto = g_strdup("SSH");
|
||||
c->remote_host = g_key_file_get_string(k, "remote", "host", NULL);
|
||||
if (!c->remote_host)
|
||||
c->remote_host = g_strdup("");
|
||||
c->remote_port = g_key_file_get_integer(k, "remote", "port", NULL);
|
||||
c->remote_user = g_key_file_get_string(k, "remote", "user", NULL);
|
||||
if (!c->remote_user)
|
||||
c->remote_user = g_strdup("");
|
||||
c->remote_auth = g_key_file_get_string(k, "remote", "login", NULL);
|
||||
if (!c->remote_auth)
|
||||
c->remote_auth = g_strdup("auto");
|
||||
c->remote_key = g_key_file_get_string(k, "remote", "key", NULL);
|
||||
if (!c->remote_key)
|
||||
c->remote_key = g_strdup("");
|
||||
c->remote_agent = g_key_file_get_string(k, "remote", "agent", NULL);
|
||||
if (!c->remote_agent)
|
||||
c->remote_agent = g_strdup("");
|
||||
c->remote_term = g_key_file_get_string(k, "remote", "terminal", NULL);
|
||||
if (!c->remote_term)
|
||||
c->remote_term = g_strdup("xterm");
|
||||
c->term_type = g_key_file_get_string(k, "terminal", "type", NULL);
|
||||
if (!c->term_type)
|
||||
c->term_type = g_strdup("xterm");
|
||||
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", "sip-anonymous", c->sip_anonymous);
|
||||
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_boolean(k, "line", "builtin", c->builtin);
|
||||
g_key_file_set_string(k, "line", "init", c->init);
|
||||
g_key_file_set_integer(k, "line", "debug", c->debug);
|
||||
g_key_file_set_boolean(k, "voice", "voicemail", c->voicemail);
|
||||
g_key_file_set_integer(k, "voice", "rings", c->vm_rings);
|
||||
g_key_file_set_integer(k, "voice", "max-seconds", c->vm_max);
|
||||
g_key_file_set_string(k, "remote", "protocol", c->remote_proto);
|
||||
g_key_file_set_string(k, "remote", "host", c->remote_host);
|
||||
g_key_file_set_integer(k, "remote", "port", c->remote_port);
|
||||
g_key_file_set_string(k, "remote", "user", c->remote_user);
|
||||
g_key_file_set_string(k, "remote", "login", c->remote_auth);
|
||||
g_key_file_set_string(k, "remote", "key", c->remote_key);
|
||||
g_key_file_set_string(k, "remote", "agent", c->remote_agent);
|
||||
g_key_file_set_string(k, "remote", "terminal", c->remote_term);
|
||||
g_key_file_set_string(k, "terminal", "type", c->term_type);
|
||||
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);
|
||||
g_free(c->remote_proto);
|
||||
g_free(c->remote_host);
|
||||
g_free(c->remote_user);
|
||||
g_free(c->remote_term);
|
||||
g_free(c->remote_auth);
|
||||
g_free(c->remote_key);
|
||||
g_free(c->remote_agent);
|
||||
g_free(c->term_type);
|
||||
}
|
||||
|
||||
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_anonymous)
|
||||
return g_strdup_printf("SIP: anonymous, no account%s",
|
||||
c->listen ? ", taking calls" : "");
|
||||
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" : "");
|
||||
}
|
||||
|
||||
gboolean config_sip_ready(const Config *c)
|
||||
{
|
||||
return c->sip_anonymous || (*c->sip_user && *c->sip_server);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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 *anonymous, *listen, *t38, *v152, *v150, *builtin;
|
||||
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"));
|
||||
}
|
||||
|
||||
/* the account's rows: hidden when there is none (anonymous) */
|
||||
static void show_account(Prefs *p)
|
||||
{
|
||||
gboolean anon = adw_switch_row_get_active(p->anonymous);
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->user), !anon);
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->password), !anon);
|
||||
gtk_widget_set_visible(GTK_WIDGET(p->server), !anon);
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(p->listen), anon ?
|
||||
"Calls that come straight to this computer's address ring "
|
||||
"the modem" :
|
||||
"Register, so calls to the account ring the modem");
|
||||
}
|
||||
|
||||
static void anonymous_changed(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
(void)o;
|
||||
(void)ps;
|
||||
show_account(data);
|
||||
}
|
||||
|
||||
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 void use_found(GtkButton *b, gpointer data)
|
||||
{
|
||||
Prefs *p = data;
|
||||
gtk_editable_set_text(GTK_EDITABLE(p->device),
|
||||
g_object_get_data(G_OBJECT(b), "tty"));
|
||||
}
|
||||
|
||||
/* a MultiTech MT9234MU plugged in: a row that says where it is (with a
|
||||
button that puts it in Device), or what it needs */
|
||||
static void device_found(Prefs *p)
|
||||
{
|
||||
UsbModem *m = usbmodem_find();
|
||||
if (!m)
|
||||
return;
|
||||
char *d = usbmodem_describe(m);
|
||||
GtkWidget *r = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(r), "Found");
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(r), d);
|
||||
if (m->tty) {
|
||||
GtkWidget *b = gtk_button_new_with_label("Use");
|
||||
gtk_widget_set_valign(b, GTK_ALIGN_CENTER);
|
||||
g_object_set_data_full(G_OBJECT(b), "tty", g_strdup(m->tty),
|
||||
g_free);
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(use_found), p);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(r), b);
|
||||
}
|
||||
adw_preferences_group_add(p->device_g, r);
|
||||
g_free(d);
|
||||
usbmodem_free(m);
|
||||
}
|
||||
|
||||
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->sip_anonymous = adw_switch_row_get_active(p->anonymous);
|
||||
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);
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
c->builtin = adw_switch_row_get_active(p->builtin);
|
||||
#endif
|
||||
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; "
|
||||
"a SIP address (sip:user@host, or user@host) is "
|
||||
"dialled as it is, and the account's password only "
|
||||
"goes to its own server.");
|
||||
p->anonymous = toggle(p->sip, "No account (anonymous)", "Dial SIP "
|
||||
"addresses straight, from \"Anonymous\": "
|
||||
"nothing registered, no numbers",
|
||||
c->sip_anonymous);
|
||||
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 (a MultiTech MT9234MU is "
|
||||
"/dev/ttyUSB0).");
|
||||
p->device = entry(p->device_g, "Device", c->device);
|
||||
device_found(p);
|
||||
|
||||
AdwPreferencesGroup *adv = group(page, "Advanced", NULL);
|
||||
p->init = entry(adv, "Commands when the modem opens", c->init);
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
p->builtin = toggle(adv, "Built-in modem", "Run the modem in this "
|
||||
"app. Off: start dmodemd", c->builtin);
|
||||
#endif
|
||||
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);
|
||||
show_account(p);
|
||||
g_signal_connect(p->anonymous, "notify::active",
|
||||
G_CALLBACK(anonymous_changed), 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));
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* 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") && config_sip_ready(&a->cfg)))
|
||||
modem_start(a);
|
||||
(void)g;
|
||||
}
|
||||
|
||||
static void shutdown(GApplication *g, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)g;
|
||||
remote_stop(a);
|
||||
if (modem_running(a))
|
||||
modem_stop(a);
|
||||
g_cancellable_cancel(a->cancel);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,655 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* With the modem built in (DMODEM_GUI_EMBED, the "builtin" setting),
|
||||
* the SIP, USB and ALSA lines start no dmodemd: libdmodem_embed runs the
|
||||
* modem in a thread of the app, and its DTE is a socket in place of the
|
||||
* pty. Its log lines and its end come from that thread, and go to the
|
||||
* main loop with g_idle_add().
|
||||
*/
|
||||
#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"
|
||||
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
#include "dmodem_embed.h"
|
||||
#endif
|
||||
|
||||
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)
|
||||
termview_feed(a->term, buf, (int)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;
|
||||
}
|
||||
|
||||
/* the DTE fd (open, non-blocking) given to the session: name is what the
|
||||
Modem page shows as its device */
|
||||
static void attach_dte(App *a, int fd, const char *name)
|
||||
{
|
||||
a->fd = fd;
|
||||
g_free(a->device);
|
||||
a->device = g_strdup(name);
|
||||
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);
|
||||
}
|
||||
|
||||
/* the device at path opened as the DTE (raw, 115200 bit/s): FALSE, with
|
||||
a message, if it can't be */
|
||||
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;
|
||||
/* (a MultiTech MT9234MU: RTS/CTS, its &K3, so that the
|
||||
modem's buffer does not overflow in a fast call) */
|
||||
if (usbmodem_is(path))
|
||||
t.c_cflag |= CRTSCTS;
|
||||
tcsetattr(fd, TCSANOW, &t);
|
||||
}
|
||||
attach_dte(a, fd, path);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/*
|
||||
* the modem built in (libdmodem_embed)
|
||||
*/
|
||||
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
/* news from the modem's thread, for the main loop: a log line, or the
|
||||
end (line NULL) with its status */
|
||||
typedef struct EmbedNews {
|
||||
App *a;
|
||||
guint gen;
|
||||
char *line;
|
||||
int status;
|
||||
} EmbedNews;
|
||||
|
||||
/* a log line, or the modem's end, on the main loop; news of an older
|
||||
start is dropped */
|
||||
static gboolean embed_news(gpointer data)
|
||||
{
|
||||
EmbedNews *n = data;
|
||||
App *a = n->a;
|
||||
if (n->gen == a->embed_gen) {
|
||||
if (n->line) {
|
||||
app_log(a, n->line);
|
||||
if (dmc_daemon_error(n->line))
|
||||
window_toast(a, n->line + 7);
|
||||
} else {
|
||||
char *m = g_strdup_printf("The built-in modem stopped%s",
|
||||
n->status < 0 ?
|
||||
" (error)." : ".");
|
||||
app_log(a, m);
|
||||
if (n->status < 0)
|
||||
window_toast(a, m);
|
||||
g_free(m);
|
||||
a->embed_running = FALSE;
|
||||
close_dte(a);
|
||||
window_state(a);
|
||||
}
|
||||
}
|
||||
g_free(n->line);
|
||||
g_free(n);
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
/* the news of start gen (ctx) to the main loop */
|
||||
static void embed_post(App *a, guint gen, const char *line, int status)
|
||||
{
|
||||
EmbedNews *n = g_new0(EmbedNews, 1);
|
||||
n->a = a;
|
||||
n->gen = gen;
|
||||
n->line = line ? g_strdup(line) : NULL;
|
||||
n->status = status;
|
||||
g_idle_add(embed_news, n);
|
||||
}
|
||||
|
||||
/* the start that a callback is for: the app and the start's number */
|
||||
typedef struct EmbedCtx {
|
||||
App *a;
|
||||
guint gen;
|
||||
} EmbedCtx;
|
||||
|
||||
/* a line of the modem's log (the modem's thread) */
|
||||
static void embed_log(void *ctx, const char *line)
|
||||
{
|
||||
EmbedCtx *c = ctx;
|
||||
embed_post(c->a, c->gen, line, 0);
|
||||
}
|
||||
|
||||
/* the modem stopped (the modem's thread) */
|
||||
static void embed_exit(void *ctx, int status)
|
||||
{
|
||||
EmbedCtx *c = ctx;
|
||||
embed_post(c->a, c->gen, NULL, status);
|
||||
}
|
||||
|
||||
/* the line settings as libdmodem_embed has them; FALSE, with a message,
|
||||
for a line it doesn't have */
|
||||
static gboolean embed_config(App *a, dmodem_embed_config *e)
|
||||
{
|
||||
Config *c = &a->cfg;
|
||||
dmodem_embed_config_init(e);
|
||||
e->country = c->country;
|
||||
e->log_level = c->debug;
|
||||
if (!g_strcmp0(c->line, "usb")) {
|
||||
e->line = DMODEM_EMBED_USB;
|
||||
e->usb = c->usb;
|
||||
} else if (!g_strcmp0(c->line, "alsa")) {
|
||||
e->line = DMODEM_EMBED_ALSA;
|
||||
e->alsa = c->alsa;
|
||||
} else {
|
||||
e->line = DMODEM_EMBED_SIP;
|
||||
if (!c->sip_anonymous) {
|
||||
e->sip_user = c->sip_user;
|
||||
e->sip_password = c->sip_password;
|
||||
e->sip_domain = c->sip_server;
|
||||
}
|
||||
e->sip_listen = c->listen;
|
||||
e->sip_t38 = c->t38;
|
||||
e->sip_v152 = c->v152;
|
||||
e->sip_v150 = c->v150;
|
||||
e->sip_srtp = !g_strcmp0(c->srtp, "no") ? 0 :
|
||||
!g_strcmp0(c->srtp, "require") ? 2 : 1;
|
||||
}
|
||||
if (!(dmodem_embed_lines() & (1 << e->line))) {
|
||||
window_toast(a, "The built-in modem has no such line in this "
|
||||
"build: start dmodemd (line settings, Advanced)");
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/* the modem started in the app on the line settings' line */
|
||||
static void embed_start(App *a)
|
||||
{
|
||||
dmodem_embed_config e;
|
||||
if (!embed_config(a, &e))
|
||||
return;
|
||||
/* the data file of the line's measurements, where the user may
|
||||
write it */
|
||||
char *dir = g_build_filename(g_get_user_data_dir(), "dmodem-gui",
|
||||
NULL);
|
||||
g_mkdir_with_parents(dir, 0700);
|
||||
char *data = g_build_filename(dir, "dmodem0.data", NULL);
|
||||
e.data_file = data;
|
||||
if (!a->embed)
|
||||
a->embed = dmodem_embed_new();
|
||||
if (!a->embed) {
|
||||
g_free(dir);
|
||||
g_free(data);
|
||||
return;
|
||||
}
|
||||
/* (one context for each start, kept: the thread may use it until
|
||||
its end) */
|
||||
EmbedCtx *ctx = g_new0(EmbedCtx, 1);
|
||||
ctx->a = a;
|
||||
ctx->gen = ++a->embed_gen;
|
||||
dmodem_embed_on_log(a->embed, embed_log, ctx);
|
||||
dmodem_embed_on_exit(a->embed, embed_exit, ctx);
|
||||
int fd = dmodem_embed_start(a->embed, &e);
|
||||
g_free(dir);
|
||||
g_free(data);
|
||||
if (fd < 0) {
|
||||
char *m = g_strdup_printf("Can't start the built-in modem: %s",
|
||||
dmodem_embed_error(a->embed));
|
||||
window_toast(a, m);
|
||||
app_log(a, m);
|
||||
g_free(m);
|
||||
window_state(a);
|
||||
return;
|
||||
}
|
||||
char *m = g_strdup_printf("The built-in modem (D-Modem %s) started.",
|
||||
dmodem_embed_version());
|
||||
app_log(a, m);
|
||||
g_free(m);
|
||||
a->embed_running = TRUE;
|
||||
attach_dte(a, fd, "Built-in modem");
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
/* the modem built in stopped: its thread ended */
|
||||
static void embed_stop(App *a)
|
||||
{
|
||||
if (!a->embed)
|
||||
return;
|
||||
/* (news of this start after now is not wanted) */
|
||||
a->embed_gen++;
|
||||
dmodem_embed_stop(a->embed);
|
||||
a->embed_running = FALSE;
|
||||
app_log(a, "The built-in modem stopped.");
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
if (c->builtin) {
|
||||
if (!g_strcmp0(c->line, "sip") && !config_sip_ready(c)) {
|
||||
window_toast(a, "Set up the SIP account first");
|
||||
prefs_show(a);
|
||||
return;
|
||||
}
|
||||
embed_start(a);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
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") && !config_sip_ready(c)) {
|
||||
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")) {
|
||||
/* (no account: dmodemd's anonymous user agent) */
|
||||
char *login = c->sip_anonymous ? g_strdup("anonymous") :
|
||||
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 {
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
if (a->embed_running) {
|
||||
/* hang up first, so the call ends cleanly */
|
||||
if (a->fd >= 0)
|
||||
dmc_hangup(a->s);
|
||||
modem_pump(a);
|
||||
embed_stop(a);
|
||||
}
|
||||
#endif
|
||||
close_dte(a);
|
||||
}
|
||||
window_state(a);
|
||||
}
|
||||
|
||||
gboolean modem_running(App *a)
|
||||
{
|
||||
return a->proc != NULL || a->embed_running || 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);
|
||||
}
|
||||
|
||||
void modem_wait(App *a, int tag, ResponseFn fn, gpointer data)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* pathview.c - the connection path at the top of the Settings page, as
|
||||
* PCOMM's "Connection Overview" draws its link: each step's
|
||||
* role above its icon, what it is below, one line joining
|
||||
* them (libdmodemctl's dmc_path). Idle, how the line
|
||||
* settings set it up; starting, calling and online, as it is.
|
||||
*/
|
||||
#include "app.h"
|
||||
|
||||
#define STEPS 4
|
||||
|
||||
typedef struct PathView {
|
||||
dmc_path *path;
|
||||
GtkWidget *role[STEPS], *line[STEPS], *icon[STEPS], *title[STEPS],
|
||||
*detail[STEPS], *headline;
|
||||
int state[STEPS], left[STEPS], right[STEPS];
|
||||
} PathView;
|
||||
|
||||
static PathView pv;
|
||||
|
||||
static const char *icon_name(int kind)
|
||||
{
|
||||
switch (kind) {
|
||||
case DMC_KIND_TERMINAL: return "utilities-terminal-symbolic";
|
||||
case DMC_KIND_SOFTMODEM:
|
||||
case DMC_KIND_MODEM: return "modem-symbolic";
|
||||
case DMC_KIND_SIP: return "call-start-symbolic";
|
||||
case DMC_KIND_USB: return "media-removable-symbolic";
|
||||
case DMC_KIND_CODEC: return "audio-card-symbolic";
|
||||
case DMC_KIND_SERIAL: return "network-wired-symbolic";
|
||||
case DMC_KIND_NETWORK: return "network-workgroup-symbolic";
|
||||
case DMC_KIND_SIP_ADDRESS: return "send-to-symbolic";
|
||||
default: return "phone-symbolic";
|
||||
}
|
||||
}
|
||||
|
||||
/* a state's colour: ready the accent, to set red, working and active
|
||||
green (libadwaita's), off the text's, faint */
|
||||
static void state_rgba(GtkWidget *w, int state, GdkRGBA *c)
|
||||
{
|
||||
switch (state) {
|
||||
case DMC_STEP_SETUP: gdk_rgba_parse(c, "#e01b24"); break;
|
||||
case DMC_STEP_WORKING:
|
||||
case DMC_STEP_ACTIVE: gdk_rgba_parse(c, "#26a269"); break;
|
||||
case DMC_STEP_OFF:
|
||||
gtk_widget_get_color(w, c);
|
||||
c->alpha = 0.3f;
|
||||
break;
|
||||
default: gdk_rgba_parse(c, "#3584e4"); break;
|
||||
}
|
||||
}
|
||||
|
||||
static const char *state_class(int state)
|
||||
{
|
||||
switch (state) {
|
||||
case DMC_STEP_SETUP: return "error";
|
||||
case DMC_STEP_WORKING:
|
||||
case DMC_STEP_ACTIVE: return "success";
|
||||
case DMC_STEP_OFF: return "dim-label";
|
||||
default: return "accent";
|
||||
}
|
||||
}
|
||||
|
||||
/* step i's icon row: the line through its middle, half to the step before
|
||||
and half to the next (dashed where one is still to set, or off), and
|
||||
the ring the icon sits in */
|
||||
static void draw_step(GtkDrawingArea *da, cairo_t *cr, int w, int h,
|
||||
gpointer data)
|
||||
{
|
||||
int i = GPOINTER_TO_INT(data);
|
||||
double y = h / 2.0, r = 22;
|
||||
static const double dash[] = { 6, 4 };
|
||||
GdkRGBA c;
|
||||
cairo_set_line_width(cr, 2);
|
||||
for (int side = 0; side < 2; side++) {
|
||||
int st = side ? pv.right[i] : pv.left[i];
|
||||
if (st < 0)
|
||||
continue;
|
||||
state_rgba(GTK_WIDGET(da), st, &c);
|
||||
gdk_cairo_set_source_rgba(cr, &c);
|
||||
cairo_set_dash(cr, dash, st == DMC_STEP_SETUP ||
|
||||
st == DMC_STEP_OFF ? 2 : 0, 0);
|
||||
cairo_move_to(cr, side ? w / 2.0 + r : 0, y);
|
||||
cairo_line_to(cr, side ? w : w / 2.0 - r, y);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
cairo_set_dash(cr, NULL, 0, 0);
|
||||
state_rgba(GTK_WIDGET(da), pv.state[i], &c);
|
||||
cairo_arc(cr, w / 2.0, y, r, 0, 2 * G_PI);
|
||||
if (pv.state[i] == DMC_STEP_ACTIVE) {
|
||||
GdkRGBA f = c;
|
||||
f.alpha = 0.2f;
|
||||
gdk_cairo_set_source_rgba(cr, &f);
|
||||
cairo_fill_preserve(cr);
|
||||
}
|
||||
gdk_cairo_set_source_rgba(cr, &c);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
|
||||
static void set_class(GtkWidget *w, const char *cls)
|
||||
{
|
||||
static const char *const all[] = { "error", "success", "dim-label",
|
||||
"accent" };
|
||||
for (guint k = 0; k < G_N_ELEMENTS(all); k++)
|
||||
gtk_widget_remove_css_class(w, all[k]);
|
||||
gtk_widget_add_css_class(w, cls);
|
||||
}
|
||||
|
||||
void pathview_update(App *a)
|
||||
{
|
||||
if (!pv.path)
|
||||
return;
|
||||
const Config *c = &a->cfg;
|
||||
int line = DMC_LINE_SIP;
|
||||
const char *where = "";
|
||||
if (!g_strcmp0(c->line, "usb")) {
|
||||
line = DMC_LINE_USB;
|
||||
where = c->usb;
|
||||
} else if (!g_strcmp0(c->line, "alsa")) {
|
||||
line = DMC_LINE_CODEC;
|
||||
where = c->alsa;
|
||||
} else if (!g_strcmp0(c->line, "device")) {
|
||||
line = DMC_LINE_DEVICE;
|
||||
where = c->device;
|
||||
}
|
||||
dmc_path_set_line(pv.path, line, where, c->sip_anonymous, c->sip_user,
|
||||
c->sip_server, c->listen);
|
||||
int st = a->s ? dmc_state(a->s) : DMC_CLOSED;
|
||||
dmc_path_set_live(pv.path, modem_running(a), st,
|
||||
st == DMC_ONLINE || st == DMC_ONLINE_COMMAND ?
|
||||
dmc_connect_text(a->s) : "");
|
||||
int n = dmc_path_steps(pv.path);
|
||||
GString *spoken = g_string_new(dmc_path_headline(pv.path));
|
||||
for (int i = 0; i < STEPS && i < n; i++) {
|
||||
pv.state[i] = dmc_path_state(pv.path, i);
|
||||
pv.left[i] = i > 0 ? dmc_path_link(pv.path, i - 1) : -1;
|
||||
pv.right[i] = i < n - 1 ? dmc_path_link(pv.path, i) : -1;
|
||||
gtk_label_set_text(GTK_LABEL(pv.role[i]), dmc_path_role(pv.path, i));
|
||||
gtk_label_set_text(GTK_LABEL(pv.title[i]), dmc_path_title(pv.path, i));
|
||||
gtk_label_set_text(GTK_LABEL(pv.detail[i]), dmc_path_detail(pv.path, i));
|
||||
gtk_image_set_from_icon_name(GTK_IMAGE(pv.icon[i]),
|
||||
icon_name(dmc_path_kind(pv.path, i)));
|
||||
set_class(pv.icon[i], state_class(pv.state[i]));
|
||||
if (pv.state[i] == DMC_STEP_SETUP)
|
||||
gtk_widget_add_css_class(pv.detail[i], "error");
|
||||
else
|
||||
gtk_widget_remove_css_class(pv.detail[i], "error");
|
||||
gtk_widget_queue_draw(pv.line[i]);
|
||||
g_string_append_printf(spoken, ". %s: %s, %s",
|
||||
dmc_path_role(pv.path, i),
|
||||
dmc_path_title(pv.path, i),
|
||||
dmc_path_detail(pv.path, i));
|
||||
}
|
||||
gtk_label_set_text(GTK_LABEL(pv.headline), dmc_path_headline(pv.path));
|
||||
set_class(pv.headline, dmc_path_needs_setup(pv.path) ? "error" :
|
||||
"dim-label");
|
||||
gtk_accessible_update_property(GTK_ACCESSIBLE(gtk_widget_get_parent(pv.headline)),
|
||||
GTK_ACCESSIBLE_PROPERTY_LABEL, spoken->str, -1);
|
||||
g_string_free(spoken, TRUE);
|
||||
}
|
||||
|
||||
static GtkWidget *label(const char *cls, gboolean wrap)
|
||||
{
|
||||
GtkWidget *l = gtk_label_new("");
|
||||
gtk_label_set_justify(GTK_LABEL(l), GTK_JUSTIFY_CENTER);
|
||||
if (wrap) {
|
||||
gtk_label_set_wrap(GTK_LABEL(l), TRUE);
|
||||
gtk_label_set_wrap_mode(GTK_LABEL(l), PANGO_WRAP_WORD_CHAR);
|
||||
gtk_label_set_max_width_chars(GTK_LABEL(l), 18);
|
||||
gtk_label_set_lines(GTK_LABEL(l), 3);
|
||||
gtk_label_set_ellipsize(GTK_LABEL(l), PANGO_ELLIPSIZE_END);
|
||||
}
|
||||
if (cls)
|
||||
gtk_widget_add_css_class(l, cls);
|
||||
return l;
|
||||
}
|
||||
|
||||
GtkWidget *pathview_new(App *a)
|
||||
{
|
||||
pv.path = dmc_path_new();
|
||||
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
|
||||
gtk_widget_add_css_class(box, "card");
|
||||
gtk_widget_set_margin_bottom(box, 6);
|
||||
GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
|
||||
gtk_box_set_homogeneous(GTK_BOX(row), TRUE);
|
||||
gtk_widget_set_margin_top(row, 12);
|
||||
for (int i = 0; i < STEPS; i++) {
|
||||
GtkWidget *col = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
|
||||
pv.role[i] = label("caption", FALSE);
|
||||
gtk_widget_add_css_class(pv.role[i], "dim-label");
|
||||
gtk_box_append(GTK_BOX(col), pv.role[i]);
|
||||
GtkWidget *ov = gtk_overlay_new();
|
||||
pv.line[i] = gtk_drawing_area_new();
|
||||
gtk_drawing_area_set_content_height(GTK_DRAWING_AREA(pv.line[i]), 48);
|
||||
gtk_widget_set_hexpand(pv.line[i], TRUE);
|
||||
gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(pv.line[i]),
|
||||
draw_step, GINT_TO_POINTER(i), NULL);
|
||||
gtk_overlay_set_child(GTK_OVERLAY(ov), pv.line[i]);
|
||||
pv.icon[i] = gtk_image_new();
|
||||
gtk_image_set_pixel_size(GTK_IMAGE(pv.icon[i]), 20);
|
||||
gtk_widget_set_halign(pv.icon[i], GTK_ALIGN_CENTER);
|
||||
gtk_widget_set_valign(pv.icon[i], GTK_ALIGN_CENTER);
|
||||
gtk_overlay_add_overlay(GTK_OVERLAY(ov), pv.icon[i]);
|
||||
gtk_box_append(GTK_BOX(col), ov);
|
||||
pv.title[i] = label("heading", FALSE);
|
||||
gtk_box_append(GTK_BOX(col), pv.title[i]);
|
||||
pv.detail[i] = label("caption", TRUE);
|
||||
gtk_widget_set_margin_start(pv.detail[i], 4);
|
||||
gtk_widget_set_margin_end(pv.detail[i], 4);
|
||||
gtk_box_append(GTK_BOX(col), pv.detail[i]);
|
||||
gtk_box_append(GTK_BOX(row), col);
|
||||
}
|
||||
gtk_box_append(GTK_BOX(box), row);
|
||||
pv.headline = label(NULL, TRUE);
|
||||
gtk_label_set_max_width_chars(GTK_LABEL(pv.headline), 60);
|
||||
gtk_widget_set_margin_bottom(pv.headline, 12);
|
||||
gtk_widget_set_margin_start(pv.headline, 12);
|
||||
gtk_widget_set_margin_end(pv.headline, 12);
|
||||
gtk_box_append(GTK_BOX(box), pv.headline);
|
||||
pathview_update(a);
|
||||
return box;
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* 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());
|
||||
|
||||
/* how a call is made, step by step: as set up when idle, as it is in
|
||||
a call */
|
||||
GtkWidget *path = adw_preferences_group_new();
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(path), pathview_new(a));
|
||||
adw_preferences_page_add(a->settings_page, ADW_PREFERENCES_GROUP(path));
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* 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;
|
||||
}
|
||||
@@ -1,887 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* termview.c - a terminal widget: a screen of libdmodemctl's dmc_vt,
|
||||
* drawn with Cairo and Pango, its keys handed to whoever
|
||||
* owns it. The Terminal page's and the Remote page's.
|
||||
*
|
||||
* Every kind of terminal the engine is (xterm, the VTs, ANSI-BBS, the
|
||||
* Commodores and Ataris, Viewdata, the Minitel, the Tektronix) is drawn
|
||||
* here: a cell's background, its character in the monospace font or, where
|
||||
* the profile has its machine's font, the glyph's bitmap (each row's
|
||||
* glyphs put in an image at the font's own size and stretched over the
|
||||
* row, so a C64's 8x8 stays sharp at any size), its lines, the pictures
|
||||
* (sixel, ReGIS, RIPscrip's, the Tektronix's) over the text, and the
|
||||
* cursor. A machine with a screen of its own size (a C64's 40x25) has its
|
||||
* cells stretched to fill the widget; DEC's double width and height lines
|
||||
* are drawn scaled.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
#define MAX_COLS 400
|
||||
|
||||
typedef struct TermView {
|
||||
GtkWidget *box, *area, *bar;
|
||||
GtkAdjustment *adj;
|
||||
dmc_vt *vt;
|
||||
TermTypedFn fn;
|
||||
void *ctx;
|
||||
PangoFontDescription *font[4]; /* regular, bold, italic, both */
|
||||
int fcw, fch, fascent; /* the font's cell */
|
||||
int cw, ch, ox, oy; /* a cell as drawn, the screen's place */
|
||||
int status_rows;
|
||||
int scroll; /* 0 the screen, -n back in history */
|
||||
gboolean focused, blink_off, has_blink, adjusting;
|
||||
int buttons;
|
||||
guint blink_tick;
|
||||
GtkIMContext *im;
|
||||
} TermView;
|
||||
|
||||
static TermView *of(GtkWidget *w)
|
||||
{
|
||||
return g_object_get_data(G_OBJECT(w), "termview");
|
||||
}
|
||||
|
||||
static void rgb(cairo_t *cr, uint32_t c)
|
||||
{
|
||||
cairo_set_source_rgb(cr, ((c >> 16) & 255) / 255.0,
|
||||
((c >> 8) & 255) / 255.0, (c & 255) / 255.0);
|
||||
}
|
||||
|
||||
/*
|
||||
* the screen's size
|
||||
*/
|
||||
|
||||
static void measure(TermView *t)
|
||||
{
|
||||
PangoContext *pc = gtk_widget_get_pango_context(t->area);
|
||||
PangoFontMetrics *m = pango_context_get_metrics(pc, t->font[0], NULL);
|
||||
int w = pango_font_metrics_get_approximate_digit_width(m);
|
||||
int a = pango_font_metrics_get_ascent(m), d = pango_font_metrics_get_descent(m);
|
||||
t->fcw = (w + PANGO_SCALE - 1) / PANGO_SCALE;
|
||||
t->fch = (a + d + PANGO_SCALE - 1) / PANGO_SCALE;
|
||||
t->fascent = a / PANGO_SCALE;
|
||||
if (t->fcw < 4)
|
||||
t->fcw = 8;
|
||||
if (t->fch < 6)
|
||||
t->fch = 16;
|
||||
pango_font_metrics_unref(m);
|
||||
}
|
||||
|
||||
static void update_bar(TermView *t)
|
||||
{
|
||||
int hist = dmc_vt_history(t->vt), rows = dmc_vt_rows(t->vt);
|
||||
t->adjusting = TRUE;
|
||||
gtk_adjustment_configure(t->adj, hist + t->scroll, 0, hist + rows, 1,
|
||||
rows, rows);
|
||||
t->adjusting = FALSE;
|
||||
}
|
||||
|
||||
/* the columns and rows that fit, or the machine's own with its cells
|
||||
stretched to fill the widget */
|
||||
static void layout(TermView *t)
|
||||
{
|
||||
int W = gtk_widget_get_width(t->area), H = gtk_widget_get_height(t->area);
|
||||
if (W <= 0 || H <= 0)
|
||||
return;
|
||||
int rc = dmc_vt_requested_cols(t->vt), rr = dmc_vt_requested_rows(t->vt);
|
||||
const char *st = dmc_vt_status_line(t->vt);
|
||||
t->status_rows = st && *st ? 1 : 0;
|
||||
int gw, gh, cw = t->fcw, ch = t->fch, cols, rows;
|
||||
gboolean glyphs = dmc_vt_glyph_cell(t->vt, &gw, &gh) != 0;
|
||||
if (glyphs && rc > 0 && rr > 0) {
|
||||
int sx = W / (rc * gw), sy = H / ((rr + t->status_rows) * gh);
|
||||
int s = sx < sy ? sx : sy;
|
||||
if (s >= 1) {
|
||||
cw = gw * s;
|
||||
ch = gh * s;
|
||||
} else {
|
||||
cw = W / rc;
|
||||
ch = H / (rr + t->status_rows);
|
||||
}
|
||||
} else {
|
||||
if (rc > 0)
|
||||
cw = W / rc;
|
||||
if (rr > 0)
|
||||
ch = H / (rr + t->status_rows);
|
||||
}
|
||||
if (cw < 2)
|
||||
cw = 2;
|
||||
if (ch < 2)
|
||||
ch = 2;
|
||||
cols = rc > 0 ? rc : W / cw;
|
||||
rows = rr > 0 ? rr : H / ch - t->status_rows;
|
||||
cols = CLAMP(cols, 10, MAX_COLS);
|
||||
rows = CLAMP(rows, 3, 200);
|
||||
t->cw = cw;
|
||||
t->ch = ch;
|
||||
t->ox = rc > 0 ? MAX(0, (W - cols * cw) / 2) : 0;
|
||||
t->oy = rr > 0 ? MAX(0, (H - (rows + t->status_rows) * ch) / 2) : 0;
|
||||
dmc_vt_set_cell_pixels(t->vt, cw, ch);
|
||||
if (cols != dmc_vt_cols(t->vt) || rows != dmc_vt_rows(t->vt)) {
|
||||
dmc_vt_resize(t->vt, cols, rows);
|
||||
update_bar(t);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* drawing
|
||||
*/
|
||||
|
||||
/* a row's machine-font glyphs at the font's size, to be stretched */
|
||||
static void draw_glyphs(TermView *t, cairo_t *cr, const dmc_cell *cells,
|
||||
int ncols)
|
||||
{
|
||||
int gw, gh;
|
||||
if (!dmc_vt_glyph_cell(t->vt, &gw, &gh)) {
|
||||
/* (soft characters only: their own size) */
|
||||
gw = 8;
|
||||
gh = 16;
|
||||
for (int x = 0; x < ncols; x++)
|
||||
if ((cells[x].flags & DMC_CELL_GLYPH) &&
|
||||
dmc_vt_glyph(t->vt, cells[x].ch, &gw, &gh))
|
||||
break;
|
||||
}
|
||||
cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
|
||||
ncols * gw, gh);
|
||||
if (cairo_surface_status(s) != CAIRO_STATUS_SUCCESS) {
|
||||
cairo_surface_destroy(s);
|
||||
return;
|
||||
}
|
||||
cairo_surface_flush(s);
|
||||
unsigned char *data = cairo_image_surface_get_data(s);
|
||||
int stride = cairo_image_surface_get_stride(s);
|
||||
for (int x = 0; x < ncols; x++) {
|
||||
const dmc_cell *c = &cells[x];
|
||||
int w, h;
|
||||
if (!(c->flags & DMC_CELL_GLYPH) || (c->flags & DMC_CELL_INVISIBLE) ||
|
||||
((c->flags & DMC_CELL_BLINK) && t->blink_off) ||
|
||||
!dmc_vt_glyph(t->vt, c->ch, &w, &h) || w <= 0 || h <= 0)
|
||||
continue;
|
||||
int span = (c->flags & DMC_CELL_WIDE) && x + 1 < ncols ? 2 : 1;
|
||||
uint32_t fg = 0xff000000u | (c->fg & 0xffffff);
|
||||
for (int y = 0; y < gh; y++) {
|
||||
uint32_t bits = dmc_vt_glyph_row(t->vt, c->ch, y * h / gh);
|
||||
if (!bits)
|
||||
continue;
|
||||
uint32_t *p = (uint32_t *)(data + (size_t)y * stride) + x * gw;
|
||||
for (int i = 0; i < gw * span; i++) {
|
||||
int gx = i * w / (gw * span);
|
||||
if ((bits >> (w - 1 - gx)) & 1)
|
||||
p[i] = fg;
|
||||
}
|
||||
}
|
||||
}
|
||||
cairo_surface_mark_dirty(s);
|
||||
cairo_save(cr);
|
||||
cairo_scale(cr, (double)t->cw / gw, (double)t->ch / gh);
|
||||
cairo_set_source_surface(cr, s, 0, 0);
|
||||
cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST);
|
||||
cairo_paint(cr);
|
||||
cairo_restore(cr);
|
||||
cairo_surface_destroy(s);
|
||||
}
|
||||
|
||||
/* the pictures' surfaces made for this drawing, by id */
|
||||
static cairo_surface_t *picture(GHashTable *made, const uint32_t *px,
|
||||
const dmc_image *im)
|
||||
{
|
||||
cairo_surface_t *s = g_hash_table_lookup(made, GUINT_TO_POINTER(im->id));
|
||||
if (s)
|
||||
return s;
|
||||
s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, im->width, im->height);
|
||||
if (cairo_surface_status(s) != CAIRO_STATUS_SUCCESS)
|
||||
return NULL;
|
||||
cairo_surface_flush(s);
|
||||
unsigned char *data = cairo_image_surface_get_data(s);
|
||||
int stride = cairo_image_surface_get_stride(s);
|
||||
for (int y = 0; y < im->height; y++) {
|
||||
uint32_t *d = (uint32_t *)(data + (size_t)y * stride);
|
||||
const uint32_t *p = px + (size_t)y * im->width;
|
||||
for (int x = 0; x < im->width; x++) {
|
||||
uint32_t v = p[x], a = v >> 24;
|
||||
/* (Cairo's are premultiplied) */
|
||||
d[x] = (a << 24) | ((((v >> 16) & 255) * a / 255) << 16) |
|
||||
((((v >> 8) & 255) * a / 255) << 8) | ((v & 255) * a / 255);
|
||||
}
|
||||
}
|
||||
cairo_surface_mark_dirty(s);
|
||||
g_hash_table_insert(made, GUINT_TO_POINTER(im->id), s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* view row vrow at (0, 0): ncols cells */
|
||||
static void draw_row(TermView *t, cairo_t *cr, PangoLayout *lay, int vrow,
|
||||
int ncols, gboolean cursor_here, GHashTable *pics)
|
||||
{
|
||||
dmc_vt *vt = t->vt;
|
||||
int cw = t->cw, ch = t->ch;
|
||||
dmc_cell cells[MAX_COLS];
|
||||
gboolean any_glyph = FALSE, any_image = FALSE;
|
||||
ncols = MIN(ncols, MAX_COLS);
|
||||
for (int x = 0; x < ncols; x++) {
|
||||
dmc_vt_cell(vt, vrow, x, &cells[x]);
|
||||
if (cells[x].flags & DMC_CELL_BLINK)
|
||||
t->has_blink = TRUE;
|
||||
if (cells[x].flags & DMC_CELL_GLYPH)
|
||||
any_glyph = TRUE;
|
||||
if (cells[x].flags & DMC_CELL_IMAGE)
|
||||
any_image = TRUE;
|
||||
}
|
||||
/* the backgrounds, in runs */
|
||||
for (int x = 0; x < ncols;) {
|
||||
int n = 1;
|
||||
while (x + n < ncols && cells[x + n].bg == cells[x].bg)
|
||||
n++;
|
||||
rgb(cr, cells[x].bg);
|
||||
cairo_rectangle(cr, x * cw, 0, n * cw, ch);
|
||||
cairo_fill(cr);
|
||||
x += n;
|
||||
}
|
||||
/* the text, in the font (stretched when the cells are) */
|
||||
double sx = (double)cw / t->fcw, sy = (double)ch / t->fch;
|
||||
int last_font = -1;
|
||||
for (int x = 0; x < ncols; x++) {
|
||||
const dmc_cell *c = &cells[x];
|
||||
int f = c->flags;
|
||||
if ((f & (DMC_CELL_GLYPH | DMC_CELL_INVISIBLE | DMC_CELL_WIDE_TAIL)) ||
|
||||
((f & DMC_CELL_BLINK) && t->blink_off) ||
|
||||
(c->ch == ' ' && !(f & DMC_CELL_COMBINING)) || c->ch == 0)
|
||||
continue;
|
||||
int fi = ((f & DMC_CELL_BOLD) ? 1 : 0) | ((f & DMC_CELL_ITALIC) ? 2 : 0);
|
||||
if (fi != last_font) {
|
||||
pango_layout_set_font_description(lay, t->font[fi]);
|
||||
last_font = fi;
|
||||
}
|
||||
if (f & DMC_CELL_COMBINING) {
|
||||
pango_layout_set_text(lay, dmc_vt_cell_text(vt, vrow, x), -1);
|
||||
} else {
|
||||
char u[8];
|
||||
int n = g_unichar_to_utf8(c->ch, u);
|
||||
pango_layout_set_text(lay, u, n);
|
||||
}
|
||||
rgb(cr, c->fg);
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, x * cw, 0);
|
||||
if (sx != 1 || sy != 1)
|
||||
cairo_scale(cr, sx, sy);
|
||||
cairo_move_to(cr, 0, 0);
|
||||
pango_cairo_show_layout(cr, lay);
|
||||
cairo_restore(cr);
|
||||
}
|
||||
if (any_glyph)
|
||||
draw_glyphs(t, cr, cells, ncols);
|
||||
/* the lines */
|
||||
double th = MAX(1, ch / 16);
|
||||
for (int x = 0; x < ncols; x++) {
|
||||
const dmc_cell *c = &cells[x];
|
||||
int f = c->flags, l = x * cw;
|
||||
if (f & DMC_CELL_INVISIBLE)
|
||||
continue;
|
||||
rgb(cr, c->fg);
|
||||
if (f & (DMC_CELL_UNDERLINE | DMC_CELL_LINK))
|
||||
cairo_rectangle(cr, l, ch - 2 * th, cw, th);
|
||||
if (f & DMC_CELL_DOUBLE_UNDERLINE) {
|
||||
cairo_rectangle(cr, l, ch - th, cw, th);
|
||||
cairo_rectangle(cr, l, ch - 3 * th, cw, th);
|
||||
}
|
||||
if (f & DMC_CELL_STRIKE)
|
||||
cairo_rectangle(cr, l, ch / 2, cw, th);
|
||||
if (f & DMC_CELL_OVERLINE)
|
||||
cairo_rectangle(cr, l, 0, cw, th);
|
||||
cairo_fill(cr);
|
||||
if (f & DMC_CELL_CURLY_UNDERLINE) {
|
||||
cairo_set_line_width(cr, th);
|
||||
cairo_move_to(cr, l, ch - 2 * th);
|
||||
for (int i = 0; i < 4; i++)
|
||||
cairo_line_to(cr, l + (i + 1) * cw / 4.0,
|
||||
ch - (i % 2 ? 2 : 1) * th - th / 2);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
}
|
||||
/* the pictures over the text */
|
||||
if (any_image)
|
||||
for (int x = 0; x < ncols; x++) {
|
||||
dmc_image im;
|
||||
const uint32_t *px;
|
||||
if (!(cells[x].flags & DMC_CELL_IMAGE) ||
|
||||
!(px = dmc_vt_cell_image(vt, vrow, x, &im)) ||
|
||||
im.cell_width <= 0 || im.cell_height <= 0)
|
||||
continue;
|
||||
cairo_surface_t *s = picture(pics, px, &im);
|
||||
if (!s)
|
||||
continue;
|
||||
cairo_save(cr);
|
||||
cairo_rectangle(cr, x * cw, 0, cw, ch);
|
||||
cairo_clip(cr);
|
||||
cairo_translate(cr, x * cw, 0);
|
||||
cairo_scale(cr, (double)cw / im.cell_width,
|
||||
(double)ch / im.cell_height);
|
||||
cairo_set_source_surface(cr, s, -im.tx * im.cell_width,
|
||||
-im.ty * im.cell_height);
|
||||
cairo_pattern_set_filter(cairo_get_source(cr),
|
||||
CAIRO_FILTER_NEAREST);
|
||||
cairo_paint(cr);
|
||||
cairo_restore(cr);
|
||||
}
|
||||
/* the cursor */
|
||||
if (cursor_here) {
|
||||
int cx = dmc_vt_cursor_col(vt);
|
||||
if (cx >= 0 && cx < ncols) {
|
||||
int w = (cells[cx].flags & DMC_CELL_WIDE) ? 2 * cw : cw;
|
||||
int style = dmc_vt_cursor_style(vt);
|
||||
rgb(cr, dmc_vt_cursor_color(vt));
|
||||
if (!t->focused) {
|
||||
cairo_set_line_width(cr, 1);
|
||||
cairo_rectangle(cr, cx * cw + 0.5, 0.5, w - 1, ch - 1);
|
||||
cairo_stroke(cr);
|
||||
} else if (style == 3 || style == 4) {
|
||||
cairo_rectangle(cr, cx * cw, ch - MAX(2, ch / 8), w,
|
||||
MAX(2, ch / 8));
|
||||
cairo_fill(cr);
|
||||
} else if (style == 5 || style == 6) {
|
||||
cairo_rectangle(cr, cx * cw, 0, MAX(2, cw / 8), ch);
|
||||
cairo_fill(cr);
|
||||
} else {
|
||||
cairo_save(cr);
|
||||
cairo_rectangle(cr, cx * cw, 0, w, ch);
|
||||
cairo_set_operator(cr, CAIRO_OPERATOR_DIFFERENCE);
|
||||
cairo_fill(cr);
|
||||
cairo_restore(cr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void draw(GtkDrawingArea *area, cairo_t *cr, int W, int H, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
dmc_vt *vt = t->vt;
|
||||
(void)area;
|
||||
rgb(cr, dmc_vt_background(vt));
|
||||
cairo_rectangle(cr, 0, 0, W, H);
|
||||
cairo_fill(cr);
|
||||
int rows = dmc_vt_rows(vt), cols = dmc_vt_cols(vt);
|
||||
int cw = t->cw, ch = t->ch;
|
||||
PangoLayout *lay = gtk_widget_create_pango_layout(t->area, NULL);
|
||||
GHashTable *pics = g_hash_table_new_full(NULL, NULL, NULL,
|
||||
(GDestroyNotify)cairo_surface_destroy);
|
||||
t->has_blink = FALSE;
|
||||
for (int y = 0; y < rows; y++) {
|
||||
int vrow = y + t->scroll;
|
||||
int size = dmc_vt_line_size(vt, vrow);
|
||||
gboolean cur = t->scroll == 0 && dmc_vt_cursor_visible(vt) &&
|
||||
dmc_vt_cursor_row(vt) == y;
|
||||
cairo_save(cr);
|
||||
cairo_translate(cr, t->ox, t->oy + y * ch);
|
||||
cairo_rectangle(cr, 0, 0, cols * cw, ch);
|
||||
cairo_clip(cr);
|
||||
if (size == DMC_LINE_SINGLE) {
|
||||
draw_row(t, cr, lay, vrow, cols, cur, pics);
|
||||
} else {
|
||||
if (size == DMC_LINE_DOUBLE_WIDTH) {
|
||||
cairo_scale(cr, 2, 1);
|
||||
} else {
|
||||
if (size == DMC_LINE_DOUBLE_BOTTOM)
|
||||
cairo_translate(cr, 0, -ch);
|
||||
cairo_scale(cr, 2, 2);
|
||||
}
|
||||
draw_row(t, cr, lay, vrow, (cols + 1) / 2, cur, pics);
|
||||
}
|
||||
cairo_restore(cr);
|
||||
}
|
||||
if (t->status_rows) {
|
||||
int y = t->oy + rows * ch;
|
||||
rgb(cr, dmc_vt_foreground(vt));
|
||||
cairo_rectangle(cr, t->ox, y, cols * cw, ch);
|
||||
cairo_fill(cr);
|
||||
pango_layout_set_font_description(lay, t->font[0]);
|
||||
pango_layout_set_text(lay, dmc_vt_status_line(vt), -1);
|
||||
rgb(cr, dmc_vt_background(vt));
|
||||
cairo_move_to(cr, t->ox, y);
|
||||
pango_cairo_show_layout(cr, lay);
|
||||
}
|
||||
g_hash_table_destroy(pics);
|
||||
g_object_unref(lay);
|
||||
}
|
||||
|
||||
/*
|
||||
* what the user does
|
||||
*/
|
||||
|
||||
static void send_text(TermView *t, const char *s, int n)
|
||||
{
|
||||
if (t->fn && n > 0)
|
||||
t->fn(s, n, t->ctx);
|
||||
}
|
||||
|
||||
static void to_bottom(TermView *t)
|
||||
{
|
||||
if (t->scroll) {
|
||||
t->scroll = 0;
|
||||
update_bar(t);
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
}
|
||||
|
||||
static int mods_of(GdkModifierType s)
|
||||
{
|
||||
int m = 0;
|
||||
if (s & GDK_SHIFT_MASK)
|
||||
m |= DMC_MOD_SHIFT;
|
||||
if (s & GDK_CONTROL_MASK)
|
||||
m |= DMC_MOD_CTRL;
|
||||
if (s & GDK_ALT_MASK)
|
||||
m |= DMC_MOD_ALT;
|
||||
return m;
|
||||
}
|
||||
|
||||
static void send_key(TermView *t, int key, int mods)
|
||||
{
|
||||
char b[64];
|
||||
to_bottom(t);
|
||||
send_text(t, b, dmc_vt_key_mods(t->vt, key, mods, b, sizeof(b)));
|
||||
}
|
||||
|
||||
static void send_cp(TermView *t, gunichar c, int mods)
|
||||
{
|
||||
char b[64];
|
||||
send_text(t, b, dmc_vt_char_bytes(t->vt, c, mods, b, sizeof(b)));
|
||||
}
|
||||
|
||||
static void send_utf8(TermView *t, const char *s, gboolean paste)
|
||||
{
|
||||
gboolean bracket = paste && dmc_vt_bracketed_paste(t->vt);
|
||||
if (bracket)
|
||||
send_text(t, "\x1b[200~", 6);
|
||||
for (const char *p = s; *p; p = g_utf8_next_char(p)) {
|
||||
gunichar c = g_utf8_get_char(p);
|
||||
if (c == '\n' && p > s && p[-1] == '\r')
|
||||
continue;
|
||||
send_cp(t, c == '\n' ? '\r' : c, 0);
|
||||
}
|
||||
if (bracket)
|
||||
send_text(t, "\x1b[201~", 6);
|
||||
}
|
||||
|
||||
static void committed(GtkIMContext *im, const char *s, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
(void)im;
|
||||
to_bottom(t);
|
||||
send_utf8(t, s, FALSE);
|
||||
}
|
||||
|
||||
static void pasted(GObject *o, GAsyncResult *res, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
char *s = gdk_clipboard_read_text_finish(GDK_CLIPBOARD(o), res, NULL);
|
||||
if (s) {
|
||||
to_bottom(t);
|
||||
send_utf8(t, s, TRUE);
|
||||
g_free(s);
|
||||
}
|
||||
g_object_unref(t->box);
|
||||
}
|
||||
|
||||
static void paste(TermView *t, gboolean primary)
|
||||
{
|
||||
GdkClipboard *c = primary ? gtk_widget_get_primary_clipboard(t->area) :
|
||||
gtk_widget_get_clipboard(t->area);
|
||||
g_object_ref(t->box);
|
||||
gdk_clipboard_read_text_async(c, NULL, pasted, t);
|
||||
}
|
||||
|
||||
static int key_of(guint kv)
|
||||
{
|
||||
switch (kv) {
|
||||
case GDK_KEY_Up: case GDK_KEY_KP_Up: return DMC_KEY_UP;
|
||||
case GDK_KEY_Down: case GDK_KEY_KP_Down: return DMC_KEY_DOWN;
|
||||
case GDK_KEY_Left: case GDK_KEY_KP_Left: return DMC_KEY_LEFT;
|
||||
case GDK_KEY_Right: case GDK_KEY_KP_Right: return DMC_KEY_RIGHT;
|
||||
case GDK_KEY_Home: case GDK_KEY_KP_Home: return DMC_KEY_HOME;
|
||||
case GDK_KEY_End: case GDK_KEY_KP_End: return DMC_KEY_END;
|
||||
case GDK_KEY_Page_Up: case GDK_KEY_KP_Page_Up: return DMC_KEY_PGUP;
|
||||
case GDK_KEY_Page_Down: case GDK_KEY_KP_Page_Down: return DMC_KEY_PGDN;
|
||||
case GDK_KEY_Insert: case GDK_KEY_KP_Insert: return DMC_KEY_INSERT;
|
||||
case GDK_KEY_Delete: case GDK_KEY_KP_Delete: return DMC_KEY_DELETE;
|
||||
case GDK_KEY_ISO_Left_Tab: return DMC_KEY_BACKTAB;
|
||||
case GDK_KEY_Tab: return DMC_KEY_TAB;
|
||||
case GDK_KEY_Return: return DMC_KEY_ENTER;
|
||||
case GDK_KEY_KP_Enter: return DMC_KEY_KP_ENTER;
|
||||
case GDK_KEY_BackSpace: return DMC_KEY_BACKSPACE;
|
||||
case GDK_KEY_Escape: return DMC_KEY_ESCAPE;
|
||||
case GDK_KEY_F11: return DMC_KEY_F11;
|
||||
case GDK_KEY_F12: return DMC_KEY_F12;
|
||||
case GDK_KEY_Find: return DMC_KEY_FIND;
|
||||
case GDK_KEY_Select: return DMC_KEY_SELECT;
|
||||
}
|
||||
if (kv >= GDK_KEY_F1 && kv <= GDK_KEY_F10)
|
||||
return DMC_KEY_F1 + (int)(kv - GDK_KEY_F1);
|
||||
if (kv >= GDK_KEY_F13 && kv <= GDK_KEY_F20)
|
||||
return DMC_KEY_F13 + (int)(kv - GDK_KEY_F13);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static gboolean key_pressed(GtkEventControllerKey *k, guint kv, guint code,
|
||||
GdkModifierType state, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
int mods = mods_of(state);
|
||||
(void)k;
|
||||
(void)code;
|
||||
if (mods == DMC_MOD_SHIFT) {
|
||||
if (kv == GDK_KEY_Page_Up || kv == GDK_KEY_Page_Down) {
|
||||
double v = gtk_adjustment_get_value(t->adj) +
|
||||
(kv == GDK_KEY_Page_Up ? -1 : 1) *
|
||||
gtk_adjustment_get_page_size(t->adj);
|
||||
gtk_adjustment_set_value(t->adj, v);
|
||||
return TRUE;
|
||||
}
|
||||
if (kv == GDK_KEY_Insert) {
|
||||
paste(t, FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if ((mods & DMC_MOD_CTRL) && (mods & DMC_MOD_SHIFT) &&
|
||||
(kv == GDK_KEY_V || kv == GDK_KEY_v)) {
|
||||
paste(t, FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
int key = key_of(kv);
|
||||
if (key) {
|
||||
send_key(t, key, mods);
|
||||
return TRUE;
|
||||
}
|
||||
/* Ctrl or Alt with a character: the terminal's controls, ESC and it */
|
||||
gunichar c = gdk_keyval_to_unicode(kv);
|
||||
if (c && (mods & (DMC_MOD_CTRL | DMC_MOD_ALT))) {
|
||||
to_bottom(t);
|
||||
send_cp(t, c, mods & (DMC_MOD_CTRL | DMC_MOD_ALT));
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/* the cell under a point */
|
||||
static void cell_at(TermView *t, double x, double y, int *col, int *row)
|
||||
{
|
||||
*col = MAX(0, (int)((x - t->ox) / t->cw));
|
||||
*row = MAX(0, (int)((y - t->oy) / t->ch));
|
||||
}
|
||||
|
||||
static gboolean mouse_report(TermView *t, int button, double x, double y,
|
||||
int press, int motion, GdkModifierType state)
|
||||
{
|
||||
if (!dmc_vt_mouse_wanted(t->vt))
|
||||
return FALSE;
|
||||
int col, row;
|
||||
char b[64];
|
||||
cell_at(t, x, y, &col, &row);
|
||||
send_text(t, b, dmc_vt_mouse(t->vt, button, col, row, press, motion,
|
||||
mods_of(state), b, sizeof(b)));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static int button_of(GtkGestureClick *g)
|
||||
{
|
||||
guint b = gtk_gesture_single_get_current_button(GTK_GESTURE_SINGLE(g));
|
||||
return b == 1 ? 0 : b == 2 ? 1 : 2;
|
||||
}
|
||||
|
||||
static void pressed(GtkGestureClick *g, int n, double x, double y, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
int b = button_of(g);
|
||||
GdkModifierType st = gtk_event_controller_get_current_event_state(
|
||||
GTK_EVENT_CONTROLLER(g));
|
||||
(void)n;
|
||||
gtk_widget_grab_focus(t->area);
|
||||
t->buttons |= 1 << b;
|
||||
if (mouse_report(t, b, x, y, 1, 0, st))
|
||||
return;
|
||||
if (b == 0) {
|
||||
/* a RIPscrip button's */
|
||||
char s[256];
|
||||
double fx = (x - t->ox) / (dmc_vt_cols(t->vt) * t->cw);
|
||||
double fy = (y - t->oy) / (dmc_vt_rows(t->vt) * t->ch);
|
||||
int k = dmc_vt_tap(t->vt, fx, fy, s, sizeof(s));
|
||||
if (k > 0) {
|
||||
to_bottom(t);
|
||||
send_text(t, s, k);
|
||||
}
|
||||
} else {
|
||||
paste(t, b == 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void released(GtkGestureClick *g, int n, double x, double y,
|
||||
gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
int b = button_of(g);
|
||||
(void)n;
|
||||
t->buttons &= ~(1 << b);
|
||||
mouse_report(t, b, x, y, 0, 0, gtk_event_controller_get_current_event_state(
|
||||
GTK_EVENT_CONTROLLER(g)));
|
||||
}
|
||||
|
||||
static void moved(GtkEventControllerMotion *m, double x, double y, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
int b = t->buttons & 1 ? 0 : t->buttons & 2 ? 1 : t->buttons & 4 ? 2 : 3;
|
||||
mouse_report(t, b, x, y, 1, 1, gtk_event_controller_get_current_event_state(
|
||||
GTK_EVENT_CONTROLLER(m)));
|
||||
}
|
||||
|
||||
static gboolean scrolled(GtkEventControllerScroll *s, double dx, double dy,
|
||||
gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
(void)dx;
|
||||
if (dmc_vt_mouse_wanted(t->vt)) {
|
||||
double x = 0, y = 0;
|
||||
GdkEvent *e = gtk_event_controller_get_current_event(
|
||||
GTK_EVENT_CONTROLLER(s));
|
||||
if (e)
|
||||
gdk_event_get_position(e, &x, &y);
|
||||
mouse_report(t, dy < 0 ? 64 : 65, x, y, 1, 0, 0);
|
||||
return TRUE;
|
||||
}
|
||||
gtk_adjustment_set_value(t->adj, gtk_adjustment_get_value(t->adj) +
|
||||
dy * 3);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static void focus_changed(TermView *t, gboolean in)
|
||||
{
|
||||
char b[16];
|
||||
t->focused = in;
|
||||
if (in)
|
||||
gtk_im_context_focus_in(t->im);
|
||||
else
|
||||
gtk_im_context_focus_out(t->im);
|
||||
send_text(t, b, dmc_vt_focus(t->vt, in, b, sizeof(b)));
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
|
||||
static void focus_in(GtkEventControllerFocus *f, gpointer data)
|
||||
{
|
||||
(void)f;
|
||||
focus_changed(data, TRUE);
|
||||
}
|
||||
|
||||
static void focus_out(GtkEventControllerFocus *f, gpointer data)
|
||||
{
|
||||
(void)f;
|
||||
focus_changed(data, FALSE);
|
||||
}
|
||||
|
||||
static void scrolled_bar(GtkAdjustment *adj, gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
if (t->adjusting)
|
||||
return;
|
||||
int hist = dmc_vt_history(t->vt);
|
||||
int pos = CLAMP((int)gtk_adjustment_get_value(adj), 0, hist);
|
||||
t->scroll = pos - hist;
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
|
||||
static void resized(GtkDrawingArea *a, int w, int h, gpointer data)
|
||||
{
|
||||
(void)a;
|
||||
(void)w;
|
||||
(void)h;
|
||||
layout(data);
|
||||
}
|
||||
|
||||
static gboolean blink(gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
t->blink_off = !t->blink_off;
|
||||
if (t->has_blink)
|
||||
gtk_widget_queue_draw(t->area);
|
||||
return G_SOURCE_CONTINUE;
|
||||
}
|
||||
|
||||
static void destroyed(gpointer data)
|
||||
{
|
||||
TermView *t = data;
|
||||
if (t->blink_tick)
|
||||
g_source_remove(t->blink_tick);
|
||||
for (int i = 0; i < 4; i++)
|
||||
pango_font_description_free(t->font[i]);
|
||||
g_object_unref(t->im);
|
||||
dmc_vt_free(t->vt);
|
||||
g_free(t);
|
||||
}
|
||||
|
||||
GtkWidget *termview_new(TermTypedFn fn, void *ctx)
|
||||
{
|
||||
TermView *t = g_new0(TermView, 1);
|
||||
t->fn = fn;
|
||||
t->ctx = ctx;
|
||||
t->vt = dmc_vt_new(80, 24, 5000);
|
||||
dmc_vt_set_backspace(t->vt, 0x7f);
|
||||
/* the brand's colours */
|
||||
dmc_vt_set_theme(t->vt, 0xe8f0ff, 0x0a0f1c, 0xe8f0ff, NULL);
|
||||
t->font[0] = pango_font_description_from_string("Monospace 11");
|
||||
for (int i = 1; i < 4; i++) {
|
||||
t->font[i] = pango_font_description_copy(t->font[0]);
|
||||
if (i & 1)
|
||||
pango_font_description_set_weight(t->font[i], PANGO_WEIGHT_BOLD);
|
||||
if (i & 2)
|
||||
pango_font_description_set_style(t->font[i], PANGO_STYLE_ITALIC);
|
||||
}
|
||||
t->box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
|
||||
t->area = gtk_drawing_area_new();
|
||||
gtk_widget_set_hexpand(t->area, TRUE);
|
||||
gtk_widget_set_vexpand(t->area, TRUE);
|
||||
gtk_widget_set_focusable(t->area, TRUE);
|
||||
gtk_widget_set_cursor_from_name(t->area, "text");
|
||||
gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(t->area), draw, t, NULL);
|
||||
g_signal_connect(t->area, "resize", G_CALLBACK(resized), t);
|
||||
t->adj = gtk_adjustment_new(0, 0, 24, 1, 24, 24);
|
||||
g_signal_connect(t->adj, "value-changed", G_CALLBACK(scrolled_bar), t);
|
||||
t->bar = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, t->adj);
|
||||
gtk_box_append(GTK_BOX(t->box), t->area);
|
||||
gtk_box_append(GTK_BOX(t->box), t->bar);
|
||||
|
||||
t->im = gtk_im_multicontext_new();
|
||||
g_signal_connect(t->im, "commit", G_CALLBACK(committed), t);
|
||||
GtkEventController *k = gtk_event_controller_key_new();
|
||||
gtk_event_controller_key_set_im_context(GTK_EVENT_CONTROLLER_KEY(k), t->im);
|
||||
g_signal_connect(k, "key-pressed", G_CALLBACK(key_pressed), t);
|
||||
gtk_widget_add_controller(t->area, k);
|
||||
gtk_im_context_set_client_widget(t->im, t->area);
|
||||
|
||||
GtkGesture *g = gtk_gesture_click_new();
|
||||
gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(g), 0);
|
||||
g_signal_connect(g, "pressed", G_CALLBACK(pressed), t);
|
||||
g_signal_connect(g, "released", G_CALLBACK(released), t);
|
||||
gtk_widget_add_controller(t->area, GTK_EVENT_CONTROLLER(g));
|
||||
GtkEventController *m = gtk_event_controller_motion_new();
|
||||
g_signal_connect(m, "motion", G_CALLBACK(moved), t);
|
||||
gtk_widget_add_controller(t->area, m);
|
||||
GtkEventController *s = gtk_event_controller_scroll_new(
|
||||
GTK_EVENT_CONTROLLER_SCROLL_VERTICAL);
|
||||
g_signal_connect(s, "scroll", G_CALLBACK(scrolled), t);
|
||||
gtk_widget_add_controller(t->area, s);
|
||||
GtkEventController *f = gtk_event_controller_focus_new();
|
||||
g_signal_connect(f, "enter", G_CALLBACK(focus_in), t);
|
||||
g_signal_connect(f, "leave", G_CALLBACK(focus_out), t);
|
||||
gtk_widget_add_controller(t->area, f);
|
||||
|
||||
g_object_set_data_full(G_OBJECT(t->box), "termview", t, destroyed);
|
||||
measure(t);
|
||||
t->cw = t->fcw;
|
||||
t->ch = t->fch;
|
||||
t->blink_tick = g_timeout_add(500, blink, t);
|
||||
return t->box;
|
||||
}
|
||||
|
||||
void termview_feed(GtkWidget *w, const char *data, int n)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
if (!t || n <= 0)
|
||||
return;
|
||||
int before = dmc_vt_history(t->vt);
|
||||
dmc_vt_feed(t->vt, data, n);
|
||||
if (t->scroll)
|
||||
t->scroll = MAX(t->scroll - (dmc_vt_history(t->vt) - before),
|
||||
-dmc_vt_history(t->vt));
|
||||
char r[256];
|
||||
int k;
|
||||
while ((k = dmc_vt_reply(t->vt, r, sizeof(r))) > 0)
|
||||
send_text(t, r, k);
|
||||
while (dmc_vt_printed(t->vt, r, sizeof(r)) > 0)
|
||||
;
|
||||
uint32_t hz;
|
||||
int ms, rest;
|
||||
while (dmc_vt_music(t->vt, &hz, &ms, &rest))
|
||||
;
|
||||
if (dmc_vt_bells(t->vt))
|
||||
gtk_widget_error_bell(t->area);
|
||||
layout(t);
|
||||
update_bar(t);
|
||||
if (dmc_vt_changed(t->vt))
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
|
||||
void termview_reset(GtkWidget *w)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
if (!t)
|
||||
return;
|
||||
dmc_vt_reset(t->vt);
|
||||
t->scroll = 0;
|
||||
layout(t);
|
||||
update_bar(t);
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
|
||||
void termview_size(GtkWidget *w, int *cols, int *rows)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
*cols = t ? dmc_vt_cols(t->vt) : 80;
|
||||
*rows = t ? dmc_vt_rows(t->vt) : 24;
|
||||
}
|
||||
|
||||
void termview_set_backspace(GtkWidget *w, int code)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
if (t)
|
||||
dmc_vt_set_backspace(t->vt, code);
|
||||
}
|
||||
|
||||
void termview_set_profile(GtkWidget *w, const char *id)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
if (!t || !dmc_vt_set_profile(t->vt, id))
|
||||
return;
|
||||
t->scroll = 0;
|
||||
layout(t);
|
||||
update_bar(t);
|
||||
gtk_widget_queue_draw(t->area);
|
||||
}
|
||||
|
||||
const char *termview_profile(GtkWidget *w)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
return t ? dmc_vt_get_profile(t->vt) : "xterm";
|
||||
}
|
||||
|
||||
void termview_focus(GtkWidget *w)
|
||||
{
|
||||
TermView *t = of(w);
|
||||
if (t)
|
||||
gtk_widget_grab_focus(t->area);
|
||||
}
|
||||
|
||||
GtkWidget *term_types_new(const char *id)
|
||||
{
|
||||
int n = dmc_vt_profile_count(), sel = 0;
|
||||
const char **labels = g_new0(const char *, n + 1);
|
||||
for (int i = 0; i < n; i++) {
|
||||
labels[i] = dmc_vt_profile_label(i);
|
||||
if (id && !strcmp(id, dmc_vt_profile_id(i)))
|
||||
sel = i;
|
||||
}
|
||||
GtkWidget *d = gtk_drop_down_new_from_strings(labels);
|
||||
g_free(labels);
|
||||
gtk_drop_down_set_selected(GTK_DROP_DOWN(d), (guint)sel);
|
||||
gtk_widget_set_tooltip_text(d, "The kind of terminal");
|
||||
return d;
|
||||
}
|
||||
|
||||
const char *term_types_chosen(GtkWidget *d)
|
||||
{
|
||||
const char *id = dmc_vt_profile_id(
|
||||
(int)gtk_drop_down_get_selected(GTK_DROP_DOWN(d)));
|
||||
return id ? id : dmc_vt_profile_id(0);
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* usbmodem.c - hardware modems on USB that the "device" line can open:
|
||||
* the MultiTech MT9234MU and MT9234ZBA-USB, found in sysfs
|
||||
*
|
||||
* These modems have a TI TUSB3410 USB UART. Linux's ti_usb_3410_5052
|
||||
* driver downloads its firmware (mts_mt9234mu.fw) into the chip; then
|
||||
* the modem is a ttyUSB. Without the firmware file the modem stays in
|
||||
* the chip's boot ROM (one configuration) and has no tty.
|
||||
*/
|
||||
#include <glib.h>
|
||||
#include <glib/gstdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
/* MultiTech's vendor ID and the products with a TUSB3410 */
|
||||
static const struct {
|
||||
const char *product, *name;
|
||||
} models[] = {
|
||||
{ "f114", "MultiTech MT9234MU" },
|
||||
{ "f115", "MultiTech MT9234ZBA-USB" },
|
||||
{ "0319", "MultiTech MT9234ZBA-USB" },
|
||||
};
|
||||
|
||||
/* the firmware file's places that Linux looks in */
|
||||
static const char *const firmware[] = {
|
||||
"/lib/firmware/updates/mts_mt9234mu.fw",
|
||||
"/lib/firmware/mts_mt9234mu.fw",
|
||||
"/usr/lib/firmware/updates/mts_mt9234mu.fw",
|
||||
"/usr/lib/firmware/mts_mt9234mu.fw",
|
||||
"/lib/firmware/mts_mt9234zba.fw",
|
||||
"/usr/lib/firmware/mts_mt9234zba.fw",
|
||||
NULL
|
||||
};
|
||||
|
||||
/* the trimmed text of sysfs file dir/name, or NULL */
|
||||
static char *attr(const char *dir, const char *name)
|
||||
{
|
||||
char *path = g_build_filename(dir, name, NULL);
|
||||
char *t = NULL;
|
||||
if (g_file_get_contents(path, &t, NULL, NULL))
|
||||
g_strstrip(t);
|
||||
g_free(path);
|
||||
return t;
|
||||
}
|
||||
|
||||
/* the first ttyUSB under USB device dir's interfaces, as /dev/ttyUSBn,
|
||||
or NULL */
|
||||
static char *tty_of(const char *dir)
|
||||
{
|
||||
char *found = NULL;
|
||||
GDir *d = g_dir_open(dir, 0, NULL);
|
||||
if (!d)
|
||||
return NULL;
|
||||
const char *e;
|
||||
while (!found && (e = g_dir_read_name(d))) {
|
||||
/* (its interfaces: "1-2:2.0") */
|
||||
if (!strchr(e, ':'))
|
||||
continue;
|
||||
char *itf = g_build_filename(dir, e, NULL);
|
||||
GDir *i = g_dir_open(itf, 0, NULL);
|
||||
const char *t;
|
||||
while (i && !found && (t = g_dir_read_name(i)))
|
||||
if (g_str_has_prefix(t, "ttyUSB"))
|
||||
found = g_strconcat("/dev/", t, NULL);
|
||||
if (i)
|
||||
g_dir_close(i);
|
||||
g_free(itf);
|
||||
}
|
||||
g_dir_close(d);
|
||||
return found;
|
||||
}
|
||||
|
||||
gboolean usbmodem_firmware_present(void)
|
||||
{
|
||||
for (int i = 0; firmware[i]; i++)
|
||||
if (g_file_test(firmware[i], G_FILE_TEST_EXISTS))
|
||||
return TRUE;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
UsbModem *usbmodem_find(void)
|
||||
{
|
||||
const char *root = "/sys/bus/usb/devices";
|
||||
GDir *d = g_dir_open(root, 0, NULL);
|
||||
if (!d)
|
||||
return NULL;
|
||||
UsbModem *m = NULL;
|
||||
const char *e;
|
||||
while (!m && (e = g_dir_read_name(d))) {
|
||||
char *dir = g_build_filename(root, e, NULL);
|
||||
char *vid = attr(dir, "idVendor");
|
||||
char *pid = vid ? attr(dir, "idProduct") : NULL;
|
||||
for (size_t k = 0; pid && !m &&
|
||||
k < sizeof(models) / sizeof(models[0]); k++) {
|
||||
if (g_ascii_strcasecmp(vid, "06e0") ||
|
||||
g_ascii_strcasecmp(pid, models[k].product))
|
||||
continue;
|
||||
m = g_new0(UsbModem, 1);
|
||||
m->name = g_strdup(models[k].name);
|
||||
m->tty = tty_of(dir);
|
||||
char *nc = attr(dir, "bNumConfigurations");
|
||||
/* (one configuration: the boot ROM's) */
|
||||
m->no_firmware = !m->tty && nc && !strcmp(nc, "1");
|
||||
g_free(nc);
|
||||
}
|
||||
g_free(vid);
|
||||
g_free(pid);
|
||||
g_free(dir);
|
||||
}
|
||||
g_dir_close(d);
|
||||
return m;
|
||||
}
|
||||
|
||||
char *usbmodem_shipped_firmware(void)
|
||||
{
|
||||
static const char *const dirs[] = {
|
||||
DMODEM_FIRMWARE_DIR, DMODEM_FIRMWARE_SRC, NULL
|
||||
};
|
||||
for (int i = 0; dirs[i]; i++) {
|
||||
char *p = g_build_filename(dirs[i], "mts_mt9234mu.fw", NULL);
|
||||
if (g_file_test(p, G_FILE_TEST_EXISTS))
|
||||
return p;
|
||||
g_free(p);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char *usbmodem_describe(const UsbModem *m)
|
||||
{
|
||||
if (m->tty)
|
||||
return g_strdup_printf("%s at %s", m->name, m->tty);
|
||||
if (m->no_firmware && !usbmodem_firmware_present()) {
|
||||
char *fw = usbmodem_shipped_firmware();
|
||||
/* (the MT9234ZBA-USB's driver asks for its own name) */
|
||||
const char *to = strstr(m->name, "ZBA") ?
|
||||
"/lib/firmware/mts_mt9234zba.fw" : "/lib/firmware/";
|
||||
char *d = g_strdup_printf("%s, with no firmware: copy %s to "
|
||||
"%s (sudo cp), then connect the "
|
||||
"modem again", m->name,
|
||||
fw ? fw : "mts_mt9234mu.fw", to);
|
||||
g_free(fw);
|
||||
return d;
|
||||
}
|
||||
if (m->no_firmware)
|
||||
return g_strdup_printf("%s, with no firmware: load the "
|
||||
"ti_usb_3410_5052 driver, then connect "
|
||||
"the modem again", m->name);
|
||||
return g_strdup_printf("%s, with no serial port: load the "
|
||||
"ti_usb_3410_5052 driver", m->name);
|
||||
}
|
||||
|
||||
gboolean usbmodem_is(const char *path)
|
||||
{
|
||||
UsbModem *m = usbmodem_find();
|
||||
gboolean is = m && m->tty && path && !strcmp(m->tty, path);
|
||||
usbmodem_free(m);
|
||||
return is;
|
||||
}
|
||||
|
||||
void usbmodem_free(UsbModem *m)
|
||||
{
|
||||
if (!m)
|
||||
return;
|
||||
g_free(m->name);
|
||||
g_free(m->tty);
|
||||
g_free(m);
|
||||
}
|
||||
@@ -1,937 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* voice.c - the Phone page: voice calls dialled and answered, their
|
||||
* sound on the sound card, the keypad's DTMF; the answering
|
||||
* machine (off until the user turns it on), its greeting and
|
||||
* the messages it took, kept as WAV files in
|
||||
* ~/.local/share/dmodem-gui/voicemail
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <glib/gstdio.h>
|
||||
|
||||
#include "app.h"
|
||||
|
||||
#ifdef HAVE_SNDFILE
|
||||
#include <sndfile.h>
|
||||
#endif
|
||||
|
||||
/* the longest greeting recorded (s) */
|
||||
#define GREETING_MAX_S 30
|
||||
|
||||
typedef struct Voice {
|
||||
GtkWidget *status, *number, *call_btn, *answer_btn, *message_btn;
|
||||
GtkWidget *pickup_btn, *hangup_btn, *keypad, *mute_btn, *listen_btn;
|
||||
GtkWidget *vm_switch, *vm_rings, *greeting_row, *record_btn;
|
||||
GtkWidget *greeting_play, *greeting_clear;
|
||||
AdwPreferencesGroup *messages;
|
||||
GPtrArray *message_rows;
|
||||
GtkWidget *messages_empty;
|
||||
guint fast; /* the 20 ms tick of a call */
|
||||
int last_state;
|
||||
gboolean muted, listening, listen_on;
|
||||
/* what plays (a message, the greeting), and what is recorded */
|
||||
int16_t *play;
|
||||
int play_n, play_pos;
|
||||
guint play_end;
|
||||
GArray *recording;
|
||||
/* the greeting, 8 kHz */
|
||||
int16_t *greeting;
|
||||
int greeting_n;
|
||||
} Voice;
|
||||
|
||||
/*
|
||||
* files
|
||||
*/
|
||||
|
||||
static char *data_dir(void)
|
||||
{
|
||||
return g_build_filename(g_get_user_data_dir(), "dmodem-gui", NULL);
|
||||
}
|
||||
|
||||
static char *messages_dir(void)
|
||||
{
|
||||
return g_build_filename(g_get_user_data_dir(), "dmodem-gui",
|
||||
"voicemail", NULL);
|
||||
}
|
||||
|
||||
static char *greeting_path(void)
|
||||
{
|
||||
return g_build_filename(g_get_user_data_dir(), "dmodem-gui",
|
||||
"greeting.wav", NULL);
|
||||
}
|
||||
|
||||
/* samples as a WAV file at path */
|
||||
static gboolean write_wav(const char *path, const int16_t *pcm, int n,
|
||||
GError **e)
|
||||
{
|
||||
char *dir = g_path_get_dirname(path);
|
||||
g_mkdir_with_parents(dir, 0700);
|
||||
g_free(dir);
|
||||
gsize len = 44 + (gsize)n * 2;
|
||||
char *b = g_malloc(len);
|
||||
dmc_wav_header(b, n);
|
||||
for (int i = 0; i < n; i++) {
|
||||
guint16 v = GUINT16_TO_LE((guint16)pcm[i]);
|
||||
memcpy(b + 44 + i * 2, &v, 2);
|
||||
}
|
||||
gboolean ok = g_file_set_contents_full(path, b, (gssize)len,
|
||||
G_FILE_SET_CONTENTS_CONSISTENT,
|
||||
0600, e);
|
||||
g_free(b);
|
||||
return ok;
|
||||
}
|
||||
|
||||
#ifdef HAVE_SNDFILE
|
||||
/* a sound file libsndfile reads (MP3, FLAC, Ogg Vorbis, Opus and the
|
||||
rest it knows) as samples at 8 kHz, mono: how many (*pcm to free()), -1 */
|
||||
static int read_sndfile(const char *path, int16_t **pcm)
|
||||
{
|
||||
SF_INFO info = { 0 };
|
||||
SNDFILE *sf = sf_open(path, SFM_READ, &info);
|
||||
*pcm = NULL;
|
||||
if (!sf)
|
||||
return -1;
|
||||
int ch = info.channels;
|
||||
if (ch < 1 || info.samplerate < 1 || info.frames < 1 ||
|
||||
info.frames > (sf_count_t)info.samplerate * 3600) {
|
||||
sf_close(sf);
|
||||
return -1;
|
||||
}
|
||||
/* read in pieces (the frame count of an MP3 is a guess), mixed to mono */
|
||||
GArray *mono = g_array_new(FALSE, FALSE, sizeof(float));
|
||||
float *buf = g_new(float, 4096 * (gsize)ch);
|
||||
sf_count_t got;
|
||||
while ((got = sf_readf_float(sf, buf, 4096)) > 0) {
|
||||
for (sf_count_t i = 0; i < got; i++) {
|
||||
float m = 0;
|
||||
for (int c = 0; c < ch; c++)
|
||||
m += buf[i * ch + c];
|
||||
m /= (float)ch;
|
||||
g_array_append_val(mono, m);
|
||||
}
|
||||
if (mono->len > (guint)info.samplerate * 3600)
|
||||
break;
|
||||
}
|
||||
g_free(buf);
|
||||
sf_close(sf);
|
||||
double step = (double)info.samplerate / 8000;
|
||||
gint64 n = mono->len ? (gint64)((mono->len - 1) / step) + 1 : 0;
|
||||
if (n < 1 || n > G_MAXINT) {
|
||||
g_array_free(mono, TRUE);
|
||||
return -1;
|
||||
}
|
||||
int16_t *out = malloc((size_t)n * sizeof(int16_t));
|
||||
if (!out) {
|
||||
g_array_free(mono, TRUE);
|
||||
return -1;
|
||||
}
|
||||
const float *x = (const float *)mono->data;
|
||||
for (gint64 i = 0; i < n; i++) {
|
||||
double t = i * step;
|
||||
guint k = (guint)t;
|
||||
double f = t - k;
|
||||
double y = x[k];
|
||||
if (k + 1 < mono->len)
|
||||
y += (x[k + 1] - y) * f;
|
||||
y *= 32767;
|
||||
out[i] = (int16_t)(y > 32767 ? 32767 : y < -32768 ? -32768 : y);
|
||||
}
|
||||
g_array_free(mono, TRUE);
|
||||
*pcm = out;
|
||||
return (int)n;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* a sound file's samples at 8 kHz, mono: WAV, AIFF and .au by
|
||||
libdmodemctl, the rest (MP3, FLAC, Ogg) by libsndfile where it's
|
||||
built in. How many (*pcm to dmc_free()), -1 */
|
||||
static int read_wav(const char *path, int16_t **pcm)
|
||||
{
|
||||
char *b;
|
||||
gsize len;
|
||||
*pcm = NULL;
|
||||
if (!g_file_get_contents(path, &b, &len, NULL))
|
||||
return -1;
|
||||
int n = len > G_MAXINT ? -1 : dmc_audio_decode(b, (int)len, pcm);
|
||||
g_free(b);
|
||||
#ifdef HAVE_SNDFILE
|
||||
if (n < 0)
|
||||
n = read_sndfile(path, pcm);
|
||||
#endif
|
||||
return n;
|
||||
}
|
||||
|
||||
/*
|
||||
* sound
|
||||
*/
|
||||
|
||||
static int call_pull(App *a, int16_t *pcm, int n)
|
||||
{
|
||||
return dmc_voice_read(a->s, pcm, n);
|
||||
}
|
||||
|
||||
static void call_push(App *a, const int16_t *pcm, int n)
|
||||
{
|
||||
if (!a->voice->muted)
|
||||
dmc_voice_write(a->s, pcm, n);
|
||||
}
|
||||
|
||||
static gboolean play_done(gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
Voice *v = a->voice;
|
||||
v->play_end = 0;
|
||||
audio_stop(a);
|
||||
g_clear_pointer(&v->play, dmc_free);
|
||||
v->play_n = v->play_pos = 0;
|
||||
voice_state(a);
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
static int play_pull(App *a, int16_t *pcm, int n)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
int k = v->play_n - v->play_pos;
|
||||
if (k > n)
|
||||
k = n;
|
||||
if (k > 0) {
|
||||
memcpy(pcm, v->play + v->play_pos, (size_t)k * 2);
|
||||
v->play_pos += k;
|
||||
}
|
||||
/* (stopped from the main loop, not inside the sound's callback) */
|
||||
if (v->play_pos >= v->play_n && !v->play_end)
|
||||
v->play_end = g_timeout_add(300, play_done, a);
|
||||
return k;
|
||||
}
|
||||
|
||||
static void record_push(App *a, const int16_t *pcm, int n)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
if (!v->recording)
|
||||
return;
|
||||
int room = GREETING_MAX_S * DMC_VOICE_RATE - (int)v->recording->len;
|
||||
if (n > room)
|
||||
n = room;
|
||||
if (n > 0)
|
||||
g_array_append_vals(v->recording, pcm, (guint)n);
|
||||
}
|
||||
|
||||
static void stop_sound(App *a)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
if (v->play_end) {
|
||||
g_source_remove(v->play_end);
|
||||
v->play_end = 0;
|
||||
}
|
||||
audio_stop(a);
|
||||
g_clear_pointer(&v->play, dmc_free);
|
||||
v->play_n = v->play_pos = 0;
|
||||
if (v->recording) {
|
||||
g_array_unref(v->recording);
|
||||
v->recording = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/* pcm (taken: dmc_free()d when done) played */
|
||||
static void play(App *a, int16_t *pcm, int n)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
stop_sound(a);
|
||||
v->play = pcm;
|
||||
v->play_n = n;
|
||||
v->play_pos = 0;
|
||||
if (!audio_start(a, play_pull, NULL)) {
|
||||
window_toast(a, "No sound: D-Modem was built without "
|
||||
"PulseAudio");
|
||||
stop_sound(a);
|
||||
}
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
/*
|
||||
* the answering machine's greeting and messages
|
||||
*/
|
||||
|
||||
static void load_greeting(App *a)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
char *p = greeting_path();
|
||||
g_clear_pointer(&v->greeting, dmc_free);
|
||||
v->greeting_n = 0;
|
||||
int16_t *pcm;
|
||||
int n = read_wav(p, &pcm);
|
||||
if (n > 0) {
|
||||
v->greeting = pcm;
|
||||
v->greeting_n = n;
|
||||
} else if (pcm) {
|
||||
dmc_free(pcm);
|
||||
}
|
||||
g_free(p);
|
||||
}
|
||||
|
||||
void voice_configure(App *a)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
dmc_voicemail_set(a->s, v->greeting, v->greeting_n, a->cfg.vm_max, 0);
|
||||
dmc_voicemail_auto(a->s, a->cfg.voicemail ? a->cfg.vm_rings : 0);
|
||||
}
|
||||
|
||||
static void refresh_messages(App *a);
|
||||
|
||||
static void play_message(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
const char *path = g_object_get_data(G_OBJECT(w), "path");
|
||||
int16_t *pcm;
|
||||
int n = read_wav(path, &pcm);
|
||||
if (n <= 0) {
|
||||
if (pcm)
|
||||
dmc_free(pcm);
|
||||
window_toast(a, "Can't read the message");
|
||||
return;
|
||||
}
|
||||
play(a, pcm, n);
|
||||
}
|
||||
|
||||
static void delete_message(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
const char *path = g_object_get_data(G_OBJECT(w), "path");
|
||||
stop_sound(a);
|
||||
if (g_remove(path) < 0)
|
||||
window_toast(a, "Can't delete the message");
|
||||
refresh_messages(a);
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
static int newest_first(gconstpointer x, gconstpointer y)
|
||||
{
|
||||
return -g_strcmp0(*(char *const *)x, *(char *const *)y);
|
||||
}
|
||||
|
||||
/* the message list from the files: 20261111-120501_5551234.wav */
|
||||
static void refresh_messages(App *a)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
for (guint i = 0; i < v->message_rows->len; i++)
|
||||
adw_preferences_group_remove(v->messages,
|
||||
g_ptr_array_index(v->message_rows, i));
|
||||
g_ptr_array_set_size(v->message_rows, 0);
|
||||
char *dir = messages_dir();
|
||||
GDir *d = g_dir_open(dir, 0, NULL);
|
||||
GPtrArray *names = g_ptr_array_new_with_free_func(g_free);
|
||||
const char *n;
|
||||
while (d && (n = g_dir_read_name(d)))
|
||||
if (g_str_has_suffix(n, ".wav"))
|
||||
g_ptr_array_add(names, g_strdup(n));
|
||||
if (d)
|
||||
g_dir_close(d);
|
||||
g_ptr_array_sort(names, newest_first);
|
||||
for (guint i = 0; i < names->len; i++) {
|
||||
const char *name = g_ptr_array_index(names, i);
|
||||
char *path = g_build_filename(dir, name, NULL);
|
||||
int y, mo, da, h, mi, se;
|
||||
char who[64] = "";
|
||||
if (sscanf(name, "%4d%2d%2d-%2d%2d%2d_%63[^.]", &y, &mo, &da,
|
||||
&h, &mi, &se, who) < 6) {
|
||||
g_free(path);
|
||||
continue;
|
||||
}
|
||||
GStatBuf st;
|
||||
long secs = !g_stat(path, &st) && st.st_size > 44 ?
|
||||
(long)((st.st_size - 44) / (2 * DMC_VOICE_RATE)) : 0;
|
||||
GtkWidget *row = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(row),
|
||||
*who ? who : "Unknown caller");
|
||||
char *sub = g_strdup_printf("%04d-%02d-%02d %02d:%02d · %ld:%02ld",
|
||||
y, mo, da, h, mi, secs / 60,
|
||||
secs % 60);
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(row), sub);
|
||||
g_free(sub);
|
||||
GtkWidget *pb = gtk_button_new_from_icon_name(
|
||||
"media-playback-start-symbolic");
|
||||
gtk_widget_set_tooltip_text(pb, "Play");
|
||||
gtk_widget_set_valign(pb, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(pb, "flat");
|
||||
g_object_set_data_full(G_OBJECT(pb), "path", g_strdup(path),
|
||||
g_free);
|
||||
g_signal_connect(pb, "clicked", G_CALLBACK(play_message), a);
|
||||
GtkWidget *db = gtk_button_new_from_icon_name(
|
||||
"user-trash-symbolic");
|
||||
gtk_widget_set_tooltip_text(db, "Delete");
|
||||
gtk_widget_set_valign(db, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(db, "flat");
|
||||
g_object_set_data_full(G_OBJECT(db), "path", path, g_free);
|
||||
g_signal_connect(db, "clicked", G_CALLBACK(delete_message), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(row), pb);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(row), db);
|
||||
adw_preferences_group_add(v->messages, row);
|
||||
g_ptr_array_add(v->message_rows, row);
|
||||
}
|
||||
gtk_widget_set_visible(v->messages_empty, v->message_rows->len == 0);
|
||||
g_ptr_array_unref(names);
|
||||
g_free(dir);
|
||||
}
|
||||
|
||||
/* the message the answering machine took, kept */
|
||||
static void save_message(App *a, const char *number)
|
||||
{
|
||||
const int16_t *pcm;
|
||||
int n = dmc_voice_message(a->s, &pcm);
|
||||
if (n <= 0)
|
||||
return;
|
||||
GDateTime *now = g_date_time_new_now_local();
|
||||
char *stamp = g_date_time_format(now, "%Y%m%d-%H%M%S");
|
||||
g_date_time_unref(now);
|
||||
/* (the number as a file name allows: digits, + * #) */
|
||||
GString *who = g_string_new("");
|
||||
for (const char *p = number; *p && who->len < 32; p++)
|
||||
if (g_ascii_isalnum(*p) || *p == '+' || *p == '*' || *p == '#')
|
||||
g_string_append_c(who, *p);
|
||||
char *name = g_strdup_printf("%s_%s.wav", stamp, who->str);
|
||||
char *dir = messages_dir();
|
||||
char *path = g_build_filename(dir, name, NULL);
|
||||
GError *e = NULL;
|
||||
if (!write_wav(path, pcm, n, &e)) {
|
||||
char *m = g_strdup_printf("Can't keep the message: %s",
|
||||
e->message);
|
||||
window_toast(a, m);
|
||||
g_free(m);
|
||||
g_error_free(e);
|
||||
} else {
|
||||
GNotification *nt = g_notification_new("New voice message");
|
||||
char *body = g_strdup_printf("From %s", *who->str ? who->str :
|
||||
"an unknown caller");
|
||||
g_notification_set_body(nt, body);
|
||||
g_application_send_notification(G_APPLICATION(a->gapp),
|
||||
"voicemail", nt);
|
||||
g_object_unref(nt);
|
||||
g_free(body);
|
||||
app_log(a, "The answering machine took a message.");
|
||||
}
|
||||
g_free(path);
|
||||
g_free(dir);
|
||||
g_free(name);
|
||||
g_free(stamp);
|
||||
g_string_free(who, TRUE);
|
||||
refresh_messages(a);
|
||||
}
|
||||
|
||||
/* the greeting: recorded from the microphone */
|
||||
static void record_greeting(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
Voice *v = a->voice;
|
||||
(void)w;
|
||||
if (v->recording) {
|
||||
/* stopped: kept */
|
||||
GArray *r = g_array_ref(v->recording);
|
||||
stop_sound(a);
|
||||
if (r->len > DMC_VOICE_RATE / 2) {
|
||||
char *p = greeting_path();
|
||||
GError *e = NULL;
|
||||
if (!write_wav(p, (int16_t *)r->data, (int)r->len, &e)) {
|
||||
window_toast(a, e->message);
|
||||
g_error_free(e);
|
||||
}
|
||||
g_free(p);
|
||||
load_greeting(a);
|
||||
voice_configure(a);
|
||||
}
|
||||
g_array_unref(r);
|
||||
voice_state(a);
|
||||
return;
|
||||
}
|
||||
stop_sound(a);
|
||||
v->recording = g_array_new(FALSE, FALSE, sizeof(int16_t));
|
||||
if (!audio_start(a, NULL, record_push)) {
|
||||
window_toast(a, "No sound: D-Modem was built without "
|
||||
"PulseAudio");
|
||||
stop_sound(a);
|
||||
}
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
static void play_greeting(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
Voice *v = a->voice;
|
||||
(void)w;
|
||||
if (v->play) {
|
||||
stop_sound(a);
|
||||
voice_state(a);
|
||||
return;
|
||||
}
|
||||
if (!v->greeting_n)
|
||||
return;
|
||||
/* (play() frees it with dmc_free(), which is free()) */
|
||||
int16_t *copy = malloc((size_t)v->greeting_n * 2);
|
||||
if (!copy)
|
||||
return;
|
||||
memcpy(copy, v->greeting, (size_t)v->greeting_n * 2);
|
||||
play(a, copy, v->greeting_n);
|
||||
}
|
||||
|
||||
static void clear_greeting(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
char *p = greeting_path();
|
||||
g_remove(p);
|
||||
g_free(p);
|
||||
load_greeting(a);
|
||||
voice_configure(a);
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
static void greeting_chosen(GObject *src, GAsyncResult *res, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL);
|
||||
if (!f)
|
||||
return;
|
||||
char *path = g_file_get_path(f);
|
||||
g_object_unref(f);
|
||||
int16_t *pcm;
|
||||
int n = path ? read_wav(path, &pcm) : -1;
|
||||
g_free(path);
|
||||
if (n <= 0) {
|
||||
if (n == 0)
|
||||
dmc_free(pcm);
|
||||
window_toast(a, "That isn't a sound file D-Modem can play");
|
||||
return;
|
||||
}
|
||||
char *p = greeting_path();
|
||||
GError *e = NULL;
|
||||
if (!write_wav(p, pcm, n, &e)) {
|
||||
window_toast(a, e->message);
|
||||
g_error_free(e);
|
||||
}
|
||||
g_free(p);
|
||||
dmc_free(pcm);
|
||||
load_greeting(a);
|
||||
voice_configure(a);
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
static void choose_greeting(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
GtkFileDialog *d = gtk_file_dialog_new();
|
||||
gtk_file_dialog_set_title(d, "Greeting");
|
||||
GtkFileFilter *f = gtk_file_filter_new();
|
||||
gtk_file_filter_set_name(f, "Sound files");
|
||||
static const char *const kinds[] = {
|
||||
"wav", "aif", "aiff", "aifc", "au", "snd",
|
||||
#ifdef HAVE_SNDFILE
|
||||
"mp3", "flac", "ogg", "oga", "opus", "caf", "w64",
|
||||
#endif
|
||||
};
|
||||
for (gsize i = 0; i < G_N_ELEMENTS(kinds); i++)
|
||||
gtk_file_filter_add_suffix(f, kinds[i]);
|
||||
GListStore *filters = g_list_store_new(GTK_TYPE_FILE_FILTER);
|
||||
g_list_store_append(filters, f);
|
||||
gtk_file_dialog_set_filters(d, G_LIST_MODEL(filters));
|
||||
g_object_unref(filters);
|
||||
g_object_unref(f);
|
||||
gtk_file_dialog_open(d, a->window, NULL, greeting_chosen, a);
|
||||
g_object_unref(d);
|
||||
}
|
||||
|
||||
static void voicemail_switched(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)ps;
|
||||
a->cfg.voicemail = adw_switch_row_get_active(ADW_SWITCH_ROW(o));
|
||||
config_save(&a->cfg);
|
||||
voice_configure(a);
|
||||
}
|
||||
|
||||
static void rings_changed(GObject *o, GParamSpec *ps, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)ps;
|
||||
a->cfg.vm_rings = (int)adw_spin_row_get_value(ADW_SPIN_ROW(o));
|
||||
config_save(&a->cfg);
|
||||
voice_configure(a);
|
||||
}
|
||||
|
||||
/*
|
||||
* calls
|
||||
*/
|
||||
|
||||
static void dialled(App *a, const dmc_event *ev, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
if (!ev->ok) {
|
||||
char *m = !strcmp(ev->result, "ERROR") ?
|
||||
g_strdup("The modem has no voice mode (D-Modem 1.1 "
|
||||
"or later has)") :
|
||||
g_strdup_printf("%c%s", g_ascii_toupper(ev->result[0]),
|
||||
ev->result + 1);
|
||||
window_toast(a, m);
|
||||
g_free(m);
|
||||
}
|
||||
}
|
||||
|
||||
static void call(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
const char *n = gtk_editable_get_text(GTK_EDITABLE(a->voice->number));
|
||||
if (!*n) {
|
||||
window_toast(a, "Enter a number or SIP address to call");
|
||||
return;
|
||||
}
|
||||
stop_sound(a);
|
||||
modem_wait(a, dmc_voice_dial(a->s, n), dialled, NULL);
|
||||
}
|
||||
|
||||
static void answer(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
stop_sound(a);
|
||||
modem_wait(a, dmc_voice_answer(a->s), dialled, NULL);
|
||||
}
|
||||
|
||||
static void take_message(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
stop_sound(a);
|
||||
modem_wait(a, dmc_voicemail_answer(a->s), dialled, NULL);
|
||||
}
|
||||
|
||||
static void pickup(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
dmc_voice_pickup(a->s);
|
||||
modem_pump(a);
|
||||
}
|
||||
|
||||
static void hangup(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)w;
|
||||
dmc_hangup(a->s);
|
||||
modem_pump(a);
|
||||
}
|
||||
|
||||
static void key(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
const char *k = gtk_button_get_label(GTK_BUTTON(w));
|
||||
int st = dmc_state(a->s);
|
||||
if (st == DMC_VOICE) {
|
||||
dmc_voice_dtmf(a->s, k[0]);
|
||||
} else {
|
||||
GtkEditable *e = GTK_EDITABLE(a->voice->number);
|
||||
int pos = -1;
|
||||
gtk_editable_insert_text(e, k, 1, &pos);
|
||||
}
|
||||
}
|
||||
|
||||
static void mute(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
a->voice->muted = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w));
|
||||
}
|
||||
|
||||
static void listen_toggled(GtkWidget *w, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
a->voice->listening = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w));
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
static gboolean fast_tick(gpointer data)
|
||||
{
|
||||
modem_pump(data);
|
||||
return G_SOURCE_CONTINUE;
|
||||
}
|
||||
|
||||
/* the sound as the call needs it: both ways in a call; the caller (if
|
||||
listening) while the answering machine has the call */
|
||||
static void call_sound(App *a, int st)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
int was = v->last_state;
|
||||
gboolean in = st == DMC_VOICE || st == DMC_VOICEMAIL;
|
||||
gboolean listen = st == DMC_VOICEMAIL && v->listening;
|
||||
if (in && !v->fast) {
|
||||
v->fast = g_timeout_add(20, fast_tick, a);
|
||||
} else if (!in && st != DMC_HANGING_UP && v->fast) {
|
||||
g_source_remove(v->fast);
|
||||
v->fast = 0;
|
||||
}
|
||||
if (st == DMC_VOICE && was != DMC_VOICE) {
|
||||
stop_sound(a);
|
||||
v->listen_on = FALSE;
|
||||
if (!audio_start(a, call_pull, call_push))
|
||||
window_toast(a, "No sound: D-Modem was built without "
|
||||
"PulseAudio");
|
||||
} else if (listen && !v->listen_on) {
|
||||
audio_start(a, call_pull, NULL);
|
||||
v->listen_on = TRUE;
|
||||
} else if (!listen && v->listen_on) {
|
||||
audio_stop(a);
|
||||
v->listen_on = FALSE;
|
||||
} else if (was == DMC_VOICE && st != DMC_VOICE) {
|
||||
audio_stop(a);
|
||||
}
|
||||
v->last_state = st;
|
||||
}
|
||||
|
||||
void voice_state(App *a)
|
||||
{
|
||||
Voice *v = a->voice;
|
||||
if (!v)
|
||||
return;
|
||||
int st = dmc_state(a->s);
|
||||
call_sound(a, st);
|
||||
const char *who = dmc_caller_number(a->s);
|
||||
char *status;
|
||||
switch (st) {
|
||||
case DMC_CLOSED:
|
||||
status = g_strdup("The modem isn't running");
|
||||
break;
|
||||
case DMC_RINGING:
|
||||
status = g_strdup_printf("Ringing%s%s", *who ? ": " : "", who);
|
||||
break;
|
||||
case DMC_VOICE:
|
||||
status = g_strdup("In a call");
|
||||
break;
|
||||
case DMC_VOICEMAIL:
|
||||
status = g_strdup_printf("Taking a message%s%s",
|
||||
*who ? " from " : "", who);
|
||||
break;
|
||||
default:
|
||||
status = g_strdup(dmc_state_name(st));
|
||||
break;
|
||||
}
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(v->status), status);
|
||||
g_free(status);
|
||||
gboolean idle = st == DMC_IDLE;
|
||||
gboolean busy = v->play || v->recording;
|
||||
gtk_widget_set_sensitive(v->call_btn, idle);
|
||||
gtk_widget_set_sensitive(v->answer_btn, st == DMC_RINGING);
|
||||
gtk_widget_set_sensitive(v->message_btn, st == DMC_RINGING);
|
||||
gtk_widget_set_visible(v->pickup_btn, st == DMC_VOICEMAIL);
|
||||
gtk_widget_set_visible(v->listen_btn, st == DMC_VOICEMAIL);
|
||||
gtk_widget_set_sensitive(v->hangup_btn,
|
||||
st == DMC_VOICE || st == DMC_VOICEMAIL ||
|
||||
(st == DMC_DIALING || st == DMC_ANSWERING));
|
||||
gtk_widget_set_sensitive(v->mute_btn, st == DMC_VOICE);
|
||||
gtk_widget_set_sensitive(v->keypad, st == DMC_VOICE || idle ||
|
||||
st == DMC_CLOSED);
|
||||
gtk_button_set_label(GTK_BUTTON(v->record_btn),
|
||||
v->recording ? "Stop" : "Record");
|
||||
gtk_widget_set_sensitive(v->record_btn, !v->play &&
|
||||
audio_available() &&
|
||||
st != DMC_VOICE && st != DMC_VOICEMAIL);
|
||||
gtk_button_set_icon_name(GTK_BUTTON(v->greeting_play),
|
||||
v->play ? "media-playback-stop-symbolic" :
|
||||
"media-playback-start-symbolic");
|
||||
gtk_widget_set_sensitive(v->greeting_play,
|
||||
(v->greeting_n > 0 || v->play) &&
|
||||
!v->recording);
|
||||
gtk_widget_set_sensitive(v->greeting_clear,
|
||||
v->greeting_n > 0 && !busy);
|
||||
char *g = v->recording ? g_strdup("Recording: speak, then Stop") :
|
||||
v->greeting_n ?
|
||||
g_strdup_printf("Your recording (%d s)",
|
||||
(v->greeting_n + DMC_VOICE_RATE / 2) /
|
||||
DMC_VOICE_RATE) :
|
||||
g_strdup("None: callers hear a beep");
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(v->greeting_row), g);
|
||||
g_free(g);
|
||||
}
|
||||
|
||||
void voice_event(App *a, const dmc_event *ev)
|
||||
{
|
||||
if (ev->type == DMC_EV_MESSAGE) {
|
||||
if (ev->ok)
|
||||
save_message(a, ev->text);
|
||||
} else if (ev->type == DMC_EV_VOICE) {
|
||||
if (!strcmp(ev->text, "b"))
|
||||
window_toast(a, "Busy");
|
||||
else if (!strcmp(ev->text, "l") &&
|
||||
dmc_state(a->s) != DMC_VOICEMAIL)
|
||||
window_toast(a, "The other end hung up");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* the page
|
||||
*/
|
||||
|
||||
static GtkWidget *button(const char *label, GCallback fn, App *a)
|
||||
{
|
||||
GtkWidget *b = gtk_button_new_with_label(label);
|
||||
gtk_widget_set_valign(b, GTK_ALIGN_CENTER);
|
||||
g_signal_connect(b, "clicked", fn, a);
|
||||
return b;
|
||||
}
|
||||
|
||||
static GtkWidget *icon_button(const char *icon, const char *tip,
|
||||
GCallback fn, App *a)
|
||||
{
|
||||
GtkWidget *b = gtk_button_new_from_icon_name(icon);
|
||||
gtk_widget_set_tooltip_text(b, tip);
|
||||
gtk_widget_set_valign(b, GTK_ALIGN_CENTER);
|
||||
gtk_widget_add_css_class(b, "flat");
|
||||
g_signal_connect(b, "clicked", fn, a);
|
||||
return b;
|
||||
}
|
||||
|
||||
GtkWidget *voice_page_new(App *a)
|
||||
{
|
||||
Voice *v = g_new0(Voice, 1);
|
||||
a->voice = v;
|
||||
v->message_rows = g_ptr_array_new();
|
||||
v->last_state = DMC_CLOSED;
|
||||
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 call */
|
||||
GtkWidget *cg = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(cg), "Voice Call");
|
||||
adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(cg),
|
||||
"Calls through the modem's voice mode, with the computer's "
|
||||
"microphone and speakers");
|
||||
v->status = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->status), "Phone");
|
||||
v->hangup_btn = button("Hang Up", G_CALLBACK(hangup), a);
|
||||
gtk_widget_add_css_class(v->hangup_btn, "destructive-action");
|
||||
v->pickup_btn = button("Pick Up", G_CALLBACK(pickup), a);
|
||||
gtk_widget_set_tooltip_text(v->pickup_btn,
|
||||
"Talk to the caller yourself");
|
||||
v->listen_btn = gtk_toggle_button_new_with_label("Listen");
|
||||
gtk_widget_set_valign(v->listen_btn, GTK_ALIGN_CENTER);
|
||||
gtk_widget_set_tooltip_text(v->listen_btn,
|
||||
"Hear the caller leave the message");
|
||||
g_signal_connect(v->listen_btn, "toggled", G_CALLBACK(listen_toggled), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->listen_btn);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->pickup_btn);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->hangup_btn);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), v->status);
|
||||
|
||||
v->number = adw_entry_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->number),
|
||||
"Number or SIP address (sip:user@host)");
|
||||
v->call_btn = button("Call", G_CALLBACK(call), a);
|
||||
gtk_widget_add_css_class(v->call_btn, "suggested-action");
|
||||
adw_entry_row_add_suffix(ADW_ENTRY_ROW(v->number), v->call_btn);
|
||||
g_signal_connect(v->number, "entry-activated", G_CALLBACK(call), a);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), v->number);
|
||||
|
||||
GtkWidget *ring = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(ring), "A call ringing");
|
||||
v->answer_btn = button("Answer", G_CALLBACK(answer), a);
|
||||
v->message_btn = button("Take a Message", G_CALLBACK(take_message), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(ring), v->message_btn);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(ring), v->answer_btn);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), ring);
|
||||
gtk_box_append(GTK_BOX(box), cg);
|
||||
|
||||
/* the keypad: digits for the number, DTMF in a call */
|
||||
GtkWidget *pad = gtk_grid_new();
|
||||
gtk_grid_set_row_spacing(GTK_GRID(pad), 6);
|
||||
gtk_grid_set_column_spacing(GTK_GRID(pad), 6);
|
||||
gtk_grid_set_row_homogeneous(GTK_GRID(pad), TRUE);
|
||||
gtk_grid_set_column_homogeneous(GTK_GRID(pad), TRUE);
|
||||
static const char *const keys = "123456789*0#";
|
||||
for (int i = 0; i < 12; i++) {
|
||||
char k[2] = { keys[i], 0 };
|
||||
GtkWidget *b = gtk_button_new_with_label(k);
|
||||
gtk_widget_add_css_class(b, "title-3");
|
||||
gtk_widget_set_size_request(b, 72, 44);
|
||||
g_signal_connect(b, "clicked", G_CALLBACK(key), a);
|
||||
gtk_grid_attach(GTK_GRID(pad), b, i % 3, i / 3, 1, 1);
|
||||
}
|
||||
v->mute_btn = gtk_toggle_button_new_with_label("Mute");
|
||||
g_signal_connect(v->mute_btn, "toggled", G_CALLBACK(mute), a);
|
||||
gtk_grid_attach(GTK_GRID(pad), v->mute_btn, 0, 4, 3, 1);
|
||||
gtk_widget_set_halign(pad, GTK_ALIGN_CENTER);
|
||||
v->keypad = pad;
|
||||
gtk_box_append(GTK_BOX(box), pad);
|
||||
|
||||
/* the answering machine */
|
||||
GtkWidget *mg = adw_preferences_group_new();
|
||||
adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(mg),
|
||||
"Answering Machine");
|
||||
adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(mg),
|
||||
"Messages are kept on this computer only");
|
||||
v->vm_switch = adw_switch_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->vm_switch),
|
||||
"Take messages");
|
||||
adw_action_row_set_subtitle(ADW_ACTION_ROW(v->vm_switch),
|
||||
"Answer calls nobody picks up, play the greeting and record");
|
||||
adw_switch_row_set_active(ADW_SWITCH_ROW(v->vm_switch), a->cfg.voicemail);
|
||||
g_signal_connect(v->vm_switch, "notify::active",
|
||||
G_CALLBACK(voicemail_switched), a);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->vm_switch);
|
||||
v->vm_rings = adw_spin_row_new_with_range(1, 15, 1);
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->vm_rings),
|
||||
"Rings before it answers");
|
||||
adw_spin_row_set_value(ADW_SPIN_ROW(v->vm_rings), a->cfg.vm_rings);
|
||||
g_signal_connect(v->vm_rings, "notify::value",
|
||||
G_CALLBACK(rings_changed), a);
|
||||
g_object_bind_property(v->vm_switch, "active", v->vm_rings,
|
||||
"sensitive", G_BINDING_SYNC_CREATE);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->vm_rings);
|
||||
v->greeting_row = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->greeting_row),
|
||||
"Greeting");
|
||||
v->greeting_play = icon_button("media-playback-start-symbolic", "Play",
|
||||
G_CALLBACK(play_greeting), a);
|
||||
v->record_btn = button("Record", G_CALLBACK(record_greeting), a);
|
||||
GtkWidget *choose = icon_button("document-open-symbolic",
|
||||
"Use a sound file",
|
||||
G_CALLBACK(choose_greeting), a);
|
||||
v->greeting_clear = icon_button("user-trash-symbolic",
|
||||
"No greeting: the beep alone",
|
||||
G_CALLBACK(clear_greeting), a);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->greeting_play);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->record_btn);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), choose);
|
||||
adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->greeting_clear);
|
||||
adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->greeting_row);
|
||||
gtk_box_append(GTK_BOX(box), mg);
|
||||
|
||||
/* the messages */
|
||||
v->messages = ADW_PREFERENCES_GROUP(adw_preferences_group_new());
|
||||
adw_preferences_group_set_title(v->messages, "Messages");
|
||||
v->messages_empty = adw_action_row_new();
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->messages_empty),
|
||||
"No messages");
|
||||
gtk_widget_add_css_class(v->messages_empty, "dim-label");
|
||||
adw_preferences_group_add(v->messages, v->messages_empty);
|
||||
gtk_box_append(GTK_BOX(box), GTK_WIDGET(v->messages));
|
||||
|
||||
char *d = data_dir();
|
||||
g_mkdir_with_parents(d, 0700);
|
||||
g_free(d);
|
||||
load_greeting(a);
|
||||
refresh_messages(a);
|
||||
voice_configure(a);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* window.c - the main window: the Modem, Phone, Terminal, Remote,
|
||||
* Settings, Call and Log pages, the same pages as the Windows and macOS apps
|
||||
* (docs/design.md)
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
#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";
|
||||
case DMC_VOICE:
|
||||
return "audio-input-microphone-symbolic";
|
||||
case DMC_VOICEMAIL:
|
||||
return "media-record-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");
|
||||
/* (what runs the line: the modem built in, or dmodemd) */
|
||||
gboolean builtin = FALSE;
|
||||
#ifdef DMODEM_GUI_EMBED
|
||||
builtin = a->cfg.builtin && g_strcmp0(a->cfg.line, "device");
|
||||
#endif
|
||||
adw_preferences_row_set_title(ADW_PREFERENCES_ROW(a->run_row),
|
||||
builtin ? "Built-in modem" : "dmodemd");
|
||||
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);
|
||||
pathview_update(a);
|
||||
voice_state(a);
|
||||
}
|
||||
|
||||
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;
|
||||
case DMC_EV_VOICE:
|
||||
case DMC_EV_MESSAGE:
|
||||
voice_event(a, ev);
|
||||
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 or SIP address 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 or SIP address (sip:user@host)");
|
||||
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 typed(const char *data, int n, void *ctx)
|
||||
{
|
||||
modem_type(ctx, data, n);
|
||||
}
|
||||
|
||||
static void typed_command(App *a, const char *cmd)
|
||||
{
|
||||
if (dmc_state(a->s) != DMC_IDLE)
|
||||
return;
|
||||
modem_type(a, cmd, strlen(cmd));
|
||||
termview_focus(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;
|
||||
termview_reset(a->term);
|
||||
}
|
||||
|
||||
static void term_type_changed(GObject *o, GParamSpec *p, gpointer data)
|
||||
{
|
||||
App *a = data;
|
||||
(void)o;
|
||||
(void)p;
|
||||
termview_set_profile(a->term, term_types_chosen(a->term_type));
|
||||
g_free(a->cfg.term_type);
|
||||
a->cfg.term_type = g_strdup(term_types_chosen(a->term_type));
|
||||
config_save(&a->cfg);
|
||||
}
|
||||
|
||||
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);
|
||||
/* the kind of terminal (a BBS by modem may want ANSI-BBS, PETSCII,
|
||||
Viewdata ...) */
|
||||
a->term_type = term_types_new(a->cfg.term_type);
|
||||
g_signal_connect(a->term_type, "notify::selected",
|
||||
G_CALLBACK(term_type_changed), a);
|
||||
gtk_box_append(GTK_BOX(bar), a->term_type);
|
||||
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 = termview_new(typed, a);
|
||||
/* (the modem takes S5, a backspace, not DEL) */
|
||||
termview_set_backspace(a->term, 0x08);
|
||||
termview_set_profile(a->term, a->cfg.term_type);
|
||||
gtk_box_append(GTK_BOX(box), a->term);
|
||||
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_AGPL_3_0_ONLY);
|
||||
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, voice_page_new(a),
|
||||
"phone", "Phone",
|
||||
"audio-input-microphone-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, remote_page_new(a),
|
||||
"remote", "Remote",
|
||||
"network-server-symbolic");
|
||||
adw_view_stack_add_titled_with_icon(a->stack, settings_page_new(a),
|
||||
"settings", "Settings",
|
||||
"preferences-system-symbolic");
|
||||
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);
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 7.1 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 608 B |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 103 KiB |
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* Bridging.h - libdmodemctl, libdmodemssh and (when the build has it) the
|
||||
* built-in modem's libdmodem_embed, for Swift
|
||||
*/
|
||||
#include "dmodemctl.h"
|
||||
#include "dmodemssh.h"
|
||||
// (the header path is set when the build has the built-in modem:
|
||||
// ../build/macos-embed.xcconfig)
|
||||
#if __has_include("dmodem_embed.h")
|
||||
#include "dmodem_embed.h"
|
||||
#endif
|
||||
@@ -1,318 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// ContentView.swift - the window: its pages (Modem, Phone, Terminal,
|
||||
// Remote, Settings, Call Stats, Log) in a sidebar
|
||||
|
||||
import SwiftUI
|
||||
|
||||
enum Page: String, CaseIterable, Identifiable {
|
||||
case modem = "Modem", phone = "Phone", terminal = "Terminal", remote = "Remote"
|
||||
case settings = "Settings"
|
||||
case stats = "Call Stats", log = "Log"
|
||||
var id: String { rawValue }
|
||||
var icon: String {
|
||||
switch self {
|
||||
case .modem: return "phone.connection"
|
||||
case .phone: return "phone"
|
||||
case .terminal: return "terminal"
|
||||
case .remote: return "network"
|
||||
case .settings: return "slider.horizontal.3"
|
||||
case .stats: return "chart.bar"
|
||||
case .log: return "doc.plaintext"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
@EnvironmentObject var remote: RemoteSession
|
||||
@State private var page: Page? = Page(rawValue: ProcessInfo.processInfo.environment["DMODEM_GUI_PAGE"] ?? "") ?? .modem
|
||||
|
||||
var body: some View {
|
||||
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 .phone: PhonePage()
|
||||
case .terminal: TerminalPane()
|
||||
case .remote: RemotePage(session: remote)
|
||||
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"
|
||||
case Int(DMC_VOICE): return "phone.fill"
|
||||
case Int(DMC_VOICEMAIL): return "recordingtape"
|
||||
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, prompt: Text("number or sip:user@host"))
|
||||
.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 {
|
||||
// (how a call is made, step by step: as set up when idle, as it is in a call)
|
||||
Section {
|
||||
PathView()
|
||||
}
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// 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()
|
||||
@StateObject private var remote = RemoteSession()
|
||||
|
||||
var body: some Scene {
|
||||
Window("D-Modem", id: "main") {
|
||||
ContentView()
|
||||
.environmentObject(modem)
|
||||
.environmentObject(modem.voice)
|
||||
.environmentObject(remote)
|
||||
.frame(minWidth: 760, minHeight: 520)
|
||||
.onAppear {
|
||||
delegate.modem = modem
|
||||
delegate.remote = remote
|
||||
}
|
||||
}
|
||||
.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?
|
||||
weak var remote: RemoteSession?
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
remote?.stop()
|
||||
modem?.stop()
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// 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 = ""
|
||||
/// SIP with no account (dmodemd's SIP_LOGIN=anonymous): nothing registered, SIP addresses
|
||||
/// (sip:user@host, user@host) dialled as they are, from "Anonymous"
|
||||
var sipAnonymous = false
|
||||
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
|
||||
/// the modem built into the app (when the build has it), not dmodemd
|
||||
var builtin = true
|
||||
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.sipAnonymous = d.bool(forKey: "sipAnonymous")
|
||||
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.builtin = d.object(forKey: "builtin") as? Bool ?? true
|
||||
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(sipAnonymous, forKey: "sipAnonymous")
|
||||
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(builtin, forKey: "builtin")
|
||||
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 sipAnonymous { return "SIP: anonymous, no account" + (listen ? ", taking calls" : "") }
|
||||
if sipUser.isEmpty || sipServer.isEmpty { return "SIP account not set up" }
|
||||
return "SIP: \(sipUser)@\(sipServer)" + (listen ? ", taking calls" : "")
|
||||
}
|
||||
}
|
||||
|
||||
var isSetUp: Bool {
|
||||
line != .sip || sipAnonymous || (!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)
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// 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") {
|
||||
Toggle("No account (anonymous)", isOn: $c.sipAnonymous)
|
||||
if !c.sipAnonymous {
|
||||
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)
|
||||
Text(c.sipAnonymous
|
||||
? "Calls go straight to a SIP address (sip:user@host, or user@host), from “Anonymous”: nothing is registered, and numbers can’t be dialled."
|
||||
: "A SIP address (sip:user@host) is dialled as it is too; the password only goes to the account’s own server.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
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 {
|
||||
if Modem.hasBuiltin {
|
||||
Toggle("Built-in modem", isOn: $c.builtin)
|
||||
Text("Off: the app starts dmodemd.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
if !Modem.hasBuiltin || !c.builtin {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,848 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// When the build has the built-in modem (DMODEM_GUI_EMBED), the SIP and
|
||||
// USB lines start it in a thread of the app (libdmodem_embed), not
|
||||
// dmodemd. Its DTE is a socket, so there is no pty.
|
||||
|
||||
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) } ?? ""
|
||||
}
|
||||
|
||||
#if DMODEM_GUI_EMBED
|
||||
/// The context of one start of the built-in modem, for the callbacks
|
||||
/// of its thread. Each start has its own, so that the news of an
|
||||
/// earlier start is ignored.
|
||||
private final class EmbedBox {
|
||||
weak var modem: Modem?
|
||||
let gen: Int
|
||||
init(_ modem: Modem, _ gen: Int) {
|
||||
self.modem = modem
|
||||
self.gen = gen
|
||||
}
|
||||
}
|
||||
|
||||
/// A log line of the built-in modem (its thread): to the main thread.
|
||||
private let embedLog: dmodem_embed_log_fn = { ctx, line in
|
||||
guard let ctx, let line else { return }
|
||||
let box = Unmanaged<EmbedBox>.fromOpaque(ctx).takeUnretainedValue()
|
||||
let s = String(cString: line)
|
||||
DispatchQueue.main.async { box.modem?.embedLine(s, gen: box.gen) }
|
||||
}
|
||||
|
||||
/// The end of the built-in modem's thread: to the main thread. This is
|
||||
/// the last call with the context, so it releases the context.
|
||||
private let embedExit: dmodem_embed_exit_fn = { ctx, status in
|
||||
guard let ctx else { return }
|
||||
let box = Unmanaged<EmbedBox>.fromOpaque(ctx).takeRetainedValue()
|
||||
DispatchQueue.main.async { box.modem?.embedEnded(Int(status), gen: box.gen) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// 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
|
||||
/// the Terminal page's kind of terminal (a dmc_vt profile's id)
|
||||
@Published var terminalType = UserDefaults.standard.string(forKey: "terminalType") ?? "xterm" {
|
||||
didSet {
|
||||
dmc_vt_set_profile(vt, terminalType)
|
||||
UserDefaults.standard.set(terminalType, forKey: "terminalType")
|
||||
screenVersion += 1
|
||||
}
|
||||
}
|
||||
|
||||
let session: OpaquePointer
|
||||
let vt: OpaquePointer
|
||||
/// voice calls and the answering machine (Voice.swift)
|
||||
let voice = Voice()
|
||||
|
||||
private var process: Process?
|
||||
/// the built-in modem (libdmodem_embed), when it was started once
|
||||
private var embed: OpaquePointer?
|
||||
/// the built-in modem's thread runs
|
||||
private var embedRunning = false
|
||||
/// bumped at each start and stop of the built-in modem
|
||||
private var embedGen = 0
|
||||
|
||||
/// The build has the built-in modem.
|
||||
static var hasBuiltin: Bool {
|
||||
#if DMODEM_GUI_EMBED
|
||||
return true
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
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)
|
||||
// (the modem takes S5, a backspace, not DEL)
|
||||
dmc_vt_set_backspace(vt, 0x08)
|
||||
dmc_vt_set_theme(vt, 0xe8f0ff, 0x0a0f1c, 0xe8f0ff, nil)
|
||||
dmc_vt_set_profile(vt, terminalType)
|
||||
voice.modem = self
|
||||
voice.configure()
|
||||
let t = Timer(timeInterval: 0.05, repeats: true) { [weak self] _ in
|
||||
self?.pump()
|
||||
}
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
timer = t
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
#if DMODEM_GUI_EMBED
|
||||
if let e = embed { dmodem_embed_free(e) }
|
||||
#endif
|
||||
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,
|
||||
DMC_VOICE, DMC_VOICEMAIL]
|
||||
.map { Int($0) }.contains(state)
|
||||
}
|
||||
|
||||
var callerNumber: String { cstr(dmc_caller_number(session)) }
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// done gets the response of the session's command tag
|
||||
private func expect(_ tag: Int32, _ done: @escaping (Response) -> Void) {
|
||||
guard tag > 0 else { return }
|
||||
waiting[tag] = done
|
||||
pump()
|
||||
}
|
||||
|
||||
private func voiceResult(_ r: Response) {
|
||||
if !r.ok {
|
||||
say(r.result == "ERROR" ? "The modem has no voice mode (D-Modem 1.1 or later has)"
|
||||
: r.result.capitalized)
|
||||
}
|
||||
}
|
||||
|
||||
func voiceDial(_ number: String) {
|
||||
let n = number.trimmingCharacters(in: .whitespaces)
|
||||
guard !n.isEmpty else { return say("Enter a number to call") }
|
||||
voice.stopSound()
|
||||
expect(dmc_voice_dial(session, n)) { [weak self] r in self?.voiceResult(r) }
|
||||
}
|
||||
|
||||
func voiceAnswer() {
|
||||
expect(dmc_voice_answer(session)) { [weak self] r in self?.voiceResult(r) }
|
||||
}
|
||||
|
||||
func voicemailAnswer() {
|
||||
expect(dmc_voicemail_answer(session)) { [weak self] r in self?.voiceResult(r) }
|
||||
}
|
||||
|
||||
func pickUp() {
|
||||
dmc_voice_pickup(session)
|
||||
pump()
|
||||
}
|
||||
|
||||
func dtmf(_ key: String) {
|
||||
guard let c = key.utf8.first else { return }
|
||||
dmc_voice_dtmf(session, CChar(bitPattern: c))
|
||||
}
|
||||
|
||||
/// 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 clearScreen() {
|
||||
dmc_vt_reset(vt)
|
||||
screenVersion += 1
|
||||
}
|
||||
|
||||
// MARK: - the bytes
|
||||
|
||||
private static func now() -> Int64 {
|
||||
Int64(DispatchTime.now().uptimeNanoseconds / 1_000_000)
|
||||
}
|
||||
|
||||
func pump() {
|
||||
voice.beforePoll()
|
||||
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)
|
||||
}
|
||||
TerminalTypes.afterFeed(vt)
|
||||
}
|
||||
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),
|
||||
text: cstr(ev.text), ok: ev.ok != 0)
|
||||
}
|
||||
}
|
||||
voice.afterPoll()
|
||||
}
|
||||
|
||||
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, text: String, ok: Bool) {
|
||||
switch type {
|
||||
case Int(DMC_EV_STATE):
|
||||
let was = lastState
|
||||
lastState = st
|
||||
state = st
|
||||
voice.sound(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()
|
||||
case Int(DMC_EV_VOICE), Int(DMC_EV_MESSAGE):
|
||||
voice.event(type, text: text, ok: ok)
|
||||
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
|
||||
|
||||
/// Opens the modem's device (a pty or a serial port) and attaches it.
|
||||
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)
|
||||
}
|
||||
attach(f, name: path)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Uses an open descriptor (a pty, a serial port, or the built-in
|
||||
/// modem's socket) as the modem's DTE, and opens the session on it.
|
||||
private func attach(_ f: Int32, name: String) {
|
||||
fd = f
|
||||
device = name
|
||||
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()
|
||||
}
|
||||
|
||||
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
|
||||
voice.sound(state)
|
||||
clearSettings()
|
||||
running = process != nil || embedRunning
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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
|
||||
}
|
||||
#if DMODEM_GUI_EMBED
|
||||
if c.builtin { return startEmbedded(c) }
|
||||
#endif
|
||||
guard let exe = findDmodemd() else {
|
||||
return say("dmodemd was not found: install D-Modem, or set its path in the line settings")
|
||||
}
|
||||
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 {
|
||||
// (no account: dmodemd's anonymous user agent)
|
||||
env["SIP_LOGIN"] = c.sipAnonymous ? "anonymous" : "\(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 || embedRunning) {
|
||||
// hang up first, so the call ends cleanly
|
||||
dmc_hangup(session)
|
||||
pump()
|
||||
}
|
||||
closeDevice()
|
||||
#if DMODEM_GUI_EMBED
|
||||
stopEmbedded()
|
||||
#endif
|
||||
process?.terminate()
|
||||
running = process != nil
|
||||
}
|
||||
|
||||
#if DMODEM_GUI_EMBED
|
||||
// MARK: - the built-in modem
|
||||
|
||||
/// Starts the built-in modem on the line settings' line, in a thread
|
||||
/// of the app, and attaches its DTE socket.
|
||||
private func startEmbedded(_ c: LineConfig) {
|
||||
var keep: [UnsafeMutablePointer<CChar>] = []
|
||||
defer { keep.forEach { free($0) } }
|
||||
/// A C string that stays until the end of this function.
|
||||
func cs(_ s: String) -> UnsafePointer<CChar>? {
|
||||
guard let p = strdup(s) else { return nil }
|
||||
keep.append(p)
|
||||
return UnsafePointer(p)
|
||||
}
|
||||
|
||||
var e = dmodem_embed_config()
|
||||
dmodem_embed_config_init(&e)
|
||||
if !c.country.isEmpty { e.country = cs(c.country) }
|
||||
e.log_level = Int32(c.debug)
|
||||
if c.line == .usb {
|
||||
e.line = Int32(DMODEM_EMBED_USB)
|
||||
e.usb = cs(c.usb)
|
||||
} else {
|
||||
e.line = Int32(DMODEM_EMBED_SIP)
|
||||
if !c.sipAnonymous {
|
||||
e.sip_user = cs(c.sipUser)
|
||||
e.sip_password = cs(c.sipPassword)
|
||||
e.sip_domain = cs(c.sipServer)
|
||||
}
|
||||
e.sip_listen = c.listen ? 1 : 0
|
||||
e.sip_t38 = c.t38 ? 1 : 0
|
||||
e.sip_v152 = c.v152 ? 1 : 0
|
||||
e.sip_v150 = c.v150 ? 1 : 0
|
||||
e.sip_srtp = c.srtp == "no" ? 0 : c.srtp == "require" ? 2 : 1
|
||||
}
|
||||
if dmodem_embed_lines() & (1 << e.line) == 0 {
|
||||
return say("The built-in modem has no such line in this build: turn off Built-in modem in the line settings")
|
||||
}
|
||||
// the data file of the line's measurements, where the user may write it
|
||||
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("D-Modem")
|
||||
try? FileManager.default.createDirectory(at: support, withIntermediateDirectories: true)
|
||||
e.data_file = cs(support.appendingPathComponent("dmodem0.data").path)
|
||||
|
||||
if embed == nil { embed = dmodem_embed_new() }
|
||||
guard let em = embed else { return say("Can't start the built-in modem") }
|
||||
embedGen += 1
|
||||
let ctx = Unmanaged.passRetained(EmbedBox(self, embedGen)).toOpaque()
|
||||
dmodem_embed_on_log(em, embedLog, ctx)
|
||||
dmodem_embed_on_exit(em, embedExit, ctx)
|
||||
let f = dmodem_embed_start(em, &e)
|
||||
if f < 0 {
|
||||
// (no thread: the context is not used)
|
||||
Unmanaged<EmbedBox>.fromOpaque(ctx).release()
|
||||
let m = "Can't start the built-in modem: \(cstr(dmodem_embed_error(em)))"
|
||||
addLog(m)
|
||||
return say(m)
|
||||
}
|
||||
addLog("The built-in modem (D-Modem \(cstr(dmodem_embed_version()))) started.")
|
||||
embedRunning = true
|
||||
running = true
|
||||
_ = fcntl(f, F_SETFL, fcntl(f, F_GETFL) | O_NONBLOCK)
|
||||
attach(f, name: "Built-in modem")
|
||||
}
|
||||
|
||||
/// Stops the built-in modem's thread. Its news after now is ignored.
|
||||
private func stopEmbedded() {
|
||||
guard let em = embed, embedRunning else { return }
|
||||
embedGen += 1
|
||||
dmodem_embed_stop(em)
|
||||
embedRunning = false
|
||||
addLog("The built-in modem stopped.")
|
||||
}
|
||||
|
||||
/// A log line of the built-in modem, on the main thread.
|
||||
fileprivate func embedLine(_ line: String, gen: Int) {
|
||||
guard gen == embedGen else { return }
|
||||
addLog(line)
|
||||
}
|
||||
|
||||
/// The built-in modem's thread ended by itself (an error, or the
|
||||
/// line closed), on the main thread.
|
||||
fileprivate func embedEnded(_ status: Int, gen: Int) {
|
||||
guard gen == embedGen, embedRunning else { return }
|
||||
embedRunning = false
|
||||
let m = status == 0 ? "The built-in modem stopped."
|
||||
: "The built-in modem stopped (error)."
|
||||
addLog(m)
|
||||
closeDevice()
|
||||
running = process != nil
|
||||
if status != 0 { say(m) }
|
||||
}
|
||||
#endif
|
||||
|
||||
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 : ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// PathView.swift - the connection path at the top of the Settings page, as
|
||||
// PCOMM's "Connection Overview" draws its link: each step's role above its
|
||||
// icon, what it is below, one line joining them (libdmodemctl's dmc_path).
|
||||
// Idle, how the line settings set it up; starting, calling and online, as
|
||||
// it is now.
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// a step of the path, as dmc_path gives it
|
||||
private struct PathStep: Identifiable {
|
||||
let id: Int
|
||||
let kind: Int32
|
||||
let state: Int32
|
||||
let role, title, detail: String
|
||||
}
|
||||
|
||||
struct PathView: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
let (steps, links, headline, setup) = Self.make(modem)
|
||||
VStack(spacing: 8) {
|
||||
HStack(alignment: .top, spacing: 0) {
|
||||
ForEach(steps) { s in
|
||||
StepView(
|
||||
step: s,
|
||||
left: s.id > 0 ? links[s.id - 1] : nil,
|
||||
right: s.id < steps.count - 1 ? links[s.id] : nil
|
||||
)
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
Text(headline)
|
||||
.font(.callout)
|
||||
.foregroundStyle(setup ? Color.red : Color.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel(headline + ". " + steps.map { "\($0.role): \($0.title), \($0.detail)" }.joined(separator: ". "))
|
||||
}
|
||||
|
||||
/// the steps, the links between them, the headline, and whether a step is still to set
|
||||
private static func make(_ modem: Modem) -> ([PathStep], [Int32], String, Bool) {
|
||||
let p = dmc_path_new()
|
||||
defer { dmc_path_free(p) }
|
||||
let c = modem.config
|
||||
let line: Int32
|
||||
let whereTo: String
|
||||
switch c.line {
|
||||
case .usb: line = Int32(DMC_LINE_USB); whereTo = c.usb
|
||||
case .device: line = Int32(DMC_LINE_DEVICE); whereTo = c.device
|
||||
case .sip: line = Int32(DMC_LINE_SIP); whereTo = ""
|
||||
}
|
||||
dmc_path_set_line(p, line, whereTo, c.sipAnonymous ? 1 : 0, c.sipUser, c.sipServer, c.listen ? 1 : 0)
|
||||
let st = Int32(modem.state)
|
||||
let online = st == Int32(DMC_ONLINE) || st == Int32(DMC_ONLINE_COMMAND)
|
||||
dmc_path_set_live(p, modem.running ? 1 : 0, st, online ? modem.detail : "")
|
||||
let n = Int(dmc_path_steps(p))
|
||||
var steps: [PathStep] = []
|
||||
var links: [Int32] = []
|
||||
for i in 0..<n {
|
||||
let k = Int32(i)
|
||||
steps.append(PathStep(
|
||||
id: i, kind: dmc_path_kind(p, k), state: dmc_path_state(p, k),
|
||||
role: cstr(dmc_path_role(p, k)), title: cstr(dmc_path_title(p, k)),
|
||||
detail: cstr(dmc_path_detail(p, k))
|
||||
))
|
||||
if i < n - 1 { links.append(dmc_path_link(p, k)) }
|
||||
}
|
||||
return (steps, links, cstr(dmc_path_headline(p)), dmc_path_needs_setup(p) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// a step: its role, its icon on the line (its links to either side), its name and what it is
|
||||
private struct StepView: View {
|
||||
let step: PathStep
|
||||
let left: Int32?
|
||||
let right: Int32?
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 4) {
|
||||
Text(step.role).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
ZStack {
|
||||
// (the line through the icons' middles: half to the step before, half to the next)
|
||||
GeometryReader { g in
|
||||
let y = g.size.height / 2
|
||||
if let left {
|
||||
Path { p in p.move(to: CGPoint(x: 0, y: y)); p.addLine(to: CGPoint(x: g.size.width / 2, y: y)) }
|
||||
.stroke(Self.color(left), style: Self.stroke(left))
|
||||
}
|
||||
if let right {
|
||||
Path { p in p.move(to: CGPoint(x: g.size.width / 2, y: y)); p.addLine(to: CGPoint(x: g.size.width, y: y)) }
|
||||
.stroke(Self.color(right), style: Self.stroke(right))
|
||||
}
|
||||
}
|
||||
Circle()
|
||||
.fill(step.state == Int32(DMC_STEP_ACTIVE) ? Self.color(step.state).opacity(0.2) : Color(nsColor: .controlBackgroundColor))
|
||||
.overlay(Circle().stroke(Self.color(step.state), lineWidth: 2))
|
||||
.frame(width: 40, height: 40)
|
||||
Image(systemName: Self.symbol(step.kind))
|
||||
.font(.system(size: 16, weight: .medium))
|
||||
.foregroundStyle(Self.color(step.state))
|
||||
}
|
||||
.frame(height: 44)
|
||||
Text(step.title).font(.headline).multilineTextAlignment(.center).lineLimit(1)
|
||||
Text(step.detail)
|
||||
.font(.caption)
|
||||
.multilineTextAlignment(.center)
|
||||
.lineLimit(3)
|
||||
.foregroundStyle(step.state == Int32(DMC_STEP_SETUP) ? Color.red : Color.secondary)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
/// a state's colour: ready the accent, to set red, dialling and online green, off faint
|
||||
static func color(_ s: Int32) -> Color {
|
||||
switch s {
|
||||
case Int32(DMC_STEP_SETUP): return .red
|
||||
case Int32(DMC_STEP_WORKING), Int32(DMC_STEP_ACTIVE): return .green
|
||||
case Int32(DMC_STEP_OFF): return Color(nsColor: .tertiaryLabelColor)
|
||||
default: return .accentColor
|
||||
}
|
||||
}
|
||||
|
||||
/// a link's line: dashed where a step is still to set, or off
|
||||
static func stroke(_ s: Int32) -> StrokeStyle {
|
||||
let dashed = s == Int32(DMC_STEP_SETUP) || s == Int32(DMC_STEP_OFF)
|
||||
return StrokeStyle(lineWidth: 2, dash: dashed ? [6, 4] : [])
|
||||
}
|
||||
|
||||
/// a step's SF Symbol
|
||||
static func symbol(_ k: Int32) -> String {
|
||||
switch k {
|
||||
case Int32(DMC_KIND_TERMINAL): return "terminal"
|
||||
case Int32(DMC_KIND_SOFTMODEM), Int32(DMC_KIND_MODEM): return "server.rack"
|
||||
case Int32(DMC_KIND_SIP): return "phone.arrow.up.right"
|
||||
case Int32(DMC_KIND_USB), Int32(DMC_KIND_SERIAL): return "cable.connector"
|
||||
case Int32(DMC_KIND_CODEC): return "waveform"
|
||||
case Int32(DMC_KIND_NETWORK): return "network"
|
||||
case Int32(DMC_KIND_SIP_ADDRESS): return "at"
|
||||
default: return "phone"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,881 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// RemoteView.swift - the Remote page: a login to a server by SSH, Telnet
|
||||
// or rlogin, in a terminal of its own (TerminalView.swift's view)
|
||||
//
|
||||
// Telnet and rlogin are a socket made here and libdmodemctl's dmc_net
|
||||
// for the protocol. SSH is libdmodemssh (the apps' own client, on
|
||||
// libssh) through SSHConnection.swift: it reads OpenSSH's config,
|
||||
// known_hosts, keys and agent, so that they are the user's. Its login
|
||||
// may instead be by the agent alone (SSH_AUTH_SOCK's, or a socket given)
|
||||
// or by a key file: OpenSSH's, PEM or PuTTY's .ppk, which can also be
|
||||
// imported into ~/.ssh in OpenSSH's form.
|
||||
|
||||
import AppKit
|
||||
import Darwin
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
final class RemoteSession: ObservableObject, TerminalHost {
|
||||
enum Proto: String, CaseIterable, Identifiable {
|
||||
case ssh = "SSH", telnet = "Telnet", rlogin = "rlogin"
|
||||
var id: String { rawValue }
|
||||
var net: Int32 {
|
||||
switch self {
|
||||
case .ssh: return Int32(DMC_NET_SSH)
|
||||
case .telnet: return Int32(DMC_NET_TELNET)
|
||||
case .rlogin: return Int32(DMC_NET_RLOGIN)
|
||||
}
|
||||
}
|
||||
var defaultPort: Int { Int(dmc_net_default_port(net)) }
|
||||
}
|
||||
|
||||
@Published var proto: Proto
|
||||
@Published var host: String
|
||||
/// empty: the protocol's
|
||||
@Published var port: String
|
||||
@Published var user: String
|
||||
@Published private(set) var running = false
|
||||
@Published private(set) var status = "Not connected"
|
||||
/// bumped when the screen changed, to draw it again
|
||||
@Published private(set) var screenVersion = 0
|
||||
/// what the SSH login asks the user, if anything
|
||||
@Published var question: Question?
|
||||
|
||||
/// an SSH login's question
|
||||
enum Question {
|
||||
/// a server not known yet: its key type and fingerprint
|
||||
case newHost(type: String, fingerprint: String)
|
||||
/// a password; why the last was refused
|
||||
case password(why: String)
|
||||
/// a key file's passphrase (for the login, or for its import from
|
||||
/// the .ppk at importing); why the last didn't open it
|
||||
case passphrase(name: String, why: String, importing: String?)
|
||||
/// the server's questions (keyboard-interactive): each with
|
||||
/// whether its answer may be shown
|
||||
case prompts(title: String, instruction: String, questions: [(String, Bool)])
|
||||
}
|
||||
|
||||
/// how SSH logs in
|
||||
enum LoginWay: String, CaseIterable, Identifiable {
|
||||
case auto, agent, key
|
||||
var id: String { rawValue }
|
||||
var label: String {
|
||||
switch self {
|
||||
case .auto: return "My keys and agent, as ssh does"
|
||||
case .agent: return "The agent's keys only"
|
||||
case .key: return "A key file"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Published var loginWay = LoginWay(rawValue: UserDefaults.standard.string(forKey: "remoteLogin") ?? "") ?? .auto {
|
||||
didSet { defaults.set(loginWay.rawValue, forKey: "remoteLogin") }
|
||||
}
|
||||
/// the key file (OpenSSH's, PEM or PuTTY's .ppk)
|
||||
@Published var keyPath = UserDefaults.standard.string(forKey: "remoteKey") ?? "" {
|
||||
didSet { defaults.set(keyPath, forKey: "remoteKey") }
|
||||
}
|
||||
/// the agent's socket (empty: SSH_AUTH_SOCK's)
|
||||
@Published var agentSocket = UserDefaults.standard.string(forKey: "remoteAgent") ?? "" {
|
||||
didSet { defaults.set(agentSocket, forKey: "remoteAgent") }
|
||||
}
|
||||
/// what an import last said
|
||||
@Published var importNote = ""
|
||||
|
||||
/// whether the agent answers, in words
|
||||
var agentState: String {
|
||||
if dmc_ssh_agent_reachable(agentSocket) != 0 { return "An agent answers there" }
|
||||
if !agentSocket.isEmpty { return "No agent answers there" }
|
||||
return ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] == nil ?
|
||||
"SSH_AUTH_SOCK is not set: give the agent's socket" : "No agent answers at SSH_AUTH_SOCK"
|
||||
}
|
||||
|
||||
/// the kind of terminal (a dmc_vt profile's id): the far end is told
|
||||
/// it when connecting
|
||||
@Published var terminalType = UserDefaults.standard.string(forKey: "remoteTerminal") ?? "xterm" {
|
||||
didSet {
|
||||
dmc_vt_set_profile(vt, terminalType)
|
||||
defaults.set(terminalType, forKey: "remoteTerminal")
|
||||
screenVersion += 1
|
||||
}
|
||||
}
|
||||
|
||||
let vt: OpaquePointer
|
||||
private var fd: Int32 = -1 // Telnet's and rlogin's socket
|
||||
private var source: DispatchSourceRead?
|
||||
private var writer: DispatchSourceWrite?
|
||||
private var net: OpaquePointer?
|
||||
/// SSH: the connection, the shell's channel, the logins tried
|
||||
private var ssh: SSHConnection?
|
||||
private var shell: Int32 = 0
|
||||
private var triedKeys = false
|
||||
private var triedFile = false
|
||||
/// the key file's text while its login goes on, and passphrases tried
|
||||
private var keyText: String?
|
||||
private var keyTries = 0
|
||||
private var asks = 0
|
||||
private var exitStatus = 0
|
||||
private var pending: [UInt8] = []
|
||||
private var cols = 80, rows = 24
|
||||
private var timer: Timer?
|
||||
/// a connection under way: older ones' results ignored
|
||||
private var gen = 0
|
||||
|
||||
private let defaults = UserDefaults.standard
|
||||
|
||||
init() {
|
||||
vt = dmc_vt_new(80, 24, 2000)
|
||||
// (Backspace is DEL to a host, not the modem's BS)
|
||||
dmc_vt_set_backspace(vt, 0x7f)
|
||||
dmc_vt_set_theme(vt, 0xe8f0ff, 0x0a0f1c, 0xe8f0ff, nil)
|
||||
proto = Proto(rawValue: defaults.string(forKey: "remoteProtocol") ?? "") ?? .ssh
|
||||
host = defaults.string(forKey: "remoteHost") ?? ""
|
||||
port = defaults.string(forKey: "remotePort") ?? ""
|
||||
user = defaults.string(forKey: "remoteUser") ?? ""
|
||||
dmc_vt_set_profile(vt, terminalType)
|
||||
}
|
||||
|
||||
deinit {
|
||||
stop()
|
||||
dmc_vt_free(vt)
|
||||
}
|
||||
|
||||
// MARK: - TerminalHost
|
||||
|
||||
func send(_ bytes: [UInt8]) {
|
||||
guard running, !bytes.isEmpty else { return }
|
||||
if let ssh {
|
||||
if shell > 0 { ssh.write(shell, bytes) }
|
||||
return
|
||||
}
|
||||
guard fd >= 0 else { return }
|
||||
if let net {
|
||||
bytes.withUnsafeBufferPointer { b in
|
||||
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
|
||||
dmc_net_type(net, $0, Int32(b.count))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pending.append(contentsOf: bytes)
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
// MARK: - connecting
|
||||
|
||||
func connect() {
|
||||
if running { return }
|
||||
let h = host.trimmingCharacters(in: .whitespaces)
|
||||
guard !h.isEmpty else { status = "Enter the server to connect to"; return }
|
||||
let p = port.isEmpty ? proto.defaultPort : (Int(port) ?? 0)
|
||||
guard p > 0 && p <= 65535 else { status = "The port is a number from 1 to 65535"; return }
|
||||
if proto == .rlogin && user.isEmpty { status = "rlogin needs a user name"; return }
|
||||
defaults.set(proto.rawValue, forKey: "remoteProtocol")
|
||||
defaults.set(h, forKey: "remoteHost")
|
||||
defaults.set(port, forKey: "remotePort")
|
||||
defaults.set(user, forKey: "remoteUser")
|
||||
|
||||
dmc_vt_reset(vt)
|
||||
cols = Int(dmc_vt_cols(vt))
|
||||
rows = Int(dmc_vt_rows(vt))
|
||||
let what = "Connecting to \(h) port \(p) by \(proto.rawValue)"
|
||||
status = what
|
||||
show("[\(what)]\r\n")
|
||||
gen += 1
|
||||
running = true
|
||||
if proto == .ssh {
|
||||
guard startSSH(host: h, port: p) else {
|
||||
ended("Could not start SSH")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// (Telnet's TERMINAL-TYPE, rlogin's TERM)
|
||||
let type = proto == .telnet ? dmc_vt_profile_telnet(terminalType) : dmc_vt_profile_term(terminalType)
|
||||
net = dmc_net_new(proto.net, user, type, Int32(cols), Int32(rows))
|
||||
connectSocket(host: h, port: p, gen: gen)
|
||||
}
|
||||
let t = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in self?.tick() }
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() { ended(nil) }
|
||||
|
||||
// MARK: - SSH
|
||||
|
||||
private func startSSH(host: String, port: Int) -> Bool {
|
||||
let u = user.isEmpty ? NSUserName() : user
|
||||
guard let c = SSHConnection(host: host, port: port, user: u) else { return false }
|
||||
// the agent: the one given, else SSH_AUTH_SOCK's
|
||||
if !agentSocket.isEmpty { c.option("agent", agentSocket) }
|
||||
if loginWay == .agent && dmc_ssh_agent_reachable(agentSocket) == 0 {
|
||||
show(agentSocket.isEmpty ? "[No agent answers: SSH_AUTH_SOCK names none]\r\n" :
|
||||
"[No agent answers at the socket given]\r\n")
|
||||
}
|
||||
ssh = c
|
||||
shell = 0
|
||||
triedKeys = false
|
||||
triedFile = false
|
||||
keyText = nil
|
||||
asks = 0
|
||||
exitStatus = 0
|
||||
c.start { [weak self, weak c] ev in
|
||||
guard let self, let c else { return }
|
||||
self.sshEvent(c, ev)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// an event of the connection's, on the main queue
|
||||
private func sshEvent(_ c: SSHConnection, _ ev: SSHConnection.Event) {
|
||||
if ev.type == DMC_SSH_EV_CLOSED {
|
||||
c.finish()
|
||||
guard c === ssh else { return }
|
||||
ssh = nil
|
||||
question = nil
|
||||
if ev.data == nil && exitStatus > 0 {
|
||||
ended("the shell exited with status \(exitStatus)")
|
||||
} else {
|
||||
ended(ev.text)
|
||||
}
|
||||
return
|
||||
}
|
||||
guard c === ssh else { return }
|
||||
switch ev.type {
|
||||
case DMC_SSH_EV_HOSTKEY:
|
||||
hostKey(c, ev.text ?? "", Int(ev.value))
|
||||
case DMC_SSH_EV_AUTH:
|
||||
login(c, methods: Int(ev.value), why: ev.text ?? "")
|
||||
case DMC_SSH_EV_PROMPTS:
|
||||
if ev.value == 0 {
|
||||
dmc_ssh_answered(c.s)
|
||||
} else {
|
||||
var qs: [(String, Bool)] = []
|
||||
for i in 0..<Int(ev.value) {
|
||||
var echo: Int32 = 0
|
||||
let q = String(cString: dmc_ssh_prompt(c.s, Int32(i), &echo))
|
||||
qs.append((q, echo != 0))
|
||||
}
|
||||
let t = ev.text ?? ""
|
||||
question = .prompts(title: t.isEmpty ? "The server asks" : t,
|
||||
instruction: String(cString: dmc_ssh_instruction(c.s)),
|
||||
questions: qs)
|
||||
}
|
||||
case DMC_SSH_EV_READY:
|
||||
if let d = ev.data, !d.isEmpty { feed(d) }
|
||||
shell = dmc_ssh_shell(c.s, dmc_vt_profile_term(terminalType), Int32(cols), Int32(rows), 0)
|
||||
status = "Connected by SSH"
|
||||
case DMC_SSH_EV_OPEN:
|
||||
if ev.value == 0 {
|
||||
show("\r\n[The server refused the shell]\r\n")
|
||||
c.disconnect()
|
||||
}
|
||||
case DMC_SSH_EV_DATA:
|
||||
if ev.channel == shell, let d = ev.data {
|
||||
feed(d)
|
||||
pump()
|
||||
}
|
||||
case DMC_SSH_EV_EXIT:
|
||||
if ev.channel == shell { exitStatus = Int(ev.value) }
|
||||
case DMC_SSH_EV_CLOSE:
|
||||
// (the shell's over: so is the connection)
|
||||
if ev.channel == shell { c.disconnect() }
|
||||
case DMC_SSH_EV_INCOMING:
|
||||
dmc_ssh_close(c.s, ev.channel)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// the server's key: known goes on; new is asked; changed is refused
|
||||
private func hostKey(_ c: SSHConnection, _ key: String, _ known: Int) {
|
||||
if known == DMC_SSH_HOST_KNOWN {
|
||||
dmc_ssh_trust(c.s, 1, 0)
|
||||
return
|
||||
}
|
||||
var fp = [CChar](repeating: 0, count: 128)
|
||||
dmc_ssh_fingerprint(key, &fp, Int32(fp.count))
|
||||
let type = String(key.prefix { $0 != " " })
|
||||
let print = String(cString: fp)
|
||||
if known == DMC_SSH_HOST_CHANGED || known == DMC_SSH_HOST_OTHER_TYPE {
|
||||
show("\r\n\u{1b}[1;31mThe server's host key has changed (it is now \(type) \(print)).\r\n" +
|
||||
"Someone may be in the middle; or the server has a new key. If that is\r\n" +
|
||||
"expected, remove its old line from ~/.ssh/known_hosts.\u{1b}[0m\r\n")
|
||||
dmc_ssh_trust(c.s, 0, 0)
|
||||
return
|
||||
}
|
||||
question = .newHost(type: type, fingerprint: print)
|
||||
}
|
||||
|
||||
/// a path with ~/ at its start made the home folder's
|
||||
private func expand(_ path: String) -> String {
|
||||
(path as NSString).expandingTildeInPath
|
||||
}
|
||||
|
||||
/// the login by the key file (its passphrase asked if it has one):
|
||||
/// false when there's nothing to try
|
||||
private func keyLogin(_ c: SSHConnection) -> Bool {
|
||||
triedFile = true
|
||||
let path = expand(keyPath)
|
||||
guard let text = try? String(contentsOfFile: path, encoding: .utf8) else {
|
||||
show("\r\n[The key file \(path) can't be read]\r\n")
|
||||
return false
|
||||
}
|
||||
if dmc_ssh_key_encrypted(text) != 0 {
|
||||
keyText = text
|
||||
keyTries = 0
|
||||
question = .passphrase(name: (path as NSString).lastPathComponent, why: "", importing: nil)
|
||||
return true
|
||||
}
|
||||
if dmc_ssh_auth_key(c.s, text, nil) == 0 { return true }
|
||||
show("\r\n[\(path) is not a key that can be read]\r\n")
|
||||
return false
|
||||
}
|
||||
|
||||
/// the methods the server last offered
|
||||
private var methods = 0
|
||||
|
||||
/// what's tried, in OpenSSH's order: its keys and agent (or what was
|
||||
/// chosen: the agent alone, or a key file), then the server's
|
||||
/// questions or a password (three times at most)
|
||||
private func login(_ c: SSHConnection, methods: Int, why: String) {
|
||||
self.methods = methods
|
||||
let file = loginWay == .key && !keyPath.isEmpty
|
||||
if methods & DMC_SSH_AUTH_PUBLICKEY != 0 && file && !triedFile {
|
||||
if keyLogin(c) { return }
|
||||
} else if methods & DMC_SSH_AUTH_PUBLICKEY != 0 && !file && !triedKeys {
|
||||
triedKeys = true
|
||||
if loginWay == .agent { dmc_ssh_auth_agent(c.s) } else { dmc_ssh_auth_auto(c.s) }
|
||||
return
|
||||
}
|
||||
keyText = nil
|
||||
asks += 1
|
||||
if asks > 3 {
|
||||
dmc_ssh_auth_cancel(c.s)
|
||||
} else if methods & DMC_SSH_AUTH_INTERACTIVE != 0 {
|
||||
dmc_ssh_auth_interactive(c.s)
|
||||
} else if methods & DMC_SSH_AUTH_PASSWORD != 0 {
|
||||
question = .password(why: asks > 1 ? why : "")
|
||||
} else {
|
||||
dmc_ssh_auth_cancel(c.s)
|
||||
}
|
||||
}
|
||||
|
||||
/// the user's answer to [question]: the answers (none for a new
|
||||
/// host's yes), or nil for no
|
||||
func answer(_ answers: [String]?) {
|
||||
guard let q = question else { return }
|
||||
if case .passphrase(let name, _, let importing) = q {
|
||||
question = nil
|
||||
passphrase(answers?.first, name: name, importing: importing)
|
||||
return
|
||||
}
|
||||
guard let c = ssh else { return }
|
||||
question = nil
|
||||
guard let answers else {
|
||||
if case .newHost = q { dmc_ssh_trust(c.s, 0, 0) } else { dmc_ssh_auth_cancel(c.s) }
|
||||
return
|
||||
}
|
||||
switch q {
|
||||
case .newHost:
|
||||
dmc_ssh_trust(c.s, 1, 1)
|
||||
case .password:
|
||||
dmc_ssh_auth_password(c.s, answers.first ?? "")
|
||||
case .passphrase:
|
||||
break
|
||||
case .prompts:
|
||||
for (i, a) in answers.enumerated() { dmc_ssh_answer(c.s, Int32(i), a) }
|
||||
dmc_ssh_answered(c.s)
|
||||
}
|
||||
}
|
||||
|
||||
/// a key's passphrase given (nil: cancelled), for the login or for an
|
||||
/// import
|
||||
private func passphrase(_ pass: String?, name: String, importing: String?) {
|
||||
if let importing {
|
||||
if let pass { importPPK(importing, passphrase: pass) }
|
||||
return
|
||||
}
|
||||
guard let c = ssh, let text = keyText else { return }
|
||||
if let pass, dmc_ssh_auth_key(c.s, text, pass) == 0 {
|
||||
keyText = nil
|
||||
return
|
||||
}
|
||||
keyTries += 1
|
||||
if pass != nil && keyTries < 3 {
|
||||
// (asked again once this alert has gone, for a new one)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, self.ssh === c else { return }
|
||||
self.question = .passphrase(name: name, why: "That passphrase does not open the key.", importing: nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
keyText = nil
|
||||
login(c, methods: methods, why: "")
|
||||
}
|
||||
|
||||
/// a key file chosen
|
||||
func chooseKey() {
|
||||
let p = NSOpenPanel()
|
||||
p.title = "Choose a Private Key"
|
||||
p.showsHiddenFiles = true
|
||||
p.directoryURL = URL(fileURLWithPath: expand("~/.ssh"))
|
||||
if p.runModal() == .OK, let u = p.url {
|
||||
keyPath = u.path
|
||||
loginWay = .key
|
||||
}
|
||||
}
|
||||
|
||||
/// a .ppk chosen to import
|
||||
func chooseImport() {
|
||||
let p = NSOpenPanel()
|
||||
p.title = "Import a PuTTY Key"
|
||||
p.message = "The key is saved in ~/.ssh in OpenSSH's form, with the same passphrase."
|
||||
p.showsHiddenFiles = true
|
||||
if p.runModal() == .OK, let u = p.url {
|
||||
guard let text = try? String(contentsOfFile: u.path, encoding: .utf8) else {
|
||||
importNote = "That file can't be read"
|
||||
return
|
||||
}
|
||||
if dmc_ssh_key_encrypted(text) != 0 {
|
||||
question = .passphrase(name: u.lastPathComponent, why: "", importing: u.path)
|
||||
} else {
|
||||
importPPK(u.path, passphrase: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// a .ppk imported: written to ~/.ssh in OpenSSH's form (with the
|
||||
/// same passphrase) and chosen
|
||||
private func importPPK(_ path: String, passphrase: String?) {
|
||||
guard let text = try? String(contentsOfFile: path, encoding: .utf8) else {
|
||||
importNote = "That file can't be read"
|
||||
return
|
||||
}
|
||||
var key: UnsafeMutablePointer<CChar>?
|
||||
var pub: UnsafeMutablePointer<CChar>?
|
||||
defer {
|
||||
if let key {
|
||||
memset(key, 0, strlen(key))
|
||||
dmc_ssh_free_string(key)
|
||||
}
|
||||
dmc_ssh_free_string(pub)
|
||||
}
|
||||
guard dmc_ssh_key_export(text, passphrase, passphrase, &key) == 0, let k = key,
|
||||
dmc_ssh_key_public(k, passphrase, &pub) == 0, let p = pub else {
|
||||
if passphrase != nil {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.question = .passphrase(name: (path as NSString).lastPathComponent,
|
||||
why: "That passphrase does not open the key.", importing: path)
|
||||
}
|
||||
} else {
|
||||
importNote = "That file is not a PuTTY key that can be read"
|
||||
}
|
||||
return
|
||||
}
|
||||
// (~/.ssh/<its name>, a name not yet taken)
|
||||
let dir = expand("~/.ssh")
|
||||
let fm = FileManager.default
|
||||
try? fm.createDirectory(atPath: dir, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
var base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
|
||||
if base.isEmpty { base = "putty-key" }
|
||||
var dest = ""
|
||||
for i in 1..<100 {
|
||||
let d = (dir as NSString).appendingPathComponent(i == 1 ? base : "\(base)-\(i)")
|
||||
if !fm.fileExists(atPath: d) && !fm.fileExists(atPath: d + ".pub") {
|
||||
dest = d
|
||||
break
|
||||
}
|
||||
}
|
||||
// (the .pub line with the .ppk's comment)
|
||||
let comment = text.split(separator: "\n").first { $0.hasPrefix("Comment: ") }
|
||||
.map { String($0.dropFirst(9)).trimmingCharacters(in: .whitespacesAndNewlines) } ?? ""
|
||||
let line = String(cString: p) + (comment.isEmpty ? "" : " " + comment) + "\n"
|
||||
guard !dest.isEmpty,
|
||||
fm.createFile(atPath: dest, contents: Data(bytes: k, count: strlen(k)),
|
||||
attributes: [.posixPermissions: 0o600]),
|
||||
fm.createFile(atPath: dest + ".pub", contents: line.data(using: .utf8),
|
||||
attributes: [.posixPermissions: 0o644]) else {
|
||||
importNote = "The key could not be saved in ~/.ssh"
|
||||
return
|
||||
}
|
||||
keyPath = dest
|
||||
loginWay = .key
|
||||
importNote = "Imported as ~/.ssh/\((dest as NSString).lastPathComponent), and chosen"
|
||||
}
|
||||
|
||||
private func feed(_ d: [UInt8]) {
|
||||
d.withUnsafeBufferPointer { b in
|
||||
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
|
||||
dmc_vt_feed(vt, $0, Int32(b.count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Telnet and rlogin
|
||||
|
||||
private func connectSocket(host: String, port: Int, gen: Int) {
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
var hints = addrinfo()
|
||||
hints.ai_family = AF_UNSPEC
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
var res: UnsafeMutablePointer<addrinfo>?
|
||||
var s: Int32 = -1
|
||||
var err = ""
|
||||
let rc = getaddrinfo(host, String(port), &hints, &res)
|
||||
if rc != 0 {
|
||||
err = String(cString: gai_strerror(rc))
|
||||
} else {
|
||||
var a = res
|
||||
while let ai = a {
|
||||
let k = socket(ai.pointee.ai_family, ai.pointee.ai_socktype, ai.pointee.ai_protocol)
|
||||
if k >= 0 {
|
||||
if Darwin.connect(k, ai.pointee.ai_addr, ai.pointee.ai_addrlen) == 0 {
|
||||
s = k
|
||||
break
|
||||
}
|
||||
err = String(cString: strerror(errno))
|
||||
close(k)
|
||||
}
|
||||
a = ai.pointee.ai_next
|
||||
}
|
||||
freeaddrinfo(res)
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
guard let self, self.gen == gen, self.running else {
|
||||
if s >= 0 { close(s) }
|
||||
return
|
||||
}
|
||||
self.socketConnected(s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func socketConnected(_ s: Int32, _ err: String) {
|
||||
guard s >= 0, let net else {
|
||||
ended(err.isEmpty ? "Could not connect" : err)
|
||||
return
|
||||
}
|
||||
var one: Int32 = 1
|
||||
setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.size))
|
||||
_ = fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK)
|
||||
fd = s
|
||||
watch()
|
||||
status = "Connected"
|
||||
dmc_net_connected(net)
|
||||
pump()
|
||||
}
|
||||
|
||||
private func watch() {
|
||||
let s = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
|
||||
s.setEventHandler { [weak self] in self?.readable() }
|
||||
s.resume()
|
||||
source = s
|
||||
}
|
||||
|
||||
// MARK: - the bytes
|
||||
|
||||
/// rlogin's control byte, sent urgent
|
||||
private func urgent() {
|
||||
guard let net, fd >= 0 else { return }
|
||||
var b: UInt8 = 0
|
||||
if recv(fd, &b, 1, Int32(MSG_OOB)) == 1 { dmc_net_urgent(net, Int32(b)) }
|
||||
}
|
||||
|
||||
private func readable() {
|
||||
guard fd >= 0 else { return }
|
||||
urgent()
|
||||
var buf = [CChar](repeating: 0, count: 8192)
|
||||
while fd >= 0 {
|
||||
let n = Darwin.read(fd, &buf, buf.count)
|
||||
if n > 0 {
|
||||
if let net {
|
||||
dmc_net_feed(net, buf, Int32(n))
|
||||
} else {
|
||||
dmc_vt_feed(vt, buf, Int32(n))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if n < 0 && errno == EINTR { continue }
|
||||
if n < 0 && errno == EAGAIN { break }
|
||||
// the end: the server closed
|
||||
pump()
|
||||
ended("Connection closed by the server")
|
||||
return
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
private func pump() {
|
||||
var buf = [CChar](repeating: 0, count: 8192)
|
||||
if let net {
|
||||
while true {
|
||||
let n = dmc_net_screen(net, &buf, Int32(buf.count))
|
||||
if n <= 0 { break }
|
||||
dmc_vt_feed(vt, buf, n)
|
||||
}
|
||||
}
|
||||
TerminalTypes.afterFeed(vt)
|
||||
// the screen's answers (where the cursor is), as if typed
|
||||
while true {
|
||||
let k = dmc_vt_reply(vt, &buf, Int32(buf.count))
|
||||
if k <= 0 { break }
|
||||
if let net {
|
||||
dmc_net_type(net, buf, k)
|
||||
} else if let ssh, shell > 0 {
|
||||
ssh.write(shell, buf[0..<Int(k)].map { UInt8(bitPattern: $0) })
|
||||
}
|
||||
}
|
||||
if let net {
|
||||
while true {
|
||||
let n = dmc_net_output(net, &buf, Int32(buf.count))
|
||||
if n <= 0 { break }
|
||||
pending.append(contentsOf: buf[0..<Int(n)].map { UInt8(bitPattern: $0) })
|
||||
}
|
||||
}
|
||||
flush()
|
||||
if dmc_vt_changed(vt) != 0 { screenVersion += 1 }
|
||||
}
|
||||
|
||||
private func flush() {
|
||||
while fd >= 0 && !pending.isEmpty {
|
||||
let w = pending.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
|
||||
if w > 0 {
|
||||
pending.removeFirst(w)
|
||||
continue
|
||||
}
|
||||
if w < 0 && errno == EINTR { continue }
|
||||
if w < 0 && errno == EAGAIN {
|
||||
if writer == nil {
|
||||
let s = DispatchSource.makeWriteSource(fileDescriptor: fd, queue: .main)
|
||||
s.setEventHandler { [weak self] in
|
||||
self?.writer?.cancel()
|
||||
self?.writer = nil
|
||||
self?.flush()
|
||||
}
|
||||
s.resume()
|
||||
writer = s
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/// the screen's size, told to the far end as it changes
|
||||
private func tick() {
|
||||
urgent()
|
||||
let c = Int(dmc_vt_cols(vt)), r = Int(dmc_vt_rows(vt))
|
||||
if c != cols || r != rows {
|
||||
cols = c
|
||||
rows = r
|
||||
if let net {
|
||||
dmc_net_resize(net, Int32(c), Int32(r))
|
||||
} else if let ssh, shell > 0 {
|
||||
ssh.resize(shell, cols: c, rows: r)
|
||||
}
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
private func show(_ s: String) {
|
||||
let b = Array(s.utf8).map { CChar(bitPattern: $0) }
|
||||
dmc_vt_feed(vt, b, Int32(b.count))
|
||||
screenVersion += 1
|
||||
}
|
||||
|
||||
private func ended(_ why: String?) {
|
||||
guard running else { return }
|
||||
running = false
|
||||
gen += 1
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
source?.cancel()
|
||||
source = nil
|
||||
writer?.cancel()
|
||||
writer = nil
|
||||
// (let go: its thread ends with it)
|
||||
ssh?.disconnect()
|
||||
ssh = nil
|
||||
shell = 0
|
||||
keyText = nil
|
||||
if case .some(.passphrase(_, _, let importing)) = question, importing != nil {
|
||||
// (an import's question stays)
|
||||
} else {
|
||||
question = nil
|
||||
}
|
||||
if fd >= 0 {
|
||||
close(fd)
|
||||
fd = -1
|
||||
}
|
||||
if let net { dmc_net_free(net) }
|
||||
net = nil
|
||||
pending.removeAll()
|
||||
show("\r\n\u{1b}[0m[\(why ?? "Disconnected")]\r\n")
|
||||
status = why ?? "Disconnected"
|
||||
}
|
||||
}
|
||||
|
||||
struct RemotePage: View {
|
||||
@ObservedObject var session: RemoteSession
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Picker("", selection: $session.proto) {
|
||||
ForEach(RemoteSession.Proto.allCases) { Text($0.rawValue).tag($0) }
|
||||
}
|
||||
.labelsHidden()
|
||||
.frame(width: 100)
|
||||
.disabled(session.running)
|
||||
TextField("Server", text: $session.host)
|
||||
.onSubmit { session.connect() }
|
||||
.disabled(session.running)
|
||||
TextField(String(session.proto.defaultPort), text: $session.port)
|
||||
.frame(width: 60)
|
||||
.help("Port (empty: the protocol's)")
|
||||
.disabled(session.running)
|
||||
TextField("User", text: $session.user)
|
||||
.frame(width: 120)
|
||||
.disabled(session.running)
|
||||
if session.proto == .ssh {
|
||||
Button {
|
||||
showLogin.toggle()
|
||||
} label: {
|
||||
Image(systemName: "key")
|
||||
}
|
||||
.help("How SSH logs in: keys, the agent, a PuTTY key")
|
||||
.disabled(session.running)
|
||||
.popover(isPresented: $showLogin, arrowEdge: .bottom) {
|
||||
LoginOptions(session: session, shown: $showLogin)
|
||||
}
|
||||
}
|
||||
if session.running {
|
||||
Button("Disconnect", role: .destructive) { session.stop() }
|
||||
} else {
|
||||
Button("Connect") { session.connect() }
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(8)
|
||||
TerminalView(host: session, version: session.screenVersion)
|
||||
HStack {
|
||||
Text(session.status).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
TerminalTypePicker(selection: $session.terminalType)
|
||||
}
|
||||
.padding(.horizontal, 8).padding(.vertical, 4)
|
||||
}
|
||||
.onChange(of: session.question != nil) { _ in
|
||||
answers = Array(repeating: "", count: answers.count)
|
||||
}
|
||||
.alert(title, isPresented: asking, presenting: session.question) { q in
|
||||
switch q {
|
||||
case .newHost:
|
||||
Button("Connect") { session.answer([]) }
|
||||
Button("Cancel", role: .cancel) { session.answer(nil) }
|
||||
case .password:
|
||||
SecureField("Password", text: answerBinding(0))
|
||||
Button("Log In") { session.answer([answers[0]]) }
|
||||
Button("Cancel", role: .cancel) { session.answer(nil) }
|
||||
case .passphrase:
|
||||
SecureField("Passphrase", text: answerBinding(0))
|
||||
Button("Unlock") { session.answer([answers[0]]) }
|
||||
Button("Cancel", role: .cancel) { session.answer(nil) }
|
||||
case .prompts(_, _, let qs):
|
||||
ForEach(qs.indices, id: \.self) { i in
|
||||
if qs[i].1 {
|
||||
TextField(qs[i].0, text: answerBinding(i))
|
||||
} else {
|
||||
SecureField(qs[i].0, text: answerBinding(i))
|
||||
}
|
||||
}
|
||||
Button("Log In") { session.answer(Array(answers.prefix(qs.count))) }
|
||||
Button("Cancel", role: .cancel) { session.answer(nil) }
|
||||
}
|
||||
} message: { q in
|
||||
switch q {
|
||||
case .newHost(let type, let fp):
|
||||
Text("This server is not known yet. Its key's fingerprint is\n\n\(type) \(fp)\n\n" +
|
||||
"If it's the one you expect, it will be added to ~/.ssh/known_hosts.")
|
||||
case .password(let why):
|
||||
Text(why)
|
||||
case .passphrase(_, let why, _):
|
||||
Text(why)
|
||||
case .prompts(_, let instruction, let qs):
|
||||
Text(instruction.isEmpty ? qs.map(\.0).joined(separator: "\n") : instruction)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// the answers being typed, cleared for each question
|
||||
@State private var answers = ["", "", "", "", "", "", "", ""]
|
||||
/// the login options' popover
|
||||
@State private var showLogin = false
|
||||
|
||||
private func answerBinding(_ i: Int) -> Binding<String> {
|
||||
Binding(get: { i < answers.count ? answers[i] : "" },
|
||||
set: { if i < answers.count { answers[i] = $0 } })
|
||||
}
|
||||
|
||||
private var asking: Binding<Bool> {
|
||||
// (dismissed by its buttons, each of which answers)
|
||||
Binding(get: { session.question != nil }, set: { _ in })
|
||||
}
|
||||
|
||||
private var title: String {
|
||||
switch session.question {
|
||||
case .newHost: return "Connect to a new server?"
|
||||
case .password: return "Log in to \(session.host)"
|
||||
case .passphrase(let name, _, _): return "Passphrase for \(name)"
|
||||
case .prompts(let t, _, _): return t
|
||||
case nil: return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// how SSH logs in: the way, the key file, a PuTTY key's import, the
|
||||
/// agent's socket
|
||||
struct LoginOptions: View {
|
||||
@ObservedObject var session: RemoteSession
|
||||
@Binding var shown: Bool
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Log in to SSH servers with").font(.headline)
|
||||
Picker("", selection: $session.loginWay) {
|
||||
ForEach(RemoteSession.LoginWay.allCases) { Text($0.label).tag($0) }
|
||||
}
|
||||
.labelsHidden()
|
||||
Text("Key file (OpenSSH's, PEM or PuTTY's .ppk)").foregroundStyle(.secondary)
|
||||
HStack {
|
||||
Text(session.keyPath.isEmpty ? "No key file chosen" :
|
||||
(session.keyPath as NSString).lastPathComponent)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
.help(session.keyPath)
|
||||
Spacer()
|
||||
Button("Choose…") {
|
||||
shown = false
|
||||
session.chooseKey()
|
||||
}
|
||||
}
|
||||
Button("Import a PuTTY Key…") {
|
||||
shown = false
|
||||
session.chooseImport()
|
||||
}
|
||||
.help("A .ppk saved in ~/.ssh in OpenSSH's form, with the same passphrase, and chosen")
|
||||
if !session.importNote.isEmpty {
|
||||
Text(session.importNote).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Text("Agent's socket").foregroundStyle(.secondary)
|
||||
TextField("Empty: SSH_AUTH_SOCK's", text: $session.agentSocket)
|
||||
Text(session.agentState).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(12)
|
||||
.frame(width: 320)
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// SSHConnection.swift - a libdmodemssh connection polled on a thread of
|
||||
// its own, each event handed to the main queue. It reads OpenSSH's
|
||||
// config and known_hosts. Its dmc_ssh is freed by finish(), once the
|
||||
// DMC_SSH_EV_CLOSED that ends it has been handed over.
|
||||
|
||||
import Foundation
|
||||
|
||||
final class SSHConnection {
|
||||
/// an event, copied off the connection's thread
|
||||
struct Event {
|
||||
let type: Int
|
||||
let channel: Int32
|
||||
let value: Int32
|
||||
let data: [UInt8]?
|
||||
|
||||
/// the data as UTF-8 text
|
||||
var text: String? { data.map { String(decoding: $0, as: UTF8.self) } }
|
||||
}
|
||||
|
||||
let s: OpaquePointer
|
||||
private let done = DispatchSemaphore(value: 0)
|
||||
private var started = false
|
||||
private var freed = false
|
||||
|
||||
init?(host: String, port: Int, user: String) {
|
||||
guard let s = dmc_ssh_new(host, Int32(port), user) else { return nil }
|
||||
self.s = s
|
||||
// OpenSSH's own config and known hosts: the user's
|
||||
dmc_ssh_option(s, "config", "")
|
||||
dmc_ssh_option(s, "knownhosts", "")
|
||||
}
|
||||
|
||||
/// an option of dmc_ssh_option's, before it starts ("agent": its socket)
|
||||
func option(_ name: String, _ value: String) {
|
||||
dmc_ssh_option(s, name, value)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if !freed {
|
||||
if started {
|
||||
dmc_ssh_disconnect(s)
|
||||
done.wait()
|
||||
}
|
||||
dmc_ssh_free(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// polled until it's over, each event to handle on the main queue
|
||||
func start(_ handle: @escaping (Event) -> Void) {
|
||||
started = true
|
||||
let s = self.s
|
||||
let done = self.done
|
||||
let t = Thread {
|
||||
var ev = dmc_ssh_event()
|
||||
while true {
|
||||
let n = dmc_ssh_poll(s, 1000, &ev)
|
||||
if n < 0 { break }
|
||||
if n == 0 { continue }
|
||||
let data: [UInt8]? = ev.data.map { p in
|
||||
p.withMemoryRebound(to: UInt8.self, capacity: Int(ev.len)) {
|
||||
Array(UnsafeBufferPointer(start: $0, count: Int(ev.len)))
|
||||
}
|
||||
}
|
||||
let e = Event(type: Int(ev.type), channel: ev.channel, value: ev.value, data: data)
|
||||
DispatchQueue.main.async { handle(e) }
|
||||
if Int(ev.type) == DMC_SSH_EV_CLOSED { break }
|
||||
}
|
||||
done.signal()
|
||||
}
|
||||
t.name = "ssh"
|
||||
t.start()
|
||||
}
|
||||
|
||||
/// what's typed, to a channel
|
||||
func write(_ channel: Int32, _ bytes: [UInt8]) {
|
||||
bytes.withUnsafeBufferPointer { b in
|
||||
b.baseAddress!.withMemoryRebound(to: CChar.self, capacity: b.count) {
|
||||
_ = dmc_ssh_write(s, channel, $0, Int32(b.count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// a shell's new size
|
||||
func resize(_ channel: Int32, cols: Int, rows: Int) {
|
||||
dmc_ssh_resize(s, channel, Int32(cols), Int32(rows))
|
||||
}
|
||||
|
||||
/// closed by the user: a DMC_SSH_EV_CLOSED comes
|
||||
func disconnect() {
|
||||
if !freed { dmc_ssh_disconnect(s) }
|
||||
}
|
||||
|
||||
/// the connection freed, once its thread has ended
|
||||
func finish() {
|
||||
guard !freed else { return }
|
||||
done.wait()
|
||||
freed = true
|
||||
dmc_ssh_free(s)
|
||||
}
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// TerminalView.swift - the modem's console and its full-screen setup, and
|
||||
// the terminal view the Remote page shares: libdmodemctl's terminal screen
|
||||
// (dmc_vt), drawn cell by cell
|
||||
//
|
||||
// Every kind of terminal the engine is (xterm, the VTs, ANSI-BBS, the
|
||||
// Commodores and Ataris, Viewdata, the Minitel, the Tektronix) is drawn
|
||||
// here: a cell's background, its character in Menlo or, where the profile
|
||||
// has its machine's font, the glyph's bitmap (a row's glyphs put in an
|
||||
// image at the font's own size and stretched over the row, so a C64's 8x8
|
||||
// stays sharp), its lines, the pictures (sixel, ReGIS, RIPscrip's, the
|
||||
// Tektronix's) over the text, and the cursor. A machine with a screen of
|
||||
// its own size (a C64's 40x25) has its cells stretched to fill the view.
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// what a terminal view shows and where its keys go: the modem, or a
|
||||
/// remote login (RemoteView.swift)
|
||||
protocol TerminalHost: AnyObject {
|
||||
var vt: OpaquePointer { get }
|
||||
/// the bytes a key or a paste sends, as the terminal sends them
|
||||
func send(_ bytes: [UInt8])
|
||||
}
|
||||
|
||||
extension Modem: TerminalHost {
|
||||
func send(_ bytes: [UInt8]) { type(bytes) }
|
||||
}
|
||||
|
||||
/// the kinds of terminal, in the pickers' order
|
||||
enum TerminalTypes {
|
||||
struct Kind: Identifiable, Hashable {
|
||||
let id: String
|
||||
let label: String
|
||||
}
|
||||
|
||||
static let all: [Kind] = (0..<Int(dmc_vt_profile_count())).map { i in
|
||||
Kind(id: String(cString: dmc_vt_profile_id(Int32(i))),
|
||||
label: String(cString: dmc_vt_profile_label(Int32(i))))
|
||||
}
|
||||
|
||||
/// what the terminal told the remote after it was fed: its bell,
|
||||
/// its music and its printer (the last two not kept)
|
||||
static func afterFeed(_ vt: OpaquePointer) {
|
||||
var buf = [CChar](repeating: 0, count: 256)
|
||||
while dmc_vt_printed(vt, &buf, Int32(buf.count)) > 0 {}
|
||||
var hz: UInt32 = 0
|
||||
var ms: Int32 = 0, rest: Int32 = 0
|
||||
while dmc_vt_music(vt, &hz, &ms, &rest) != 0 {}
|
||||
if dmc_vt_bells(vt) > 0 { NSSound.beep() }
|
||||
}
|
||||
}
|
||||
|
||||
/// a picker of the kinds of terminal
|
||||
struct TerminalTypePicker: View {
|
||||
@Binding var selection: String
|
||||
|
||||
var body: some View {
|
||||
Picker("Terminal", selection: $selection) {
|
||||
ForEach(TerminalTypes.all) { Text($0.label).tag($0.id) }
|
||||
}
|
||||
.frame(maxWidth: 260)
|
||||
.help("The kind of terminal")
|
||||
}
|
||||
}
|
||||
|
||||
struct TerminalPane: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Group {
|
||||
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)")
|
||||
}
|
||||
.disabled(!modem.isIdle)
|
||||
Spacer()
|
||||
TerminalTypePicker(selection: $modem.terminalType)
|
||||
Button("Clear") { modem.clearScreen() }
|
||||
}
|
||||
.padding(8)
|
||||
TerminalView(host: modem, version: modem.screenVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TerminalView: NSViewRepresentable {
|
||||
let host: TerminalHost
|
||||
let version: Int
|
||||
|
||||
func makeNSView(context: Context) -> TerminalNSView {
|
||||
let v = TerminalNSView()
|
||||
v.host = host
|
||||
return v
|
||||
}
|
||||
|
||||
func updateNSView(_ v: TerminalNSView, context: Context) {
|
||||
v.host = host
|
||||
v.relayout()
|
||||
v.needsDisplay = true
|
||||
}
|
||||
}
|
||||
|
||||
final class TerminalNSView: NSView {
|
||||
weak var host: TerminalHost?
|
||||
private let font = NSFont(name: "Menlo", size: 13) ?? .monospacedSystemFont(ofSize: 13, weight: .regular)
|
||||
private lazy var fonts: [NSFont] = {
|
||||
let m = NSFontManager.shared
|
||||
let b = m.convert(font, toHaveTrait: .boldFontMask)
|
||||
return [font, b, m.convert(font, toHaveTrait: .italicFontMask),
|
||||
m.convert(b, toHaveTrait: .italicFontMask)]
|
||||
}()
|
||||
/// the font's cell, and a cell as drawn
|
||||
private var fontCell = NSSize(width: 8, height: 16)
|
||||
private var cell = NSSize(width: 8, height: 16)
|
||||
private var origin = NSPoint(x: 0, y: 0)
|
||||
private var statusRows = 0
|
||||
private var scroll = 0 // rows up into the scrollback
|
||||
private var blinkOff = false, hasBlink = false
|
||||
private var blinkTimer: Timer?
|
||||
private var buttons = 0
|
||||
|
||||
override init(frame: NSRect) {
|
||||
super.init(frame: frame)
|
||||
let w = ("M" as NSString).size(withAttributes: [.font: font]).width
|
||||
fontCell = NSSize(width: ceil(w), height: ceil(font.ascender - font.descender + font.leading))
|
||||
cell = fontCell
|
||||
let t = Timer(timeInterval: 0.5, repeats: true) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.blinkOff.toggle()
|
||||
if self.hasBlink { self.needsDisplay = true }
|
||||
}
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
blinkTimer = t
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) { fatalError("not used") }
|
||||
|
||||
deinit { blinkTimer?.invalidate() }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
override var acceptsFirstResponder: Bool { true }
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
window?.makeFirstResponder(self)
|
||||
}
|
||||
|
||||
override func becomeFirstResponder() -> Bool {
|
||||
focusChanged(true)
|
||||
return true
|
||||
}
|
||||
|
||||
override func resignFirstResponder() -> Bool {
|
||||
focusChanged(false)
|
||||
return true
|
||||
}
|
||||
|
||||
private func focusChanged(_ on: Bool) {
|
||||
guard let host else { return }
|
||||
var buf = [CChar](repeating: 0, count: 16)
|
||||
let n = dmc_vt_focus(host.vt, on ? 1 : 0, &buf, Int32(buf.count))
|
||||
send(buf, n)
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func setFrameSize(_ size: NSSize) {
|
||||
super.setFrameSize(size)
|
||||
relayout()
|
||||
}
|
||||
|
||||
/// the columns and rows that fit, or the machine's own with its cells
|
||||
/// stretched to fill the view
|
||||
func relayout() {
|
||||
guard let vt = host?.vt else { return }
|
||||
let W = bounds.width, H = bounds.height
|
||||
guard W > 0, H > 0 else { return }
|
||||
let rc = Int(dmc_vt_requested_cols(vt)), rr = Int(dmc_vt_requested_rows(vt))
|
||||
let st = dmc_vt_status_line(vt).map { String(cString: $0) } ?? ""
|
||||
statusRows = st.isEmpty ? 0 : 1
|
||||
var gw: Int32 = 0, gh: Int32 = 0
|
||||
let glyphs = dmc_vt_glyph_cell(vt, &gw, &gh) != 0
|
||||
var cw = fontCell.width, ch = fontCell.height
|
||||
if glyphs && rc > 0 && rr > 0 {
|
||||
let s = min(floor(W / CGFloat(rc * Int(gw))), floor(H / CGFloat((rr + statusRows) * Int(gh))))
|
||||
if s >= 1 {
|
||||
cw = CGFloat(gw) * s
|
||||
ch = CGFloat(gh) * s
|
||||
} else {
|
||||
cw = floor(W / CGFloat(rc))
|
||||
ch = floor(H / CGFloat(rr + statusRows))
|
||||
}
|
||||
} else {
|
||||
if rc > 0 { cw = floor(W / CGFloat(rc)) }
|
||||
if rr > 0 { ch = floor(H / CGFloat(rr + statusRows)) }
|
||||
}
|
||||
cw = max(2, cw)
|
||||
ch = max(2, ch)
|
||||
let cols = max(10, min(400, rc > 0 ? rc : Int(W / cw)))
|
||||
let rows = max(3, min(200, rr > 0 ? rr : Int(H / ch) - statusRows))
|
||||
cell = NSSize(width: cw, height: ch)
|
||||
origin = NSPoint(x: rc > 0 ? max(0, floor((W - CGFloat(cols) * cw) / 2)) : 0,
|
||||
y: rr > 0 ? max(0, floor((H - CGFloat(rows + statusRows) * ch) / 2)) : 0)
|
||||
dmc_vt_set_cell_pixels(vt, Int32(cw), Int32(ch))
|
||||
if cols != Int(dmc_vt_cols(vt)) || rows != Int(dmc_vt_rows(vt)) {
|
||||
dmc_vt_resize(vt, Int32(cols), Int32(rows))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - drawing
|
||||
|
||||
private static func color(_ c: UInt32) -> CGColor {
|
||||
CGColor(srgbRed: CGFloat((c >> 16) & 0xff) / 255, green: CGFloat((c >> 8) & 0xff) / 255,
|
||||
blue: CGFloat(c & 0xff) / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// pixels (0xAARRGGBB, not premultiplied) as an image
|
||||
private static func image(_ px: UnsafePointer<UInt32>, _ w: Int, _ h: Int) -> CGImage? {
|
||||
var data = [UInt32](repeating: 0, count: w * h)
|
||||
for i in 0..<(w * h) {
|
||||
let v = px[i], a = v >> 24
|
||||
data[i] = (a << 24) | ((((v >> 16) & 255) * a / 255) << 16) |
|
||||
((((v >> 8) & 255) * a / 255) << 8) | ((v & 255) * a / 255)
|
||||
}
|
||||
return data.withUnsafeMutableBytes { b -> CGImage? in
|
||||
guard let ctx = CGContext(data: b.baseAddress, width: w, height: h, bitsPerComponent: 8,
|
||||
bytesPerRow: w * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,
|
||||
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue |
|
||||
CGBitmapInfo.byteOrder32Little.rawValue) else { return nil }
|
||||
return ctx.makeImage()
|
||||
}
|
||||
}
|
||||
|
||||
/// an image drawn upright in rect (the view is flipped), unsmoothed
|
||||
private static func draw(_ img: CGImage, in r: CGRect, _ ctx: CGContext) {
|
||||
ctx.saveGState()
|
||||
ctx.interpolationQuality = .none
|
||||
ctx.translateBy(x: r.minX, y: r.maxY)
|
||||
ctx.scaleBy(x: 1, y: -1)
|
||||
ctx.draw(img, in: CGRect(origin: .zero, size: r.size))
|
||||
ctx.restoreGState()
|
||||
}
|
||||
|
||||
override func draw(_ dirty: NSRect) {
|
||||
guard let ctx = NSGraphicsContext.current?.cgContext else { return }
|
||||
guard let vt = host?.vt else {
|
||||
NSColor.black.setFill()
|
||||
bounds.fill()
|
||||
return
|
||||
}
|
||||
ctx.setFillColor(Self.color(dmc_vt_background(vt)))
|
||||
ctx.fill(bounds)
|
||||
let rows = Int(dmc_vt_rows(vt)), cols = Int(dmc_vt_cols(vt))
|
||||
scroll = min(scroll, Int(dmc_vt_history(vt)))
|
||||
hasBlink = false
|
||||
var pictures: [UInt32: CGImage] = [:]
|
||||
for y in 0..<rows {
|
||||
let vrow = Int32(y - scroll)
|
||||
let size = Int(dmc_vt_line_size(vt, vrow))
|
||||
let cursor = scroll == 0 && dmc_vt_cursor_visible(vt) != 0 && Int(dmc_vt_cursor_row(vt)) == y
|
||||
ctx.saveGState()
|
||||
ctx.translateBy(x: origin.x, y: origin.y + CGFloat(y) * cell.height)
|
||||
ctx.clip(to: CGRect(x: 0, y: 0, width: CGFloat(cols) * cell.width, height: cell.height))
|
||||
var n = cols
|
||||
if size != Int(DMC_LINE_SINGLE) {
|
||||
n = (cols + 1) / 2
|
||||
if size == Int(DMC_LINE_DOUBLE_WIDTH) {
|
||||
ctx.scaleBy(x: 2, y: 1)
|
||||
} else {
|
||||
if size == Int(DMC_LINE_DOUBLE_BOTTOM) { ctx.translateBy(x: 0, y: -cell.height) }
|
||||
ctx.scaleBy(x: 2, y: 2)
|
||||
}
|
||||
}
|
||||
drawRow(vt, vrow, n, cursor, ctx, &pictures)
|
||||
ctx.restoreGState()
|
||||
}
|
||||
if statusRows > 0, let s = dmc_vt_status_line(vt) {
|
||||
let r = CGRect(x: origin.x, y: origin.y + CGFloat(rows) * cell.height,
|
||||
width: CGFloat(cols) * cell.width, height: cell.height)
|
||||
ctx.setFillColor(Self.color(dmc_vt_foreground(vt)))
|
||||
ctx.fill(r)
|
||||
(String(cString: s) as NSString).draw(at: r.origin, withAttributes: [
|
||||
.font: font, .foregroundColor: NSColor(cgColor: Self.color(dmc_vt_background(vt))) ?? .black])
|
||||
}
|
||||
}
|
||||
|
||||
private func drawRow(_ vt: OpaquePointer, _ vrow: Int32, _ ncols: Int, _ cursor: Bool,
|
||||
_ ctx: CGContext, _ pictures: inout [UInt32: CGImage]) {
|
||||
let cw = cell.width, ch = cell.height
|
||||
var cells = [dmc_cell](repeating: dmc_cell(), count: ncols)
|
||||
var anyGlyph = false, anyImage = false
|
||||
for x in 0..<ncols {
|
||||
dmc_vt_cell(vt, vrow, Int32(x), &cells[x])
|
||||
let f = Int(cells[x].flags)
|
||||
if f & Int(DMC_CELL_BLINK) != 0 { hasBlink = true }
|
||||
if f & Int(DMC_CELL_GLYPH) != 0 { anyGlyph = true }
|
||||
if f & Int(DMC_CELL_IMAGE) != 0 { anyImage = true }
|
||||
}
|
||||
// the backgrounds, in runs
|
||||
var x = 0
|
||||
while x < ncols {
|
||||
var n = 1
|
||||
while x + n < ncols && cells[x + n].bg == cells[x].bg { n += 1 }
|
||||
ctx.setFillColor(Self.color(cells[x].bg))
|
||||
ctx.fill(CGRect(x: CGFloat(x) * cw, y: 0, width: CGFloat(n) * cw, height: ch))
|
||||
x += n
|
||||
}
|
||||
// the text, in the font
|
||||
let ty = max(0, floor((ch - fontCell.height) / 2))
|
||||
for x in 0..<ncols {
|
||||
let c = cells[x], f = Int(c.flags)
|
||||
if f & Int(DMC_CELL_GLYPH | DMC_CELL_INVISIBLE | DMC_CELL_WIDE_TAIL) != 0 { continue }
|
||||
if f & Int(DMC_CELL_BLINK) != 0 && blinkOff { continue }
|
||||
if c.ch == 0 || (c.ch == 32 && f & Int(DMC_CELL_COMBINING) == 0) { continue }
|
||||
let s: String
|
||||
if f & Int(DMC_CELL_COMBINING) != 0, let t = dmc_vt_cell_text(vt, vrow, Int32(x)) {
|
||||
s = String(cString: t)
|
||||
} else {
|
||||
s = Unicode.Scalar(c.ch).map { String(Character($0)) } ?? "?"
|
||||
}
|
||||
let fi = (f & Int(DMC_CELL_BOLD) != 0 ? 1 : 0) | (f & Int(DMC_CELL_ITALIC) != 0 ? 2 : 0)
|
||||
(s as NSString).draw(at: NSPoint(x: CGFloat(x) * cw, y: ty), withAttributes: [
|
||||
.font: fonts[fi], .foregroundColor: NSColor(cgColor: Self.color(c.fg)) ?? .white])
|
||||
}
|
||||
if anyGlyph { drawGlyphs(vt, cells, ctx) }
|
||||
// the lines
|
||||
let th = max(1, floor(ch / 16))
|
||||
for x in 0..<ncols {
|
||||
let c = cells[x], f = Int(c.flags), l = CGFloat(x) * cw
|
||||
if f & Int(DMC_CELL_INVISIBLE) != 0 { continue }
|
||||
ctx.setFillColor(Self.color(c.fg))
|
||||
if f & Int(DMC_CELL_UNDERLINE | DMC_CELL_LINK) != 0 {
|
||||
ctx.fill(CGRect(x: l, y: ch - 2 * th, width: cw, height: th))
|
||||
}
|
||||
if f & Int(DMC_CELL_DOUBLE_UNDERLINE) != 0 {
|
||||
ctx.fill(CGRect(x: l, y: ch - th, width: cw, height: th))
|
||||
ctx.fill(CGRect(x: l, y: ch - 3 * th, width: cw, height: th))
|
||||
}
|
||||
if f & Int(DMC_CELL_CURLY_UNDERLINE) != 0 {
|
||||
ctx.setStrokeColor(Self.color(c.fg))
|
||||
ctx.setLineWidth(th)
|
||||
ctx.move(to: CGPoint(x: l, y: ch - 2 * th))
|
||||
for i in 0..<4 {
|
||||
ctx.addLine(to: CGPoint(x: l + CGFloat(i + 1) * cw / 4,
|
||||
y: ch - (i % 2 == 1 ? 2 : 1) * th - th / 2))
|
||||
}
|
||||
ctx.strokePath()
|
||||
}
|
||||
if f & Int(DMC_CELL_STRIKE) != 0 {
|
||||
ctx.fill(CGRect(x: l, y: floor(ch / 2), width: cw, height: th))
|
||||
}
|
||||
if f & Int(DMC_CELL_OVERLINE) != 0 {
|
||||
ctx.fill(CGRect(x: l, y: 0, width: cw, height: th))
|
||||
}
|
||||
}
|
||||
// the pictures over the text
|
||||
if anyImage {
|
||||
for x in 0..<ncols where Int(cells[x].flags) & Int(DMC_CELL_IMAGE) != 0 {
|
||||
var im = dmc_image()
|
||||
guard let px = dmc_vt_cell_image(vt, vrow, Int32(x), &im),
|
||||
im.cell_width > 0, im.cell_height > 0 else { continue }
|
||||
var img = pictures[im.id]
|
||||
if img == nil {
|
||||
img = Self.image(px, Int(im.width), Int(im.height))
|
||||
pictures[im.id] = img
|
||||
}
|
||||
guard let img else { continue }
|
||||
let sx = cw / CGFloat(im.cell_width), sy = ch / CGFloat(im.cell_height)
|
||||
ctx.saveGState()
|
||||
ctx.clip(to: CGRect(x: CGFloat(x) * cw, y: 0, width: cw, height: ch))
|
||||
Self.draw(img, in: CGRect(x: CGFloat(x) * cw - CGFloat(im.tx) * cw,
|
||||
y: -CGFloat(im.ty) * ch,
|
||||
width: CGFloat(im.width) * sx,
|
||||
height: CGFloat(im.height) * sy), ctx)
|
||||
ctx.restoreGState()
|
||||
}
|
||||
}
|
||||
// the cursor
|
||||
if cursor {
|
||||
let cx = Int(dmc_vt_cursor_col(vt))
|
||||
if cx >= 0 && cx < ncols {
|
||||
let w = Int(cells[cx].flags) & Int(DMC_CELL_WIDE) != 0 ? 2 * cw : cw
|
||||
let r = CGRect(x: CGFloat(cx) * cw, y: 0, width: w, height: ch)
|
||||
let style = Int(dmc_vt_cursor_style(vt))
|
||||
let cc = Self.color(dmc_vt_cursor_color(vt))
|
||||
if window?.firstResponder !== self {
|
||||
ctx.setStrokeColor(cc)
|
||||
ctx.setLineWidth(1)
|
||||
ctx.stroke(r.insetBy(dx: 0.5, dy: 0.5))
|
||||
} else if style == 3 || style == 4 {
|
||||
ctx.setFillColor(cc)
|
||||
ctx.fill(CGRect(x: r.minX, y: ch - max(2, floor(ch / 8)), width: w, height: max(2, floor(ch / 8))))
|
||||
} else if style == 5 || style == 6 {
|
||||
ctx.setFillColor(cc)
|
||||
ctx.fill(CGRect(x: r.minX, y: 0, width: max(2, floor(cw / 8)), height: ch))
|
||||
} else {
|
||||
ctx.saveGState()
|
||||
ctx.setBlendMode(.difference)
|
||||
ctx.setFillColor(cc)
|
||||
ctx.fill(r)
|
||||
ctx.restoreGState()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// a row's machine-font glyphs at the font's size, stretched over it
|
||||
private func drawGlyphs(_ vt: OpaquePointer, _ cells: [dmc_cell], _ ctx: CGContext) {
|
||||
var gw: Int32 = 8, gh: Int32 = 16
|
||||
if dmc_vt_glyph_cell(vt, &gw, &gh) == 0 {
|
||||
// (soft characters only: their own size)
|
||||
for c in cells where Int(c.flags) & Int(DMC_CELL_GLYPH) != 0 {
|
||||
if dmc_vt_glyph(vt, c.ch, &gw, &gh) != 0 { break }
|
||||
}
|
||||
}
|
||||
let n = cells.count, W = n * Int(gw), H = Int(gh)
|
||||
guard W > 0, H > 0 else { return }
|
||||
var px = [UInt32](repeating: 0, count: W * H)
|
||||
for (x, c) in cells.enumerated() {
|
||||
let f = Int(c.flags)
|
||||
var w: Int32 = 0, h: Int32 = 0
|
||||
if f & Int(DMC_CELL_GLYPH) == 0 || f & Int(DMC_CELL_INVISIBLE) != 0 ||
|
||||
(f & Int(DMC_CELL_BLINK) != 0 && blinkOff) ||
|
||||
dmc_vt_glyph(vt, c.ch, &w, &h) == 0 || w <= 0 || h <= 0 { continue }
|
||||
let span = f & Int(DMC_CELL_WIDE) != 0 && x + 1 < n ? 2 : 1
|
||||
let fg = 0xff00_0000 | (c.fg & 0xffffff)
|
||||
let cellW = Int(gw) * span
|
||||
for y in 0..<H {
|
||||
let bits = dmc_vt_glyph_row(vt, c.ch, Int32(y * Int(h) / H))
|
||||
if bits == 0 { continue }
|
||||
for i in 0..<cellW where x * Int(gw) + i < W {
|
||||
let gx = i * Int(w) / cellW
|
||||
if (bits >> UInt32(Int(w) - 1 - gx)) & 1 != 0 {
|
||||
px[y * W + x * Int(gw) + i] = fg
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let img = px.withUnsafeBufferPointer { Self.image($0.baseAddress!, W, H) }
|
||||
if let img {
|
||||
Self.draw(img, in: CGRect(x: 0, y: 0, width: CGFloat(n) * cell.width, height: cell.height), ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - the mouse
|
||||
|
||||
private func send(_ buf: [CChar], _ n: Int32) {
|
||||
guard n > 0 else { return }
|
||||
host?.send(buf[0..<Int(n)].map { UInt8(bitPattern: $0) })
|
||||
}
|
||||
|
||||
private func mods(_ f: NSEvent.ModifierFlags) -> Int32 {
|
||||
var m: Int32 = 0
|
||||
if f.contains(.shift) { m |= Int32(DMC_MOD_SHIFT) }
|
||||
if f.contains(.option) { m |= Int32(DMC_MOD_ALT) }
|
||||
if f.contains(.control) { m |= Int32(DMC_MOD_CTRL) }
|
||||
return m
|
||||
}
|
||||
|
||||
private func mouseReport(_ e: NSEvent, _ button: Int, press: Bool, motion: Bool) -> Bool {
|
||||
guard let vt = host?.vt, dmc_vt_mouse_wanted(vt) != 0 else { return false }
|
||||
let p = convert(e.locationInWindow, from: nil)
|
||||
let col = max(0, Int((p.x - origin.x) / cell.width)), row = max(0, Int((p.y - origin.y) / cell.height))
|
||||
var buf = [CChar](repeating: 0, count: 64)
|
||||
let n = dmc_vt_mouse(vt, Int32(button), Int32(col), Int32(row), press ? 1 : 0, motion ? 1 : 0,
|
||||
mods(e.modifierFlags), &buf, Int32(buf.count))
|
||||
send(buf, n)
|
||||
return true
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
window?.makeFirstResponder(self)
|
||||
buttons |= 1
|
||||
if mouseReport(event, 0, press: true, motion: false) { return }
|
||||
// a RIPscrip button's
|
||||
guard let vt = host?.vt else { return }
|
||||
let p = convert(event.locationInWindow, from: nil)
|
||||
let fx = Double((p.x - origin.x) / (CGFloat(dmc_vt_cols(vt)) * cell.width))
|
||||
let fy = Double((p.y - origin.y) / (CGFloat(dmc_vt_rows(vt)) * cell.height))
|
||||
var buf = [CChar](repeating: 0, count: 256)
|
||||
let n = dmc_vt_tap(vt, fx, fy, &buf, Int32(buf.count))
|
||||
if n > 0 {
|
||||
scroll = 0
|
||||
send(buf, n)
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseUp(with event: NSEvent) {
|
||||
buttons &= ~1
|
||||
_ = mouseReport(event, 0, press: false, motion: false)
|
||||
}
|
||||
|
||||
override func mouseDragged(with event: NSEvent) {
|
||||
_ = mouseReport(event, 0, press: true, motion: true)
|
||||
}
|
||||
|
||||
override func rightMouseDown(with event: NSEvent) {
|
||||
if mouseReport(event, 2, press: true, motion: false) {
|
||||
buttons |= 4
|
||||
return
|
||||
}
|
||||
super.rightMouseDown(with: event)
|
||||
}
|
||||
|
||||
override func rightMouseUp(with event: NSEvent) {
|
||||
if buttons & 4 != 0 {
|
||||
buttons &= ~4
|
||||
_ = mouseReport(event, 2, press: false, motion: false)
|
||||
}
|
||||
}
|
||||
|
||||
override func menu(for event: NSEvent) -> NSMenu? {
|
||||
if let vt = host?.vt, dmc_vt_mouse_wanted(vt) != 0 { return nil }
|
||||
let m = NSMenu()
|
||||
m.addItem(withTitle: "Paste", action: #selector(paste(_:)), keyEquivalent: "")
|
||||
return m
|
||||
}
|
||||
|
||||
override func scrollWheel(with event: NSEvent) {
|
||||
guard let vt = host?.vt else { return }
|
||||
if event.scrollingDeltaY != 0 &&
|
||||
mouseReport(event, event.scrollingDeltaY > 0 ? 64 : 65, press: true, motion: false) { 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 vt = host?.vt else { return }
|
||||
let flags = event.modifierFlags
|
||||
if flags.contains(.command) {
|
||||
super.keyDown(with: event)
|
||||
return
|
||||
}
|
||||
scroll = 0
|
||||
let m = mods(flags)
|
||||
var buf = [CChar](repeating: 0, count: 64)
|
||||
if let k = special(event) {
|
||||
let n = dmc_vt_key_mods(vt, Int32(k), m, &buf, Int32(buf.count))
|
||||
send(buf, n)
|
||||
return
|
||||
}
|
||||
// Control and Option (as Meta) with a key: the terminal's controls,
|
||||
// ESC and it
|
||||
if m & Int32(DMC_MOD_CTRL | DMC_MOD_ALT) != 0,
|
||||
let c = event.charactersIgnoringModifiers?.unicodeScalars.first {
|
||||
let n = dmc_vt_char_bytes(vt, c.value, m & Int32(DMC_MOD_CTRL | DMC_MOD_ALT), &buf, Int32(buf.count))
|
||||
send(buf, n)
|
||||
return
|
||||
}
|
||||
guard let s = event.characters else { return }
|
||||
for c in s.unicodeScalars {
|
||||
let n = dmc_vt_char_bytes(vt, c.value, 0, &buf, Int32(buf.count))
|
||||
send(buf, n)
|
||||
}
|
||||
}
|
||||
|
||||
private func special(_ e: NSEvent) -> Int? {
|
||||
switch Int(e.keyCode) {
|
||||
case 36: return Int(DMC_KEY_ENTER)
|
||||
case 76: return Int(DMC_KEY_KP_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
|
||||
case NSF11FunctionKey: return Int(DMC_KEY_F11)
|
||||
case NSF12FunctionKey: return Int(DMC_KEY_F12)
|
||||
case NSF13FunctionKey...NSF20FunctionKey:
|
||||
return Int(DMC_KEY_F13) + Int(c.value) - NSF13FunctionKey
|
||||
case NSFindFunctionKey: return Int(DMC_KEY_FIND)
|
||||
case NSSelectFunctionKey: return Int(DMC_KEY_SELECT)
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
@objc func paste(_ sender: Any?) {
|
||||
guard let vt = host?.vt, let s = NSPasteboard.general.string(forType: .string) else { return }
|
||||
let bracket = dmc_vt_bracketed_paste(vt) != 0
|
||||
var out: [UInt8] = bracket ? Array("\u{1b}[200~".utf8) : []
|
||||
var buf = [CChar](repeating: 0, count: 64)
|
||||
// lines end in CR, as a terminal sends them
|
||||
let text = s.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r")
|
||||
for c in text.unicodeScalars {
|
||||
let n = dmc_vt_char_bytes(vt, c.value, 0, &buf, Int32(buf.count))
|
||||
if n > 0 { out += buf[0..<Int(n)].map { UInt8(bitPattern: $0) } }
|
||||
}
|
||||
if bracket { out += Array("\u{1b}[201~".utf8) }
|
||||
scroll = 0
|
||||
host?.send(out)
|
||||
}
|
||||
}
|
||||
@@ -1,694 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 D-Modem Authors
|
||||
//
|
||||
// Voice.swift - the Phone page: voice calls dialled and answered, their
|
||||
// sound on the Mac's microphone and speakers (AVAudioEngine), the
|
||||
// keypad's DTMF; the answering machine (off until the user turns it on),
|
||||
// its greeting and the messages it took, kept as WAV files in
|
||||
// ~/Library/Application Support/D-Modem/Voicemail
|
||||
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import UserNotifications
|
||||
|
||||
/// Samples between the sound card's thread and the main one, the newest
|
||||
/// `capacity` of them kept.
|
||||
final class SampleQueue {
|
||||
private var buf: [Float]
|
||||
private var head = 0
|
||||
private var count = 0
|
||||
private let lock = NSLock()
|
||||
|
||||
init(capacity: Int) {
|
||||
buf = [Float](repeating: 0, count: capacity)
|
||||
}
|
||||
|
||||
func push(_ x: UnsafeBufferPointer<Float>) {
|
||||
lock.lock()
|
||||
for v in x {
|
||||
if count == buf.count {
|
||||
head = (head + 1) % buf.count
|
||||
count -= 1
|
||||
}
|
||||
buf[(head + count) % buf.count] = v
|
||||
count += 1
|
||||
}
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// up to n into p: how many
|
||||
func pop(into p: UnsafeMutablePointer<Float>, _ n: Int) -> Int {
|
||||
lock.lock()
|
||||
let k = min(n, count)
|
||||
for i in 0..<k {
|
||||
p[i] = buf[head]
|
||||
head = (head + 1) % buf.count
|
||||
}
|
||||
count -= k
|
||||
lock.unlock()
|
||||
return k
|
||||
}
|
||||
|
||||
var available: Int {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return count
|
||||
}
|
||||
|
||||
func clear() {
|
||||
lock.lock()
|
||||
head = 0
|
||||
count = 0
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sound card at the line's own rate, 8 kHz mono: the engine's mixer
|
||||
/// and a converter make it the hardware's.
|
||||
final class AudioIO {
|
||||
let speaker = SampleQueue(capacity: Int(DMC_VOICE_RATE))
|
||||
let mic = SampleQueue(capacity: Int(DMC_VOICE_RATE))
|
||||
private var engine: AVAudioEngine?
|
||||
private var tapped = false
|
||||
private let format = AVAudioFormat(commonFormat: .pcmFormatFloat32,
|
||||
sampleRate: Double(DMC_VOICE_RATE),
|
||||
channels: 1, interleaved: false)!
|
||||
|
||||
var running: Bool { engine != nil }
|
||||
|
||||
/// the speaker from `speaker`, the microphone into `mic`: false if
|
||||
/// there is no sound
|
||||
func start(play: Bool, record: Bool) -> Bool {
|
||||
stop()
|
||||
let e = AVAudioEngine()
|
||||
let fmt = format
|
||||
if play {
|
||||
let q = speaker
|
||||
let src = AVAudioSourceNode(format: fmt) { _, _, frames, abl -> OSStatus in
|
||||
let list = UnsafeMutableAudioBufferListPointer(abl)
|
||||
guard let p = list[0].mData?.assumingMemoryBound(to: Float.self) else { return noErr }
|
||||
let n = Int(frames)
|
||||
let got = q.pop(into: p, n)
|
||||
var i = got
|
||||
while i < n {
|
||||
p[i] = 0
|
||||
i += 1
|
||||
}
|
||||
return noErr
|
||||
}
|
||||
e.attach(src)
|
||||
e.connect(src, to: e.mainMixerNode, format: fmt)
|
||||
}
|
||||
if record {
|
||||
let input = e.inputNode
|
||||
let hw = input.outputFormat(forBus: 0)
|
||||
guard hw.sampleRate > 0, hw.channelCount > 0,
|
||||
let conv = AVAudioConverter(from: hw, to: fmt) else { return false }
|
||||
let q = mic
|
||||
input.installTap(onBus: 0, bufferSize: 1024, format: hw) { buffer, _ in
|
||||
let cap = AVAudioFrameCount(Double(buffer.frameLength) * fmt.sampleRate / hw.sampleRate) + 32
|
||||
guard let out = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: cap) else { return }
|
||||
var given = false
|
||||
var err: NSError?
|
||||
_ = conv.convert(to: out, error: &err) { _, status in
|
||||
if given {
|
||||
status.pointee = .noDataNow
|
||||
return nil
|
||||
}
|
||||
given = true
|
||||
status.pointee = .haveData
|
||||
return buffer
|
||||
}
|
||||
if let d = out.floatChannelData?[0], out.frameLength > 0 {
|
||||
q.push(UnsafeBufferPointer(start: d, count: Int(out.frameLength)))
|
||||
}
|
||||
}
|
||||
tapped = true
|
||||
}
|
||||
do {
|
||||
e.prepare()
|
||||
try e.start()
|
||||
} catch {
|
||||
if tapped { e.inputNode.removeTap(onBus: 0) }
|
||||
tapped = false
|
||||
return false
|
||||
}
|
||||
engine = e
|
||||
return true
|
||||
}
|
||||
|
||||
func stop() {
|
||||
if let e = engine {
|
||||
if tapped { e.inputNode.removeTap(onBus: 0) }
|
||||
e.stop()
|
||||
}
|
||||
tapped = false
|
||||
engine = nil
|
||||
speaker.clear()
|
||||
mic.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/// A message the answering machine took.
|
||||
struct VoiceMessage: Identifiable {
|
||||
var url: URL
|
||||
var who: String
|
||||
var date: Date
|
||||
var seconds: Int
|
||||
var id: URL { url }
|
||||
}
|
||||
|
||||
final class Voice: ObservableObject {
|
||||
weak var modem: Modem?
|
||||
let audio = AudioIO()
|
||||
|
||||
@Published var voicemail: Bool {
|
||||
didSet { save(); configure() }
|
||||
}
|
||||
@Published var rings: Int {
|
||||
didSet { save(); configure() }
|
||||
}
|
||||
@Published var muted = false
|
||||
@Published var listening = false {
|
||||
didSet { modem.map { sound(Int($0.state)) } }
|
||||
}
|
||||
@Published private(set) var messages: [VoiceMessage] = []
|
||||
@Published private(set) var greetingSeconds = 0
|
||||
@Published private(set) var recording = false
|
||||
/// what plays: a message's file, or the greeting's
|
||||
@Published private(set) var playing: URL?
|
||||
|
||||
private let maxSeconds: Int
|
||||
private var greeting: [Int16] = []
|
||||
private var playBuf: [Int16] = []
|
||||
private var playPos = 0
|
||||
private var recBuf: [Int16] = []
|
||||
private var timer: Timer?
|
||||
private var lastState = Int(DMC_CLOSED)
|
||||
private var listenOn = false
|
||||
|
||||
/// the longest greeting recorded (s)
|
||||
private static let greetingMax = 30
|
||||
private static let defaults = UserDefaults.standard
|
||||
|
||||
init() {
|
||||
let d = Voice.defaults
|
||||
voicemail = d.bool(forKey: "voicemail")
|
||||
let r = d.integer(forKey: "voicemailRings")
|
||||
rings = (1...15).contains(r) ? r : 4
|
||||
let m = d.integer(forKey: "voicemailMaxSeconds")
|
||||
maxSeconds = m >= 10 ? m : 120
|
||||
loadGreeting()
|
||||
refreshMessages()
|
||||
}
|
||||
|
||||
private func save() {
|
||||
let d = Voice.defaults
|
||||
d.set(voicemail, forKey: "voicemail")
|
||||
d.set(rings, forKey: "voicemailRings")
|
||||
}
|
||||
|
||||
// MARK: - files
|
||||
|
||||
private static var dir: URL {
|
||||
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("D-Modem")
|
||||
}
|
||||
private static var messagesDir: URL { dir.appendingPathComponent("Voicemail") }
|
||||
static var greetingURL: URL { dir.appendingPathComponent("greeting.wav") }
|
||||
|
||||
static func writeWav(_ pcm: [Int16], to url: URL) throws {
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true)
|
||||
var head = [CChar](repeating: 0, count: 44)
|
||||
dmc_wav_header(&head, Int32(pcm.count))
|
||||
var d = Data(head.map { UInt8(bitPattern: $0) })
|
||||
d.reserveCapacity(44 + pcm.count * 2)
|
||||
for v in pcm {
|
||||
let u = UInt16(bitPattern: v)
|
||||
d.append(UInt8(u & 0xff))
|
||||
d.append(UInt8(u >> 8))
|
||||
}
|
||||
try d.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
/// a sound file's samples at 8 kHz, mono: WAV, AIFF and .au by the
|
||||
/// library, the rest (MP3, AAC/M4A, FLAC, ALAC, CAF) by the Mac's own
|
||||
/// decoders; nil if it is not one D-Modem reads
|
||||
static func readWav(_ url: URL) -> [Int16]? {
|
||||
guard let d = try? Data(contentsOf: url), d.count < Int(Int32.max) else { return nil }
|
||||
var pcm: UnsafeMutablePointer<Int16>?
|
||||
let n = d.withUnsafeBytes { b in
|
||||
dmc_audio_decode(b.baseAddress?.assumingMemoryBound(to: CChar.self),
|
||||
Int32(b.count), &pcm)
|
||||
}
|
||||
defer { dmc_free(pcm) }
|
||||
guard n >= 0, let p = pcm else { return readBySystem(url) }
|
||||
return Array(UnsafeBufferPointer(start: p, count: Int(n)))
|
||||
}
|
||||
|
||||
/// a sound file the system decodes, as samples at 8 kHz, mono (five
|
||||
/// minutes at most); nil if it can't
|
||||
static func readBySystem(_ url: URL, maxSeconds: Int = 300) -> [Int16]? {
|
||||
guard let f = try? AVAudioFile(forReading: url) else { return nil }
|
||||
let src = f.processingFormat
|
||||
guard src.sampleRate > 0, src.channelCount > 0,
|
||||
let dst = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false),
|
||||
let conv = AVAudioConverter(from: src, to: dst),
|
||||
let inBuf = AVAudioPCMBuffer(pcmFormat: src, frameCapacity: 4096),
|
||||
let outBuf = AVAudioPCMBuffer(pcmFormat: dst, frameCapacity: AVAudioFrameCount(4096 * 8000 / src.sampleRate) + 64)
|
||||
else { return nil }
|
||||
// (the channels mixed, not the first alone)
|
||||
conv.downmix = true
|
||||
var out: [Int16] = []
|
||||
var ended = false
|
||||
while out.count < maxSeconds * 8000 {
|
||||
outBuf.frameLength = 0
|
||||
var err: NSError?
|
||||
let st = conv.convert(to: outBuf, error: &err) { _, status in
|
||||
if !ended {
|
||||
do { try f.read(into: inBuf) } catch { inBuf.frameLength = 0 }
|
||||
ended = inBuf.frameLength == 0
|
||||
}
|
||||
if ended {
|
||||
status.pointee = .endOfStream
|
||||
return nil
|
||||
}
|
||||
status.pointee = .haveData
|
||||
return inBuf
|
||||
}
|
||||
if let x = outBuf.floatChannelData?[0] {
|
||||
for i in 0..<Int(outBuf.frameLength) {
|
||||
out.append(Int16(max(-32768, min(32767, x[i] * 32767))))
|
||||
}
|
||||
}
|
||||
if st == .error || st == .endOfStream { break }
|
||||
}
|
||||
return out.isEmpty ? nil : out
|
||||
}
|
||||
|
||||
private func loadGreeting() {
|
||||
greeting = Voice.readWav(Voice.greetingURL) ?? []
|
||||
greetingSeconds = (greeting.count + Int(DMC_VOICE_RATE) / 2) / Int(DMC_VOICE_RATE)
|
||||
}
|
||||
|
||||
/// the answering machine's settings to the session
|
||||
func configure() {
|
||||
guard let s = modem?.session else { return }
|
||||
greeting.withUnsafeBufferPointer { g in
|
||||
dmc_voicemail_set(s, g.baseAddress, Int32(g.count), Int32(maxSeconds), 0)
|
||||
}
|
||||
dmc_voicemail_auto(s, voicemail ? Int32(rings) : 0)
|
||||
}
|
||||
|
||||
func refreshMessages() {
|
||||
let fm = FileManager.default
|
||||
let names = (try? fm.contentsOfDirectory(atPath: Voice.messagesDir.path)) ?? []
|
||||
let parse = DateFormatter()
|
||||
parse.dateFormat = "yyyyMMdd-HHmmss"
|
||||
parse.locale = Locale(identifier: "en_US_POSIX")
|
||||
messages = names.filter { $0.hasSuffix(".wav") }.sorted(by: >).compactMap { name in
|
||||
// 20261111-120501_5551234.wav
|
||||
let base = String(name.dropLast(4))
|
||||
let parts = base.split(separator: "_", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
guard let stamp = parts.first, let date = parse.date(from: String(stamp)) else { return nil }
|
||||
let who = parts.count > 1 ? String(parts[1]) : ""
|
||||
let url = Voice.messagesDir.appendingPathComponent(name)
|
||||
let size = (try? fm.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
|
||||
return VoiceMessage(url: url, who: who.isEmpty ? "Unknown caller" : who, date: date,
|
||||
seconds: max(0, (size - 44) / (2 * Int(DMC_VOICE_RATE))))
|
||||
}
|
||||
}
|
||||
|
||||
/// the message the answering machine took, kept
|
||||
private func saveMessage(from number: String) {
|
||||
guard let s = modem?.session else { return }
|
||||
var p: UnsafePointer<Int16>?
|
||||
let n = dmc_voice_message(s, &p)
|
||||
guard n > 0, let p else { return }
|
||||
let pcm = Array(UnsafeBufferPointer(start: p, count: Int(n)))
|
||||
let who = String(number.filter { $0.isLetter || $0.isNumber || $0 == "+" || $0 == "#" }.prefix(32))
|
||||
let f = DateFormatter()
|
||||
f.dateFormat = "yyyyMMdd-HHmmss"
|
||||
f.locale = Locale(identifier: "en_US_POSIX")
|
||||
let url = Voice.messagesDir.appendingPathComponent("\(f.string(from: Date()))_\(who).wav")
|
||||
do {
|
||||
try Voice.writeWav(pcm, to: url)
|
||||
} catch {
|
||||
modem?.say("Can't keep the message: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
modem?.addLog("The answering machine took a message.")
|
||||
refreshMessages()
|
||||
let c = UNMutableNotificationContent()
|
||||
c.title = "New voice message"
|
||||
c.body = "From " + (who.isEmpty ? "an unknown caller" : who)
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.requestAuthorization(options: [.alert, .sound]) { ok, _ in
|
||||
guard ok else { return }
|
||||
center.add(UNNotificationRequest(identifier: "voicemail", content: c, trigger: nil))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - what the session does
|
||||
|
||||
/// the session's events of voice calls
|
||||
func event(_ type: Int, text: String, ok: Bool) {
|
||||
if type == Int(DMC_EV_MESSAGE) {
|
||||
if ok { saveMessage(from: text) }
|
||||
} else if type == Int(DMC_EV_VOICE) {
|
||||
if text == "b" { modem?.say("Busy") }
|
||||
if text == "l" && lastState != Int(DMC_VOICEMAIL) { modem?.say("The other end hung up") }
|
||||
}
|
||||
}
|
||||
|
||||
/// the sound as the call needs it: both ways in a call; the caller (if
|
||||
/// listening) while the answering machine has the call
|
||||
func sound(_ st: Int) {
|
||||
let was = lastState
|
||||
let inCall = st == Int(DMC_VOICE) || st == Int(DMC_VOICEMAIL)
|
||||
let listen = st == Int(DMC_VOICEMAIL) && listening
|
||||
if st == Int(DMC_VOICE) && was != Int(DMC_VOICE) {
|
||||
stopSound()
|
||||
listenOn = false
|
||||
if !audio.start(play: true, record: true) {
|
||||
modem?.say("No sound: allow D-Modem the microphone in System Settings")
|
||||
}
|
||||
} else if listen && !listenOn {
|
||||
_ = audio.start(play: true, record: false)
|
||||
listenOn = true
|
||||
} else if !listen && listenOn {
|
||||
audio.stop()
|
||||
listenOn = false
|
||||
} else if was == Int(DMC_VOICE) && st != Int(DMC_VOICE) {
|
||||
audio.stop()
|
||||
}
|
||||
lastState = st
|
||||
tick(inCall || playing != nil || recording)
|
||||
}
|
||||
|
||||
/// the 20 ms tick that a call, a playback or a recording needs
|
||||
private func tick(_ on: Bool) {
|
||||
if on && timer == nil {
|
||||
let t = Timer(timeInterval: 0.02, repeats: true) { [weak self] _ in
|
||||
self?.modem?.pump()
|
||||
}
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
timer = t
|
||||
} else if !on, let t = timer {
|
||||
t.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// before the session runs: the microphone's samples to it (or to the
|
||||
/// greeting being recorded)
|
||||
func beforePoll() {
|
||||
guard audio.running else { return }
|
||||
var f = [Float](repeating: 0, count: 512)
|
||||
while true {
|
||||
let n = f.withUnsafeMutableBufferPointer { audio.mic.pop(into: $0.baseAddress!, 512) }
|
||||
if n <= 0 { break }
|
||||
let pcm = f[0..<n].map { Int16(max(-32768, min(32767, $0 * 32767))) }
|
||||
if recording {
|
||||
let room = Voice.greetingMax * Int(DMC_VOICE_RATE) - recBuf.count
|
||||
recBuf += pcm.prefix(max(0, room))
|
||||
} else if lastState == Int(DMC_VOICE), !muted, let s = modem?.session {
|
||||
pcm.withUnsafeBufferPointer { dmc_voice_write(s, $0.baseAddress, Int32($0.count)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// after: the far end's samples to the speaker, or the next of what
|
||||
/// plays
|
||||
func afterPoll() {
|
||||
if playing != nil {
|
||||
let want = Int(DMC_VOICE_RATE) / 4
|
||||
while audio.speaker.available < want && playPos < playBuf.count {
|
||||
let k = min(512, playBuf.count - playPos)
|
||||
let f = playBuf[playPos..<(playPos + k)].map { Float($0) / 32768 }
|
||||
f.withUnsafeBufferPointer { audio.speaker.push($0) }
|
||||
playPos += k
|
||||
}
|
||||
if playPos >= playBuf.count && audio.speaker.available == 0 {
|
||||
stopSound()
|
||||
}
|
||||
return
|
||||
}
|
||||
guard audio.running, let s = modem?.session else { return }
|
||||
var pcm = [Int16](repeating: 0, count: 512)
|
||||
while true {
|
||||
let n = Int(dmc_voice_read(s, &pcm, 512))
|
||||
if n <= 0 { break }
|
||||
let f = pcm[0..<n].map { Float($0) / 32768 }
|
||||
f.withUnsafeBufferPointer { audio.speaker.push($0) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - what the page does
|
||||
|
||||
func stopSound() {
|
||||
audio.stop()
|
||||
playing = nil
|
||||
playBuf = []
|
||||
playPos = 0
|
||||
recording = false
|
||||
recBuf = []
|
||||
listenOn = false
|
||||
tick(lastState == Int(DMC_VOICE) || lastState == Int(DMC_VOICEMAIL))
|
||||
}
|
||||
|
||||
private func play(_ pcm: [Int16], _ url: URL) {
|
||||
stopSound()
|
||||
playBuf = pcm
|
||||
playPos = 0
|
||||
guard audio.start(play: true, record: false) else {
|
||||
modem?.say("No sound to play it on")
|
||||
return
|
||||
}
|
||||
playing = url
|
||||
tick(true)
|
||||
}
|
||||
|
||||
func play(_ m: VoiceMessage) {
|
||||
if playing == m.url {
|
||||
stopSound()
|
||||
return
|
||||
}
|
||||
guard let pcm = Voice.readWav(m.url) else {
|
||||
modem?.say("Can't read the message")
|
||||
return
|
||||
}
|
||||
play(pcm, m.url)
|
||||
}
|
||||
|
||||
func delete(_ m: VoiceMessage) {
|
||||
if playing == m.url { stopSound() }
|
||||
try? FileManager.default.removeItem(at: m.url)
|
||||
refreshMessages()
|
||||
}
|
||||
|
||||
func playGreeting() {
|
||||
if playing == Voice.greetingURL {
|
||||
stopSound()
|
||||
return
|
||||
}
|
||||
if !greeting.isEmpty { play(greeting, Voice.greetingURL) }
|
||||
}
|
||||
|
||||
func recordGreeting() {
|
||||
if recording {
|
||||
let pcm = recBuf
|
||||
stopSound()
|
||||
if pcm.count > Int(DMC_VOICE_RATE) / 2 {
|
||||
do {
|
||||
try Voice.writeWav(pcm, to: Voice.greetingURL)
|
||||
} catch {
|
||||
modem?.say("Can't keep the greeting: \(error.localizedDescription)")
|
||||
}
|
||||
loadGreeting()
|
||||
configure()
|
||||
}
|
||||
return
|
||||
}
|
||||
stopSound()
|
||||
recBuf = []
|
||||
guard audio.start(play: false, record: true) else {
|
||||
modem?.say("No microphone: allow D-Modem the microphone in System Settings")
|
||||
return
|
||||
}
|
||||
recording = true
|
||||
tick(true)
|
||||
}
|
||||
|
||||
func chooseGreeting() {
|
||||
let p = NSOpenPanel()
|
||||
p.title = "Greeting"
|
||||
p.allowedContentTypes = [UTType.audio]
|
||||
p.allowsMultipleSelection = false
|
||||
guard p.runModal() == .OK, let url = p.url else { return }
|
||||
guard let pcm = Voice.readWav(url), !pcm.isEmpty else {
|
||||
modem?.say("That isn't a sound file D-Modem can play")
|
||||
return
|
||||
}
|
||||
do {
|
||||
try Voice.writeWav(pcm, to: Voice.greetingURL)
|
||||
} catch {
|
||||
modem?.say("Can't keep the greeting: \(error.localizedDescription)")
|
||||
}
|
||||
loadGreeting()
|
||||
configure()
|
||||
}
|
||||
|
||||
func clearGreeting() {
|
||||
if playing == Voice.greetingURL { stopSound() }
|
||||
try? FileManager.default.removeItem(at: Voice.greetingURL)
|
||||
loadGreeting()
|
||||
configure()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - the page
|
||||
|
||||
struct PhonePage: View {
|
||||
@EnvironmentObject var modem: Modem
|
||||
@EnvironmentObject var voice: Voice
|
||||
@State private var number = ""
|
||||
|
||||
private var st: Int { modem.state }
|
||||
|
||||
private var status: String {
|
||||
let who = modem.callerNumber
|
||||
switch st {
|
||||
case Int(DMC_CLOSED): return "The modem isn't running"
|
||||
case Int(DMC_RINGING): return who.isEmpty ? "Ringing" : "Ringing: \(who)"
|
||||
case Int(DMC_VOICE): return "In a call"
|
||||
case Int(DMC_VOICEMAIL): return who.isEmpty ? "Taking a message" : "Taking a message from \(who)"
|
||||
default: return modem.stateName
|
||||
}
|
||||
}
|
||||
|
||||
private let keys = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["*", "0", "#"]]
|
||||
|
||||
private func key(_ k: String) {
|
||||
if st == Int(DMC_VOICE) {
|
||||
modem.dtmf(k)
|
||||
} else {
|
||||
number += k
|
||||
}
|
||||
}
|
||||
|
||||
private static let when: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.dateStyle = .medium
|
||||
f.timeStyle = .short
|
||||
return f
|
||||
}()
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
LabeledContent("Phone", value: status)
|
||||
HStack {
|
||||
TextField("Number to call", text: $number, prompt: Text("number or sip:user@host"))
|
||||
.onSubmit { if modem.isIdle { modem.voiceDial(number) } }
|
||||
Button("Call") { modem.voiceDial(number) }
|
||||
.disabled(!modem.isIdle)
|
||||
}
|
||||
HStack {
|
||||
Button("Answer") { voice.stopSound(); modem.voiceAnswer() }
|
||||
.disabled(st != Int(DMC_RINGING))
|
||||
Button("Take a Message") { voice.stopSound(); modem.voicemailAnswer() }
|
||||
.disabled(st != Int(DMC_RINGING))
|
||||
if st == Int(DMC_VOICEMAIL) {
|
||||
Button("Pick Up") { modem.pickUp() }
|
||||
.help("Talk to the caller yourself")
|
||||
Toggle("Listen", isOn: $voice.listening)
|
||||
.help("Hear the caller leave the message")
|
||||
}
|
||||
Spacer()
|
||||
Toggle("Mute", isOn: $voice.muted)
|
||||
.disabled(st != Int(DMC_VOICE))
|
||||
Button("Hang Up", role: .destructive) { modem.hangUp() }
|
||||
.disabled(![DMC_VOICE, DMC_VOICEMAIL, DMC_DIALING, DMC_ANSWERING]
|
||||
.map { Int($0) }.contains(st))
|
||||
}
|
||||
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
|
||||
ForEach(keys, id: \.self) { row in
|
||||
GridRow {
|
||||
ForEach(row, id: \.self) { k in
|
||||
Button { key(k) } label: {
|
||||
Text(k).font(.title2.monospacedDigit()).frame(width: 48, height: 28)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.disabled(!(st == Int(DMC_VOICE) || st == Int(DMC_IDLE) || st == Int(DMC_CLOSED)))
|
||||
} header: {
|
||||
Text("Voice Call")
|
||||
} footer: {
|
||||
Text("Calls through the modem's voice mode, with the Mac's microphone and speakers.")
|
||||
}
|
||||
|
||||
Section {
|
||||
Toggle("Take messages", isOn: $voice.voicemail)
|
||||
Stepper("Rings before it answers: \(voice.rings)", value: $voice.rings, in: 1...15)
|
||||
.disabled(!voice.voicemail)
|
||||
LabeledContent("Greeting") {
|
||||
HStack {
|
||||
Text(voice.recording ? "Recording: speak, then Stop"
|
||||
: voice.greetingSeconds > 0 ? "Your recording (\(voice.greetingSeconds) s)"
|
||||
: "None: callers hear a beep")
|
||||
.foregroundStyle(.secondary)
|
||||
Button { voice.playGreeting() } label: {
|
||||
Image(systemName: voice.playing == Voice.greetingURL ? "stop.fill" : "play.fill")
|
||||
}
|
||||
.help("Play")
|
||||
.disabled(voice.greetingSeconds == 0 || voice.recording)
|
||||
Button(voice.recording ? "Stop" : "Record") { voice.recordGreeting() }
|
||||
.disabled(voice.playing != nil || st == Int(DMC_VOICE) || st == Int(DMC_VOICEMAIL))
|
||||
Button { voice.chooseGreeting() } label: { Image(systemName: "folder") }
|
||||
.help("Use a sound file")
|
||||
Button { voice.clearGreeting() } label: { Image(systemName: "trash") }
|
||||
.help("No greeting: the beep alone")
|
||||
.disabled(voice.greetingSeconds == 0 || voice.recording)
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
}
|
||||
} header: {
|
||||
Text("Answering Machine")
|
||||
} footer: {
|
||||
Text("It answers calls nobody picks up, plays the greeting and records. Messages are kept on this Mac only.")
|
||||
}
|
||||
|
||||
Section("Messages") {
|
||||
if voice.messages.isEmpty {
|
||||
Text("No messages").foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(voice.messages) { m in
|
||||
HStack {
|
||||
VStack(alignment: .leading) {
|
||||
Text(m.who)
|
||||
Text("\(PhonePage.when.string(from: m.date)) · \(m.seconds / 60):\(String(format: "%02d", m.seconds % 60))")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button { voice.play(m) } label: {
|
||||
Image(systemName: voice.playing == m.url ? "stop.fill" : "play.fill")
|
||||
}
|
||||
.help("Play")
|
||||
.disabled(voice.recording || st == Int(DMC_VOICE))
|
||||
Button { voice.delete(m) } label: { Image(systemName: "trash") }
|
||||
.help("Delete")
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
}
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
# The macOS app's Xcode project, made by XcodeGen. libssh and mbedTLS
|
||||
# (for libdmodemssh), and the built-in modem (libdmodem_embed, from the
|
||||
# submodule external/D-Modem), are built first by the repository's
|
||||
# CMake, for both architectures, into ../build. CMake also writes
|
||||
# ../build/macos-embed.xcconfig: the built-in modem's libraries, or
|
||||
# nothing when the build has no built-in modem.
|
||||
# cmake -S .. -B ../build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" \
|
||||
# -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build ../build
|
||||
# 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
|
||||
configFiles:
|
||||
Debug: ../build/macos-embed.xcconfig
|
||||
Release: ../build/macos-embed.xcconfig
|
||||
sources:
|
||||
- path: DModem
|
||||
- path: ../core/src
|
||||
buildPhase: sources
|
||||
- path: ../ssh/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 $(SRCROOT)/../ssh/include $(SRCROOT)/../build/dmodem-libssh/include $(DMODEM_EMBED_HEADERS)
|
||||
GCC_PREPROCESSOR_DEFINITIONS: LIBSSH_STATIC=1
|
||||
# libssh and mbedTLS, and the built-in modem, as CMake built them
|
||||
# (see above)
|
||||
LIBRARY_SEARCH_PATHS: $(SRCROOT)/../build/dmodem-libssh/lib
|
||||
OTHER_LDFLAGS: -lssh -lmbedtls -lmbedx509 -lmbedcrypto -leverest -lp256m $(DMODEM_EMBED_LDFLAGS)
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS: $(inherited) $(DMODEM_EMBED_SWIFT)
|
||||
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 Authors. AGPL-3.0-only.
|
||||
INFOPLIST_KEY_NSMicrophoneUsageDescription: D-Modem uses the microphone for voice calls and to record the answering machine's greeting.
|
||||
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,
|
||||
# or the built-in modem uses the network and USB: no sandbox
|
||||
ENABLE_APP_SANDBOX: NO
|
||||
# the microphone, for voice calls (the hardened runtime asks for it)
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT: YES
|
||||
entitlements:
|
||||
path: DModem/DModem.entitlements
|
||||
properties:
|
||||
com.apple.security.device.audio-input: true
|
||||
@@ -3,7 +3,7 @@ INHERIT: .site/mkdocs-base.yml
|
||||
# theme and workflow (brand's docs/sites.md). The site is built from a copy
|
||||
# of docs/ (.site/docs). docs/index.md is the home page of the site, and the
|
||||
# README stays the summary on GitHub.
|
||||
site_name: D-Modem desktop apps
|
||||
site_name: D-Modem desktop app
|
||||
site_description: D-Modem on the desktop, for Windows 95 to Windows 11, macOS and Linux
|
||||
site_url: https://d-modem.github.io/gui/
|
||||
repo_url: https://github.com/D-Modem/gui
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# libdmodemssh: D-Modem's SSH client (dmodemssh.h), on libssh 0.11.
|
||||
# The system's libssh when it is 0.11 or later (and
|
||||
# -DDMODEM_SSH_BUNDLED=OFF), else libssh and mbedTLS built here from
|
||||
# their release tarballs: always for the Windows and macOS apps, which
|
||||
# ship no libraries of the system's.
|
||||
# their release tarballs: always for the app on Windows and macOS, which
|
||||
# ships no libraries of the system's.
|
||||
if(WIN32 OR APPLE)
|
||||
set(_bundled ON)
|
||||
else()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Renders assets/dmodem.svg (D-Modem/brand's mark, avatar/org-avatar.svg, on a tile) to the
|
||||
// PNGs the apps' icons are made from, with Playwright's Chromium:
|
||||
// PNGs the app's icon is 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');
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Makes the apps' icon files from tools/icons.js's PNGs (build/icons):
|
||||
"""Makes the app's icon file 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
|
||||
|
||||
@@ -88,23 +86,5 @@ def ico(path):
|
||||
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'))
|
||||
@@ -3,9 +3,8 @@
|
||||
* Copyright (C) 2026 D-Modem Authors
|
||||
*
|
||||
* main.cpp - the main window: a tab for each page (Modem, Phone,
|
||||
* Terminal, Remote, Settings, Call Stats, Log, as the macOS
|
||||
* and Linux apps
|
||||
* have them) and a status bar
|
||||
* Terminal, Remote, Settings, Call Stats, Log) and a status
|
||||
* bar
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
@@ -102,3 +102,29 @@ if(APPLE)
|
||||
else()
|
||||
target_link_libraries(dmodem-win32 PRIVATE dl pthread)
|
||||
endif()
|
||||
|
||||
# The install on Linux (cmake --install): the app, its desktop entry,
|
||||
# its AppStream data and its icon. Also the firmware of the MultiTech
|
||||
# MT9234MU (the licence is unknown: firmware/README.md).
|
||||
if(UNIX AND NOT APPLE)
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS dmodem-win32 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)
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/firmware/mts_mt9234mu.fw
|
||||
${PROJECT_SOURCE_DIR}/firmware/README.md
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/dmodem-gui/firmware)
|
||||
option(DMODEM_GUI_INSTALL_FIRMWARE
|
||||
"Also install mts_mt9234mu.fw (and mts_mt9234zba.fw) in /lib/firmware" OFF)
|
||||
if(DMODEM_GUI_INSTALL_FIRMWARE)
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/firmware/mts_mt9234mu.fw
|
||||
DESTINATION /lib/firmware)
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/firmware/mts_mt9234mu.fw
|
||||
DESTINATION /lib/firmware RENAME mts_mt9234zba.fw)
|
||||
endif()
|
||||
endif()
|
||||
@@ -2,10 +2,10 @@
|
||||
Name=D-Modem
|
||||
GenericName=Softmodem
|
||||
Comment=Dial up over SIP, a USB modem or a softmodem codec
|
||||
Exec=dmodem-gui
|
||||
Exec=dmodem-win32
|
||||
Icon=io.github.d_modem.DModem
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Categories=Network;Dialup;GTK;
|
||||
Categories=Network;Dialup;
|
||||
Keywords=modem;dial-up;V.92;fax;SIP;AT;
|
||||
StartupNotify=true
|
||||