From ece56c6386637203e7aa37c8dcda48593c95270e Mon Sep 17 00:00:00 2001 From: Mehmet Fiskindal Date: Sat, 21 Nov 2026 23:38:31 +0300 Subject: [PATCH 1/3] Fix Sailfish device input and pixel scaling - Integrate Maliit for on-screen keyboard input and share SDL keyboard handling - Render the canvas at physical resolution with automatic phone DPR - Build from app-local configuration and keep output under `.gea-sailfish` --- targets/sailfish-os/CMakeLists.txt | 14 +- targets/sailfish-os/README.md | 110 +++++++--- targets/sailfish-os/build-sailfish-os.ps1 | 3 +- targets/sailfish-os/build-sailfish-os.sh | 2 +- targets/sailfish-os/config.mjs | 119 ++++++++++ .../sailfish-os/include/sailfish_keyboard.h | 9 + targets/sailfish-os/main/sailfish_display.cpp | 80 ++++++- .../sailfish-os/main/sailfish_keyboard.cpp | 183 ++++++++++++++++ targets/sailfish-os/main/sailfish_main.cpp | 204 ++++++++---------- targets/sailfish-os/prepare.mjs | 127 ++++++----- targets/sailfish-os/test/config.test.mjs | 114 ++++++++++ 11 files changed, 761 insertions(+), 204 deletions(-) create mode 100644 targets/sailfish-os/config.mjs create mode 100644 targets/sailfish-os/include/sailfish_keyboard.h create mode 100644 targets/sailfish-os/main/sailfish_keyboard.cpp create mode 100644 targets/sailfish-os/test/config.test.mjs diff --git a/targets/sailfish-os/CMakeLists.txt b/targets/sailfish-os/CMakeLists.txt index 5c000b2..8eee2ef 100644 --- a/targets/sailfish-os/CMakeLists.txt +++ b/targets/sailfish-os/CMakeLists.txt @@ -10,6 +10,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(PkgConfig REQUIRED) pkg_check_modules(SDL2 REQUIRED IMPORTED_TARGET sdl2) pkg_check_modules(CURL REQUIRED IMPORTED_TARGET libcurl) +pkg_check_modules(MALIIT REQUIRED IMPORTED_TARGET maliit-glib) include(${CMAKE_CURRENT_SOURCE_DIR}/sources.cmake) add_executable(${GEA_PACKAGE_NAME} ${GEA_C_SOURCES} ${GEA_CXX_SOURCES}) @@ -20,6 +21,9 @@ target_compile_options(${GEA_PACKAGE_NAME} PRIVATE target_compile_definitions(${GEA_PACKAGE_NAME} PRIVATE GEA_EMBEDDED_HAS_GENERATED_FONTS=1 GEA_EMBEDDED_TTF_RUNTIME_FONTS=1 + # The Sailfish keyboard (Maliit, main/sailfish_keyboard.cpp) handles text + # entry; the engine's own on-screen keyboard would open on top of it. + GEA_EMBEDDED_ENABLE_VIRTUAL_KEYBOARD=0 $<$:GEA_EMBEDDED_GIF_C_API> GEA_SAILFISH_APP_ID="${GEA_APP_ID}" GEA_SAILFISH_APP_TITLE="${GEA_APP_TITLE}" @@ -27,7 +31,15 @@ target_compile_definitions(${GEA_PACKAGE_NAME} PRIVATE GEA_SAILFISH_APPLICATION_NAME="${GEA_SAILFISH_APPLICATION_NAME}") set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/platform/main/sailfish_main.cpp PROPERTIES COMPILE_DEFINITIONS GEA_SAILFISH_DEFAULT_DPR=${GEA_SAILFISH_DEFAULT_DPR}) -target_link_libraries(${GEA_PACKAGE_NAME} PRIVATE PkgConfig::SDL2 PkgConfig::CURL pthread m rt) +target_link_libraries(${GEA_PACKAGE_NAME} PRIVATE PkgConfig::SDL2 PkgConfig::CURL PkgConfig::MALIIT pthread m rt) +# App-declared link dependencies (gea.sailfish.pkgConfigModules and +# nativeSystemLibraries); the spec lists each module as a BuildRequires. +foreach(GEA_APP_PKG_MODULE IN LISTS GEA_APP_PKG_MODULES) + string(MAKE_C_IDENTIFIER "GEA_APP_PKG_${GEA_APP_PKG_MODULE}" GEA_APP_PKG_PREFIX) + pkg_check_modules(${GEA_APP_PKG_PREFIX} REQUIRED IMPORTED_TARGET ${GEA_APP_PKG_MODULE}) + target_link_libraries(${GEA_PACKAGE_NAME} PRIVATE PkgConfig::${GEA_APP_PKG_PREFIX}) +endforeach() +target_link_libraries(${GEA_PACKAGE_NAME} PRIVATE ${GEA_APP_SYSTEM_LIBRARIES}) target_link_options(${GEA_PACKAGE_NAME} PRIVATE -Wl,--export-dynamic) install(TARGETS ${GEA_PACKAGE_NAME} RUNTIME DESTINATION bin) diff --git a/targets/sailfish-os/README.md b/targets/sailfish-os/README.md index 1d985cf..58f64e8 100644 --- a/targets/sailfish-os/README.md +++ b/targets/sailfish-os/README.md @@ -3,22 +3,23 @@ Builds a Gea JSX/CSS app into a local Sailfish OS RPM. The host runs Vite and geatsc; `sfdk` compiles the staged C/C++ sources for Sailfish OS 5.1.0.11. -Requirements: Node.js 20.19+, `npm install` in this Linux repository and in -the app's workspace, a checkout of `geastack/core`, and Sailfish SDK with the -selected build target. The default core checkout is `../core` relative to this -Linux repository. Pass `--core-repo` (Bash) or `-CoreRepository` (PowerShell) -for another location. +Requirements: Node.js 20.19+, `npm install` in the app (with `@geastack/linux` +as a dependency), and Sailfish SDK with the selected build target. -Code generation uses this repository's npm core, compiler, and plugin. The -source manifest and native framework come from the core checkout. Preparation -checks that the npm core and checkout package versions match and fails before -code generation if they differ. Use `npm ci` for the locked tool dependencies -and a matching core checkout. Local core edits are still included in the build. +The GeaStack packages (core, compiler, plugin and the native framework +packages) are resolved from the app the way Node resolves them, with this +repository's own `node_modules` as a fallback. A `geastack/core` checkout is +optional: pass `--core-repo` (Bash) or `-CoreRepository` (PowerShell) to build +the native framework from it instead. Its version must then match the installed +`@geastack/core`, and local core edits are included in the build. -From the Linux repository on Linux: +Build output goes to `/.gea-sailfish/`, never into the installed package; +add that directory to the app's `.gitignore`. + +From the app directory on Linux: ```sh -./targets/sailfish-os/build-sailfish-os.sh ../examples/apps/tic-tac-toe --arch i486 +./node_modules/@geastack/linux/targets/sailfish-os/build-sailfish-os.sh . --arch aarch64 ``` The script finds `sfdk` on `PATH`. Pass `--sfdk /path/to/SailfishOS/bin/sfdk` @@ -35,6 +36,23 @@ Set only permissions the app actually needs, such as `Audio` for sound and `"permissions": ["Audio", "Internet"]`. An empty list does not allow networking; permissions are not inferred from app source code. +`"sandboxing": false` in `gea.sailfish` writes `Sandboxing=Disabled` to the +`[X-Sailjail]` section, for apps that must run other programs or see the whole +file system, such as a terminal. Harbour does not accept unsandboxed apps. + +App-owned native code is listed in `gea.nativeSources` (app-relative `.c`, +`.cc`, `.cpp` or `.cxx` files). They are copied into the project under +`app_native/` with their relative paths and compiled with the app. Link +dependencies go in `gea.sailfish`: + +| Key | Meaning | +| --- | --- | +| `nativeIncludeDirectories` | App-relative directories added to the include path | +| `nativeSystemLibraries` | Library names linked with `-l`, such as `util` for `openpty` | +| `pkgConfigModules` | pkg-config modules, such as `maliit-glib`; each one is also a `BuildRequires` | + +Paths must stay inside the app directory. + From the Linux repository on Windows: ```powershell @@ -44,7 +62,7 @@ From the Linux repository on Windows: Use `-SdkRoot` when Sailfish SDK is installed outside `C:\SailfishOS`. The RPM is written to -`targets/sailfish-os/build/-/project/RPMS/`. +`/.gea-sailfish/build/-/project/RPMS/`. Use `-PrepareOnly` in PowerShell for code generation without invoking `sfdk`. Before submitting a device package to Harbour, run `sfdk check` on its RPM. The `i486` build is for the emulator; build for the architecture of the target @@ -61,21 +79,57 @@ configuration use the `sailfish_` and `GEA_SAILFISH_` prefixes. Storage uses the organization and application names from the app's Sailjail identity. Runtime overrides are `GEA_SAILFISH_WIDTH`, `GEA_SAILFISH_HEIGHT`, -`GEA_SAILFISH_SCALE`, `GEA_SAILFISH_DPR`, and `GEA_SAILFISH_STORAGE_DIR`. - -Scale and DPR both default to 1: one CSS pixel is one canvas pixel and one SDL -window coordinate unit. The initial canvas is 410x502; resize events update it -to the available window dimensions divided by scale. DPR controls canvas pixels -per CSS pixel, while scale controls presentation magnification. Font generation -uses the same initial 410x502 viewport and the app's DPR; runtime TTF fonts adapt -to the current viewport and DPR after resize. CMake defaults to a Release build. - -Set `gea.sailfish.devicePixelRatio` in the app's `package.json` to change its -CSS density (default 1). For example, `"devicePixelRatio": 2` renders one CSS -pixel as two canvas pixels while keeping the SDL window scale at 1. A 720x1527 -window then provides a 360x763.5 CSS viewport. The same setting is used for font -generation and the executable's default DPR; `GEA_SAILFISH_DPR` overrides it at -runtime. This is useful for phone layouts designed around a 360 CSS pixel width. +`GEA_SAILFISH_SCALE`, `GEA_SAILFISH_DPR`, `GEA_SAILFISH_HIGHDPI` (`0` creates +the window without `SDL_WINDOW_ALLOW_HIGHDPI`), and `GEA_SAILFISH_STORAGE_DIR`. + +Hardware keys and text use the same SDL keyboard producer as the Raspberry Pi +OS target (`rpios_keyboard.h`). Key events carry `key`, `code`, `keyCode` and +the Shift/Control/Alt/Meta flags, and Escape is delivered to the app like any +other key; the app quits on the window close request or SIGTERM. Text from +`SDL_TEXTINPUT` is inserted into the focused input as UTF-8, and Backspace +removes one whole character. F11 toggles fullscreen. + +The Sailfish on-screen keyboard (Maliit, through `maliit-glib`) opens while an +input is focused and closes when focus leaves it; `type="password"` inputs ask +for hidden text. Committed text and special keys (Backspace, Enter, Tab, +arrows, Home/End, Delete, Escape) are delivered as SDL events, so they reach the +app exactly like a hardware keyboard. Word prediction and auto-correction are +turned off because the target does not draw pre-edit text. When the keyboard +opens, the compositor shrinks the window and the app receives a resize. + +Scale defaults to 1. The canvas +covers the window's drawable in physical pixels divided by scale, at startup and +after every resize, so a Wayland output scale does not stretch a low-resolution +canvas (which made text blocky). The texture is presented with nearest +filtering and integer scaling only, so one canvas pixel is exactly one panel +pixel at scale 1. DPR controls canvas pixels per CSS pixel, while scale controls +presentation magnification. CMake defaults to a Release build. + +`gea.sailfish.devicePixelRatio` in the app's `package.json` sets the CSS +density. It defaults to `"auto"`. On ARM builds (`aarch64`, `armv7hl`) auto is +pixel-perfect: the executable takes the largest integer DPR that keeps the +panel's short side at least 360 CSS pixels, so every CSS pixel is a whole NxN +block of panel pixels and edges never fall between pixels. The DPR is derived +from the panel, not the window, so it does not change when the on-screen +keyboard shrinks the window. On the current Sailfish phones this gives: + +| Device | Panel | Auto DPR | CSS viewport | +|---|---|---|---| +| Jolla C2 | 720x1600 | 2 | 360x800 | +| Xperia XA2, XA2 Plus, XA2 Ultra | 1080x1920 (XA2 Plus 1080x2160) | 3 | 360x640 (360x720) | +| Xperia 10, 10 Plus, 10 II, 10 III, 10 IV, 10 V | 1080x2520 | 3 | 360x840 | +| Jolla Phone (2026) | 1080x2340 | 3 | 360x780 | + +On the i486 emulator, auto is 1 (one CSS pixel per canvas pixel). A number +(0.5 to 8) is used as given on every architecture and multiplied by the Wayland +output scale (physical pixels per window point). `GEA_SAILFISH_DPR` (a number or +`auto`) overrides the setting at runtime; the startup log shows the chosen DPR +and CSS viewport. A non-integer DPR is not pixel-perfect: CSS edges can land +between panel pixels. + +Font generation uses the initial 410x502 viewport and the app's DPR; an auto +ARM build generates fonts for DPR 2 and 3. Runtime TTF fonts adapt to the +current viewport and DPR after resize. Fonts declared with `@font-face` are embedded as TTF files and rasterized at runtime. Character coverage depends on the core checkout's runtime TTF diff --git a/targets/sailfish-os/build-sailfish-os.ps1 b/targets/sailfish-os/build-sailfish-os.ps1 index a5bc532..a16a7a4 100644 --- a/targets/sailfish-os/build-sailfish-os.ps1 +++ b/targets/sailfish-os/build-sailfish-os.ps1 @@ -12,7 +12,8 @@ if ($CoreRepository) { $argsForNode += (Resolve-Path $CoreRepository).Path } & node @argsForNode if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($PrepareOnly) { exit 0 } -$project = Join-Path $here "build/$((Get-Content (Join-Path $AppDirectory 'package.json') | ConvertFrom-Json).gea.id)-$Architecture/project" +$appRoot = (Resolve-Path $AppDirectory).Path +$project = Join-Path $appRoot ".gea-sailfish/build/$((Get-Content (Join-Path $appRoot 'package.json') | ConvertFrom-Json).gea.id)-$Architecture/project" $sfdk = Join-Path $SdkRoot 'bin/sfdk.exe' if (!(Test-Path $sfdk)) { throw "Sailfish SDK missing at $sfdk" } Push-Location $project diff --git a/targets/sailfish-os/build-sailfish-os.sh b/targets/sailfish-os/build-sailfish-os.sh index 58969f4..7ee5c74 100755 --- a/targets/sailfish-os/build-sailfish-os.sh +++ b/targets/sailfish-os/build-sailfish-os.sh @@ -53,5 +53,5 @@ if [[ "$SFDK_BIN" == */* ]]; then fi command -v "$SFDK_BIN" >/dev/null || { echo "sfdk not found: $SFDK_BIN" >&2; exit 1; } APP_ID="$(node -e 'const fs=require("node:fs"); const p=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); process.stdout.write(p.gea.id)' "$APP_DIR/package.json")" -PROJECT_DIR="$TARGET_DIR/build/$APP_ID-$ARCH/project" +PROJECT_DIR="$APP_DIR/.gea-sailfish/build/$APP_ID-$ARCH/project" (cd "$PROJECT_DIR" && "$SFDK_BIN" -c "target=SailfishOS-5.1.0.11-$ARCH" build) diff --git a/targets/sailfish-os/config.mjs b/targets/sailfish-os/config.mjs new file mode 100644 index 0000000..c5067a8 --- /dev/null +++ b/targets/sailfish-os/config.mjs @@ -0,0 +1,119 @@ +// Reads and validates an app's package.json for the Sailfish OS target, and +// renders the .desktop entry and RPM spec. No side effects besides reading the +// files the app names, so it can be tested without the SDK or the framework. +import fs from 'node:fs' +import path from 'node:path' + +const NATIVE_SOURCE = /\.(c|cc|cpp|cxx)$/ +const LIBRARY_NAME = /^[A-Za-z][A-Za-z0-9_.+-]*$/ +const PKG_CONFIG_MODULE = /^[A-Za-z0-9][A-Za-z0-9_.+-]*$/ + +const stringList = (value, name) => { + if (value === undefined) return [] + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item)) throw new Error(`${name} must be an array of nonempty strings`) + return [...new Set(value)] +} + +// An app-relative path that stays inside the app after symlinks are resolved. +const appPath = (appDir, value, name, kind) => { + if (path.isAbsolute(value) || value.split(/[\\/]/).includes('..') || /[\x00-\x1f\x7f"$;\\]/.test(value)) throw new Error(`${name}: invalid path ${value}`) + const realApp = fs.realpathSync(appDir) + let real + try { + real = fs.realpathSync(path.join(appDir, value)) + } catch { + throw new Error(`${name}: missing ${value}`) + } + const relative = path.relative(realApp, real) + if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw new Error(`${name}: ${value} escapes the app directory`) + const stat = fs.statSync(real) + if (kind === 'file' ? !stat.isFile() : !stat.isDirectory()) throw new Error(`${name}: ${value} is not a ${kind === 'file' ? 'regular file' : 'directory'}`) + return { relative: relative.split(path.sep).join('/'), absolute: real } +} + +export function readSailfishConfig(appDir, meta) { + const app = meta.gea + if (!app?.id || !/^[a-z0-9][a-z0-9-]*$/.test(app.id)) throw new Error('gea.id must be a lowercase package identifier') + const appName = String(app.name || app.id) + const rpmLicense = String(meta.license || 'MIT') + if (/[\x00-\x1f\x7f%\\";$]/.test(appName)) throw new Error('gea.name must not contain control characters or RPM/CMake syntax') + if (/[\x00-\x1f\x7f%]/.test(rpmLicense)) throw new Error('package license must not contain control characters or RPM macros') + const sailfish = app.sailfish || {} + const organizationName = sailfish.organizationName || 'org.geastack' + const applicationName = sailfish.applicationName || app.id.replaceAll('-', '_') + const permissions = sailfish.permissions || [] + const devicePixelRatio = sailfish.devicePixelRatio ?? 'auto' + const sandboxing = sailfish.sandboxing ?? true + if (devicePixelRatio !== 'auto' && (typeof devicePixelRatio !== 'number' || !Number.isFinite(devicePixelRatio) || devicePixelRatio < 0.5 || devicePixelRatio > 8)) throw new Error('gea.sailfish.devicePixelRatio must be "auto" or a number between 0.5 and 8') + if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/.test(organizationName)) throw new Error('gea.sailfish.organizationName must be a reverse-domain name') + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(applicationName)) throw new Error('gea.sailfish.applicationName must contain only letters, digits, and underscores') + if (!Array.isArray(permissions) || !permissions.every((item) => typeof item === 'string' && /^[A-Za-z]+$/.test(item))) throw new Error('gea.sailfish.permissions must be an array of permission names') + if (typeof sandboxing !== 'boolean') throw new Error('gea.sailfish.sandboxing must be true or false') + + const npmVersion = meta.version || '0.1.0' + const versionMatch = typeof npmVersion === 'string' && npmVersion.match(/^(\d+\.\d+\.\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/) + if (!versionMatch) throw new Error('package.json version must be a valid x.y.z version with optional prerelease and build metadata') + const rpmVersion = versionMatch[1] + (versionMatch[2] ? `~${versionMatch[2].replaceAll('-', '.')}` : '') + + const nativeSources = stringList(app.nativeSources, 'gea.nativeSources').map((value) => { + if (!NATIVE_SOURCE.test(value)) throw new Error(`gea.nativeSources: unsupported source ${value} (use .c, .cc, .cpp or .cxx)`) + return appPath(appDir, value, 'gea.nativeSources', 'file') + }) + const nativeIncludeDirectories = stringList(sailfish.nativeIncludeDirectories, 'gea.sailfish.nativeIncludeDirectories') + .map((value) => appPath(appDir, value, 'gea.sailfish.nativeIncludeDirectories', 'directory')) + const nativeSystemLibraries = stringList(sailfish.nativeSystemLibraries, 'gea.sailfish.nativeSystemLibraries') + for (const name of nativeSystemLibraries) if (!LIBRARY_NAME.test(name)) throw new Error(`gea.sailfish.nativeSystemLibraries: invalid library ${name}`) + const pkgConfigModules = stringList(sailfish.pkgConfigModules, 'gea.sailfish.pkgConfigModules') + for (const name of pkgConfigModules) if (!PKG_CONFIG_MODULE.test(name)) throw new Error(`gea.sailfish.pkgConfigModules: invalid module ${name}`) + + return { + id: app.id, + entry: app.entry || 'index.tsx', + icons: app.icons || {}, + appName, + rpmLicense, + rpmVersion, + packageName: `harbour-gea-${app.id}`, + organizationName, + applicationName, + permissions: [...new Set(permissions)], + devicePixelRatio, + sandboxing, + nativeSources, + nativeIncludeDirectories, + nativeSystemLibraries, + pkgConfigModules, + } +} + +// Integer DPRs an "auto" build is expected to pick on Sailfish phones: 2 on +// 720-pixel-wide panels (Jolla C2) and 3 on 1080-pixel-wide panels (Xperia XA2, +// Xperia 10 through 10 V, Jolla Phone). Build-time fonts are generated for both; +// other sizes fall back to the runtime TTF rasterizer. +const PHONE_DENSITIES = [2, 3] + +// The DPR compiled into the executable (0: derive an integer DPR from the +// panel at startup, see sailfish_main.cpp) and the ratios fonts are generated +// for. "auto" is panel-derived on ARM phones; the x86 emulator keeps one CSS +// pixel per canvas pixel. +export function sailfishDensity(config, arch) { + const ratio = config.devicePixelRatio + if (ratio !== 'auto') return { runtime: ratio, fontRatios: [ratio] } + if (arch === 'i486') return { runtime: 1, fontRatios: [1] } + return { runtime: 0, fontRatios: [...PHONE_DENSITIES] } +} + +export function desktopEntry(config) { + const sailjail = [ + ...(config.sandboxing ? [] : ['Sandboxing=Disabled']), + `OrganizationName=${config.organizationName}`, + `ApplicationName=${config.applicationName}`, + `Permissions=${config.permissions.join(';')}`, + ] + return `[Desktop Entry]\nType=Application\nName=${config.appName}\nExec=${config.packageName}\nIcon=${config.packageName}\nX-Nemo-Application-Type=generic\n\n[X-Sailjail]\n${sailjail.join('\n')}\n` +} + +export function rpmSpec(config) { + const buildRequires = [...new Set(['cmake', 'pkgconfig(sdl2)', 'pkgconfig(libcurl)', 'pkgconfig(maliit-glib)', ...config.pkgConfigModules.map((name) => `pkgconfig(${name})`)])] + return `Name: ${config.packageName}\nVersion: ${config.rpmVersion}\nRelease: 1\nSummary: Gea ${config.appName} for Sailfish OS\nLicense: ${config.rpmLicense}\n${buildRequires.map((item) => `BuildRequires: ${item}\n`).join('')}\n%description\nGea JSX application for Sailfish OS.\n\n%build\n%cmake .\n%make_build\n\n%install\n%make_install\n\n%files\n%{_bindir}/${config.packageName}\n%{_datadir}/applications/${config.packageName}.desktop\n%{_datadir}/icons/hicolor/*/apps/${config.packageName}.png\n` +} diff --git a/targets/sailfish-os/include/sailfish_keyboard.h b/targets/sailfish-os/include/sailfish_keyboard.h new file mode 100644 index 0000000..f356565 --- /dev/null +++ b/targets/sailfish-os/include/sailfish_keyboard.h @@ -0,0 +1,9 @@ +#pragma once +/* Sailfish OS on-screen keyboard (Maliit) client; see main/sailfish_keyboard.cpp. */ + +void sailfish_keyboard_init(); +// Runs pending Maliit D-Bus work; call before reading SDL events each frame. +void sailfish_keyboard_pump(); +// Shows the keyboard while an input is focused (-1: none) and hides it after. +void sailfish_keyboard_update(int activeInputId, bool hiddenText); +void sailfish_keyboard_shutdown(); diff --git a/targets/sailfish-os/main/sailfish_display.cpp b/targets/sailfish-os/main/sailfish_display.cpp index 791519e..dc50d34 100644 --- a/targets/sailfish-os/main/sailfish_display.cpp +++ b/targets/sailfish-os/main/sailfish_display.cpp @@ -14,8 +14,9 @@ * framework relies on a working clip to constrain each dirty-region * replay; stubbing them tanks fps (see the geaos header comment). * - The window is an integer-scaled view of the logical canvas - * (GEA_SAILFISH_SCALE, default 1). After a window resize, the canvas is - * resized to window size / scale. At the default scale and DPR of 1, + * (GEA_SAILFISH_SCALE, default 1). The canvas is the renderer output in + * physical pixels / scale, at startup and after every window resize, so + * a Wayland output scale does not stretch a low-resolution canvas. At the default scale and DPR of 1, * one CSS pixel is one canvas pixel and one SDL window coordinate unit. * * Window size / scale / DPR come from the environment so apps tuned for a @@ -23,7 +24,9 @@ * GEA_SAILFISH_WIDTH initial canvas width (default 410) * GEA_SAILFISH_HEIGHT initial canvas height (default 502) * GEA_SAILFISH_SCALE integer window scale (default 1) - * GEA_SAILFISH_DPR canvas pixels per CSS pixel (app setting, otherwise 1) + * GEA_SAILFISH_DPR canvas pixels per CSS pixel, or "auto" (app setting; + * "auto" is an integer derived from the panel, see + * sailfish_main.cpp) * * The window is resizable: the main loop reacts to SDL_WINDOWEVENT_SIZE_CHANGED * by calling sailfish_display_resize(), which reallocates the framebuffer + @@ -115,7 +118,8 @@ void ensure_window() #ifndef GEA_SAILFISH_APP_TITLE #define GEA_SAILFISH_APP_TITLE "gea" #endif - int window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE; + int window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; + if (env_int("GEA_SAILFISH_HIGHDPI", 1, 0, 1)) window_flags |= SDL_WINDOW_ALLOW_HIGHDPI; window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; g_window = SDL_CreateWindow(GEA_SAILFISH_APP_TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, @@ -137,9 +141,36 @@ void ensure_window() std::fprintf(stderr, "[sailfish display] SDL_CreateRenderer failed: %s\n", SDL_GetError()); return; } + // The canvas covers the renderer's output in physical pixels (divided by + // scale), not the window size: under a Wayland output scale the window size + // is in points, and a points-sized canvas stretched to the output made every + // glyph a block of pixels. One canvas pixel is one panel pixel at scale 1. + { + int output_w = 0, output_h = 0; + if (SDL_GetRendererOutputSize(g_renderer, &output_w, &output_h) == 0 && output_w > 0 && output_h > 0) { + const int w = std::clamp(output_w / g_window_scale, 64, 4096); + const int h = std::clamp(output_h / g_window_scale, 64, 4096); + if (w != g_canvas_width || h != g_canvas_height) { + const size_t pixels = (size_t)w * (size_t)h; + uint16_t *fb = static_cast(std::calloc(pixels, sizeof(uint16_t))); + if (fb) { + std::free(g_framebuffer); + g_framebuffer = fb; + g_framebuffer_pixels = pixels; + g_canvas_width = w; + g_canvas_height = h; + g_canvas.bindPixels(g_framebuffer, g_canvas_width, g_canvas_height); + } + } + } + } // Integer-scale the logical canvas to the window; nearest keeps pixels crisp. + // Integer scale makes SDL letterbox a remainder instead of stretching the + // canvas by a fraction, so one canvas pixel always covers exactly scale x + // scale panel pixels (1x1 at the default scale). SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); SDL_RenderSetLogicalSize(g_renderer, g_canvas_width, g_canvas_height); + SDL_RenderSetIntegerScale(g_renderer, SDL_TRUE); g_texture = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, g_canvas_width, g_canvas_height); @@ -150,9 +181,13 @@ void ensure_window() SDL_RendererInfo info{}; SDL_GetRendererInfo(g_renderer, &info); g_sdl_ok = true; - std::fprintf(stderr, "[sailfish display] SDL window %dx%d (scale %d, renderer %s%s)\n", + int window_w = 0, window_h = 0, output_w = 0, output_h = 0; + SDL_GetWindowSize(g_window, &window_w, &window_h); + SDL_GetRendererOutputSize(g_renderer, &output_w, &output_h); + std::fprintf(stderr, "[sailfish display] SDL window %dx%d (scale %d, renderer %s%s) window=%dx%d output=%dx%d highdpi=%d\n", g_canvas_width, g_canvas_height, g_window_scale, info.name, - (info.flags & SDL_RENDERER_PRESENTVSYNC) ? ", vsync" : ""); + (info.flags & SDL_RENDERER_PRESENTVSYNC) ? ", vsync" : "", + window_w, window_h, output_w, output_h, (window_flags & SDL_WINDOW_ALLOW_HIGHDPI) ? 1 : 0); } void upload_rect(int x0, int y0, int x1, int y1) @@ -245,6 +280,39 @@ extern "C" void sailfish_display_toggle_fullscreen() } extern "C" int sailfish_display_window_scale() { return g_window_scale; } +// Physical pixel size of the window's drawable (the renderer output); the +// canvas is this size divided by the window scale. Returns 0 before SDL is up. +extern "C" int sailfish_display_output_size(int *width, int *height) +{ + if (!g_sdl_ok || SDL_GetRendererOutputSize(g_renderer, width, height) != 0) return 0; + return *width > 0 && *height > 0; +} +// Physical pixels per window point (the Wayland output scale; 1 without one). +// The main loop multiplies the app's DPR by it, so CSS sizes keep the size +// they had on a points-sized canvas while being drawn at full resolution. +extern "C" double sailfish_display_output_ratio() +{ + int window_w = 0, window_h = 0, output_w = 0, output_h = 0; + if (!g_sdl_ok) return 1.0; + SDL_GetWindowSize(g_window, &window_w, &window_h); + if (window_w <= 0 || SDL_GetRendererOutputSize(g_renderer, &output_w, &output_h) != 0 || output_w <= 0) return 1.0; + const double ratio = (double)output_w / (double)window_w; + return ratio >= 1.0 && ratio <= 8.0 ? ratio : 1.0; +} +// Short side of the panel in physical pixels: the largest short side the +// fullscreen drawable has reported. Kept as a maximum so the on-screen keyboard +// shrinking the window (in either orientation) does not change it; the main +// loop derives the "auto" DPR from it. Returns 0 before SDL is up. +extern "C" int sailfish_display_panel_short_side() +{ + static int panel = 0; + int w = 0, h = 0; + if (g_sdl_ok && SDL_GetRendererOutputSize(g_renderer, &w, &h) == 0 && w > 0 && h > 0) + panel = std::max(panel, std::min(w, h)); + return panel; +} +extern "C" Uint32 sailfish_display_window_id() { return g_window ? SDL_GetWindowID(g_window) : 0; } +extern "C" bool sailfish_display_keyboard_focus() { return g_window && (SDL_GetWindowFlags(g_window) & SDL_WINDOW_INPUT_FOCUS); } // Rebuild the framebuffer + streaming texture at a new logical size (window // resized or fullscreen toggled). The canvas rebinds to the new buffer; the diff --git a/targets/sailfish-os/main/sailfish_keyboard.cpp b/targets/sailfish-os/main/sailfish_keyboard.cpp new file mode 100644 index 0000000..35690df --- /dev/null +++ b/targets/sailfish-os/main/sailfish_keyboard.cpp @@ -0,0 +1,183 @@ +/* targets/sailfish-os/main/sailfish_keyboard.cpp + * Sailfish OS on-screen keyboard (Maliit) client. + * + * SDL's Wayland backend does not talk to the Sailfish keyboard, so focusing an + * would never raise it. This client asks the Maliit server to show the + * keyboard while an input is focused and turns what the keyboard sends into + * ordinary SDL events: committed text becomes SDL_TEXTINPUT and special keys + * (Backspace, Enter, arrows, ...) become SDL_KEYDOWN/SDL_KEYUP. Everything then + * takes the same path as a hardware keyboard (the shared keyboard Producer), + * including UTF-8 text, Enter commits and whole-character Backspace. + * + * Maliit talks D-Bus through GLib, so the default GLib main context is pumped + * once per frame before SDL events are read. Without a Maliit server (for + * example on a desktop session) the client logs once and stays inert. */ + +#include "sailfish_keyboard.h" + +#include +#include +#include + +#include +#include + +extern "C" Uint32 sailfish_display_window_id(); + +namespace { + +MaliitInputMethod *g_input_method = nullptr; +MaliitServer *g_server = nullptr; +MaliitContext *g_context = nullptr; +bool g_visible = false; +int g_focused_input = -1; + +// Qt key codes the Sailfish keyboard sends for keys that are not text. +SDL_Keycode sdlKeyForQt(int key) +{ + switch (key) { + case 0x01000000: return SDLK_ESCAPE; + case 0x01000001: return SDLK_TAB; + case 0x01000003: return SDLK_BACKSPACE; + case 0x01000004: return SDLK_RETURN; + case 0x01000005: return SDLK_KP_ENTER; + case 0x01000007: return SDLK_DELETE; + case 0x01000010: return SDLK_HOME; + case 0x01000011: return SDLK_END; + case 0x01000012: return SDLK_LEFT; + case 0x01000013: return SDLK_UP; + case 0x01000014: return SDLK_RIGHT; + case 0x01000015: return SDLK_DOWN; + default: return SDLK_UNKNOWN; + } +} + +void pushKey(Uint32 type, SDL_Keycode sym) +{ + SDL_Event event{}; + event.type = type; + event.key.timestamp = SDL_GetTicks(); + event.key.windowID = sailfish_display_window_id(); + event.key.state = type == SDL_KEYDOWN ? SDL_PRESSED : SDL_RELEASED; + event.key.keysym.sym = sym; + event.key.keysym.scancode = SDL_GetScancodeFromKey(sym); + SDL_PushEvent(&event); +} + +// SDL_TEXTINPUT holds at most 31 bytes; split longer commits (pasted text, +// whole words) on UTF-8 character boundaries. +void pushText(const char *utf8) +{ + const std::size_t capacity = sizeof(SDL_TextInputEvent::text) - 1; + std::size_t length = std::strlen(utf8); + while (length) { + std::size_t take = length < capacity ? length : capacity; + while (take < length && take && (static_cast(utf8[take]) & 0xc0) == 0x80) --take; + if (!take) return; // malformed: a continuation run longer than an event + SDL_Event event{}; + event.type = SDL_TEXTINPUT; + event.text.timestamp = SDL_GetTicks(); + event.text.windowID = sailfish_display_window_id(); + std::memcpy(event.text.text, utf8, take); + SDL_PushEvent(&event); + utf8 += take; + length -= take; + } +} + +gboolean onCommitString(MaliitContext *context, GDBusMethodInvocation *invocation, + const gchar *text, gint, gint, gint, gpointer) +{ + if (text && *text) pushText(text); + maliit_context_complete_commit_string(context, invocation); + return TRUE; +} + +// QEvent::KeyRelease is 7; anything else is treated as a press. +gboolean onKeyEvent(MaliitContext *context, GDBusMethodInvocation *invocation, + gint type, gint key, gint, const gchar *text, gboolean, gint, guchar, gpointer) +{ + const SDL_Keycode sym = sdlKeyForQt(key); + if (sym != SDLK_UNKNOWN) pushKey(type == 7 ? SDL_KEYUP : SDL_KEYDOWN, sym); + else if (type != 7 && text && *text) pushText(text); + maliit_context_complete_key_event(context, invocation); + return TRUE; +} + +void updateWidgetInformation(bool focused, bool hiddenText) +{ + if (!g_server) return; + GVariantBuilder builder; + g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&builder, "{sv}", "focusState", g_variant_new_boolean(focused)); + g_variant_builder_add(&builder, "{sv}", "hiddenText", g_variant_new_boolean(hiddenText)); + // Pre-edit text is not rendered by the target, so the keyboard must commit + // every key at once instead of holding words back for prediction. + g_variant_builder_add(&builder, "{sv}", "predictionEnabled", g_variant_new_boolean(false)); + g_variant_builder_add(&builder, "{sv}", "correctionEnabled", g_variant_new_boolean(false)); + GVariant *state = g_variant_ref_sink(g_variant_builder_end(&builder)); + GError *error = nullptr; + if (!maliit_server_call_update_widget_information_sync(g_server, state, TRUE, nullptr, &error)) { + std::fprintf(stderr, "[sailfish keyboard] widget update failed: %s\n", error ? error->message : "unknown"); + if (error) g_error_free(error); + } + g_variant_unref(state); +} + +} // namespace + +void sailfish_keyboard_init() +{ + GError *error = nullptr; + g_context = maliit_get_context_sync(nullptr, &error); + if (!g_context) { + std::fprintf(stderr, "[sailfish keyboard] Maliit unavailable: %s\n", error ? error->message : "unknown"); + if (error) g_error_free(error); + return; + } + g_server = maliit_get_server_sync(nullptr, &error); + if (!g_server) { + std::fprintf(stderr, "[sailfish keyboard] Maliit server unavailable: %s\n", error ? error->message : "unknown"); + if (error) g_error_free(error); + g_object_unref(g_context); + g_context = nullptr; + return; + } + g_signal_connect(g_context, "handle-commit-string", G_CALLBACK(onCommitString), nullptr); + g_signal_connect(g_context, "handle-key-event", G_CALLBACK(onKeyEvent), nullptr); + g_input_method = maliit_input_method_new(); + std::fprintf(stderr, "[sailfish keyboard] Maliit ready\n"); +} + +void sailfish_keyboard_pump() +{ + if (!g_context) return; + while (g_main_context_iteration(nullptr, FALSE)) {} +} + +void sailfish_keyboard_update(int activeInputId, bool hiddenText) +{ + if (!g_input_method) return; + const bool show = activeInputId >= 0; + if (show == g_visible && activeInputId == g_focused_input) return; + g_focused_input = activeInputId; + updateWidgetInformation(show, hiddenText); + if (show == g_visible) return; + g_visible = show; + if (show) maliit_input_method_show(g_input_method); + else maliit_input_method_hide(g_input_method); + std::fprintf(stderr, "[sailfish keyboard] %s (input %d)\n", show ? "show" : "hide", activeInputId); +} + +void sailfish_keyboard_shutdown() +{ + if (g_input_method && g_visible) maliit_input_method_hide(g_input_method); + g_visible = false; + g_focused_input = -1; + if (g_input_method) g_object_unref(g_input_method); + if (g_server) g_object_unref(g_server); + if (g_context) g_object_unref(g_context); + g_input_method = nullptr; + g_server = nullptr; + g_context = nullptr; +} diff --git a/targets/sailfish-os/main/sailfish_main.cpp b/targets/sailfish-os/main/sailfish_main.cpp index f4dbf49..4a94e15 100644 --- a/targets/sailfish-os/main/sailfish_main.cpp +++ b/targets/sailfish-os/main/sailfish_main.cpp @@ -13,7 +13,7 @@ * per frame: * pump SDL events: * mouse (pointer 0) / fingers (multi-touch) → touch event queue - * keys → input::queueKeyDown, text → focused value + * keys/text → keyboard Producer (rpios_keyboard.h) → focused node * wheel → Tree::scrollByKeyStep + input::queueRotaryDelta * window resize/minimize/expose → display resize / pause / re-present * dispatch queued events (touch → TouchRuntime; key/rotary drains) @@ -43,9 +43,14 @@ #include "ui/style.h" #include "ui/tree_internal.h" #include "touch.h" +// Shared with Raspberry Pi OS: SDL key/text events with key/code/modifier +// metadata, UTF-8 text and whole-code-point Backspace for focused inputs. + +#include "sailfish_keyboard.h" #include +#include #include #include #include @@ -63,6 +68,11 @@ extern "C" int sailfish_display_consume_vsync_wait(); extern "C" void sailfish_display_present(); extern "C" void sailfish_display_toggle_fullscreen(); extern "C" int sailfish_display_window_scale(); +extern "C" Uint32 sailfish_display_window_id(); +extern "C" int sailfish_display_output_size(int *width, int *height); +extern "C" double sailfish_display_output_ratio(); +extern "C" int sailfish_display_panel_short_side(); +extern "C" bool sailfish_display_keyboard_focus(); extern "C" int sailfish_display_resize(int new_width, int new_height); extern "C" int gea_embedded_apps_launch(const char *app_id); extern "C" void sailfish_runtime_storage_load(); @@ -79,16 +89,41 @@ void installAppLauncherPlatform(const char *currentAppId); namespace { +// The app's DPR: GEA_SAILFISH_DPR, otherwise the build's default. 0 means +// "auto" (the default on ARM phone builds, see config.mjs sailfishDensity). double devicePixelRatio() { const char *v = std::getenv("GEA_SAILFISH_DPR"); if (v && *v) { + if (std::strcmp(v, "auto") == 0) return 0.0; const double dpr = std::atof(v); if (dpr >= 0.5 && dpr <= 8.0) return dpr; } return GEA_SAILFISH_DEFAULT_DPR; } +// CSS width an "auto" DPR keeps at least: the common phone layout width. +constexpr int kAutoCssShortSide = 360; + +// The DPR handed to the framework. An explicit app DPR is multiplied by the +// output scale (the canvas is in physical pixels, see sailfish_display.cpp). +// "auto" is pixel-perfect: the largest integer that keeps the panel's short +// side at least 360 CSS pixels wide, so every CSS pixel is a whole N x N block +// of canvas pixels and edges never land between panel pixels. Every current +// Sailfish phone is 720 or 1080 pixels wide: Jolla C2 (720x1600) gets 2 and a +// 360x800 viewport; Xperia XA2 family (1080x1920), Xperia 10 through 10 V +// (1080x2520) and Jolla Phone (1080x2340) get 3 and 360 CSS pixels across. +// It is derived from the panel, not the window, so the on-screen keyboard +// opening does not change the density. +double effectiveDevicePixelRatio() +{ + const double app = devicePixelRatio(); + if (app > 0.0) return app * sailfish_display_output_ratio(); + const int scale = std::max(1, sailfish_display_window_scale()); + const int shortSide = sailfish_display_panel_short_side() / scale; + return (double)std::max(1, shortSide / kAutoCssShortSide); +} + // Drive CSS animations each frame. Like geaos, this target runs its own loop // and calls Application::frame() directly instead of going through the // runtime's run_app_frame(), which is the only place that starts and ticks the @@ -173,31 +208,6 @@ void injectFinger(gea::platform::touch::Phase phase, bool touching, float nx, fl // ---- keyboard -------------------------------------------------------------- -// SDL keysym → web keyCode (the framework's key event currency; see -// input::queueKeyDown). Unmapped keys return 0 and are dropped. -int webKeyCodeForSdl(SDL_Keycode sym) -{ - if (sym >= SDLK_a && sym <= SDLK_z) return 'A' + (int)(sym - SDLK_a); - if (sym >= SDLK_0 && sym <= SDLK_9) return '0' + (int)(sym - SDLK_0); - switch (sym) { - case SDLK_RETURN: - case SDLK_KP_ENTER: return 13; - case SDLK_BACKSPACE: return 8; - case SDLK_TAB: return 9; - case SDLK_SPACE: return 32; - case SDLK_PAGEUP: return 33; - case SDLK_PAGEDOWN: return 34; - case SDLK_END: return 35; - case SDLK_HOME: return 36; - case SDLK_LEFT: return 37; - case SDLK_UP: return 38; - case SDLK_RIGHT: return 39; - case SDLK_DOWN: return 40; - case SDLK_DELETE: return 46; - default: return 0; - } -} - // Mark a mutated so its new value actually reaches the panel — same // bits the virtual keyboard sets (see virtual_keyboard.cpp applyKeyToActiveInput: // render.dirty alone records the DrawText command but the dirty-region tracker @@ -213,60 +223,7 @@ void markNodeFullyDirty(gea::embedded::ui::Tree &tree, int nodeId) node.render.non_scroll_dirty = 1; } -// Physical-keyboard text entry: mutate the focused 's value attribute -// and fire the synthetic input/keydown events, mirroring what the on-screen -// virtual keyboard does for taps. Returns false when no input is focused. -bool appendTextToActiveInput(const char *utf8) -{ - auto &tree = gea::embedded::ui::Tree::instance(); - const int activeId = tree.activeInputId(); - if (activeId < 0) return false; - - const char *currentValue = tree.getAttribute(activeId, "value"); - std::string next = currentValue ? std::string(currentValue) : std::string(); - bool changed = false; - for (const char *p = utf8; *p; p++) { - // ASCII printable only — the raster pipeline's fonts cover ASCII. - if (*p >= 32 && *p < 127) { - next.push_back(*p); - changed = true; - } - } - if (!changed) return true; - tree.setAttribute(activeId, "value", next.c_str()); - markNodeFullyDirty(tree, activeId); - - gea::framework::events::PointerEvent ev{}; - ev.type = gea::framework::events::PointerEventType::Input; - ev.targetId = activeId; - tree.dispatchEvent(ev); - return true; -} - -bool applyBackspaceToActiveInput() -{ - auto &tree = gea::embedded::ui::Tree::instance(); - const int activeId = tree.activeInputId(); - if (activeId < 0) return false; - - const char *currentValue = tree.getAttribute(activeId, "value"); - std::string next = currentValue ? std::string(currentValue) : std::string(); - if (!next.empty()) { - next.pop_back(); - tree.setAttribute(activeId, "value", next.c_str()); - markNodeFullyDirty(tree, activeId); - gea::framework::events::PointerEvent ev{}; - ev.type = gea::framework::events::PointerEventType::Input; - ev.targetId = activeId; - tree.dispatchEvent(ev); - } - gea::framework::events::PointerEvent kd{}; - kd.type = gea::framework::events::PointerEventType::KeyDown; - kd.targetId = activeId; - kd.keyCode = 8; - tree.dispatchEvent(kd); - return true; -} +gea::rpios::keyboard::Producer g_keyboard; // ---- per-frame input drains (mirrors core/runtime.cpp, which this target // excludes because it runs its own loop) ------------------------------------ @@ -280,17 +237,21 @@ void dispatchRotaryInput() void dispatchKeyInput() { - auto &tree = gea::embedded::ui::Tree::instance(); - for (int keyCode = gea::framework::input::consumeKeyDown(); keyCode != 0; - keyCode = gea::framework::input::consumeKeyDown()) { + g_keyboard.bind(sailfish_display_window_id(), sailfish_display_keyboard_focus()); + g_keyboard.drain(sailfish_display_toggle_fullscreen); + // Non-SDL hardware producers still use the integer queue. SDL keys never + // enter it, so they are not delivered twice or stripped of their metadata. + gea::framework::input::HardwareKeyEvent key{}; + while (gea::framework::input::consumeKeyEvent(key)) { + auto owner = gea::embedded::ui::Document::instance().activeElement(); + if (!owner.valid()) owner = gea::embedded::ui::NodeHandle(gea::embedded::ui::Tree::instance().mountedRoot()); + if (!owner.isConnected() || owner.disabled() || + gea::embedded::ui::selector::disabled(gea::embedded::ui::Tree::instance(), owner.id())) continue; gea::framework::events::PointerEvent event{}; - event.type = gea::framework::events::PointerEventType::KeyDown; - event.keyCode = keyCode; - event.bubbles = true; - event.cancelable = true; - - const int inputId = tree.activeInputId(); - event.targetId = inputId; + event.type = key.pressed ? gea::framework::events::PointerEventType::KeyDown + : gea::framework::events::PointerEventType::KeyUp; + event.keyCode = key.keyCode; + event.targetId = owner.id(); gea::embedded::ui::dispatchRootKeyEvent(event); } } @@ -307,32 +268,24 @@ void pumpSdlEvents() { using gea::platform::touch::Phase; static bool mouseDown = false; + g_keyboard.bind(sailfish_display_window_id(), sailfish_display_keyboard_focus()); + // On-screen keyboard input arrives as SDL events pushed from here. + sailfish_keyboard_pump(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: g_stop = 1; break; - case SDL_KEYDOWN: { - const SDL_Keycode sym = event.key.keysym.sym; - if (sym == SDLK_ESCAPE) { - g_stop = 1; - break; - } - if (sym == SDLK_F11) { - sailfish_display_toggle_fullscreen(); - break; - } - // Backspace/Enter on a focused take the virtual-keyboard - // path (value mutation + synthetic events); everything else is - // queued as a web keyCode and drained by dispatchKeyInput. - if (sym == SDLK_BACKSPACE && applyBackspaceToActiveInput()) break; - const int keyCode = webKeyCodeForSdl(sym); - if (keyCode != 0) gea::framework::input::queueKeyDown(keyCode); - break; - } + // Escape and every other key go to the app; quitting is SDL_QUIT or + // SIGTERM only. F11 (fullscreen) is a default action in drain(). + case SDL_KEYDOWN: + case SDL_KEYUP: case SDL_TEXTINPUT: - appendTextToActiveInput(event.text.text); + case SDL_TEXTEDITING: + case SDL_TEXTEDITING_EXT: + g_keyboard.accept(event); + if (event.type == SDL_TEXTEDITING_EXT) SDL_free(event.editExt.text); break; case SDL_MOUSEWHEEL: { static const bool inputTrace = [] { @@ -388,6 +341,8 @@ void pumpSdlEvents() break; } case SDL_WINDOWEVENT: + g_keyboard.accept(event); + if (event.window.windowID != sailfish_display_window_id()) break; switch (event.window.event) { case SDL_WINDOWEVENT_SIZE_CHANGED: g_resize_pending = true; @@ -457,6 +412,10 @@ void geaRetireNativeProcess() noexcept { static bool retired = false; // Actual process exit on the application thread. if (retired) return; retired = true; + try { sailfish_keyboard_shutdown(); } + catch (...) { std::fputs("Gea: Maliit keyboard retirement failed\n", stderr); } + try { g_keyboard.shutdown(); } + catch (...) { std::fputs("Gea: SDL keyboard retirement failed\n", stderr); } try { gea_native_application_terminate(); } catch (...) { std::fputs("Gea: application termination callback failed; retiring SDK callbacks\n", stderr); } try { gea::host::retireScheduledCallbacks(); } @@ -497,9 +456,16 @@ int main(int argc, char **argv) int w = sailfish_canvas_width(); int h = sailfish_canvas_height(); - const double dpr = devicePixelRatio(); + // The canvas is in physical pixels (sailfish_display.cpp); see + // effectiveDevicePixelRatio for how the app's DPR maps onto them. + double dpr = effectiveDevicePixelRatio(); - std::fprintf(stderr, "[sailfish] init %dx%d dpr=%.1f app=%s\n", w, h, dpr, GEA_SAILFISH_APP_ID); + if (devicePixelRatio() > 0.0) + std::fprintf(stderr, "[sailfish] init %dx%d dpr=%.2f (app %.2f x output %.2f) app=%s\n", w, h, dpr, + devicePixelRatio(), sailfish_display_output_ratio(), GEA_SAILFISH_APP_ID); + else + std::fprintf(stderr, "[sailfish] init %dx%d dpr=%.0f (auto, panel short side %d) css=%.0fx%.0f app=%s\n", + w, h, dpr, sailfish_display_panel_short_side(), w / dpr, h / dpr, GEA_SAILFISH_APP_ID); // Record the app identity: AppManager platform (Apps.currentInstalledAppId) // and the C-side current-id used by generated launcher code. @@ -527,6 +493,8 @@ int main(int argc, char **argv) // Physical-keyboard text entry for focused nodes (SDL_TEXTINPUT). SDL_StartTextInput(); + // The Sailfish on-screen keyboard follows input focus (Maliit). + sailfish_keyboard_init(); auto &tree = gea::embedded::ui::Tree::instance(); @@ -560,12 +528,17 @@ int main(int argc, char **argv) // and mark every node dirty so the next refresh repaints the world. if (g_resize_pending) { g_resize_pending = false; + // The window event reports points; the canvas follows the + // drawable's physical pixels (see sailfish_display.cpp). const int scale = sailfish_display_window_scale(); - const int newW = g_resize_window_w / (scale > 0 ? scale : 1); - const int newH = g_resize_window_h / (scale > 0 ? scale : 1); + int outputW = g_resize_window_w, outputH = g_resize_window_h; + sailfish_display_output_size(&outputW, &outputH); + const int newW = outputW / (scale > 0 ? scale : 1); + const int newH = outputH / (scale > 0 ? scale : 1); if (sailfish_display_resize(newW, newH)) { w = sailfish_canvas_width(); h = sailfish_canvas_height(); + dpr = effectiveDevicePixelRatio(); gea::embedded::ui::setViewportMetrics(w, h, dpr); gea::embedded::ui::Document::setPreferredMountSize(w, h); gea::embedded::ui::dispatchWindowLifecycleEvent(gea::framework::events::PointerEventType::WindowResize); @@ -585,6 +558,11 @@ int main(int argc, char **argv) dispatchKeyInput(); driveCssAnimations(static_cast(nowMs)); gea::framework::app::Application::frame(nowMs); + { + const int activeInput = tree.activeInputId(); + const char *inputType = activeInput >= 0 ? tree.getAttribute(activeInput, "type") : nullptr; + sailfish_keyboard_update(activeInput, inputType && std::strcmp(inputType, "password") == 0); + } // Persist localStorage mutations from this frame (no-op unless changed; // mirrors runtime.cpp's per-frame Storage.flushPending()). Both views: // the geatsc runtime store (bridge) and the native facade. diff --git a/targets/sailfish-os/prepare.mjs b/targets/sailfish-os/prepare.mjs index 56b6558..a3a1a93 100644 --- a/targets/sailfish-os/prepare.mjs +++ b/targets/sailfish-os/prepare.mjs @@ -2,8 +2,10 @@ import fs from 'node:fs' import path from 'node:path' import { spawnSync } from 'node:child_process' +import { createRequire } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' import sharp from 'sharp' +import { desktopEntry, readSailfishConfig, rpmSpec, sailfishDensity } from './config.mjs' const here = path.dirname(fileURLToPath(import.meta.url)) const linuxRoot = path.resolve(here, '../..') @@ -13,80 +15,93 @@ if (!appArg || !['i486', 'armv7hl', 'aarch64'].includes(arch)) { process.exit(2) } const appDir = path.resolve(appArg) -const coreRepo = path.resolve(coreArg || path.join(linuxRoot, '../core')) -const corePackage = path.join(coreRepo, 'packages/core') -const npmCore = path.join(linuxRoot, 'node_modules/@geastack/core') -const coreMetadata = path.join(corePackage, 'package.json') -if (!fs.existsSync(coreMetadata)) throw new Error(`missing core package: ${coreMetadata}`) -const checkoutVersion = JSON.parse(fs.readFileSync(coreMetadata, 'utf8')).version -const installedVersion = JSON.parse(fs.readFileSync(path.join(npmCore, 'package.json'), 'utf8')).version -if (!checkoutVersion || checkoutVersion !== installedVersion) { - throw new Error(`core version mismatch: npm @geastack/core ${installedVersion}, checkout ${checkoutVersion}. Use a core checkout matching the installed npm package, or install the matching npm version.`) -} const meta = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8')) -const app = meta.gea -if (!app?.id || !/^[a-z0-9][a-z0-9-]*$/.test(app.id)) throw new Error('gea.id must be a lowercase package identifier') -const appName = String(app.name || app.id) -const rpmLicense = String(meta.license || 'MIT') -if (/[\x00-\x1f\x7f%\\";$]/.test(appName)) throw new Error('gea.name must not contain control characters or RPM/CMake syntax') -if (/[\x00-\x1f\x7f%]/.test(rpmLicense)) throw new Error('package license must not contain control characters or RPM macros') -const sailfish = app.sailfish || {} -const organizationName = sailfish.organizationName || 'org.geastack' -const applicationName = sailfish.applicationName || app.id.replaceAll('-', '_') -const permissions = sailfish.permissions || [] -const devicePixelRatio = sailfish.devicePixelRatio ?? 1 -if (typeof devicePixelRatio !== 'number' || !Number.isFinite(devicePixelRatio) || devicePixelRatio < 0.5 || devicePixelRatio > 8) throw new Error('gea.sailfish.devicePixelRatio must be a number between 0.5 and 8') -if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/.test(organizationName)) throw new Error('gea.sailfish.organizationName must be a reverse-domain name') -if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(applicationName)) throw new Error('gea.sailfish.applicationName must contain only letters, digits, and underscores') -if (!Array.isArray(permissions) || !permissions.every((item) => typeof item === 'string' && /^[A-Za-z]+$/.test(item))) throw new Error('gea.sailfish.permissions must be an array of permission names') -const npmVersion = meta.version || '0.1.0' -const versionMatch = typeof npmVersion === 'string' && npmVersion.match(/^(\d+\.\d+\.\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/) -if (!versionMatch) throw new Error('package.json version must be a valid x.y.z version with optional prerelease and build metadata') -const rpmVersion = versionMatch[1] + (versionMatch[2] ? `~${versionMatch[2].replaceAll('-', '.')}` : '') -const entry = app.entry || 'index.tsx' -if (!fs.existsSync(path.join(appDir, entry))) throw new Error(`app entry missing: ${entry}`) -const packageName = `harbour-gea-${app.id}` -const generated = path.join(here, 'generated', app.id) -const stage = path.join(here, 'build', `${app.id}-${arch}`, 'project') +const config = readSailfishConfig(appDir, meta) +const density = sailfishDensity(config, arch) + +// GeaStack packages resolve the way Node resolves them for the app, so an app +// that installs @geastack/linux from npm (with hoisted dependencies) works. +// This repository's own node_modules is the fallback for in-repo development. +const resolvers = [createRequire(path.join(appDir, 'package.json')), createRequire(path.join(linuxRoot, 'package.json'))] +const resolvePackage = (name) => { + for (const resolver of resolvers) { + try { + return path.dirname(resolver.resolve(`${name}/package.json`)) + } catch {} + } + throw new Error(`cannot resolve ${name} from ${appDir} or ${linuxRoot}; run npm install in the app`) +} +const npmCore = resolvePackage('@geastack/core') +const npmCoreVersion = JSON.parse(fs.readFileSync(path.join(npmCore, 'package.json'), 'utf8')).version + +// The framework sources come from the installed packages, or from a core +// checkout when one is given; a checkout must match the installed core. +const coreRepo = coreArg ? path.resolve(coreArg) : null +if (coreRepo) { + const coreMetadata = path.join(coreRepo, 'packages/core/package.json') + if (!fs.existsSync(coreMetadata)) throw new Error(`missing core package: ${coreMetadata}`) + const checkoutVersion = JSON.parse(fs.readFileSync(coreMetadata, 'utf8')).version + if (!checkoutVersion || checkoutVersion !== npmCoreVersion) { + throw new Error(`core version mismatch: npm @geastack/core ${npmCoreVersion}, checkout ${checkoutVersion}. Use a core checkout matching the installed npm package, or install the matching npm version.`) + } +} +const frameworkPackages = ['core', 'host', 'engine', 'elements', 'geaos'] +const frameworkSource = (name) => coreRepo ? path.join(coreRepo, 'packages', name) : resolvePackage(`@geastack/${name}`) + +if (!fs.existsSync(path.join(appDir, config.entry))) throw new Error(`app entry missing: ${config.entry}`) +// Build output belongs to the app, never to the installed package. +const output = path.join(appDir, '.gea-sailfish') +const generated = path.join(output, 'generated', config.id) +const stage = path.join(output, 'build', `${config.id}-${arch}`, 'project') fs.mkdirSync(path.dirname(generated), { recursive: true }) -// The npm scripts/runtime and native checkout must have the same core version. const args = [path.join(npmCore, 'scripts/build-gea-vite-geatsc.mjs'), - '--app-dir', appDir, '--entry', entry, '--out-dir', generated, - '--geatsc-bin', path.join(linuxRoot, 'node_modules/@geastack/compiler/dist/cli.js'), - '--geatsc-gea-plugin', path.join(linuxRoot, 'node_modules/@geastack/geatsc-plugin-gea/dist/index.js'), - '--font-viewport-width', '410', '--font-viewport-height', '502', '--font-device-pixel-ratio', String(devicePixelRatio), + '--app-dir', appDir, '--entry', config.entry, '--out-dir', generated, + '--geatsc-bin', path.join(resolvePackage('@geastack/compiler'), 'dist/cli.js'), + '--geatsc-gea-plugin', path.join(resolvePackage('@geastack/geatsc-plugin-gea'), 'dist/index.js'), + '--font-viewport-width', '410', '--font-viewport-height', '502', + ...density.fontRatios.flatMap((ratio) => ['--font-device-pixel-ratio', String(ratio)]), '--runtime-ttf-fonts'] -const result = spawnSync(process.execPath, args, { stdio: 'inherit', cwd: linuxRoot }) +const result = spawnSync(process.execPath, args, { stdio: 'inherit', cwd: appDir }) if (result.status !== 0) process.exit(result.status || 1) // sfdk mounts this project into its Linux build engine. Every compiled input // must therefore be inside this directory, with no Windows absolute paths. const resolvedStage = path.resolve(stage) -const allowedParent = path.resolve(here, 'build') + path.sep +const allowedParent = path.resolve(output, 'build') + path.sep if (!resolvedStage.startsWith(allowedParent)) throw new Error('unsafe stage directory') fs.rmSync(stage, { recursive: true, force: true }) fs.mkdirSync(stage, { recursive: true }) -const copyTree = (from, to) => fs.cpSync(from, to, { recursive: true, +const copyTree = (from, to) => fs.cpSync(from, to, { recursive: true, dereference: true, filter: (item) => !['.git', 'node_modules', 'dist', 'build', 'test', 'tests', '.build-test'].includes(path.basename(item)) }) -for (const name of ['core', 'host', 'engine', 'elements', 'geaos']) { - const source = path.join(coreRepo, 'packages', name) +for (const name of frameworkPackages) { + const source = frameworkSource(name) if (!fs.existsSync(source)) throw new Error(`missing framework package: ${source}`) copyTree(source, path.join(stage, 'framework', name)) } copyTree(generated, path.join(stage, 'generated')) copyTree(path.join(here, 'main'), path.join(stage, 'platform/main')) copyTree(path.join(here, 'include'), path.join(stage, 'platform/include')) +// The SDL keyboard producer is shared with the Raspberry Pi OS target. +fs.copyFileSync(path.join(here, '../raspberry-pi-os/main/rpios_keyboard.h'), path.join(stage, 'platform/include/rpios_keyboard.h')) fs.copyFileSync(path.join(here, 'CMakeLists.txt'), path.join(stage, 'CMakeLists.txt')) -const env = Object.fromEntries(['core', 'host', 'engine', 'elements', 'geaos'].map((name) => [ +// App-owned native code keeps its app-relative layout under app_native/. +const appNative = (relative) => `app_native/${relative}` +for (const { relative, absolute } of [...config.nativeSources, ...config.nativeIncludeDirectories]) { + const target = path.join(stage, appNative(relative)) + fs.mkdirSync(path.dirname(target), { recursive: true }) + fs.cpSync(absolute, target, { recursive: true, dereference: true }) +} + +const env = Object.fromEntries(frameworkPackages.map((name) => [ ({ core: 'GEA_CORE', host: 'GEA_HOST_DIR', engine: 'GEA_ENGINE_DIR', elements: 'GEA_ELEMENTS_DIR', geaos: 'GEA_GEAOS_PACKAGE_DIR' })[name], path.join(stage, 'framework', name).replaceAll('\\', '/')])) -const { includeFlags, cSources, cxxSources } = await import(pathToFileURL(path.join(coreRepo, 'packages/core/gea_sources.mjs'))) +const { includeFlags, cSources, cxxSources } = await import(pathToFileURL(path.join(frameworkSource('core'), 'gea_sources.mjs'))) const rel = (file) => path.relative(stage, file).replaceAll('\\', '/') const c = [...cSources(env).map(rel), 'platform/main/sailfish_apps.c'] const cxx = cxxSources({ ...env, GEA_DESKTOP_WEBSOCKET_CURL: '1' }).filter((s) => !/\/(?:host\/camera|runtime|services\/[a-z_]+)\.cpp$/.test(s)).map(rel) if (!cxx.some((s) => s.endsWith('/host/websocket_curl.cpp'))) throw new Error('framework does not provide the native Linux WebSocket transport') -for (const name of ['display', 'audio', 'memory', 'network', 'sensors', 'storage', 'storage_bridge', 'timers', 'app_platform', 'main']) cxx.push(`platform/main/sailfish_${name}.cpp`) +for (const name of ['display', 'audio', 'memory', 'network', 'sensors', 'storage', 'storage_bridge', 'timers', 'app_platform', 'keyboard', 'main']) cxx.push(`platform/main/sailfish_${name}.cpp`) cxx.push('framework/core/gea_app_entry.cpp') for (const line of fs.readFileSync(path.join(generated, 'geatsc-sources.txt'), 'utf8').split(/\r?\n/).filter(Boolean)) { const file = path.resolve(line) @@ -96,14 +111,18 @@ for (const line of fs.readFileSync(path.join(generated, 'geatsc-sources.txt'), ' for (const name of ['gea_embedded_font_generated.cpp', 'gea_embedded_assets_generated.cpp']) { if (fs.existsSync(path.join(generated, name))) cxx.push(`generated/${name}`) } -const includes = ['platform/include', 'generated', ...includeFlags(env).map((s) => rel(s.slice(2)))] +for (const { relative } of config.nativeSources) (relative.endsWith('.c') ? c : cxx).push(appNative(relative)) +const includes = ['platform/include', 'generated', ...includeFlags(env).map((s) => rel(s.slice(2))), + ...config.nativeIncludeDirectories.map(({ relative }) => appNative(relative))] for (const file of [...c, ...cxx]) if (!fs.existsSync(path.join(stage, file))) throw new Error(`source missing: ${file}`) const cmakeList = (key, values) => `set(${key}\n${values.map((s) => ` "${'${CMAKE_CURRENT_SOURCE_DIR}'}/${s}"`).join('\n')}\n)\n` +const cmakeNames = (key, values) => `set(${key}${values.map((s) => ` "${s}"`).join('')})\n` fs.writeFileSync(path.join(stage, 'sources.cmake'), - `set(GEA_PACKAGE_NAME "${packageName}")\nset(GEA_APP_ID "${app.id}")\nset(GEA_APP_TITLE "${appName}")\nset(GEA_SAILFISH_ORGANIZATION_NAME "${organizationName}")\nset(GEA_SAILFISH_APPLICATION_NAME "${applicationName}")\n` + - `set(GEA_SAILFISH_DEFAULT_DPR ${devicePixelRatio})\n` + - cmakeList('GEA_INCLUDE_DIRS', [...new Set(includes)]) + cmakeList('GEA_C_SOURCES', c) + cmakeList('GEA_CXX_SOURCES', cxx)) -const icon = app.icons?.['512'] || app.icons?.['256'] || app.icons?.['128'] + `set(GEA_PACKAGE_NAME "${config.packageName}")\nset(GEA_APP_ID "${config.id}")\nset(GEA_APP_TITLE "${config.appName}")\nset(GEA_SAILFISH_ORGANIZATION_NAME "${config.organizationName}")\nset(GEA_SAILFISH_APPLICATION_NAME "${config.applicationName}")\n` + + `set(GEA_SAILFISH_DEFAULT_DPR ${density.runtime})\n` + + cmakeList('GEA_INCLUDE_DIRS', [...new Set(includes)]) + cmakeList('GEA_C_SOURCES', c) + cmakeList('GEA_CXX_SOURCES', cxx) + + cmakeNames('GEA_APP_PKG_MODULES', config.pkgConfigModules) + cmakeNames('GEA_APP_SYSTEM_LIBRARIES', config.nativeSystemLibraries)) +const icon = config.icons['512'] || config.icons['256'] || config.icons['128'] if (!icon || !fs.existsSync(path.join(appDir, icon))) throw new Error('app needs an icon source') fs.mkdirSync(path.join(stage, 'icons')) for (const size of [86, 108, 128, 172]) { @@ -111,7 +130,7 @@ for (const size of [86, 108, 128, 172]) { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 }, }).png().toFile(path.join(stage, 'icons', `${size}.png`)) } -fs.writeFileSync(path.join(stage, `${packageName}.desktop`), `[Desktop Entry]\nType=Application\nName=${appName}\nExec=${packageName}\nIcon=${packageName}\nX-Nemo-Application-Type=generic\n\n[X-Sailjail]\nOrganizationName=${organizationName}\nApplicationName=${applicationName}\nPermissions=${[...new Set(permissions)].join(';')}\n`) +fs.writeFileSync(path.join(stage, `${config.packageName}.desktop`), desktopEntry(config)) fs.mkdirSync(path.join(stage, 'rpm')) -fs.writeFileSync(path.join(stage, 'rpm', `${packageName}.spec`), `Name: ${packageName}\nVersion: ${rpmVersion}\nRelease: 1\nSummary: Gea ${appName} for Sailfish OS\nLicense: ${rpmLicense}\nBuildRequires: cmake\nBuildRequires: pkgconfig(sdl2)\nBuildRequires: pkgconfig(libcurl)\n\n%description\nGea JSX application for Sailfish OS.\n\n%build\n%cmake .\n%make_build\n\n%install\n%make_install\n\n%files\n%{_bindir}/${packageName}\n%{_datadir}/applications/${packageName}.desktop\n%{_datadir}/icons/hicolor/*/apps/${packageName}.png\n`) +fs.writeFileSync(path.join(stage, 'rpm', `${config.packageName}.spec`), rpmSpec(config)) console.log(stage) diff --git a/targets/sailfish-os/test/config.test.mjs b/targets/sailfish-os/test/config.test.mjs new file mode 100644 index 0000000..832180f --- /dev/null +++ b/targets/sailfish-os/test/config.test.mjs @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { desktopEntry, readSailfishConfig, rpmSpec, sailfishDensity } from '../config.mjs' + +const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gea-sailfish-config-')) +const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'gea-sailfish-outside-')) +process.on('exit', () => { + fs.rmSync(appDir, { recursive: true, force: true }) + fs.rmSync(outside, { recursive: true, force: true }) +}) +fs.mkdirSync(path.join(appDir, 'native/include'), { recursive: true }) +fs.writeFileSync(path.join(appDir, 'native/host.cpp'), '') +fs.writeFileSync(path.join(appDir, 'native/helper.c'), '') +fs.writeFileSync(path.join(appDir, 'native/notes.txt'), '') +fs.writeFileSync(path.join(outside, 'evil.cpp'), '') +fs.symlinkSync(path.join(outside, 'evil.cpp'), path.join(appDir, 'native/link.cpp')) + +const base = (gea = {}, extra = {}) => ({ version: '1.2.3', license: 'MIT', ...extra, gea: { id: 'probe-app', name: 'Probe', ...gea } }) +const read = (gea, extra) => readSailfishConfig(appDir, base(gea, extra)) + +let failures = 0 +const test = (name, fn) => { + try { + fn() + console.log(`ok - ${name}`) + } catch (error) { + failures++ + console.log(`not ok - ${name}\n ${error.message}`) + } +} + +test('defaults keep the sandbox and the existing identity', () => { + const config = read() + assert.equal(config.packageName, 'harbour-gea-probe-app') + assert.equal(config.applicationName, 'probe_app') + assert.equal(config.sandboxing, true) + const desktop = desktopEntry(config) + assert.doesNotMatch(desktop, /Sandboxing/) + assert.match(desktop, /\[X-Sailjail\]\nOrganizationName=org\.geastack\nApplicationName=probe_app\nPermissions=\n$/) +}) + +test('density defaults to auto: panel-derived on ARM, 1 on the emulator', () => { + const config = read() + assert.equal(config.devicePixelRatio, 'auto') + // 0 tells the executable to derive an integer DPR from the panel. + assert.deepEqual(sailfishDensity(config, 'aarch64'), { runtime: 0, fontRatios: [2, 3] }) + assert.deepEqual(sailfishDensity(config, 'armv7hl'), { runtime: 0, fontRatios: [2, 3] }) + assert.deepEqual(sailfishDensity(config, 'i486'), { runtime: 1, fontRatios: [1] }) +}) + +test('an explicit density is used on every architecture', () => { + const config = read({ sailfish: { devicePixelRatio: 2.5 } }) + assert.deepEqual(sailfishDensity(config, 'aarch64'), { runtime: 2.5, fontRatios: [2.5] }) + assert.deepEqual(sailfishDensity(config, 'i486'), { runtime: 2.5, fontRatios: [2.5] }) + assert.deepEqual(sailfishDensity(read({ sailfish: { devicePixelRatio: 'auto' } }), 'aarch64').runtime, 0) + assert.throws(() => read({ sailfish: { devicePixelRatio: 'native' } }), /devicePixelRatio/) + assert.throws(() => read({ sailfish: { devicePixelRatio: 0 } }), /devicePixelRatio/) +}) + +test('sandboxing: false opts out of Sailjail', () => { + const desktop = desktopEntry(read({ sailfish: { sandboxing: false, permissions: ['Audio', 'Internet', 'Audio'] } })) + assert.match(desktop, /\[X-Sailjail\]\nSandboxing=Disabled\nOrganizationName=/) + assert.match(desktop, /Permissions=Audio;Internet\n$/) +}) + +test('sandboxing must be a boolean', () => { + assert.throws(() => read({ sailfish: { sandboxing: 'no' } }), /sandboxing must be true or false/) +}) + +test('native sources resolve inside the app', () => { + const config = read({ nativeSources: ['native/host.cpp', 'native/helper.c', 'native/host.cpp'] }) + assert.deepEqual(config.nativeSources.map((s) => s.relative), ['native/host.cpp', 'native/helper.c']) + assert.equal(config.nativeSources[0].absolute, fs.realpathSync(path.join(appDir, 'native/host.cpp'))) +}) + +test('native sources reject escapes, missing files and other extensions', () => { + assert.throws(() => read({ nativeSources: ['../x.cpp'] }), /invalid path/) + assert.throws(() => read({ nativeSources: [path.join(appDir, 'native/host.cpp')] }), /invalid path/) + assert.throws(() => read({ nativeSources: ['native/missing.cpp'] }), /missing/) + assert.throws(() => read({ nativeSources: ['native/notes.txt'] }), /unsupported source/) + assert.throws(() => read({ nativeSources: ['native/link.cpp'] }), /escapes the app directory/) + assert.throws(() => read({ nativeSources: 'native/host.cpp' }), /array of nonempty strings/) +}) + +test('include directories must be app directories', () => { + const config = read({ sailfish: { nativeIncludeDirectories: ['native/include'] } }) + assert.deepEqual(config.nativeIncludeDirectories.map((d) => d.relative), ['native/include']) + assert.throws(() => read({ sailfish: { nativeIncludeDirectories: ['native/host.cpp'] } }), /not a directory/) +}) + +test('system libraries and pkg-config modules are plain names', () => { + const config = read({ sailfish: { nativeSystemLibraries: ['util'], pkgConfigModules: ['maliit-glib'] } }) + assert.deepEqual(config.nativeSystemLibraries, ['util']) + assert.throws(() => read({ sailfish: { nativeSystemLibraries: ['-lfoo'] } }), /invalid library/) + assert.throws(() => read({ sailfish: { nativeSystemLibraries: ['util;rm'] } }), /invalid library/) + assert.throws(() => read({ sailfish: { pkgConfigModules: ['a b'] } }), /invalid module/) +}) + +test('spec lists pkg-config modules as BuildRequires', () => { + const spec = rpmSpec(read({ sailfish: { pkgConfigModules: ['glib-2.0', 'maliit-glib'] } })) + assert.match(spec, /BuildRequires: pkgconfig\(libcurl\)\nBuildRequires: pkgconfig\(maliit-glib\)\nBuildRequires: pkgconfig\(glib-2.0\)\n\n%description/) + assert.match(spec, /^Name: harbour-gea-probe-app\nVersion: 1\.2\.3\n/) +}) + +test('prerelease versions sort before the release in RPM', () => { + assert.equal(read({}, { version: '1.2.3-beta-2' }).rpmVersion, '1.2.3~beta.2') +}) + +if (failures) { + console.log(`${failures} failed`) + process.exit(1) +} From 57531a1fa98d5e0b6062942be76c985b4a7ad082 Mon Sep 17 00:00:00 2001 From: Mehmet Fiskindal Date: Sun, 22 Nov 2026 00:14:06 +0300 Subject: [PATCH 2/3] Include shared Raspberry Pi OS keyboard handler --- targets/sailfish-os/main/sailfish_main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/targets/sailfish-os/main/sailfish_main.cpp b/targets/sailfish-os/main/sailfish_main.cpp index 4a94e15..94e4ac9 100644 --- a/targets/sailfish-os/main/sailfish_main.cpp +++ b/targets/sailfish-os/main/sailfish_main.cpp @@ -45,7 +45,7 @@ #include "touch.h" // Shared with Raspberry Pi OS: SDL key/text events with key/code/modifier // metadata, UTF-8 text and whole-code-point Backspace for focused inputs. - +#include "rpios_keyboard.h" #include "sailfish_keyboard.h" #include From 390c7f7db428b9a5e21f276e270664b18a7fd99a Mon Sep 17 00:00:00 2001 From: Mehmet Date: Mon, 23 Nov 2026 12:35:55 +0300 Subject: [PATCH 3/3] feat(sailfish-os): implement real SDL2 audio backend with oscillator voice table --- .vscode/settings.json | 3 + targets/sailfish-os/main/sailfish_audio.cpp | 777 +++++++++++++++++++- 2 files changed, 750 insertions(+), 30 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..19b9baa --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "/Users/mehmetfiskindal/Developer/linux/targets/sailfish-os" +} \ No newline at end of file diff --git a/targets/sailfish-os/main/sailfish_audio.cpp b/targets/sailfish-os/main/sailfish_audio.cpp index 6446fba..3e51e6b 100644 --- a/targets/sailfish-os/main/sailfish_audio.cpp +++ b/targets/sailfish-os/main/sailfish_audio.cpp @@ -1,23 +1,741 @@ /* targets/sailfish-os/main/sailfish_audio.cpp - * Audio is stubbed on the linux target for now. Apps just want sound to not - * crash the runtime; an SDL_audio/ALSA oscillator backend is a follow-up. - * Every method returns inert values and discards input. - * (Same surface as macos_audio.cpp plus the playFile/playPcm/stopPlayback - * trio geaos_audio.cpp defines — all are required to link host/audio.cpp.) */ + * Real SDL2 audio backend for gea::platform::audio on Sailfish OS. + * + * Uses SDL2's PulseAudio driver (compiled into Sailfish OS libSDL2-2.0.so.0) + * and sets PULSE_PROP_media.role=x-maemo before opening the audio device so + * Sailfish OS routes playback through the normal system volume policy instead + * of ignoring hardware volume controls. + * + * Architecture mirrors apple_audio.mm: + * - Lock-free single-consumer command ring feeds a fixed voice table on the + * SDL audio callback thread (zero allocations on the render thread). + * - Supports Sine, Square, Sawtooth, and Triangle oscillators with + * sample-accurate start(when), stop(when), setValue(), setValueAtTime(), + * and smooth attack/release ramps to prevent clicks on short notes. + * - Also mixes one-shot PCM buffers (playPcm) and WAV files (playFile). + * - Falls back silently to a monotonic steady clock if audio is disabled + * (GEA_AUDIO_DISABLED=1) or no output device is available. + */ #include "audio.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + namespace gea::platform::audio { namespace { -int g_volume = 80; + +constexpr int kMaxOscillators = 512; +constexpr int kMaxVoices = 64; +constexpr int kMaxVoiceEvents = 8; +constexpr int kCommandCapacity = 2048; +constexpr double kTwoPi = 6.28318530717958647692; +constexpr double kDefaultFrequency = 440.0; +constexpr double kMinFrequency = 8.0; +constexpr double kMaxFrequency = 20000.0; +constexpr double kAttackSeconds = 0.0025; +constexpr double kReleaseSeconds = 0.006; +constexpr double kVoiceGain = 0.25; +constexpr double kMaxVoiceSeconds = 30.0; +constexpr double kDefaultSampleRate = 48000.0; +constexpr Uint16 kDesiredBufferSamples = 512; + +double steadySeconds() +{ + static const auto origin = std::chrono::steady_clock::now(); + return std::chrono::duration(std::chrono::steady_clock::now() - origin).count(); +} + +OscillatorType normalizeType(OscillatorType type) +{ + switch (type) { + case OscillatorType::Sine: + case OscillatorType::Square: + case OscillatorType::Sawtooth: + case OscillatorType::Triangle: + return type; + } + return OscillatorType::Sine; +} + +double normalizeFrequency(double frequency) +{ + if (!std::isfinite(frequency)) return kDefaultFrequency; + if (frequency < kMinFrequency) return kMinFrequency; + if (frequency > kMaxFrequency) return kMaxFrequency; + return frequency; } +double waveform(OscillatorType type, double phase) +{ + switch (type) { + case OscillatorType::Square: + return phase < 0.5 ? 1.0 : -1.0; + case OscillatorType::Sawtooth: + return 2.0 * phase - 1.0; + case OscillatorType::Triangle: + if (phase < 0.25) return 4.0 * phase; + if (phase < 0.75) return 2.0 - 4.0 * phase; + return 4.0 * phase - 4.0; + case OscillatorType::Sine: + break; + } + return std::sin(phase * kTwoPi); +} + +bool envFlagSet(const char *name) +{ + const char *value = std::getenv(name); + return value != nullptr && value[0] != '\0' && std::strcmp(value, "0") != 0; +} + +enum class CommandKind : std::uint8_t { + StartVoice, + StopVoice, + SetFrequency, + SetType, + ScheduleFrequency, +}; + +struct Command { + CommandKind kind = CommandKind::StartVoice; + OscillatorType type = OscillatorType::Sine; + NativeAudioHandle voice = 0; + double frequency = kDefaultFrequency; + std::int64_t frame = 0; +}; + +class CommandQueue { +public: + bool push(const Command &command) + { + std::lock_guard guard(producers_); + const std::uint32_t tail = tail_.load(std::memory_order_relaxed); + const std::uint32_t next = (tail + 1u) % kCommandCapacity; + if (next == head_.load(std::memory_order_acquire)) return false; + items_[tail] = command; + tail_.store(next, std::memory_order_release); + return true; + } + + bool pop(Command &out) + { + const std::uint32_t head = head_.load(std::memory_order_relaxed); + if (head == tail_.load(std::memory_order_acquire)) return false; + out = items_[head]; + head_.store((head + 1u) % kCommandCapacity, std::memory_order_release); + return true; + } + +private: + Command items_[kCommandCapacity]{}; + std::atomic head_{0}; + std::atomic tail_{0}; + std::mutex producers_; +}; + +struct VoiceEvent { + std::int64_t frame = 0; + double phaseIncrement = 0.0; +}; + +struct Voice { + bool active = false; + NativeAudioHandle id = 0; + OscillatorType type = OscillatorType::Sine; + double phase = 0.0; + double phaseIncrement = 0.0; + std::int64_t startFrame = 0; + std::int64_t stopFrame = 0; + std::int64_t endFrame = 0; + bool stopScheduled = false; + VoiceEvent events[kMaxVoiceEvents]{}; + int eventHead = 0; + int eventCount = 0; +}; + +struct ScheduledValue { + double time = 0.0; + double value = kDefaultFrequency; +}; + +struct OscillatorRecord { + NativeAudioHandle handle = 0; + OscillatorType type = OscillatorType::Sine; + double frequency = kDefaultFrequency; + bool connected = false; + bool started = false; + bool stopped = false; + bool voiceLaunched = false; + double startTime = 0.0; + double stopTime = 0.0; + ScheduledValue pending[kMaxVoiceEvents]{}; + int pendingCount = 0; +}; + +class Engine { +public: + static Engine &instance() + { + // Deliberately leaked so the SDL audio thread never races a static + // destructor during process shutdown. + static Engine *engine = new Engine(); + return *engine; + } + + double currentTime() + { + ensureSetup(); + return currentTimeLocked(); + } + + NativeAudioHandle createOscillator() + { + ensureSetup(); + std::lock_guard guard(recordsMutex_); + const int slot = nextSlot_; + nextSlot_ = (nextSlot_ + 1) % kMaxOscillators; + const NativeAudioHandle handle = + (static_cast(++generation_) << 10) | static_cast(slot + 1); + records_[slot] = OscillatorRecord{}; + records_[slot].handle = handle; + return handle; + } + + double frequency(NativeAudioHandle handle) + { + std::lock_guard guard(recordsMutex_); + const OscillatorRecord *record = find(handle); + return record ? record->frequency : 0.0; + } + + void setFrequency(NativeAudioHandle handle, double value) + { + Command command; + bool live = false; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr || !std::isfinite(value)) return; + record->frequency = value; + live = record->voiceLaunched && !record->stopped; + command = Command{CommandKind::SetFrequency, record->type, handle, normalizeFrequency(value), 0}; + } + if (live) commands_.push(command); + } + + OscillatorType type(NativeAudioHandle handle) + { + std::lock_guard guard(recordsMutex_); + const OscillatorRecord *record = find(handle); + return record ? record->type : OscillatorType::Sine; + } + + void setType(NativeAudioHandle handle, OscillatorType type) + { + Command command; + bool live = false; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr) return; + record->type = normalizeType(type); + live = record->voiceLaunched && !record->stopped; + command = Command{CommandKind::SetType, record->type, handle, record->frequency, 0}; + } + if (live) commands_.push(command); + } + + void scheduleFrequency(NativeAudioHandle handle, double value, double time) + { + ensureSetup(); + Command command; + bool emit = false; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr || !std::isfinite(value)) return; + if (record->voiceLaunched && !record->stopped) { + emit = true; + command = Command{CommandKind::ScheduleFrequency, record->type, handle, + normalizeFrequency(value), frameFor(time)}; + } else if (record->pendingCount < kMaxVoiceEvents) { + record->pending[record->pendingCount++] = ScheduledValue{time, value}; + } + } + if (emit) commands_.push(command); + } + + void connect(NativeAudioHandle handle) + { + Command commands[kMaxVoiceEvents + 2]; + int count = 0; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr || record->connected) return; + record->connected = true; + if (record->started && !record->voiceLaunched) { + record->voiceLaunched = true; + count = launchCommands(*record, handle, commands); + } + } + for (int i = 0; i < count; ++i) commands_.push(commands[i]); + } + + void start(NativeAudioHandle handle, double when) + { + ensureSetup(); + Command commands[kMaxVoiceEvents + 2]; + int count = 0; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr || record->started) return; + record->started = true; + const double now = currentTimeLocked(); + double at = (std::isfinite(when) && when > 0.0) ? when : now; + if (at < now) at = now; + record->startTime = at; + if (record->connected) { + record->voiceLaunched = true; + count = launchCommands(*record, handle, commands); + } + } + for (int i = 0; i < count; ++i) commands_.push(commands[i]); + } + + void stop(NativeAudioHandle handle, double when) + { + ensureSetup(); + Command command; + bool emit = false; + { + std::lock_guard guard(recordsMutex_); + OscillatorRecord *record = find(handle); + if (record == nullptr || !record->started || record->stopped) return; + record->stopped = true; + const double now = currentTimeLocked(); + double at = (std::isfinite(when) && when > 0.0) ? when : now; + if (at < record->startTime) at = record->startTime; + record->stopTime = at; + emit = record->voiceLaunched; + command = Command{CommandKind::StopVoice, record->type, handle, record->frequency, frameFor(at)}; + } + if (emit) commands_.push(command); + } + + int volume() const { return volume_.load(std::memory_order_relaxed); } + + void setVolume(int percent) + { + if (percent < 0) percent = 0; + if (percent > 100) percent = 100; + volume_.store(percent, std::memory_order_relaxed); + } + + bool playPcm(const std::int16_t *samples, std::size_t sampleCount, int sampleRate, int channels) + { + ensureSetup(); + if (samples == nullptr || sampleCount == 0 || device_ == 0) return false; + if (channels < 1) channels = 1; + if (channels > 2) channels = 2; + if (sampleRate <= 0) sampleRate = 16000; + const std::size_t inFrames = sampleCount / static_cast(channels); + if (inFrames == 0) return false; + + const double outRate = sampleRate_.load(std::memory_order_relaxed); + const double ratio = static_cast(sampleRate) / outRate; + const std::size_t outFrames = std::max(1, static_cast(std::llround(static_cast(inFrames) / ratio))); + std::vector stereo(outFrames * 2u); + for (std::size_t i = 0; i < outFrames; ++i) { + const double srcPos = static_cast(i) * ratio; + const std::size_t idx0 = std::min(inFrames - 1u, static_cast(srcPos)); + const std::size_t idx1 = std::min(inFrames - 1u, idx0 + 1u); + const float frac = static_cast(srcPos - static_cast(idx0)); + const float l0 = static_cast(samples[idx0 * static_cast(channels)]) / 32768.0f; + const float l1 = static_cast(samples[idx1 * static_cast(channels)]) / 32768.0f; + const float r0 = channels == 2 + ? static_cast(samples[idx0 * 2u + 1u]) / 32768.0f + : l0; + const float r1 = channels == 2 + ? static_cast(samples[idx1 * 2u + 1u]) / 32768.0f + : l1; + stereo[i * 2u] = l0 + (l1 - l0) * frac; + stereo[i * 2u + 1u] = r0 + (r1 - r0) * frac; + } + + SDL_LockAudioDevice(device_); + pcmStereo_.swap(stereo); + pcmCursor_ = 0; + SDL_UnlockAudioDevice(device_); + return true; + } + + bool playFile(const std::string &path) + { + ensureSetup(); + if (path.empty() || device_ == 0) return false; + SDL_AudioSpec wavSpec{}; + Uint8 *wavBuf = nullptr; + Uint32 wavLen = 0; + if (SDL_LoadWAV(path.c_str(), &wavSpec, &wavBuf, &wavLen) == nullptr) return false; + + SDL_AudioCVT cvt{}; + const int outRate = static_cast(std::llround(sampleRate_.load(std::memory_order_relaxed))); + const int built = SDL_BuildAudioCVT(&cvt, wavSpec.format, wavSpec.channels, wavSpec.freq, + AUDIO_F32SYS, 2, outRate); + if (built < 0) { + SDL_FreeWAV(wavBuf); + return false; + } + std::vector stereo; + if (built == 0) { + const std::size_t floats = wavLen / sizeof(float); + stereo.resize(floats); + std::memcpy(stereo.data(), wavBuf, floats * sizeof(float)); + } else { + std::vector work(static_cast(wavLen) * static_cast(cvt.len_mult)); + std::memcpy(work.data(), wavBuf, wavLen); + cvt.buf = work.data(); + cvt.len = static_cast(wavLen); + if (SDL_ConvertAudio(&cvt) != 0) { + SDL_FreeWAV(wavBuf); + return false; + } + const std::size_t floats = static_cast(cvt.len_cvt) / sizeof(float); + stereo.resize(floats); + std::memcpy(stereo.data(), work.data(), floats * sizeof(float)); + } + SDL_FreeWAV(wavBuf); + + SDL_LockAudioDevice(device_); + pcmStereo_.swap(stereo); + pcmCursor_ = 0; + SDL_UnlockAudioDevice(device_); + return true; + } + + void stopPlayback() + { + if (device_ == 0) return; + SDL_LockAudioDevice(device_); + pcmStereo_.clear(); + pcmCursor_ = 0; + SDL_UnlockAudioDevice(device_); + } + +private: + Engine() = default; + + void ensureSetup() + { + if (setupDone_.load(std::memory_order_acquire)) return; + std::lock_guard guard(setupMutex_); + if (setupDone_.load(std::memory_order_relaxed)) return; + + if (envFlagSet("GEA_AUDIO_DISABLED")) { + if (envFlagSet("GEA_AUDIO_DEBUG")) { + std::fprintf(stderr, "[sailfish audio] disabled via GEA_AUDIO_DISABLED\n"); + } + setupDone_.store(true, std::memory_order_release); + return; + } + + // Sailfish OS PulseAudio policy ignores system volume controls for + // streams without a recognized media.role. Use x-maemo unless the + // caller explicitly overrides it. + setenv("PULSE_PROP_media.role", "x-maemo", 0); +#ifdef GEA_SAILFISH_APP_TITLE + setenv("PULSE_PROP_application.name", GEA_SAILFISH_APP_TITLE, 0); +#endif + + if ((SDL_WasInit(SDL_INIT_AUDIO) & SDL_INIT_AUDIO) == 0) { + if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) { + std::fprintf(stderr, "[sailfish audio] SDL_InitSubSystem(AUDIO) failed: %s\n", SDL_GetError()); + setupDone_.store(true, std::memory_order_release); + return; + } + } + + SDL_AudioSpec want{}; + SDL_AudioSpec have{}; + want.freq = static_cast(kDefaultSampleRate); + want.format = AUDIO_F32SYS; + want.channels = 2; + want.samples = kDesiredBufferSamples; + want.callback = &Engine::audioCallback; + want.userdata = this; + + const SDL_AudioDeviceID dev = SDL_OpenAudioDevice( + nullptr, 0, &want, &have, + SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_SAMPLES_CHANGE); + if (dev == 0) { + std::fprintf(stderr, "[sailfish audio] SDL_OpenAudioDevice failed: %s\n", SDL_GetError()); + setupDone_.store(true, std::memory_order_release); + return; + } + + const double rate = have.freq > 0 ? static_cast(have.freq) : kDefaultSampleRate; + sampleRate_.store(rate, std::memory_order_relaxed); + attackFrames_ = std::max(1.0, kAttackSeconds * rate); + releaseFrames_ = std::max(1.0, kReleaseSeconds * rate); + frameOffset_.store(static_cast(std::llround(steadySeconds() * rate)), + std::memory_order_relaxed); + renderedFrames_.store(0, std::memory_order_relaxed); + device_ = dev; + running_.store(true, std::memory_order_release); + SDL_PauseAudioDevice(device_, 0); + + if (envFlagSet("GEA_AUDIO_DEBUG")) { + const char *driver = SDL_GetCurrentAudioDriver(); + std::fprintf(stderr, + "[sailfish audio] started driver=%s freq=%d channels=%d samples=%u media.role=%s\n", + driver ? driver : "unknown", have.freq, static_cast(have.channels), + static_cast(have.samples), + std::getenv("PULSE_PROP_media.role") ? std::getenv("PULSE_PROP_media.role") : ""); + } + + setupDone_.store(true, std::memory_order_release); + } + + static void audioCallback(void *userdata, Uint8 *stream, int len) + { + if (userdata == nullptr || stream == nullptr || len <= 0) return; + static_cast(userdata)->renderStereoFloat( + reinterpret_cast(stream), + static_cast(len) / (sizeof(float) * 2u)); + } + + void renderStereoFloat(float *interleaved, std::size_t frameCount) + { + Command command; + while (commands_.pop(command)) applyCommand(command); + + const std::int64_t base = + frameOffset_.load(std::memory_order_relaxed) + renderedFrames_.load(std::memory_order_relaxed); + const double vol = static_cast(volume_.load(std::memory_order_relaxed)) / 100.0; + const double oscGain = vol * kVoiceGain; + const double attack = attackFrames_; + const double release = releaseFrames_; + + const std::size_t pcmTotalFrames = pcmStereo_.size() / 2u; + + for (std::size_t i = 0; i < frameCount; ++i) { + const std::int64_t frame = base + static_cast(i); + double mixed = 0.0; + + for (Voice &voice : voices_) { + if (!voice.active) continue; + if (frame >= voice.endFrame) { + voice.active = false; + continue; + } + if (frame < voice.startFrame) continue; + + while (voice.eventCount > 0 && frame >= voice.events[voice.eventHead].frame) { + voice.phaseIncrement = voice.events[voice.eventHead].phaseIncrement; + voice.eventHead = (voice.eventHead + 1) % kMaxVoiceEvents; + --voice.eventCount; + } + + double level = 1.0; + const double sinceStart = static_cast(frame - voice.startFrame); + if (sinceStart < attack) level = sinceStart / attack; + if (voice.stopScheduled && frame >= voice.stopFrame) { + const double sinceStop = static_cast(frame - voice.stopFrame); + const double decay = 1.0 - sinceStop / release; + level *= decay > 0.0 ? decay : 0.0; + } + + mixed += waveform(voice.type, voice.phase) * level; + voice.phase += voice.phaseIncrement; + if (voice.phase >= 1.0) voice.phase -= 1.0; + } + + double left = mixed * oscGain; + double right = left; + + if (pcmCursor_ < pcmTotalFrames) { + left += static_cast(pcmStereo_[pcmCursor_ * 2u]) * vol; + right += static_cast(pcmStereo_[pcmCursor_ * 2u + 1u]) * vol; + ++pcmCursor_; + } + + left = std::clamp(left, -1.0, 1.0); + right = std::clamp(right, -1.0, 1.0); + interleaved[i * 2u] = static_cast(left); + interleaved[i * 2u + 1u] = static_cast(right); + } + + renderedFrames_.fetch_add(static_cast(frameCount), std::memory_order_relaxed); + } + + OscillatorRecord *find(NativeAudioHandle handle) + { + if (handle == 0) return nullptr; + const NativeAudioHandle slot = (handle & static_cast(0x3ffu)); + if (slot == 0 || slot > static_cast(kMaxOscillators)) return nullptr; + OscillatorRecord &record = records_[slot - 1]; + return record.handle == handle ? &record : nullptr; + } + + int launchCommands(const OscillatorRecord &record, NativeAudioHandle handle, Command *out) const + { + double initial = record.frequency; + int count = 0; + for (int i = 0; i < record.pendingCount; ++i) { + if (record.pending[i].time <= record.startTime) initial = record.pending[i].value; + } + out[count++] = Command{CommandKind::StartVoice, record.type, handle, normalizeFrequency(initial), + frameFor(record.startTime)}; + for (int i = 0; i < record.pendingCount; ++i) { + const ScheduledValue &event = record.pending[i]; + if (event.time <= record.startTime) continue; + out[count++] = Command{CommandKind::ScheduleFrequency, record.type, handle, + normalizeFrequency(event.value), frameFor(event.time)}; + } + if (record.stopped) { + out[count++] = Command{CommandKind::StopVoice, record.type, handle, + normalizeFrequency(record.frequency), frameFor(record.stopTime)}; + } + return count; + } + + double currentTimeLocked() const + { + if (!running_.load(std::memory_order_acquire)) return steadySeconds(); + const double rate = sampleRate_.load(std::memory_order_relaxed); + const std::int64_t frames = + frameOffset_.load(std::memory_order_relaxed) + renderedFrames_.load(std::memory_order_relaxed); + return static_cast(frames) / rate; + } + + std::int64_t frameFor(double seconds) const + { + const double rate = sampleRate_.load(std::memory_order_relaxed); + const double frame = seconds * rate; + if (!std::isfinite(frame) || frame < 0.0) return 0; + if (frame > 9.0e15) return static_cast(9.0e15); + return static_cast(std::llround(frame)); + } + + void applyCommand(const Command &command) + { + switch (command.kind) { + case CommandKind::StartVoice: { + Voice *voice = allocateVoice(); + if (voice == nullptr) return; + const double rate = sampleRate_.load(std::memory_order_relaxed); + voice->active = true; + voice->id = command.voice; + voice->type = command.type; + voice->phase = 0.0; + voice->phaseIncrement = command.frequency / rate; + voice->startFrame = command.frame; + voice->stopFrame = 0; + voice->stopScheduled = false; + voice->endFrame = command.frame + static_cast(kMaxVoiceSeconds * rate); + voice->eventHead = 0; + voice->eventCount = 0; + return; + } + case CommandKind::StopVoice: { + Voice *voice = findVoice(command.voice); + if (voice == nullptr) return; + std::int64_t at = command.frame; + if (at < voice->startFrame) at = voice->startFrame; + voice->stopFrame = at; + voice->stopScheduled = true; + voice->endFrame = at + static_cast(releaseFrames_) + 1; + return; + } + case CommandKind::SetFrequency: { + Voice *voice = findVoice(command.voice); + if (voice == nullptr) return; + voice->phaseIncrement = command.frequency / sampleRate_.load(std::memory_order_relaxed); + return; + } + case CommandKind::SetType: { + Voice *voice = findVoice(command.voice); + if (voice == nullptr) return; + voice->type = command.type; + return; + } + case CommandKind::ScheduleFrequency: { + Voice *voice = findVoice(command.voice); + if (voice == nullptr || voice->eventCount >= kMaxVoiceEvents) return; + const int slot = (voice->eventHead + voice->eventCount) % kMaxVoiceEvents; + voice->events[slot] = + VoiceEvent{command.frame, command.frequency / sampleRate_.load(std::memory_order_relaxed)}; + ++voice->eventCount; + return; + } + } + } + + Voice *allocateVoice() + { + Voice *oldest = &voices_[0]; + for (Voice &voice : voices_) { + if (!voice.active) return &voice; + if (voice.startFrame < oldest->startFrame) oldest = &voice; + } + return oldest; + } + + Voice *findVoice(NativeAudioHandle id) + { + for (Voice &voice : voices_) { + if (voice.active && voice.id == id) return &voice; + } + return nullptr; + } + + std::mutex setupMutex_; + std::atomic setupDone_{false}; + std::atomic running_{false}; + std::atomic sampleRate_{kDefaultSampleRate}; + std::atomic frameOffset_{0}; + std::atomic renderedFrames_{0}; + std::atomic volume_{80}; + SDL_AudioDeviceID device_ = 0; + double attackFrames_ = kAttackSeconds * kDefaultSampleRate; + double releaseFrames_ = kReleaseSeconds * kDefaultSampleRate; + + std::mutex recordsMutex_; + OscillatorRecord records_[kMaxOscillators]{}; + int nextSlot_ = 0; + std::uint32_t generation_ = 0; + + CommandQueue commands_; + Voice voices_[kMaxVoices]{}; + std::vector pcmStereo_; + std::size_t pcmCursor_ = 0; +}; + +} // namespace + // AudioParam AudioParam::AudioParam(NativeAudioHandle oscillator) : oscillator_(oscillator) {} -double AudioParam::value() const { return 0.0; } -void AudioParam::setValue(double) {} -void AudioParam::setValueAtTime(double, double) {} +double AudioParam::value() const { return Engine::instance().frequency(oscillator_); } +void AudioParam::setValue(double value) { Engine::instance().setFrequency(oscillator_, value); } +void AudioParam::setValueAtTime(double value, double start_time) +{ + Engine::instance().scheduleFrequency(oscillator_, value, start_time); +} // AudioNode AudioNode::AudioNode(NativeAudioHandle native) : native_(native) {} @@ -28,31 +746,30 @@ AudioDestinationNode::AudioDestinationNode(NativeAudioHandle native) : AudioNode // OscillatorNode OscillatorNode::OscillatorNode(NativeAudioHandle native) : AudioNode(native), frequency(native) {} -OscillatorType OscillatorNode::type() const { return OscillatorType::Sine; } -void OscillatorNode::setType(OscillatorType) {} -void OscillatorNode::connect(const AudioDestinationNode &) {} -void OscillatorNode::start(double) {} -void OscillatorNode::stop(double) {} +OscillatorType OscillatorNode::type() const { return Engine::instance().type(nativeId()); } +void OscillatorNode::setType(OscillatorType type) { Engine::instance().setType(nativeId(), type); } +void OscillatorNode::connect(const AudioDestinationNode &) { Engine::instance().connect(nativeId()); } +void OscillatorNode::start(double when) { Engine::instance().start(nativeId(), when); } +void OscillatorNode::stop(double when) { Engine::instance().stop(nativeId(), when); } // AudioContext -double AudioContext::currentTime() const { return 0.0; } -AudioDestinationNode AudioContext::destination() const { return AudioDestinationNode(0); } -OscillatorNode AudioContext::createOscillator() const { return OscillatorNode(0); } +double AudioContext::currentTime() const { return Engine::instance().currentTime(); } +AudioDestinationNode AudioContext::destination() const { return AudioDestinationNode(1); } +OscillatorNode AudioContext::createOscillator() const +{ + return OscillatorNode(static_cast(Engine::instance().createOscillator())); +} // AudioSystem AudioContext AudioSystem::sharedContext() { return AudioContext{}; } -int AudioSystem::volume() { return g_volume; } -void AudioSystem::setVolume(int v) -{ - if (v < 0) v = 0; - if (v > 100) v = 100; - g_volume = v; -} -bool AudioSystem::playFile(const std::string &) { return false; } -bool AudioSystem::playPcm(const std::int16_t *, std::size_t, int, int) { return false; } -void AudioSystem::stopPlayback() {} -// No PCM stream output is queued by this backend (only the ESP32 runtime -// streams PCM), so a flush has nothing to discard. -void AudioSystem::flushPlayback() {} +int AudioSystem::volume() { return Engine::instance().volume(); } +void AudioSystem::setVolume(int v) { Engine::instance().setVolume(v); } +bool AudioSystem::playFile(const std::string &path) { return Engine::instance().playFile(path); } +bool AudioSystem::playPcm(const std::int16_t *samples, std::size_t sample_count, int sample_rate, int channels) +{ + return Engine::instance().playPcm(samples, sample_count, sample_rate, channels); +} +void AudioSystem::stopPlayback() { Engine::instance().stopPlayback(); } +void AudioSystem::flushPlayback() { Engine::instance().stopPlayback(); } } // namespace gea::platform::audio