-# 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.
-
@@ -78,25 +78,24 @@ a USB modem or a hardware modem.
[All the features](features.md){ .md-button }
-

+

-## 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
diff --git a/linux/firmware/README.md b/firmware/README.md
similarity index 92%
rename from linux/firmware/README.md
rename to firmware/README.md
index 47e22db..b0de4b4 100644
--- a/linux/firmware/README.md
+++ b/firmware/README.md
@@ -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`,
diff --git a/linux/firmware/mts_mt9234mu.fw b/firmware/mts_mt9234mu.fw
similarity index 100%
rename from linux/firmware/mts_mt9234mu.fw
rename to firmware/mts_mt9234mu.fw
diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt
deleted file mode 100644
index 0445e63..0000000
--- a/linux/CMakeLists.txt
+++ /dev/null
@@ -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)
diff --git a/linux/src/app.h b/linux/src/app.h
deleted file mode 100644
index 3573fee..0000000
--- a/linux/src/app.h
+++ /dev/null
@@ -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
-
-#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
diff --git a/linux/src/audio.c b/linux/src/audio.c
deleted file mode 100644
index 2822cfe..0000000
--- a/linux/src/audio.c
+++ /dev/null
@@ -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
-
-#include "app.h"
-
-#ifdef HAVE_PULSE
-
-#include
-#include
-
-/* 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
diff --git a/linux/src/config.c b/linux/src/config.c
deleted file mode 100644
index 6a29ef1..0000000
--- a/linux/src/config.c
+++ /dev/null
@@ -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
-
-#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:@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));
-}
diff --git a/linux/src/main.c b/linux/src/main.c
deleted file mode 100644
index 0adee8a..0000000
--- a/linux/src/main.c
+++ /dev/null
@@ -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;
-}
diff --git a/linux/src/modem.c b/linux/src/modem.c
deleted file mode 100644
index d6eedab..0000000
--- a/linux/src/modem.c
+++ /dev/null
@@ -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
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-#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);
-}
diff --git a/linux/src/pathview.c b/linux/src/pathview.c
deleted file mode 100644
index 60d1ac4..0000000
--- a/linux/src/pathview.c
+++ /dev/null
@@ -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;
-}
diff --git a/linux/src/remote.c b/linux/src/remote.c
deleted file mode 100644
index 99a6660..0000000
--- a/linux/src/remote.c
+++ /dev/null
@@ -1,1256 +0,0 @@
-/*
- * SPDX-License-Identifier: AGPL-3.0-only
- * Copyright (C) 2026 D-Modem Authors
- *
- * remote.c - the Remote page: a login to a server by SSH, Telnet or
- * rlogin, in a terminal of its own, beside the modem's
- *
- * Telnet and rlogin are a TCP connection made here and libdmodemctl's
- * dmc_net for the protocol. SSH is libdmodemssh (the apps' own client,
- * on libssh) on a thread of its own, its events brought to the main
- * loop; 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 (an
- * ssh-agent's socket, SSH_AUTH_SOCK's or one given) or by a key file:
- * OpenSSH's, PEM or PuTTY's .ppk, which can also be imported into
- * ~/.ssh in OpenSSH's form. Either way the terminal only shows bytes
- * and gives what is typed.
- */
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "app.h"
-#include "dmodemssh.h"
-
-/* the protocols in the drop-down's order */
-static const int protos[] = { DMC_NET_SSH, DMC_NET_TELNET, DMC_NET_RLOGIN };
-
-typedef struct Remote {
- App *a;
- GtkWidget *proto, *host, *port, *user, *go, *status;
- /* how SSH logs in: its menu, the way, the key file, the agent */
- GtkWidget *login, *auth, *key_label, *agent, *agent_state;
- GtkWidget *term, *type;
- int cols, rows;
- /* what runs: its protocol (0: none) */
- int running;
- /* Telnet, rlogin: the socket and the protocol */
- GSocketClient *client;
- GCancellable *cancel;
- GSocketConnection *conn;
- GSocket *sock;
- GSource *in_src, *out_src;
- dmc_net *net;
- GByteArray *pending;
- /* SSH: the connection (its thread polls it), the shell's channel,
- the logins tried, a question's dialog */
- struct Ssh *ssh;
- int shell, tried, asks, exit_status;
- /* the methods the server last offered; the key file's text and the
- passphrases tried for it */
- int methods, key_tries;
- char *key_text;
- AdwDialog *dialog;
- guint size_tick;
-} Remote;
-
-static Remote *R;
-
-static void set_status(Remote *r, const char *text)
-{
- gtk_label_set_text(GTK_LABEL(r->status), text);
-}
-
-static void controls(Remote *r)
-{
- gboolean idle = !r->running;
- gtk_widget_set_sensitive(r->proto, idle);
- gtk_widget_set_sensitive(r->host, idle);
- gtk_widget_set_sensitive(r->port, idle);
- gtk_widget_set_sensitive(r->user, idle);
- if (r->login)
- gtk_widget_set_sensitive(r->login, idle);
- gtk_button_set_label(GTK_BUTTON(r->go), idle ? "Connect" : "Disconnect");
- if (idle) {
- gtk_widget_add_css_class(r->go, "suggested-action");
- gtk_widget_remove_css_class(r->go, "destructive-action");
- } else {
- gtk_widget_remove_css_class(r->go, "suggested-action");
- gtk_widget_add_css_class(r->go, "destructive-action");
- }
-}
-
-static void show(Remote *r, const char *data, gssize n)
-{
- termview_feed(r->term, data, n < 0 ? (int)strlen(data) : (int)n);
-}
-
-/* the key file's text let go of (wiped) */
-static void key_forget(Remote *r)
-{
- if (r->key_text) {
- memset(r->key_text, 0, strlen(r->key_text));
- g_clear_pointer(&r->key_text, g_free);
- }
-}
-
-static void ssh_disconnect(Remote *r);
-
-/* the connection over, with why (NULL: the user's doing) */
-static void ended(Remote *r, const char *why)
-{
- if (!r->running)
- return;
- r->running = 0;
- if (r->cancel) {
- g_cancellable_cancel(r->cancel);
- g_clear_object(&r->cancel);
- }
- if (r->in_src) {
- g_source_destroy(r->in_src);
- g_clear_pointer(&r->in_src, g_source_unref);
- }
- if (r->out_src) {
- g_source_destroy(r->out_src);
- g_clear_pointer(&r->out_src, g_source_unref);
- }
- if (r->conn)
- g_io_stream_close(G_IO_STREAM(r->conn), NULL, NULL);
- g_clear_object(&r->conn);
- r->sock = NULL;
- g_clear_object(&r->client);
- g_clear_pointer(&r->net, dmc_net_free);
- if (r->pending)
- g_byte_array_set_size(r->pending, 0);
- /* (the connection is freed once its thread has said it's closed) */
- if (r->ssh)
- ssh_disconnect(r);
- key_forget(r);
- r->shell = 0;
- if (r->size_tick)
- g_source_remove(r->size_tick);
- r->size_tick = 0;
- char *line = g_strdup_printf("\r\n\x1b[0m[%s]\r\n", why ? why :
- "Disconnected");
- show(r, line, -1);
- g_free(line);
- set_status(r, why ? why : "Disconnected");
- controls(r);
-}
-
-/*
- * Telnet and rlogin
- */
-
-static gboolean writable(GSocket *s, GIOCondition c, gpointer data);
-
-/* the protocol's output to the socket, as much as it takes now */
-static void flush(Remote *r)
-{
- char buf[4096];
- int n;
- while ((n = dmc_net_output(r->net, buf, sizeof(buf))) > 0)
- g_byte_array_append(r->pending, (guint8 *)buf, n);
- while (r->pending->len > 0) {
- GError *e = NULL;
- gssize w = g_socket_send(r->sock, (char *)r->pending->data,
- r->pending->len, NULL, &e);
- if (w < 0) {
- if (g_error_matches(e, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
- g_error_free(e);
- if (!r->out_src) {
- r->out_src = g_socket_create_source(
- r->sock, G_IO_OUT, NULL);
- g_source_set_callback(r->out_src,
- (GSourceFunc)(void (*)(void))writable,
- r, NULL);
- g_source_attach(r->out_src, NULL);
- }
- return;
- }
- char *why = g_strdup(e->message);
- g_error_free(e);
- ended(r, why);
- g_free(why);
- return;
- }
- g_byte_array_remove_range(r->pending, 0, (guint)w);
- }
-}
-
-static gboolean writable(GSocket *s, GIOCondition c, gpointer data)
-{
- Remote *r = data;
- (void)s;
- (void)c;
- g_clear_pointer(&r->out_src, g_source_unref);
- flush(r);
- return G_SOURCE_REMOVE;
-}
-
-static void pump(Remote *r)
-{
- char buf[8192];
- int n;
- while ((n = dmc_net_screen(r->net, buf, sizeof(buf))) > 0)
- show(r, buf, n);
- flush(r);
-}
-
-static gboolean readable(GSocket *s, GIOCondition c, gpointer data)
-{
- Remote *r = data;
- char buf[8192];
- /* rlogin's control byte, sent urgent */
- if (c & G_IO_PRI) {
- char b;
- if (recv(g_socket_get_fd(s), &b, 1, MSG_OOB) == 1)
- dmc_net_urgent(r->net, (unsigned char)b);
- }
- if (c & (G_IO_IN | G_IO_HUP | G_IO_ERR)) {
- GError *e = NULL;
- gssize n = g_socket_receive(s, buf, sizeof(buf), NULL, &e);
- if (n < 0 && g_error_matches(e, G_IO_ERROR,
- G_IO_ERROR_WOULD_BLOCK)) {
- g_error_free(e);
- } else if (n <= 0) {
- char *why = e ? g_strdup(e->message) :
- g_strdup("Connection closed by the server");
- g_clear_error(&e);
- pump(r);
- ended(r, why);
- g_free(why);
- return G_SOURCE_REMOVE;
- } else {
- dmc_net_feed(r->net, buf, (int)n);
- }
- }
- pump(r);
- return G_SOURCE_CONTINUE;
-}
-
-static void connected(GObject *src, GAsyncResult *res, gpointer data)
-{
- Remote *r = data;
- GError *e = NULL;
- GSocketConnection *c = g_socket_client_connect_to_host_finish(
- G_SOCKET_CLIENT(src), res, &e);
- if (!c) {
- /* (cancelled: ended() has said so) */
- if (!g_error_matches(e, G_IO_ERROR, G_IO_ERROR_CANCELLED))
- ended(r, e->message);
- g_error_free(e);
- return;
- }
- r->conn = c;
- r->sock = g_socket_connection_get_socket(c);
- g_socket_set_blocking(r->sock, FALSE);
- g_socket_set_option(r->sock, IPPROTO_TCP, TCP_NODELAY, 1, NULL);
- r->in_src = g_socket_create_source(r->sock, G_IO_IN | G_IO_PRI |
- G_IO_HUP | G_IO_ERR, NULL);
- g_source_set_callback(r->in_src, (GSourceFunc)(void (*)(void))readable,
- r, NULL);
- g_source_attach(r->in_src, NULL);
- set_status(r, "Connected");
- dmc_net_connected(r->net);
- pump(r);
-}
-
-/*
- * SSH: libdmodemssh, polled on a thread of its own
- */
-
-/* a connection and the thread that polls it */
-typedef struct Ssh {
- dmc_ssh *s;
- GThread *thread;
-} Ssh;
-
-/* one of its events, brought to the main loop */
-typedef struct SshEv {
- Remote *r;
- Ssh *ssh;
- int type, channel, value, len;
- char *data;
-} SshEv;
-
-static void ssh_ev_free(gpointer p)
-{
- SshEv *e = p;
- g_free(e->data);
- g_free(e);
-}
-
-static gboolean ssh_event(gpointer p);
-
-/* the connection polled until it's over, each event to the main loop */
-static gpointer ssh_poll(gpointer p)
-{
- SshEv *start = p;
- Remote *r = start->r;
- Ssh *ssh = start->ssh;
- dmc_ssh_event ev;
- int n;
-
- g_free(start);
- while ((n = dmc_ssh_poll(ssh->s, 1000, &ev)) >= 0) {
- if (n == 0)
- continue;
- SshEv *e = g_new0(SshEv, 1);
- e->r = r;
- e->ssh = ssh;
- e->type = ev.type;
- e->channel = ev.channel;
- e->value = ev.value;
- e->len = ev.len;
- e->data = ev.data ? g_memdup2(ev.data, (gsize)ev.len + 1) : NULL;
- g_main_context_invoke_full(NULL, G_PRIORITY_DEFAULT, ssh_event,
- e, ssh_ev_free);
- if (ev.type == DMC_SSH_EV_CLOSED)
- break;
- }
- return NULL;
-}
-
-/* a dialog of the login's closed: its answer, or none (cancel) */
-static void dialog_gone(Remote *r)
-{
- if (r->dialog) {
- AdwDialog *d = r->dialog;
- r->dialog = NULL;
- adw_dialog_force_close(d);
- }
-}
-
-/* the host key dialog answered */
-static void hostkey_answered(AdwAlertDialog *d, const char *response, gpointer data)
-{
- Remote *r = data;
- Ssh *ssh = g_object_get_data(G_OBJECT(d), "ssh");
- (void)d;
- r->dialog = NULL;
- if (ssh != r->ssh)
- return;
- dmc_ssh_trust(ssh->s, !strcmp(response, "connect"), 1);
-}
-
-/* the server's key: known goes on; new is asked; changed is refused */
-static void ssh_hostkey(Remote *r, const char *key, int known)
-{
- char fp[128] = "";
- dmc_ssh_fingerprint(key, fp, sizeof(fp));
- if (known == DMC_SSH_HOST_KNOWN) {
- dmc_ssh_trust(r->ssh->s, 1, 0);
- return;
- }
- if (known == DMC_SSH_HOST_CHANGED || known == DMC_SSH_HOST_OTHER_TYPE) {
- char *m = g_strdup_printf(
- "\r\n\x1b[1;31mThe server's host key has changed (it is now %.*s %s).\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.\x1b[0m\r\n",
- (int)strcspn(key, " "), key, fp);
- show(r, m, -1);
- g_free(m);
- dmc_ssh_trust(r->ssh->s, 0, 0);
- return;
- }
- char *body = g_strdup_printf(
- "This server is not known yet. Its key's fingerprint is\n\n%.*s %s\n\n"
- "If it's the one you expect, it will be added to ~/.ssh/known_hosts.",
- (int)strcspn(key, " "), key, fp);
- AdwDialog *d = adw_alert_dialog_new("Connect to a new server?", body);
- g_free(body);
- adw_alert_dialog_add_responses(ADW_ALERT_DIALOG(d), "cancel", "Cancel",
- "connect", "Connect", NULL);
- adw_alert_dialog_set_response_appearance(ADW_ALERT_DIALOG(d), "connect",
- ADW_RESPONSE_SUGGESTED);
- adw_alert_dialog_set_default_response(ADW_ALERT_DIALOG(d), "connect");
- adw_alert_dialog_set_close_response(ADW_ALERT_DIALOG(d), "cancel");
- g_object_set_data(G_OBJECT(d), "ssh", r->ssh);
- g_signal_connect(d, "response", G_CALLBACK(hostkey_answered), r);
- r->dialog = d;
- adw_dialog_present(d, GTK_WIDGET(r->a->window));
-}
-
-/* a password or the server's questions answered (or cancelled) */
-static void answers_given(AdwAlertDialog *d, const char *response, gpointer data)
-{
- Remote *r = data;
- Ssh *ssh = g_object_get_data(G_OBJECT(d), "ssh");
- GPtrArray *entries = g_object_get_data(G_OBJECT(d), "entries");
- int prompts = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(d), "prompts"));
- r->dialog = NULL;
- if (ssh != r->ssh)
- return;
- if (strcmp(response, "ok")) {
- dmc_ssh_auth_cancel(ssh->s);
- return;
- }
- if (!prompts) {
- dmc_ssh_auth_password(ssh->s, gtk_editable_get_text(
- GTK_EDITABLE(g_ptr_array_index(entries, 0))));
- return;
- }
- for (guint i = 0; i < entries->len; i++)
- dmc_ssh_answer(ssh->s, (int)i, gtk_editable_get_text(
- GTK_EDITABLE(g_ptr_array_index(entries, i))));
- dmc_ssh_answered(ssh->s);
-}
-
-/* a dialog asking for a password (prompts 0) or the server's questions */
-static void ask(Remote *r, const char *heading, const char *body, int prompts)
-{
- AdwDialog *d = adw_alert_dialog_new(heading, body && *body ? body : NULL);
- GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
- GPtrArray *entries = g_ptr_array_new();
- int n = prompts ? prompts : 1;
- for (int i = 0; i < n; i++) {
- int echo = 0;
- const char *q = prompts ? dmc_ssh_prompt(r->ssh->s, i, &echo) : "Password";
- GtkWidget *e = echo ? gtk_entry_new() : gtk_password_entry_new();
- if (echo)
- gtk_entry_set_placeholder_text(GTK_ENTRY(e), q);
- else
- g_object_set(e, "placeholder-text", q, NULL);
- if (prompts) {
- GtkWidget *l = gtk_label_new(q);
- gtk_label_set_xalign(GTK_LABEL(l), 0);
- gtk_label_set_wrap(GTK_LABEL(l), TRUE);
- gtk_box_append(GTK_BOX(box), l);
- }
- gtk_box_append(GTK_BOX(box), e);
- g_ptr_array_add(entries, e);
- /* (Enter answers) */
- g_object_set(e, "activates-default", TRUE, NULL);
- }
- adw_alert_dialog_set_extra_child(ADW_ALERT_DIALOG(d), box);
- adw_alert_dialog_add_responses(ADW_ALERT_DIALOG(d), "cancel", "Cancel",
- "ok", "Log In", NULL);
- adw_alert_dialog_set_response_appearance(ADW_ALERT_DIALOG(d), "ok",
- ADW_RESPONSE_SUGGESTED);
- adw_alert_dialog_set_default_response(ADW_ALERT_DIALOG(d), "ok");
- adw_alert_dialog_set_close_response(ADW_ALERT_DIALOG(d), "cancel");
- g_object_set_data(G_OBJECT(d), "ssh", r->ssh);
- g_object_set_data_full(G_OBJECT(d), "entries", entries,
- (GDestroyNotify)g_ptr_array_unref);
- g_object_set_data(G_OBJECT(d), "prompts", GINT_TO_POINTER(prompts));
- g_signal_connect(d, "response", G_CALLBACK(answers_given), r);
- r->dialog = d;
- adw_dialog_present(d, GTK_WIDGET(r->a->window));
- gtk_widget_grab_focus(g_ptr_array_index(entries, 0));
-}
-
-/* a passphrase given (NULL: cancelled), to what asked for it */
-typedef void (*PassFn)(Remote *r, const char *pass, gpointer data);
-
-static void passphrase_given(AdwAlertDialog *d, const char *response, gpointer data)
-{
- Remote *r = data;
- PassFn fn = g_object_get_data(G_OBJECT(d), "fn");
- GtkWidget *e = g_object_get_data(G_OBJECT(d), "entry");
- if (r->dialog == ADW_DIALOG(d))
- r->dialog = NULL;
- fn(r, strcmp(response, "ok") ? NULL : gtk_editable_get_text(GTK_EDITABLE(e)),
- g_object_get_data(G_OBJECT(d), "arg"));
-}
-
-/* a key's passphrase asked for (why: a try's failure, or NULL); fn
- gets it with arg (freed with free_arg); login: the connection's
- dialog, closed with it */
-static void ask_passphrase(Remote *r, const char *name, const char *why,
- PassFn fn, gpointer arg, GDestroyNotify free_arg,
- gboolean login)
-{
- char *head = g_strdup_printf("Passphrase for %s", name);
- AdwDialog *d = adw_alert_dialog_new(head, why);
- g_free(head);
- GtkWidget *e = gtk_password_entry_new();
- g_object_set(e, "placeholder-text", "Passphrase", "activates-default", TRUE, NULL);
- adw_alert_dialog_set_extra_child(ADW_ALERT_DIALOG(d), e);
- adw_alert_dialog_add_responses(ADW_ALERT_DIALOG(d), "cancel", "Cancel",
- "ok", "Unlock", NULL);
- adw_alert_dialog_set_response_appearance(ADW_ALERT_DIALOG(d), "ok",
- ADW_RESPONSE_SUGGESTED);
- adw_alert_dialog_set_default_response(ADW_ALERT_DIALOG(d), "ok");
- adw_alert_dialog_set_close_response(ADW_ALERT_DIALOG(d), "cancel");
- g_object_set_data(G_OBJECT(d), "fn", (gpointer)fn);
- g_object_set_data(G_OBJECT(d), "entry", e);
- g_object_set_data_full(G_OBJECT(d), "arg", arg, free_arg);
- g_signal_connect(d, "response", G_CALLBACK(passphrase_given), r);
- if (login)
- r->dialog = d;
- adw_dialog_present(d, GTK_WIDGET(r->a->window));
- gtk_widget_grab_focus(e);
-}
-
-/* a path with ~/ at its start made the home folder's */
-static char *expand(const char *path)
-{
- if (path[0] == '~' && path[1] == '/')
- return g_build_filename(g_get_home_dir(), path + 2, NULL);
- return g_strdup(path);
-}
-
-/* what's tried, in OpenSSH's order: keys and the agent (or what was
- chosen: the agent alone, or a key file), then the server's questions
- or a password (three times at most) */
-enum { TRIED_KEYS = 1, TRIED_FILE = 2 };
-
-static void ssh_auth(Remote *r, int methods, const char *why);
-
-/* the key file's passphrase given: the login by it, or another try */
-static void key_passphrase(Remote *r, const char *pass, gpointer data)
-{
- Ssh *ssh = data;
- if (ssh != r->ssh || !r->key_text)
- return;
- char *name = g_path_get_basename(r->a->cfg.remote_key);
- if (pass && dmc_ssh_auth_key(ssh->s, r->key_text, pass) == 0) {
- r->tried |= TRIED_FILE;
- } else if (pass && ++r->key_tries < 3) {
- ask_passphrase(r, name, "That passphrase does not open the key.",
- key_passphrase, ssh, NULL, TRUE);
- } else {
- r->tried |= TRIED_FILE;
- key_forget(r);
- ssh_auth(r, r->methods, "");
- }
- g_free(name);
-}
-
-/* the login by the key file: its passphrase asked for if it has one;
- FALSE when there's nothing to try */
-static gboolean key_login(Remote *r)
-{
- char *path = expand(r->a->cfg.remote_key);
- char *name = g_path_get_basename(path);
- gboolean ok = FALSE;
-
- key_forget(r);
- if (!g_file_get_contents(path, &r->key_text, NULL, NULL)) {
- char *m = g_strdup_printf("\r\n[The key file %s can't be read]\r\n", path);
- show(r, m, -1);
- g_free(m);
- r->tried |= TRIED_FILE;
- } else if (dmc_ssh_key_encrypted(r->key_text)) {
- r->key_tries = 0;
- ask_passphrase(r, name, NULL, key_passphrase, r->ssh, NULL, TRUE);
- ok = TRUE;
- } else {
- r->tried |= TRIED_FILE;
- ok = dmc_ssh_auth_key(r->ssh->s, r->key_text, NULL) == 0;
- if (!ok) {
- char *m = g_strdup_printf("\r\n[%s is not a key that can be read]\r\n", path);
- show(r, m, -1);
- g_free(m);
- }
- }
- g_free(name);
- g_free(path);
- return ok;
-}
-
-static void ssh_auth(Remote *r, int methods, const char *why)
-{
- Ssh *ssh = r->ssh;
- const char *how = r->a->cfg.remote_auth;
- gboolean file = !strcmp(how, "key") && *r->a->cfg.remote_key;
-
- r->methods = methods;
- if ((methods & DMC_SSH_AUTH_PUBLICKEY) && file && !(r->tried & TRIED_FILE)) {
- if (key_login(r))
- return;
- } else if ((methods & DMC_SSH_AUTH_PUBLICKEY) && !file &&
- !(r->tried & TRIED_KEYS)) {
- r->tried |= TRIED_KEYS;
- if (!strcmp(how, "agent"))
- dmc_ssh_auth_agent(ssh->s);
- else
- dmc_ssh_auth_auto(ssh->s);
- return;
- }
- if (r->asks++ >= 3) {
- dmc_ssh_auth_cancel(ssh->s);
- return;
- }
- const char *body = r->asks > 1 && *why ? why : NULL;
- char *who = g_strdup_printf("Log in to %s", gtk_editable_get_text(
- GTK_EDITABLE(r->host)));
- if (methods & DMC_SSH_AUTH_INTERACTIVE)
- dmc_ssh_auth_interactive(ssh->s);
- else if (methods & DMC_SSH_AUTH_PASSWORD)
- ask(r, who, body, 0);
- else
- dmc_ssh_auth_cancel(ssh->s);
- g_free(who);
-}
-
-/* an event of the connection's, on the main loop */
-static gboolean ssh_event(gpointer p)
-{
- SshEv *e = p;
- Remote *r = e->r;
- Ssh *ssh = e->ssh;
-
- if (e->type == DMC_SSH_EV_CLOSED) {
- /* (its thread has ended: the connection can go) */
- g_thread_join(ssh->thread);
- dmc_ssh_free(ssh->s);
- g_free(ssh);
- if (ssh != r->ssh)
- return G_SOURCE_REMOVE;
- r->ssh = NULL;
- dialog_gone(r);
- if (!e->data && r->exit_status > 0) {
- char *why = g_strdup_printf("the shell exited with status %d",
- r->exit_status);
- ended(r, why);
- g_free(why);
- } else {
- ended(r, e->data);
- }
- return G_SOURCE_REMOVE;
- }
- if (ssh != r->ssh)
- return G_SOURCE_REMOVE;
- switch (e->type) {
- case DMC_SSH_EV_HOSTKEY:
- ssh_hostkey(r, e->data, e->value);
- break;
- case DMC_SSH_EV_AUTH:
- ssh_auth(r, e->value, e->data);
- break;
- case DMC_SSH_EV_PROMPTS:
- if (e->value == 0) {
- dmc_ssh_answered(ssh->s);
- } else {
- ask(r, e->data && *e->data ? e->data : "The server asks",
- dmc_ssh_instruction(ssh->s), e->value);
- }
- break;
- case DMC_SSH_EV_READY:
- if (e->data && *e->data) {
- show(r, e->data, e->len);
- }
- r->shell = dmc_ssh_shell(ssh->s, dmc_vt_profile_term(termview_profile(r->term)), r->cols, r->rows, 0);
- set_status(r, "Connected by SSH");
- break;
- case DMC_SSH_EV_OPEN:
- if (!e->value) {
- show(r, "\r\n[The server refused the shell]\r\n", -1);
- dmc_ssh_disconnect(ssh->s);
- }
- break;
- case DMC_SSH_EV_DATA:
- if (e->channel == r->shell)
- show(r, e->data, e->len);
- break;
- case DMC_SSH_EV_EXIT:
- if (e->channel == r->shell)
- r->exit_status = e->value;
- break;
- case DMC_SSH_EV_CLOSE:
- /* (the shell's over: so is the connection) */
- if (e->channel == r->shell)
- dmc_ssh_disconnect(ssh->s);
- break;
- case DMC_SSH_EV_INCOMING:
- /* (nothing was asked for that opens these) */
- dmc_ssh_close(ssh->s, e->channel);
- break;
- }
- return G_SOURCE_REMOVE;
-}
-
-/* the connection closed by the user: its thread ends with it */
-static void ssh_disconnect(Remote *r)
-{
- dialog_gone(r);
- dmc_ssh_disconnect(r->ssh->s);
-}
-
-static gboolean start_ssh(Remote *r, const char *host, int port,
- const char *user)
-{
- dmc_ssh *s = dmc_ssh_new(host, port, *user ? user : g_get_user_name());
- if (!s) {
- window_toast(r->a, "Could not start SSH");
- return FALSE;
- }
- /* OpenSSH's own config and known hosts: the user's */
- dmc_ssh_option(s, "config", "");
- dmc_ssh_option(s, "knownhosts", "");
- /* the agent: the one given, else SSH_AUTH_SOCK's */
- const char *agent = r->a->cfg.remote_agent;
- if (*agent)
- dmc_ssh_option(s, "agent", agent);
- if (!strcmp(r->a->cfg.remote_auth, "agent") && !dmc_ssh_agent_reachable(agent))
- show(r, *agent ? "[No agent answers at the socket given]\r\n" :
- "[No agent answers: SSH_AUTH_SOCK names none]\r\n", -1);
- Ssh *ssh = g_new0(Ssh, 1);
- ssh->s = s;
- r->ssh = ssh;
- r->shell = 0;
- r->tried = 0;
- r->asks = 0;
- key_forget(r);
- r->exit_status = 0;
- SshEv *start = g_new0(SshEv, 1);
- start->r = r;
- start->ssh = ssh;
- ssh->thread = g_thread_new("ssh", ssh_poll, start);
- return TRUE;
-}
-
-/*
- * the page
- */
-
-/* the terminal's size, told to the far end as it changes */
-static gboolean size_check(gpointer data)
-{
- Remote *r = data;
- int c, w;
- termview_size(r->term, &c, &w);
- if (c == r->cols && w == r->rows)
- return G_SOURCE_CONTINUE;
- r->cols = c;
- r->rows = w;
- if (r->net && r->sock) {
- dmc_net_resize(r->net, c, w);
- flush(r);
- } else if (r->ssh && r->shell > 0) {
- dmc_ssh_resize(r->ssh->s, r->shell, c, w);
- }
- return G_SOURCE_CONTINUE;
-}
-
-static void committed(const char *text, int size, void *data)
-{
- Remote *r = data;
- if (!r->running)
- return;
- if (r->ssh && r->shell > 0) {
- dmc_ssh_write(r->ssh->s, r->shell, text, (int)size);
- } else if (r->net && r->sock) {
- dmc_net_type(r->net, text, (int)size);
- flush(r);
- }
-}
-
-static int chosen_proto(Remote *r)
-{
- guint i = gtk_drop_down_get_selected(GTK_DROP_DOWN(r->proto));
- return i < G_N_ELEMENTS(protos) ? protos[i] : DMC_NET_SSH;
-}
-
-/* the default port shown for the protocol */
-static void proto_changed(GObject *o, GParamSpec *p, gpointer data)
-{
- Remote *r = data;
- (void)o;
- (void)p;
- char ps[16];
- g_snprintf(ps, sizeof(ps), "%d", dmc_net_default_port(chosen_proto(r)));
- gtk_entry_set_placeholder_text(GTK_ENTRY(r->port), ps);
- if (r->login)
- gtk_widget_set_visible(r->login, chosen_proto(r) == DMC_NET_SSH);
-}
-
-static void connect_clicked(GtkWidget *w, gpointer data)
-{
- Remote *r = data;
- App *a = r->a;
- (void)w;
- if (r->running) {
- ended(r, NULL);
- return;
- }
- char *host = g_strstrip(g_strdup(
- gtk_editable_get_text(GTK_EDITABLE(r->host))));
- const char *user = gtk_editable_get_text(GTK_EDITABLE(r->user));
- const char *pt = gtk_editable_get_text(GTK_EDITABLE(r->port));
- int proto = chosen_proto(r);
- int port = *pt ? atoi(pt) : dmc_net_default_port(proto);
- if (!*host) {
- window_toast(a, "Enter the server to connect to");
- g_free(host);
- return;
- }
- if (port <= 0 || port > 65535) {
- window_toast(a, "The port is a number from 1 to 65535");
- g_free(host);
- return;
- }
- if (proto == DMC_NET_RLOGIN && !*user) {
- window_toast(a, "rlogin needs a user name");
- g_free(host);
- return;
- }
- /* kept for next time */
- g_free(a->cfg.remote_proto);
- a->cfg.remote_proto = g_strdup(dmc_net_name(proto));
- g_free(a->cfg.remote_host);
- a->cfg.remote_host = g_strdup(host);
- a->cfg.remote_port = *pt ? port : 0;
- g_free(a->cfg.remote_user);
- a->cfg.remote_user = g_strdup(user);
- config_save(&a->cfg);
-
- termview_reset(r->term);
- termview_size(r->term, &r->cols, &r->rows);
- char *what = g_strdup_printf("Connecting to %s port %d by %s", host,
- port, dmc_net_name(proto));
- set_status(r, what);
- char *line = g_strdup_printf("[%s]\r\n", what);
- show(r, line, -1);
- g_free(line);
- g_free(what);
-
- if (proto == DMC_NET_SSH) {
- if (!start_ssh(r, host, port, user)) {
- set_status(r, "Not connected");
- g_free(host);
- return;
- }
- } else {
- /* (Telnet's TERMINAL-TYPE, rlogin's TERM) */
- const char *type = termview_profile(r->term);
- r->net = dmc_net_new(proto, user, proto == DMC_NET_TELNET ?
- dmc_vt_profile_telnet(type) :
- dmc_vt_profile_term(type), r->cols, r->rows);
- r->client = g_socket_client_new();
- g_socket_client_set_timeout(r->client, 20);
- r->cancel = g_cancellable_new();
- g_socket_client_connect_to_host_async(r->client, host,
- (guint16)port, r->cancel,
- connected, r);
- }
- r->running = proto;
- r->size_tick = g_timeout_add(250, size_check, r);
- controls(r);
- termview_focus(r->term);
- g_free(host);
-}
-
-static void type_changed(GObject *o, GParamSpec *p, gpointer data)
-{
- Remote *r = data;
- (void)o;
- (void)p;
- const char *id = term_types_chosen(r->type);
- termview_set_profile(r->term, id);
- g_free(r->a->cfg.remote_term);
- r->a->cfg.remote_term = g_strdup(id);
- config_save(&r->a->cfg);
-}
-
-/*
- * how SSH logs in: its menu
- */
-
-/* the ways in the drop-down's order, as the config has them */
-static const char *const hows[] = { "auto", "agent", "key" };
-
-/* the key file shown (and its row's tooltip) */
-static void key_shown(Remote *r)
-{
- const char *k = r->a->cfg.remote_key;
- char *name = *k ? g_path_get_basename(k) : g_strdup("No key file chosen");
- gtk_label_set_text(GTK_LABEL(r->key_label), name);
- gtk_widget_set_tooltip_text(r->key_label, *k ? k : NULL);
- g_free(name);
-}
-
-/* whether the agent answers, under its socket's entry */
-static void agent_shown(Remote *r)
-{
- const char *a = r->a->cfg.remote_agent;
- const char *m = dmc_ssh_agent_reachable(a) ? "An agent answers there" :
- *a ? "No agent answers there" :
- g_getenv("SSH_AUTH_SOCK") ? "No agent answers at SSH_AUTH_SOCK" :
- "SSH_AUTH_SOCK is not set: give the agent's socket";
- gtk_label_set_text(GTK_LABEL(r->agent_state), m);
-}
-
-/* the way chosen, kept */
-static void how_changed(GObject *o, GParamSpec *p, gpointer data)
-{
- Remote *r = data;
- (void)o;
- (void)p;
- guint i = gtk_drop_down_get_selected(GTK_DROP_DOWN(r->auth));
- g_free(r->a->cfg.remote_auth);
- r->a->cfg.remote_auth = g_strdup(hows[i < G_N_ELEMENTS(hows) ? i : 0]);
- config_save(&r->a->cfg);
-}
-
-/* the key file set, and the login by it chosen */
-static void key_set(Remote *r, const char *path)
-{
- g_free(r->a->cfg.remote_key);
- r->a->cfg.remote_key = g_strdup(path);
- gtk_drop_down_set_selected(GTK_DROP_DOWN(r->auth), 2);
- config_save(&r->a->cfg);
- key_shown(r);
-}
-
-/* the agent's socket typed, kept */
-static void agent_changed(GtkEditable *e, gpointer data)
-{
- Remote *r = data;
- g_free(r->a->cfg.remote_agent);
- r->a->cfg.remote_agent = g_strstrip(g_strdup(gtk_editable_get_text(e)));
- config_save(&r->a->cfg);
- agent_shown(r);
-}
-
-/* a file dialog for keys, in ~/.ssh, *.ppk alone when ppk */
-static GtkFileDialog *key_dialog(const char *title, gboolean ppk)
-{
- GtkFileDialog *d = gtk_file_dialog_new();
- gtk_file_dialog_set_title(d, title);
- char *dir = g_build_filename(g_get_home_dir(), ".ssh", NULL);
- GFile *f = g_file_new_for_path(dir);
- if (g_file_test(dir, G_FILE_TEST_IS_DIR))
- gtk_file_dialog_set_initial_folder(d, f);
- g_object_unref(f);
- g_free(dir);
- GListStore *filters = g_list_store_new(GTK_TYPE_FILE_FILTER);
- GtkFileFilter *putty = gtk_file_filter_new();
- gtk_file_filter_set_name(putty, "PuTTY keys (.ppk)");
- gtk_file_filter_add_pattern(putty, "*.ppk");
- if (!ppk) {
- GtkFileFilter *all = gtk_file_filter_new();
- gtk_file_filter_set_name(all, "All keys (OpenSSH's, PEM, PuTTY's)");
- gtk_file_filter_add_pattern(all, "*");
- g_list_store_append(filters, all);
- g_object_unref(all);
- }
- g_list_store_append(filters, putty);
- g_object_unref(putty);
- gtk_file_dialog_set_filters(d, G_LIST_MODEL(filters));
- g_object_unref(filters);
- return d;
-}
-
-static void key_chosen(GObject *src, GAsyncResult *res, gpointer data)
-{
- GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL);
- if (!f)
- return;
- char *p = g_file_get_path(f);
- if (p)
- key_set(data, p);
- g_free(p);
- g_object_unref(f);
-}
-
-static void choose_key(GtkButton *b, gpointer data)
-{
- Remote *r = data;
- gtk_menu_button_popdown(GTK_MENU_BUTTON(r->login));
- (void)b;
- GtkFileDialog *d = key_dialog("Choose a Private Key", FALSE);
- gtk_file_dialog_open(d, r->a->window, NULL, key_chosen, r);
- g_object_unref(d);
-}
-
-/* where an imported key goes: ~/.ssh/, a name not yet taken */
-static char *import_path(const char *ppk)
-{
- char *dir = g_build_filename(g_get_home_dir(), ".ssh", NULL);
- char *base = g_path_get_basename(ppk);
- char *dot = strrchr(base, '.');
- if (dot && !g_ascii_strcasecmp(dot, ".ppk"))
- *dot = 0;
- if (!*base) {
- g_free(base);
- base = g_strdup("putty-key");
- }
- g_mkdir_with_parents(dir, 0700);
- char *path = NULL;
- for (int i = 1; i < 100; i++) {
- char *name = i == 1 ? g_strdup(base) : g_strdup_printf("%s-%d", base, i);
- path = g_build_filename(dir, name, NULL);
- char *pub = g_strconcat(path, ".pub", NULL);
- gboolean taken = g_file_test(path, G_FILE_TEST_EXISTS) ||
- g_file_test(pub, G_FILE_TEST_EXISTS);
- g_free(pub);
- g_free(name);
- if (!taken)
- break;
- g_clear_pointer(&path, g_free);
- }
- g_free(base);
- g_free(dir);
- return path;
-}
-
-/* a .ppk imported with its passphrase (NULL: cancelled): written to
- ~/.ssh in OpenSSH's form, with the same passphrase, and chosen */
-static void import_with(Remote *r, const char *pass, gpointer data)
-{
- const char *ppk = data;
- char *text = NULL, *key = NULL, *pub = NULL;
- char *name = g_path_get_basename(ppk);
-
- if (!g_file_get_contents(ppk, &text, NULL, NULL)) {
- window_toast(r->a, "The PuTTY key can't be read");
- g_free(name);
- return;
- }
- gboolean enc = dmc_ssh_key_encrypted(text);
- if (enc && !pass)
- goto done;
- if (dmc_ssh_key_export(text, pass, pass, &key) || dmc_ssh_key_public(key, pass, &pub)) {
- if (enc)
- ask_passphrase(r, name, "That passphrase does not open the key.",
- import_with, g_strdup(ppk), g_free, FALSE);
- else
- window_toast(r->a, "That file is not a PuTTY key that can be read");
- goto done;
- }
- char *path = import_path(ppk);
- char *pubpath = path ? g_strconcat(path, ".pub", NULL) : NULL;
- /* (the .pub line with the .ppk's comment, as OpenSSH's have theirs) */
- const char *c = strstr(text, "\nComment: ");
- char *comment = c ? g_strndup(c + 10, strcspn(c + 10, "\r\n")) : g_strdup("");
- char *line = g_strdup_printf("%s%s%s\n", pub, *comment ? " " : "", comment);
- GError *e = NULL;
- if (path && g_file_set_contents_full(path, key, -1, G_FILE_SET_CONTENTS_CONSISTENT, 0600, &e) &&
- g_file_set_contents_full(pubpath, line, -1, G_FILE_SET_CONTENTS_CONSISTENT, 0644, &e)) {
- key_set(r, path);
- const char *home = g_get_home_dir();
- gsize hl = strlen(home);
- char *m = !strncmp(path, home, hl) && path[hl] == '/' ?
- g_strdup_printf("Imported as ~%s, and chosen for SSH logins", path + hl) :
- g_strdup_printf("Imported as %s, and chosen for SSH logins", path);
- window_toast(r->a, m);
- g_free(m);
- } else {
- char *m = g_strdup_printf("The key could not be saved: %s",
- e ? e->message : "no room in ~/.ssh");
- window_toast(r->a, m);
- g_free(m);
- }
- g_clear_error(&e);
- g_free(line);
- g_free(comment);
- g_free(pubpath);
- g_free(path);
-done:
- if (key) {
- memset(key, 0, strlen(key));
- dmc_ssh_free_string(key);
- }
- dmc_ssh_free_string(pub);
- memset(text, 0, strlen(text));
- g_free(text);
- g_free(name);
-}
-
-static void ppk_chosen(GObject *src, GAsyncResult *res, gpointer data)
-{
- Remote *r = data;
- GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL);
- if (!f)
- return;
- char *p = g_file_get_path(f);
- char *text = NULL;
- if (p && g_file_get_contents(p, &text, NULL, NULL) && dmc_ssh_key_encrypted(text)) {
- char *name = g_path_get_basename(p);
- ask_passphrase(r, name, NULL, import_with, g_strdup(p), g_free, FALSE);
- g_free(name);
- } else if (p) {
- import_with(r, NULL, p);
- }
- if (text) {
- memset(text, 0, strlen(text));
- g_free(text);
- }
- g_free(p);
- g_object_unref(f);
-}
-
-static void import_clicked(GtkButton *b, gpointer data)
-{
- Remote *r = data;
- gtk_menu_button_popdown(GTK_MENU_BUTTON(r->login));
- (void)b;
- GtkFileDialog *d = key_dialog("Import a PuTTY Key", TRUE);
- gtk_file_dialog_open(d, r->a->window, NULL, ppk_chosen, r);
- g_object_unref(d);
-}
-
-/* the menu's button: the way to log in, the key file, the agent's
- socket, and a .ppk's import */
-static GtkWidget *login_menu(Remote *r)
-{
- App *a = r->a;
- GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
- gtk_widget_set_margin_start(box, 6);
- gtk_widget_set_margin_end(box, 6);
- gtk_widget_set_margin_top(box, 6);
- gtk_widget_set_margin_bottom(box, 6);
-
- GtkWidget *l = gtk_label_new("Log in to SSH servers with");
- gtk_label_set_xalign(GTK_LABEL(l), 0);
- gtk_widget_add_css_class(l, "heading");
- gtk_box_append(GTK_BOX(box), l);
- const char *names[] = { "My keys and agent, as ssh does",
- "The agent's keys only", "A key file", NULL };
- r->auth = gtk_drop_down_new_from_strings(names);
- guint i;
- for (i = 0; i < G_N_ELEMENTS(hows); i++)
- if (!strcmp(a->cfg.remote_auth, hows[i]))
- gtk_drop_down_set_selected(GTK_DROP_DOWN(r->auth), i);
- g_signal_connect(r->auth, "notify::selected", G_CALLBACK(how_changed), r);
- gtk_box_append(GTK_BOX(box), r->auth);
-
- l = gtk_label_new("Key file (OpenSSH's, PEM or PuTTY's .ppk)");
- gtk_label_set_xalign(GTK_LABEL(l), 0);
- gtk_widget_add_css_class(l, "dim-label");
- gtk_box_append(GTK_BOX(box), l);
- GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
- r->key_label = gtk_label_new(NULL);
- gtk_label_set_xalign(GTK_LABEL(r->key_label), 0);
- gtk_label_set_ellipsize(GTK_LABEL(r->key_label), PANGO_ELLIPSIZE_MIDDLE);
- gtk_widget_set_hexpand(r->key_label, TRUE);
- gtk_box_append(GTK_BOX(row), r->key_label);
- GtkWidget *b = gtk_button_new_with_label("Choose…");
- g_signal_connect(b, "clicked", G_CALLBACK(choose_key), r);
- gtk_box_append(GTK_BOX(row), b);
- gtk_box_append(GTK_BOX(box), row);
- key_shown(r);
-
- b = gtk_button_new_with_label("Import a PuTTY Key…");
- gtk_widget_set_tooltip_text(b, "A .ppk saved in ~/.ssh in OpenSSH's form, "
- "with the same passphrase, and chosen");
- g_signal_connect(b, "clicked", G_CALLBACK(import_clicked), r);
- gtk_box_append(GTK_BOX(box), b);
-
- l = gtk_label_new("Agent's socket");
- gtk_label_set_xalign(GTK_LABEL(l), 0);
- gtk_widget_add_css_class(l, "dim-label");
- gtk_box_append(GTK_BOX(box), l);
- r->agent = gtk_entry_new();
- gtk_entry_set_placeholder_text(GTK_ENTRY(r->agent), "Empty: SSH_AUTH_SOCK's");
- gtk_editable_set_text(GTK_EDITABLE(r->agent), a->cfg.remote_agent);
- g_signal_connect(r->agent, "changed", G_CALLBACK(agent_changed), r);
- gtk_box_append(GTK_BOX(box), r->agent);
- r->agent_state = gtk_label_new(NULL);
- gtk_label_set_xalign(GTK_LABEL(r->agent_state), 0);
- gtk_widget_add_css_class(r->agent_state, "dim-label");
- gtk_widget_add_css_class(r->agent_state, "caption");
- gtk_box_append(GTK_BOX(box), r->agent_state);
- agent_shown(r);
-
- GtkWidget *pop = gtk_popover_new();
- gtk_popover_set_child(GTK_POPOVER(pop), box);
- r->login = gtk_menu_button_new();
- gtk_menu_button_set_icon_name(GTK_MENU_BUTTON(r->login), "dialog-password-symbolic");
- gtk_widget_set_tooltip_text(r->login, "How SSH logs in: keys, the agent, a PuTTY key");
- gtk_menu_button_set_popover(GTK_MENU_BUTTON(r->login), pop);
- return r->login;
-}
-
-static int proto_index(const char *name)
-{
- guint i;
- for (i = 0; i < G_N_ELEMENTS(protos); i++)
- if (name && !g_ascii_strcasecmp(name, dmc_net_name(protos[i])))
- return (int)i;
- return 0;
-}
-
-GtkWidget *remote_page_new(App *a)
-{
- Remote *r = g_new0(Remote, 1);
- R = r;
- r->a = a;
- r->pending = g_byte_array_new();
-
- GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
- GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
- gtk_widget_set_margin_start(bar, 6);
- gtk_widget_set_margin_end(bar, 6);
- gtk_widget_set_margin_top(bar, 6);
- gtk_widget_set_margin_bottom(bar, 6);
-
- const char *names[] = { "SSH", "Telnet", "rlogin", NULL };
- r->proto = gtk_drop_down_new_from_strings(names);
- gtk_widget_set_tooltip_text(r->proto, "How to log in");
- gtk_box_append(GTK_BOX(bar), r->proto);
-
- r->host = gtk_entry_new();
- gtk_entry_set_placeholder_text(GTK_ENTRY(r->host), "Server");
- gtk_widget_set_hexpand(r->host, TRUE);
- gtk_box_append(GTK_BOX(bar), r->host);
-
- r->port = gtk_entry_new();
- gtk_entry_set_input_purpose(GTK_ENTRY(r->port), GTK_INPUT_PURPOSE_DIGITS);
- gtk_editable_set_width_chars(GTK_EDITABLE(r->port), 6);
- gtk_editable_set_max_width_chars(GTK_EDITABLE(r->port), 6);
- gtk_widget_set_tooltip_text(r->port, "Port (empty: the protocol's)");
- gtk_box_append(GTK_BOX(bar), r->port);
-
- r->user = gtk_entry_new();
- gtk_entry_set_placeholder_text(GTK_ENTRY(r->user), "User");
- gtk_editable_set_width_chars(GTK_EDITABLE(r->user), 12);
- gtk_box_append(GTK_BOX(bar), r->user);
- gtk_box_append(GTK_BOX(bar), login_menu(r));
-
- r->go = gtk_button_new_with_label("Connect");
- g_signal_connect(r->go, "clicked", G_CALLBACK(connect_clicked), r);
- g_signal_connect(r->host, "activate", G_CALLBACK(connect_clicked), r);
- gtk_box_append(GTK_BOX(bar), r->go);
- gtk_box_append(GTK_BOX(box), bar);
-
- /* what was used last */
- gtk_drop_down_set_selected(GTK_DROP_DOWN(r->proto),
- (guint)proto_index(a->cfg.remote_proto));
- gtk_editable_set_text(GTK_EDITABLE(r->host), a->cfg.remote_host);
- if (a->cfg.remote_port > 0) {
- char ps[16];
- g_snprintf(ps, sizeof(ps), "%d", a->cfg.remote_port);
- gtk_editable_set_text(GTK_EDITABLE(r->port), ps);
- }
- gtk_editable_set_text(GTK_EDITABLE(r->user), a->cfg.remote_user);
- g_signal_connect(r->proto, "notify::selected", G_CALLBACK(proto_changed), r);
- proto_changed(NULL, NULL, r);
-
- r->term = termview_new(committed, r);
- termview_set_profile(r->term, a->cfg.remote_term);
- gtk_box_append(GTK_BOX(box), r->term);
-
- GtkWidget *foot = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
- gtk_widget_set_margin_start(foot, 8);
- gtk_widget_set_margin_end(foot, 6);
- gtk_widget_set_margin_top(foot, 4);
- gtk_widget_set_margin_bottom(foot, 4);
- r->status = gtk_label_new("Not connected");
- gtk_label_set_xalign(GTK_LABEL(r->status), 0);
- gtk_widget_set_hexpand(r->status, TRUE);
- gtk_widget_add_css_class(r->status, "dim-label");
- gtk_box_append(GTK_BOX(foot), r->status);
- /* the kind of terminal: the far end is told it when connecting */
- r->type = term_types_new(a->cfg.remote_term);
- g_signal_connect(r->type, "notify::selected", G_CALLBACK(type_changed), r);
- gtk_box_append(GTK_BOX(foot), r->type);
- gtk_box_append(GTK_BOX(box), foot);
- controls(r);
- return box;
-}
-
-void remote_stop(App *a)
-{
- (void)a;
- if (R && R->running)
- ended(R, NULL);
-}
diff --git a/linux/src/settings.c b/linux/src/settings.c
deleted file mode 100644
index 03ee3a3..0000000
--- a/linux/src/settings.c
+++ /dev/null
@@ -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
-#include
-
-#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);
-}
diff --git a/linux/src/stats.c b/linux/src/stats.c
deleted file mode 100644
index 991f997..0000000
--- a/linux/src/stats.c
+++ /dev/null
@@ -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;
-}
diff --git a/linux/src/termview.c b/linux/src/termview.c
deleted file mode 100644
index bbee9c9..0000000
--- a/linux/src/termview.c
+++ /dev/null
@@ -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
-#include
-
-#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);
-}
diff --git a/linux/src/usbmodem.c b/linux/src/usbmodem.c
deleted file mode 100644
index 1a70f98..0000000
--- a/linux/src/usbmodem.c
+++ /dev/null
@@ -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
-#include
-#include
-
-#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);
-}
diff --git a/linux/src/voice.c b/linux/src/voice.c
deleted file mode 100644
index ce1118b..0000000
--- a/linux/src/voice.c
+++ /dev/null
@@ -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
-#include
-
-#include
-
-#include "app.h"
-
-#ifdef HAVE_SNDFILE
-#include
-#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;
-}
diff --git a/linux/src/window.c b/linux/src/window.c
deleted file mode 100644
index 1ab4a7f..0000000
--- a/linux/src/window.c
+++ /dev/null
@@ -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
-
-#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);
-}
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/DModem/Assets.xcassets/AppIcon.appiconset/Contents.json
deleted file mode 100644
index 2e12d45..0000000
--- a/macos/DModem/Assets.xcassets/AppIcon.appiconset/Contents.json
+++ /dev/null
@@ -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"
- }
-}
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
deleted file mode 100644
index 3cda607..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png
deleted file mode 100644
index 46b4c49..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
deleted file mode 100644
index 668f3ec..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png
deleted file mode 100644
index 8e26efc..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
deleted file mode 100644
index 46b4c49..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png
deleted file mode 100644
index 632546b..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
deleted file mode 100644
index 8e26efc..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png
deleted file mode 100644
index a3e5c33..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
deleted file mode 100644
index 632546b..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png b/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png
deleted file mode 100644
index caa1cde..0000000
Binary files a/macos/DModem/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png and /dev/null differ
diff --git a/macos/DModem/Assets.xcassets/Contents.json b/macos/DModem/Assets.xcassets/Contents.json
deleted file mode 100644
index 73c0059..0000000
--- a/macos/DModem/Assets.xcassets/Contents.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/macos/DModem/Bridging.h b/macos/DModem/Bridging.h
deleted file mode 100644
index 0b153f4..0000000
--- a/macos/DModem/Bridging.h
+++ /dev/null
@@ -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
diff --git a/macos/DModem/ContentView.swift b/macos/DModem/ContentView.swift
deleted file mode 100644
index baefe7e..0000000
--- a/macos/DModem/ContentView.swift
+++ /dev/null
@@ -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) }
- }
- }
- }
-}
diff --git a/macos/DModem/DModemApp.swift b/macos/DModem/DModemApp.swift
deleted file mode 100644
index bd7b2ec..0000000
--- a/macos/DModem/DModemApp.swift
+++ /dev/null
@@ -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()
- }
-}
diff --git a/macos/DModem/LineConfig.swift b/macos/DModem/LineConfig.swift
deleted file mode 100644
index cd7a9c9..0000000
--- a/macos/DModem/LineConfig.swift
+++ /dev/null
@@ -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)
- }
-}
diff --git a/macos/DModem/LineSettingsView.swift b/macos/DModem/LineSettingsView.swift
deleted file mode 100644
index 1731828..0000000
--- a/macos/DModem/LineSettingsView.swift
+++ /dev/null
@@ -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 }
- }
- }
-}
diff --git a/macos/DModem/Modem.swift b/macos/DModem/Modem.swift
deleted file mode 100644
index 01b9f65..0000000
--- a/macos/DModem/Modem.swift
+++ /dev/null
@@ -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?) -> 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.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.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..= 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..= 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] = []
- defer { keep.forEach { free($0) } }
- /// A C string that stays until the end of this function.
- func cs(_ s: String) -> UnsafePointer? {
- 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.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.. 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.. 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.. 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"
- }
- }
-}
diff --git a/macos/DModem/RemoteView.swift b/macos/DModem/RemoteView.swift
deleted file mode 100644
index 0e67156..0000000
--- a/macos/DModem/RemoteView.swift
+++ /dev/null
@@ -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.. 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?
- var pub: UnsafeMutablePointer?
- 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/, 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?
- 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.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..= 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 {
- Binding(get: { i < answers.count ? answers[i] : "" },
- set: { if i < answers.count { answers[i] = $0 } })
- }
-
- private var asking: Binding {
- // (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)
- }
-}
diff --git a/macos/DModem/SSHConnection.swift b/macos/DModem/SSHConnection.swift
deleted file mode 100644
index 643bbdf..0000000
--- a/macos/DModem/SSHConnection.swift
+++ /dev/null
@@ -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)
- }
-}
diff --git a/macos/DModem/TerminalView.swift b/macos/DModem/TerminalView.swift
deleted file mode 100644
index e28c8b1..0000000
--- a/macos/DModem/TerminalView.swift
+++ /dev/null
@@ -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.. 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, _ 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.. 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.. 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..> 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.. 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..) {
- 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, _ n: Int) -> Int {
- lock.lock()
- let k = min(n, count)
- for i in 0.. 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?
- 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..).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?
- 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..= 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.. 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)
- }
-}
diff --git a/macos/project.yml b/macos/project.yml
deleted file mode 100644
index 1e3247e..0000000
--- a/macos/project.yml
+++ /dev/null
@@ -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
diff --git a/mkdocs.yml b/mkdocs.yml
index 4324a3b..829bf38 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -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
diff --git a/ssh/CMakeLists.txt b/ssh/CMakeLists.txt
index 549e238..756b765 100644
--- a/ssh/CMakeLists.txt
+++ b/ssh/CMakeLists.txt
@@ -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()
diff --git a/tools/icons.js b/tools/icons.js
index 551b624..ec9c748 100644
--- a/tools/icons.js
+++ b/tools/icons.js
@@ -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');
diff --git a/tools/icons.py b/tools/icons.py
index e6dedbe..163b128 100644
--- a/tools/icons.py
+++ b/tools/icons.py
@@ -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'))
diff --git a/windows/src/main.cpp b/windows/src/main.cpp
index 2b2506d..42a5520 100644
--- a/windows/src/main.cpp
+++ b/windows/src/main.cpp
@@ -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
#include
diff --git a/winport/CMakeLists.txt b/winport/CMakeLists.txt
index b9aa7c3..20567a6 100644
--- a/winport/CMakeLists.txt
+++ b/winport/CMakeLists.txt
@@ -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()
diff --git a/linux/data/io.github.d_modem.DModem.desktop b/winport/data/io.github.d_modem.DModem.desktop
similarity index 83%
rename from linux/data/io.github.d_modem.DModem.desktop
rename to winport/data/io.github.d_modem.DModem.desktop
index 56d80da..493c451 100644
--- a/linux/data/io.github.d_modem.DModem.desktop
+++ b/winport/data/io.github.d_modem.DModem.desktop
@@ -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
diff --git a/linux/data/io.github.d_modem.DModem.metainfo.xml b/winport/data/io.github.d_modem.DModem.metainfo.xml
similarity index 100%
rename from linux/data/io.github.d_modem.DModem.metainfo.xml
rename to winport/data/io.github.d_modem.DModem.metainfo.xml