diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9b4b298..82c56b1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -218,11 +218,15 @@ jobs: name: dmodem-win32-macos path: dmodem-win32-macos-arm64.tar.gz + # The built-in modem (external/D-Modem) is built by CMake, which + # writes build/macos-embed.xcconfig for the Xcode project macos: name: macOS (SwiftUI) runs-on: macos-15 steps: - uses: actions/checkout@v4 + with: + submodules: true - name: Library tests run: | cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo \ @@ -239,6 +243,11 @@ jobs: xcodebuild -project DModem.xcodeproj -scheme DModem \ -configuration Release -derivedDataPath ../build/xcode \ CODE_SIGN_IDENTITY=- build + - name: The built-in modem is in the app + run: | + app=build/xcode/Build/Products/Release/D-Modem.app/Contents/MacOS/D-Modem + lipo -archs "$app" + nm "$app" | grep -q dmodem_embed_start # (ditto keeps the bundle's symbolic links and executable bits) - name: Package run: ditto -c -k --keepParent build/xcode/Build/Products/Release/D-Modem.app D-Modem-macos.zip diff --git a/CMakeLists.txt b/CMakeLists.txt index fd719b5..3faf0f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,9 +4,11 @@ # The macOS app (macos/) builds with Xcode and takes the core from here. # With DMODEM_GUI_WINPORT, the Windows app also builds for Linux and # macOS, over clang-retro MFC's portable Win32 layer (winport/). -# With DMODEM_GUI_EMBED, the Linux app and the Windows app (Windows 98 -# SE and later) have the modem in them (libdmodem_embed from the D-Modem -# submodule, external/D-Modem): they need no dmodemd. +# With DMODEM_GUI_EMBED, the Linux app, the Windows app (Windows 98 SE +# and later) and the macOS app have the modem in them (libdmodem_embed +# from the D-Modem submodule, external/D-Modem): they need no dmodemd. +# For the macOS app, CMake writes macos-embed.xcconfig +# (cmake/MacosEmbed.cmake). cmake_minimum_required(VERSION 3.16) project(dmodem-gui VERSION 1.0.0 LANGUAGES C) @@ -18,8 +20,8 @@ option(DMODEM_GUI_SSH "Build libdmodemssh (libssh) for the Remote page" ON) option(DMODEM_GUI_WINPORT "Build the Windows app for Linux or macOS (winport/)" OFF) set(CLANG_RETRO_MFC "" CACHE PATH "A clang-retro MFC checkout, for DMODEM_GUI_WINPORT") -# the modem built in (docs/embedded-modem.md): the Linux app, when the -# submodule is there (git submodule update --init) +# the modem built in (docs/embedded-modem.md): the Linux and macOS apps, +# when the submodule is there (git submodule update --init) set(DMODEM_GUI_DMODEM_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/D-Modem CACHE PATH "The D-Modem tree, for DMODEM_GUI_EMBED") # and the Windows app for Windows 98 SE and later: the modem is C++17 on @@ -29,13 +31,15 @@ set(_embed_default OFF) if(EXISTS ${DMODEM_GUI_DMODEM_DIR}/CMakeLists.txt) if(UNIX AND NOT APPLE AND DMODEM_GUI_LINUX AND NOT DMODEM_GUI_WINPORT) set(_embed_default ON) + elseif(APPLE AND NOT DMODEM_GUI_WINPORT) + set(_embed_default ON) elseif(WIN32 AND NOT CLANG_RETRO_CONFIG MATCHES "picolibc") set(_embed_default ON) endif() endif() option(DMODEM_GUI_EMBED "Build the modem into the app (libdmodem_embed)" ${_embed_default}) -if(DMODEM_GUI_EMBED AND (WIN32 OR DMODEM_GUI_LINUX)) +if(DMODEM_GUI_EMBED AND (WIN32 OR APPLE OR DMODEM_GUI_LINUX)) if(NOT EXISTS ${DMODEM_GUI_DMODEM_DIR}/CMakeLists.txt) message(FATAL_ERROR "DMODEM_GUI_EMBED: no D-Modem in " "${DMODEM_GUI_DMODEM_DIR} (git submodule update --init)") @@ -105,3 +109,8 @@ if(DMODEM_GUI_LINUX AND UNIX AND NOT APPLE) message(STATUS "gtk4 or libadwaita-1 not found: the Linux app is not built") endif() endif() + +# the macOS app (Xcode): the built-in modem's libraries, for its project +if(APPLE AND NOT DMODEM_GUI_WINPORT) + include(cmake/MacosEmbed.cmake) +endif() diff --git a/README.md b/README.md index f6430ad..5fd9472 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ Native apps for D-Modem on Windows, macOS and Linux. -The Linux and Windows apps have the modem built in, so they need no dmodemd. -The macOS app starts dmodemd (or connects to a dmodemd that already runs). It +The apps (not the Windows 95 build) have the modem built in, so they need no dmodemd (refer to +[The built-in modem](docs/embedded-modem.md)). Each app shows the modem as a desktop program. You can dial and answer from a window, change the settings without AT commands, and see the results of the last call. All three apps are thin native shells over one small C library, diff --git a/cmake/MacosEmbed.cmake b/cmake/MacosEmbed.cmake new file mode 100644 index 0000000..2ec2aa2 --- /dev/null +++ b/cmake/MacosEmbed.cmake @@ -0,0 +1,40 @@ +# The macOS app (macos/) builds with Xcode, not CMake. This file writes +# ${CMAKE_BINARY_DIR}/macos-embed.xcconfig, which the Xcode project +# (macos/project.yml) includes: +# DMODEM_EMBED_HEADERS the directory of dmodem_embed.h +# DMODEM_EMBED_LDFLAGS the static libraries of libdmodem_embed, all of +# them, and the system libraries they need +# DMODEM_EMBED_SWIFT DMODEM_GUI_EMBED, for Swift's #if +# Without the built-in modem, the three values are empty. +# +# A small program, dmodem_embed_link, links the library. Its linker +# launcher (macos-embed/link-capture.sh) keeps the link command that +# CMake made, with all the libraries that the library needs. Then +# macos-embed/xcconfig.cmake makes the file from that command. + +set(_xcconfig ${CMAKE_BINARY_DIR}/macos-embed.xcconfig) +if(DMODEM_GUI_EMBED AND TARGET dmodem_embed) + if(CMAKE_VERSION VERSION_LESS 3.21) + message(FATAL_ERROR "The built-in modem of the macOS app needs CMake 3.21 or later") + endif() + set(_dir ${CMAKE_CURRENT_LIST_DIR}/macos-embed) + set(_cmd ${CMAKE_BINARY_DIR}/macos-embed.link) + add_executable(dmodem_embed_link ${_dir}/main.c) + target_link_libraries(dmodem_embed_link PRIVATE dmodem_embed) + set_target_properties(dmodem_embed_link PROPERTIES + LINKER_LANGUAGE CXX + C_LINKER_LAUNCHER "${_dir}/link-capture.sh;${_cmd}" + CXX_LINKER_LAUNCHER "${_dir}/link-capture.sh;${_cmd}") + add_custom_command(TARGET dmodem_embed_link POST_BUILD + COMMAND ${CMAKE_COMMAND} -DIN=${_cmd} -DOUT=${_xcconfig} + -DHEADERS=${DMODEM_GUI_DMODEM_DIR}/frontend/embed + -P ${_dir}/xcconfig.cmake + VERBATIM) +else() + file(WRITE ${_xcconfig} +"// Made by CMake (cmake/MacosEmbed.cmake): no built-in modem +DMODEM_EMBED_HEADERS = +DMODEM_EMBED_LDFLAGS = +DMODEM_EMBED_SWIFT = +") +endif() diff --git a/cmake/macos-embed/link-capture.sh b/cmake/macos-embed/link-capture.sh new file mode 100755 index 0000000..690f030 --- /dev/null +++ b/cmake/macos-embed/link-capture.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright (C) 2026 D-Modem Authors +# +# link-capture.sh - the linker launcher of dmodem_embed_link +# (cmake/MacosEmbed.cmake). It writes the directory and the link +# command, one argument on each line, to . Then it runs the +# command. +# +# Usage: link-capture.sh [...] + +out=$1 +shift +{ + pwd + printf '%s\n' "$@" +} > "$out" +exec "$@" diff --git a/cmake/macos-embed/main.c b/cmake/macos-embed/main.c new file mode 100644 index 0000000..efe2b4e --- /dev/null +++ b/cmake/macos-embed/main.c @@ -0,0 +1,15 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * main.c - dmodem_embed_link (cmake/MacosEmbed.cmake): a program that + * links libdmodem_embed, so that CMake gives the full link command of + * the library + */ +#include "dmodem_embed.h" + +/* Uses the library, so that the linker includes it. */ +int main(void) +{ + return dmodem_embed_version() ? 0 : 1; +} diff --git a/cmake/macos-embed/xcconfig.cmake b/cmake/macos-embed/xcconfig.cmake new file mode 100644 index 0000000..c2c029e --- /dev/null +++ b/cmake/macos-embed/xcconfig.cmake @@ -0,0 +1,40 @@ +# xcconfig.cmake - makes macos-embed.xcconfig from the link command that +# link-capture.sh wrote (cmake/MacosEmbed.cmake). It keeps the static +# libraries, the -l libraries and the frameworks of the command. A +# relative path is made absolute from the directory of the command. +# +# Usage: cmake -DIN= -DOUT= +# -DHEADERS= -P xcconfig.cmake + +file(STRINGS ${IN} _args) +list(POP_FRONT _args _dir) +set(_ld "") +set(_framework OFF) +foreach(_a ${_args}) + if(_framework) + string(APPEND _ld " -framework ${_a}") + set(_framework OFF) + elseif(_a STREQUAL "-framework") + set(_framework ON) + elseif(_a MATCHES "^-framework ") + string(APPEND _ld " ${_a}") + elseif(_a MATCHES "^-l" OR _a STREQUAL "-pthread") + string(APPEND _ld " ${_a}") + elseif(_a MATCHES "\\.a$") + get_filename_component(_p "${_a}" ABSOLUTE BASE_DIR "${_dir}") + string(APPEND _ld " \"${_p}\"") + endif() +endforeach() +# (the modem is C++: the app, Swift and C, links libc++ for it) +if(NOT _ld MATCHES " -lc\\+\\+") + string(APPEND _ld " -lc++") +endif() +file(WRITE ${OUT}.new +"// Made by CMake (cmake/MacosEmbed.cmake): the built-in modem +DMODEM_EMBED_HEADERS = \"${HEADERS}\" +DMODEM_EMBED_LDFLAGS =${_ld} +DMODEM_EMBED_SWIFT = DMODEM_GUI_EMBED +") +# (the same file is not written again, so Xcode does not rebuild) +file(COPY_FILE ${OUT}.new ${OUT} ONLY_IF_DIFFERENT) +file(REMOVE ${OUT}.new) diff --git a/docs/building.md b/docs/building.md index 5b95ed7..06f05a6 100644 --- a/docs/building.md +++ b/docs/building.md @@ -37,8 +37,12 @@ modem. The win9x build does not include the built-in modem: The app is in `windows/dmodem.exe` of the build directory. MSVC (`cmake -S . -B build -A Win32`) and MinGW also build the same code. -macOS: first use `cmake -S . -B build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build build` -(this builds libssh, for SSH). Then use `brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`. +macOS: first use `git submodule update --init`, then +`cmake -S . -B build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 && cmake --build build`. +This builds libssh (for SSH) and the built-in modem, and writes +`build/macos-embed.xcconfig` for the Xcode project. CMake 3.21 or later +is necessary for the built-in modem. Then use +`brew install xcodegen && cd macos && xcodegen && open DModem.xcodeproj`. The Windows app on Linux or macOS: get [clang-retro MFC](https://github.com/clang-retro/mfc), clang and `llvm-rc` (on macOS, `brew install llvm`). Then: diff --git a/docs/design.md b/docs/design.md index 14519b3..609864b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -335,7 +335,7 @@ the pty in the group of the user (`-g`). Thus dmodemd does not need root. Each app can also use a modem that already runs: a device path on Linux and macOS, or a TCP address or a COM port on Windows. -The Linux and Windows apps do not start dmodemd by default. They run the +The Linux, macOS and Windows apps do not start dmodemd by default. They run the modem in a thread (`libdmodem_embed`), and its DTE is a socket. Refer to [The built-in modem](embedded-modem.md). diff --git a/docs/embedded-modem.md b/docs/embedded-modem.md index 770c30a..f65da97 100644 --- a/docs/embedded-modem.md +++ b/docs/embedded-modem.md @@ -1,8 +1,8 @@ # The built-in modem -The Linux app and the Windows app (Windows 98 SE and later) have the -D-Modem modem in them. Thus, these apps do not need a separate `dmodemd`. -The macOS app and the Windows 95 build still use `dmodemd` at this time. +The Linux app, the macOS app and the Windows app (Windows 98 SE and +later) have the D-Modem modem in them. Thus, these apps do not need a +separate `dmodemd`. The Windows 95 build still uses `dmodemd`. ## What it does @@ -16,19 +16,20 @@ repository ([docs/embed.md](https://github.com/D-Modem/D-Modem/blob/main/docs/em 3. When you click **Stop**, the app hangs up the call and stops the thread. The built-in modem has these lines: a SIP account (or no account), a USB -modem, and a softmodem codec (ALSA). For "A modem that already runs", the +modem, and a softmodem codec (ALSA, Linux only). For "A modem that already runs", the app opens the device and starts no modem. ## Differences from dmodemd - There is no pty and no `/dev/ttyDM0` link. Other programs cannot use the built-in modem. To share the modem with other programs, start `dmodemd`. -- The app does not need root (Linux) or a firewall exception for a TCP - port (Windows). +- The app does not need root (Linux), a pty (macOS) or a firewall + exception for a TCP port (Windows). - A USB modem needs a udev rule that lets the user open the device. - A softmodem codec needs the user in the `audio` group. - The modem keeps the measurements of the line in - `~/.local/share/dmodem-gui/dmodem0.data` (Linux), or in + `~/.local/share/dmodem-gui/dmodem0.data` (Linux), + `~/Library/Application Support/D-Modem/dmodem0.data` (macOS), or `%APPDATA%\D-Modem\dmodem0.data` (Windows). - The **Log** page shows the log of the modem. @@ -40,6 +41,12 @@ On Linux: 2. In **Advanced**, set **Built-in modem** to off. 3. Optional: set the path of `dmodemd`. +On macOS: + +1. Open the line settings (**D-Modem > Settings**). +2. In **The modem**, set **Built-in modem** to off. +3. Optional: set the path of `dmodemd`. + On Windows, the Line Settings dialog does not have this setting yet. Close the app, and add this line to the `[line]` section of `%APPDATA%\D-Modem\dmodem.ini`: @@ -55,8 +62,8 @@ The D-Modem source is a git submodule in `external/D-Modem`. To get it: git submodule update --init If the submodule is there, CMake builds the built-in modem -(`DMODEM_GUI_EMBED`, on by default) for the Linux app, and for the Windows -app with the clang-retro configurations `win98`, `winme`, `win7` and later. +(`DMODEM_GUI_EMBED`, on by default) for the Linux app, the macOS app, and +the Windows app with the clang-retro configurations `win98`, `winme`, `win7` and later. It is off for `win32-picolibc` (the Windows 95 build) and for the Windows app on Linux and macOS (`DMODEM_GUI_WINPORT`). To build the app with no built-in modem, use `-DDMODEM_GUI_EMBED=OFF`. For a USB line and an ALSA line, also @@ -64,12 +71,21 @@ install `libusb-1.0-0-dev` and `libasound2-dev`. The first build downloads libre and Mbed TLS for the SIP line of the modem. +The macOS app builds with Xcode, not with CMake. CMake builds the +libraries of the built-in modem, and writes `build/macos-embed.xcconfig`. +This file gives Xcode the header path, the libraries and the Swift +condition `DMODEM_GUI_EMBED`. The Xcode project (`macos/project.yml`) +includes this file. Thus, do the CMake build before `xcodegen`. Refer to +[Building](building.md). + ## Licence D-Modem and the GUI are both under the AGPL-3.0-only, or a commercial licence from the D-Modem Authors. Thus the two combine under each licence. The built-in modem links libre (BSD-3-Clause), Mbed TLS (Apache-2.0), and -on Linux the libusb and ALSA libraries of the system (LGPL-2.1). +on Linux the libusb and ALSA libraries of the system (LGPL-2.1). On +Windows and macOS, the build links libusb (LGPL-2.1) statically, as +`dmodemd` does. ## Status @@ -79,7 +95,7 @@ on Linux the libusb and ALSA libraries of the system (LGPL-2.1). | Windows 98 SE and later | Done (`win98` build). It builds, and its imports agree with Windows 98 SE. It is not tested on Windows or Wine yet. | | Windows 7 and later | Done (`win7` build). It builds. It is not tested on Windows or Wine yet. | | Windows 95 and NT 4.0 | Not possible. Refer to "Windows 95" below. | -| macOS | Not done. Xcode must link the library. | +| macOS | Done. CI builds it and checks that the library is in the app. It is not tested on a Mac yet. | ### Windows 95 diff --git a/macos/DModem/Bridging.h b/macos/DModem/Bridging.h index 8e86fc0..0b153f4 100644 --- a/macos/DModem/Bridging.h +++ b/macos/DModem/Bridging.h @@ -2,7 +2,13 @@ * SPDX-License-Identifier: AGPL-3.0-only * Copyright (C) 2026 D-Modem Authors * - * Bridging.h - libdmodemctl and libdmodemssh, for Swift + * 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/LineConfig.swift b/macos/DModem/LineConfig.swift index f4a5ca7..cd7a9c9 100644 --- a/macos/DModem/LineConfig.swift +++ b/macos/DModem/LineConfig.swift @@ -36,6 +36,8 @@ struct LineConfig { 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 @@ -57,6 +59,7 @@ struct LineConfig { 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) ?? "" @@ -78,6 +81,7 @@ struct LineConfig { 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) diff --git a/macos/DModem/LineSettingsView.swift b/macos/DModem/LineSettingsView.swift index ed82cdc..1731828 100644 --- a/macos/DModem/LineSettingsView.swift +++ b/macos/DModem/LineSettingsView.swift @@ -64,9 +64,16 @@ struct LineSettingsView: View { TextField("Init string", text: $c.initString, prompt: Text("sent each time it opens")) .font(.body.monospaced()) if c.line != .device { - HStack { - TextField("dmodemd", text: $c.dmodemd, prompt: Text("looked for")) - Button("Choose…") { choosing = true } + 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) } diff --git a/macos/DModem/Modem.swift b/macos/DModem/Modem.swift index 707c14a..01b9f65 100644 --- a/macos/DModem/Modem.swift +++ b/macos/DModem/Modem.swift @@ -7,6 +7,10 @@ // 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 @@ -17,6 +21,36 @@ 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 @@ -88,6 +122,21 @@ final class Modem: ObservableObject { 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] = [] @@ -115,6 +164,9 @@ final class Modem: ObservableObject { 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) @@ -351,6 +403,7 @@ final class Modem: ObservableObject { // 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 { @@ -366,8 +419,15 @@ final class Modem: ObservableObject { 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 = path + device = name let s = DispatchSource.makeReadSource(fileDescriptor: f, queue: .main) s.setEventHandler { [weak self] in self?.readable() } s.resume() @@ -380,7 +440,6 @@ final class Modem: ObservableObject { loadSettings() refreshStats() pump() - return true } private func readable() { @@ -419,7 +478,7 @@ final class Modem: ObservableObject { lastState = state voice.sound(state) clearSettings() - running = process != nil + running = process != nil || embedRunning } // MARK: - dmodemd @@ -444,9 +503,6 @@ final class Modem: ObservableObject { running = openDevice(c.device) return } - guard let exe = findDmodemd() else { - return say("dmodemd was not found: install D-Modem, or set its path in the line settings") - } if !c.isSetUp { say("Set up the SIP account first") if !NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) { @@ -454,6 +510,12 @@ final class Modem: ObservableObject { } 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) @@ -545,16 +607,113 @@ final class Modem: ObservableObject { } func stop() { - if fd >= 0 && process != nil { + if fd >= 0 && (process != nil || embedRunning) { // hang up first, so the call ends cleanly dmc_hangup(session) pump() } closeDevice() + #if DMODEM_GUI_EMBED + stopEmbedded() + #endif process?.terminate() running = process != nil } + #if DMODEM_GUI_EMBED + // MARK: - the built-in modem + + /// Starts the built-in modem on the line settings' line, in a thread + /// of the app, and attaches its DTE socket. + private func startEmbedded(_ c: LineConfig) { + var keep: [UnsafeMutablePointer] = [] + 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() diff --git a/macos/project.yml b/macos/project.yml index d1bfd98..1e3247e 100644 --- a/macos/project.yml +++ b/macos/project.yml @@ -1,6 +1,9 @@ # The macOS app's Xcode project, made by XcodeGen. libssh and mbedTLS -# (for libdmodemssh) are built first by the repository's CMake, for both -# architectures, into ../build: +# (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 @@ -14,6 +17,9 @@ targets: DModem: type: application platform: macOS + configFiles: + Debug: ../build/macos-embed.xcconfig + Release: ../build/macos-embed.xcconfig sources: - path: DModem - path: ../core/src @@ -26,11 +32,13 @@ targets: 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 + 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, as CMake built them (see above) + # 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 + 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 @@ -42,8 +50,8 @@ targets: ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon CODE_SIGN_IDENTITY: "-" ENABLE_HARDENED_RUNTIME: YES - # dmodemd runs as a child process and the modem's pty is opened: - # no sandbox + # 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