diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d9b86e3..3bfb3414 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -426,13 +426,23 @@ jobs: # From its GitHub release, checked against its SHA-256 (winget's # manifest for 0.9.9.0 gives the same), rather than Chocolatey's - # community feed, whose outages fail the job. An Inno Setup - # installer, into Program Files, where coverage.sh looks for it. + # community feed, whose outages fail the job. The asset URL's host + # can answer 504 for long stretches, so a failed download falls + # back to the API through gh. An Inno Setup installer, into + # Program Files, where coverage.sh looks for it. - name: Install OpenCppCoverage + env: + GH_TOKEN: ${{ github.token }} run: | $exe = "$env:RUNNER_TEMP\OpenCppCoverageSetup-x64-0.9.9.0.exe" - Invoke-WebRequest -Uri 'https://github.com/OpenCppCoverage/OpenCppCoverage/releases/download/release-0.9.9.0/OpenCppCoverageSetup-x64-0.9.9.0.exe' ` - -OutFile $exe -MaximumRetryCount 3 -RetryIntervalSec 10 + try { + Invoke-WebRequest -Uri 'https://github.com/OpenCppCoverage/OpenCppCoverage/releases/download/release-0.9.9.0/OpenCppCoverageSetup-x64-0.9.9.0.exe' ` + -OutFile $exe -MaximumRetryCount 3 -RetryIntervalSec 10 + } catch { + Write-Warning "Invoke-WebRequest failed ($_); trying gh release download" + gh release download release-0.9.9.0 -R OpenCppCoverage/OpenCppCoverage -p OpenCppCoverageSetup-x64-0.9.9.0.exe -O $exe --clobber + if ($LASTEXITCODE -ne 0) { Write-Error 'could not download OpenCppCoverage'; exit 1 } + } $sha = (Get-FileHash -Algorithm SHA256 $exe).Hash if ($sha -ne '2295a733da39412c61e4f478677519dd0bb1893d88313ce56b468c9e50517888') { Write-Error "unexpected SHA-256 $sha"; exit 1 @@ -676,9 +686,10 @@ jobs: cmake --build build # linuxdeploy and its Qt plugin, which make-appimage.sh downloads - # from GitHub's releases (a 504 there has failed the job) and checks - # by SHA-256 either way. Keyed on the script, which pins them; one - # copy an arch, saved on main's pushes only. + # from GitHub's releases (curl with retries, then the API through + # gh, since the asset URLs' host can answer 504 for long stretches) + # and checks by SHA-256 either way. Keyed on the script, which pins + # them; one copy an arch, saved on main's pushes only. - name: Restore linuxdeploy from the cache id: linuxdeploy-cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -687,6 +698,8 @@ jobs: key: linuxdeploy-${{ runner.arch }}-${{ hashFiles('packaging/linux/make-appimage.sh') }} - name: Pack and check the AppImage + env: + GH_TOKEN: ${{ github.token }} run: | VERSION=$(sed -n '/^project(Havne/,/)/s/^ *VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt) QMAKE="$QT_ROOT_DIR/bin/qmake" bash packaging/linux/make-appimage.sh "$VERSION-ci" build dist diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dc56f07f..3c216338 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -376,6 +376,8 @@ jobs: key: linuxdeploy-${{ runner.arch }}-${{ hashFiles('packaging/linux/make-appimage.sh') }} - name: Build and pack the AppImage + env: + GH_TOKEN: ${{ github.token }} run: | cmake -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF -DCMAKE_PREFIX_PATH="$QT_ROOT_DIR" cmake --build build @@ -504,6 +506,9 @@ jobs: echo "TARBALL_ARM=dist/havne-core-$VERSION-linux-aarch64.tar.gz" echo "DEBUG_TARBALL_ARM=dist/havne-core-$VERSION-linux-aarch64-debug.tar.gz" echo "SBOM=dist/havne-$VERSION.spdx.json" + # the AppImage runtime's sources (packaging/linux/runtime-sources.sh) + echo "FUSE_SOURCE=dist/fuse-3.15.0.tar.xz" + echo "RUNTIME_SOURCE=dist/type2-runtime-20251108.tar.gz" # the wheels carry the version as PEP 440 spells it: 0.6.0rc1 wheel="dist/havne-${VERSION/-rc/rc}-py3-none" echo "WHEEL_WIN=$wheel-win_amd64.whl" @@ -512,6 +517,15 @@ jobs: echo "WHEEL_MACOS=$wheel-macosx_13_0_arm64.whl" } >> "$GITHUB_ENV" + # The AppImage runtime links libfuse statically: LGPL-2.1 section 6 + # wants libfuse's source and the runtime's beside it, each checked + # against its pinned SHA-256 (THIRD_PARTY_NOTICES.txt names them) + - name: The AppImage runtime's sources + run: | + bash packaging/linux/runtime-sources.sh dist + [ -s "$FUSE_SOURCE" ] && [ -s "$RUNTIME_SOURCE" ] \ + || { echo "::error::runtime-sources.sh wrote other names than $FUSE_SOURCE and $RUNTIME_SOURCE"; exit 1; } + # One document over every download but the debug files, which carry # no component of their own; validated before anything is published. # The commit's time dates it, so a rerun writes the same document. @@ -531,6 +545,7 @@ jobs: "${APPIMAGE_ARM#dist/}" "${DEB_ARM#dist/}" "${DBGSYM_ARM#dist/}" "${TARBALL_ARM#dist/}" \ "${DEBUG_TARBALL_ARM#dist/}" "${WHEEL_WIN#dist/}" "${WHEEL_LINUX#dist/}" \ "${WHEEL_LINUX_ARM#dist/}" "${WHEEL_MACOS#dist/}" "${SBOM#dist/}" \ + "${FUSE_SOURCE#dist/}" "${RUNTIME_SOURCE#dist/}" \ > SHA256SUMS.txt) cat dist/SHA256SUMS.txt @@ -557,6 +572,8 @@ jobs: ${{ env.WHEEL_LINUX }} ${{ env.WHEEL_LINUX_ARM }} ${{ env.WHEEL_MACOS }} + ${{ env.FUSE_SOURCE }} + ${{ env.RUNTIME_SOURCE }} # Checked with gh attestation verify -R erickramer42/havne # --predicate-type https://spdx.dev/Document/v2.3 @@ -593,7 +610,7 @@ jobs: files=("$ZIP" "$SYMBOLS" "$APK" "$APPIMAGE" "$DEB" "$DBGSYM" "$TARBALL" "$DEBUG_TARBALL" "$APPIMAGE_ARM" "$DEB_ARM" "$DBGSYM_ARM" "$TARBALL_ARM" "$DEBUG_TARBALL_ARM" "$WHEEL_WIN" "$WHEEL_LINUX" "$WHEEL_LINUX_ARM" "$WHEEL_MACOS" - "$SBOM" dist/SHA256SUMS.txt "dist/havne-$VERSION.intoto.jsonl") + "$SBOM" "$FUSE_SOURCE" "$RUNTIME_SOURCE" dist/SHA256SUMS.txt "dist/havne-$VERSION.intoto.jsonl") if gh release view "$TAG" > /dev/null 2>&1; then gh release upload "$TAG" "${files[@]}" --clobber else diff --git a/CHANGELOG.md b/CHANGELOG.md index 19469e16..aef03b4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,179 @@ way, is in [docs/engineering-log.md](docs/engineering-log.md). ## [Unreleased] +## [0.7.0] - 2026-11-08 + +### Added + +- The Dashboard can be built by hand: Edit (or, on a phone, a long press + on a gauge) adds dials, rings, bars, cells, digits, numbers, sparklines + and shift lights for any of the profile's numeric signals, with or + without a connected vehicle, and sets each gauge's label, range, + warning zones, decimals, size and place. Pages can be added, renamed, + moved and removed, and Reset brings back the built-in layout. Each + change is saved as it is made, separately for the phone and the + desktop, and the layout is the same for every vehicle + ([ADR-0057](docs/adr/0057-dashboards.md)). +- Three more Dashboard gauges: Cells (a tachometer-style bar of cells + along a rising curve), Digits (a seven-segment readout) and Sparkline + (10 to 120 seconds, with its low and high). A bar can stand up and + leave its ticks out, and any gauge with a scale can mark its held peak. +- Low glare and Night themes: amber and red on near black, for a cabin + after dark. Choose one under Settings, Display; it is kept between + runs. The gauges, the charts' traces, Home's logo and the Windows title + bar (and Android's window background) follow it. +- Start log in the header records the signals ticked on Live from the + press on, asking the ECU for those alone, and shows the log's time and + size while it runs. Stop log opens it on Recordings, and a disconnect + ends it where you are. It is refused while Record sessions records. + The Dashboard's header says when a log wasn't started or ended without + Stop log, and why, until Dismiss or the next log + ([ADR-0056](docs/adr/0056-analysis-log.md)). +- `havne-cli log [--signal ]...` is the same log + from the command line: the session asks only the signals named, + records to a folder of its own, writes a `log` line every 10 s with + the recording's size, and ends at Ctrl+C or `--seconds`. `export` then + takes the picked columns by itself. +- `havne-cli export` takes `--rows sweep|` (a grid instead of a row + a sweep), `--units metric|imperial` and `--signal ` (the columns, + repeated, in order), beside `--layout`. +- The recording viewer shows a recording's frames: a Values | Frames + switch beside Save report opens the Log page's table, filter and By ID + list over the part in view (the first 10,000 frames when more lie in + it), and a tap on a row puts the chart's cursor there. +- `havne-cli frames [--from S] [--to S]` and Python's + `havne.read_frames` read a recording's frames between two times + (`ecuio_recording_read_frames`). +- The Recordings page imports a CSV or candump log as a recording, on + every platform (Android's document picker too): Import guesses the + file's kind from its first line and asks for a candump log's bus when + it holds several. +- Importing a CSV in the app needs no column map file: the Import panel + reads the file's header and shows what it guessed (the time column and + its unit, then each column with its name, unit and kind and the first + rows of its cells). Each column can be left out or put back, renamed, + given another unit or kind, and a time of plain numbers takes its unit + from a choice of s, ms and us. **Save as map** keeps the edited map + under the settings folder's `maps/`, and a **Saved maps** list offers + it for the next file; **Column map...** still picks a file and skips + the guess. +- A CSV with no column map is read by its header from the command line + too: `havne-cli import csv ` guesses the time column and + its unit, the delimiter, a preamble, decimal commas, each signal's + name, unit and kind, and the placeholders that mean no value, then + imports with that map, writing the guess and its notes first. + `--time-unit s|ms|us` gives a time of plain numbers its unit when the + header names none, and `--print-map` prints the guessed map alone, to + edit and pass with `--map`. Python's `havne.guess_csv_map(path)` + returns the same guess, and `havne.import_csv(path, folder)` imports + with it. +- The Log page filters by an ID mask (candump's `ID:mask`, beside IDs + and ranges), a length (byte counts and ranges) and a time (a range of + the table's seconds, either end open), and By ID draws the bytes that + changed from an ID's frame before in the warning color. +- The health report names the vehicle's baseline recording: its start, + length, profile and backend, and whether the report's own recording is + it, never its folder (whose name holds the vehicle's label). The app's + Save report on Diagnostics and in the log viewer names the picked + vehicle's; `havne-cli health` takes `--baseline `. A + baseline that's gone or can't be read is said so, and the report is + still written ([ADR-0054](docs/adr/0054-exports-and-imports.md)'s + appendix "the health report as built"). +- A running session's requests can be narrowed to picked signals + (`ecuio_session_set_focus`; Python `Session.set_focus`): the picked + requests run in the fast class and the rest wait, until a count of 0 + asks the whole set again. A focus that would leave a requesting + session nothing to ask is refused + ([ADR-0056](docs/adr/0056-analysis-log.md) section 2). +- A recorder attaches to a session that is already running + (`ecuio_session_record` after start; Python `Session.record` after + `start()`): the recording holds the frames from then on, its header + says what the link's state and the focus were at the attach, and once + it closes another can attach. One recorder at a time + ([ADR-0056](docs/adr/0056-analysis-log.md) section 3). +- `ecuio_export_estimate` gives the rows and exact size a wide CSV export + would write, for up to 64 row intervals in one pass, before anything + is written. A count above 64 is `ECUIO_ERR_INVALID_ARGUMENT`. +- The C ABI names a signal file's key for one of its signals + (`ecuio_signal_file_key`) and the span a signal's field decodes to + (`ecuio_def_range`), which the Dashboard's gauges start from. + +### Changed + +- **Breaking for scripts that read the CSV export, and for C callers of + `ecuio_export`:** the CSV export's default is the wide layout + ([ADR-0056](docs/adr/0056-analysis-log.md) section 5): `Time (ms)` then + a column a signal, a row each sweep (or on a grid, `--rows `), each + cell in the signal's decimal places and units, the columns the + recording's focus or the ones named (`--signal`), CRLF and no comment + line. The long form as before, a row a value under a comment line, is + `havne-cli export --layout long` (C: `layout = ECUIO_CSV_LONG`; an + `ecuio_export_options_t` with its reserved words zeroed, which v0.6.0 + callers pass, writes wide). A `--signal` name the recording has no + values for is an empty column, said on stderr and counted in the + `exported` line's `missing`. A wide export of more than 16,384 columns, + picked ones too, is refused. +- Python's `Recording(folder, profile=..., signals=...)` raises + `ValueError` when given both, since a recording decodes through one + set. Before, `signals` won without a word. +- A recording's `latency.csv` writes each row's `t_s` on the recording's + clock, as `host_us` in its other files, so reply timing plots against + the frames of a recording begun mid-session. A recording made before + this holds the session's time there. +- Settings is a list of pages (Connection, Vehicle, Signals, Recording, + Display, Advanced) instead of folding sections. Add a signal is a page + of its own, and the buttons on a phone are a finger's size. +- A gauge past its danger value shows a mark beside its reading, and the + danger zones are drawn heavier (in every theme), so danger doesn't rest + on color alone. +- The shift lights flash at 3 Hz at most, down from about 7 Hz. +- The Connection page's presets start collapsed, `j2534://` shows on + Windows only, and the WiFi labels carry the address in smaller text. +- The mock's MAF shows two decimals. + +### Fixed + +- A session kept connected while one request's answers paused for 36 + minutes or more and then resumed (the key turned off with the app, + `havne-cli stream` or `havne-cli health` connected over J2534, ELM327 + or SocketCAN, and on again later) hung the session's worker for good. + Since v0.3.5, which brought reply timing + ([ADR-0042](docs/adr/0042-reply-timing.md)). +- `havne-cli stream --record` crashed when its output went away (the + reader of its pipe gone, a full disk under stdout) instead of ending + quietly. It ends quietly with the recording closed whole, its end + line's why `output-failed`. Since v0.4.0, which brought `--record`. +- A `--seconds` above 366 days is a usage error for `stream`, `play` and + `sim`, instead of wrapping and ending at once. +- A phone's tab bar: each tab is at least 48 dp at any zoom, with a gap + above the window's edge so a low tap doesn't land on Back or Home, and + a phone keeps its tab bar in both orientations. The header and tab bar + no longer count the system's bars twice. +- On Android, a tap on Refresh or Scan asks for Nearby devices again + after a refusal, a refusal Android answers at once names the way to + the permission with an Open settings button, and the page reads the + permission again when the app returns. +- The Linux AppImage and the Android APK carry Qt's notice and the + LGPL-3.0 and GPL-3.0 texts, as the Windows zip does, with Havne's + license and those of the other libraries they bundle: + `usr/share/doc/havne/` in the AppImage, `assets/havne/` in the APK. +- The Windows zip, the AppImage and the APK carry the credits and license + texts for the third-party code inside Qt + (`licenses/Qt-third-party.txt`), rather than a link to them. The + Windows zip carries the license texts for its software OpenGL renderer. +- The Windows download no longer includes Microsoft's shader compiler + DLLs (`D3Dcompiler_47.dll`, `dxcompiler.dll`, `dxil.dll`). Havne runs + the same without them, and the download is smaller. +- The Linux AppImage starts with a pinned AppImage runtime (type2-runtime + 20251108), checked against its SHA-256, instead of the newest build + downloaded at packing time. Its notice names the runtime and what it + contains (libfuse, squashfuse, musl, mimalloc, zstd, zlib), with their + license texts, and each release attaches the sources of libfuse and the + runtime. +- The Android APK no longer carries Qt's QML debugger plugins (about + 1.3 MB). They were never usable: the release app is built without QML + debugging. + ## [0.6.0] - 2026-11-07 ### Added @@ -903,7 +1076,8 @@ The first release with a Windows download shell with a responsive layout. - CI on Windows, macOS and Linux, running the core's tests. -[Unreleased]: https://github.com/erickramer42/havne/compare/v0.6.0...HEAD +[Unreleased]: https://github.com/erickramer42/havne/compare/v0.7.0...HEAD +[0.7.0]: https://github.com/erickramer42/havne/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/erickramer42/havne/compare/v0.5.1...v0.6.0 [0.5.1]: https://github.com/erickramer42/havne/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/erickramer42/havne/compare/v0.4.1...v0.5.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index e70dc5bc..d9004c0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) project(Havne - VERSION 0.6.0 + VERSION 0.7.0 DESCRIPTION "Cross-platform ECU reading, logging, and tuning" LANGUAGES C CXX ) diff --git a/README.md b/README.md index b2efc6f6..b048af28 100644 --- a/README.md +++ b/README.md @@ -1,205 +1,59 @@ # Havne -_From Norwegian *havn*, a harbor or port: Havne reaches a car through its ports. The verb *havne* is to end up somewhere, as in *havne i grøfta*, in the ditch; staying out of it is still your job._ +_From Norwegian *havn*, a port: Havne reaches a car through its ports._ [![CI](https://github.com/erickramer42/havne/actions/workflows/ci.yml/badge.svg)](https://github.com/erickramer42/havne/actions/workflows/ci.yml) [![Coverage](https://codecov.io/gh/erickramer42/havne/graph/badge.svg)](https://codecov.io/gh/erickramer42/havne) [![Release](https://img.shields.io/github/v/release/erickramer42/havne)](https://github.com/erickramer42/havne/releases/latest) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/erickramer42/havne/badge)](https://scorecard.dev/viewer/?uri=github.com/erickramer42/havne) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/15816/badge)](https://www.bestpractices.dev/projects/15816) -Havne is a cross-platform OBD-II scan tool and data logger built on a -Qt-free C++17 core behind a stable C ABI. It shows live data, reads -trouble codes and readiness monitors, records every frame to replay -and compare, reads manufacturer-specific signals from data files you -write or import, and shares a recording or a car's health report with -the car's identity scrubbed out. - -It reaches a car through J2534 Pass-Thru adapters on Windows, -ELM327-compatible adapters over USB, Bluetooth or WiFi on every -platform, and SocketCAN on Linux. It runs on Windows, Linux (x86_64 -and 64-bit ARM) and Android, builds and passes its tests on macOS, and -runs on the iOS Simulator; a simulated vehicle drives every page with -no hardware. Three front ends share the core: a Qt 6 / QML app; -`havne-cli`, which streams any session as JSON lines and is written -against the public headers alone; and the `havne` Python package. +Havne reads a car through J2534, ELM327 or SocketCAN adapters on Windows, Linux and Android: live data, trouble codes, and recordings to replay or share, scrubbed. A Qt-free C++17 core behind a C ABI serves a Qt app, `havne-cli` and Python. [Download](https://github.com/erickramer42/havne/releases/latest). > [!WARNING] -> **Experimental.** It has read one car through two adapters and listened to it through a third; other vehicles and adapters are untested. It can clear trouble codes, asking and saving them first, but has erased a stored code only on its fakes and simulated vehicle. Read [DISCLAIMER.md](DISCLAIMER.md) before connecting it to a vehicle. +> **Experimental.** It has read one car through two adapters and listened through a third; other cars and adapters are untested. Read [DISCLAIMER.md](DISCLAIMER.md) before connecting it to a vehicle. -![The Havne Dashboard through a quarter mile on the warmed-up simulated vehicle: launch control holds the engine near 4,000 rpm at the line, the tires spin off it, three upshifts at 6,800 rpm refill the shift lights, and speed climbs to about 107 mph at the line while coolant rises from 194 to 216 deg F, where the fan cuts in, and the oil from 221 to 235 deg F, before the driver lifts](docs/images/dashboard.gif) +![The Dashboard through a quarter mile](docs/images/dashboard.gif) -*The Dashboard on the simulated vehicle (`mock://demo`), in real time: -a quarter mile off launch control on a warm loop.* +*The Dashboard, simulated.* ## Engineering highlights -- **Vendor drivers run out of process.** Each J2534 DLL, often 32-bit, - runs in a single-threaded surrogate of its own architecture behind a - private named pipe, so a crashing driver takes down its surrogate, - not the app ([ADR-0025](docs/adr/0025-one-j2534-backend.md), - [ADR-0014](docs/adr/0014-single-threaded-surrogate.md)). -- **Fast paths, measured.** The worker decodes with no allocation per - frame, backpressure bounds the frames in flight, and QML gets values - at 10 Hz whatever the bus rate: a recorded engine start replays - through decode at over 300,000 frames a second, about 70 times a - full classic CAN bus, in a load test every CI run repeats. Recording - costs the worker 31 to 47 ns a frame (a single-producer ring to the - recorder's own writer thread), and the reader opens an hour of 50 - signals, 1.8 million rows, in under 0.2 s - ([ADR-0024](docs/adr/0024-decode-on-the-worker.md), - [ADR-0049](docs/adr/0049-recordings-in-core.md), - [load test](docs/testing.md#load-test-the-replay-fixture-through-the-bridge)). -- **Measured on a real car, and fixed by what it showed.** A second CAN - controller listening on the test car's bus timed the Pass-Thru: a - reply was whole on the wire 14 ms after its request but reached the - session about 52 ms later, most of it in Havne's own read of the - adapter. With that read fixed, a request's latency fell from - 65.5-73.7 ms to 16.4 ms; packing up to six PIDs into a request had - already brought 2.7 times the replies a minute. Each session is - written up with its scrubbed logs - ([2026-11-01](docs/bench-sessions/2026-11-01-vehicle.md), - [2026-11-03](docs/bench-sessions/2026-11-03-socketcan-car.md), - [2026-11-04](docs/bench-sessions/2026-11-04-two-ecu-car.md), - [2026-11-05](docs/bench-sessions/2026-11-05-two-ecu-car-rerun.md)). -- **Protocol logic with no I/O, unit-tested and fuzzed.** The request - engine, ISO-TP and the ELM327 wire layer take no I/O, clock or - allocation, so every rule is a unit test over canned bytes; they and - every other parser run under libFuzzer with ASan and UBSan in CI. - Core's ISO-TP is also held to the Linux kernel's on a virtual CAN bus, - and to a recording of the test car with its replies broken on purpose - ([ADR-0015](docs/adr/0015-request-engine.md), - [ADR-0040](docs/adr/0040-socketcan-requests-isotp.md), - [ADR-0041](docs/adr/0041-replay-fault-injection.md), - [fuzz/README.md](fuzz/README.md)). -- **A user's signals are data, checked before the car.** Signal files - and plugins are JSON that core reads strictly from bytes, never a - path, so every platform loads them alike, iOS included. Anything wrong - is refused at load with its line and column, and a plugin's fixtures - run through the simulated ECU in CI, so its scaling is checked with no - car ([ADR-0051](docs/adr/0051-signal-files.md), - [ADR-0052](docs/adr/0052-plugin-framework.md)). -- **Scrubbed by construction, then checked.** An export plans the file - from the frames' ISO-TP reassembly, leaving out identification - replies, text signals and any segment it can't attribute; then every - message and the file itself are searched for the car's VIN, - calibration IDs and anything shaped like a VIN, and a match writes - nothing. One rule set serves the pcapng, CSV and folder exports, the - health report and the Log page's frames - ([ADR-0054](docs/adr/0054-exports-and-imports.md)). -- **A stable C ABI, for any language.** Opaque handles, flat functions - and POD structs with reserved room; CI compiles every public header as - strict C, compares the ABI with the last release's and builds the core - with no Qt installed. The shared library exports the C API and nothing - else, and a pull queue hands frames and values to a caller's own - thread, which is how Python reads core through ctypes, with no - compiler at install time - ([ADR-0001](docs/adr/0001-qt-free-core-c-abi.md), - [ADR-0053](docs/adr/0053-python-bindings.md)). -- **Tested in tiers.** A harness tier drives the whole J2534 stack - against an in-tree fake driver, 32-bit included, and ELM327 against a - fake adapter; what only hardware can confirm is listed with its - evidence, and each decision is an [ADR](docs/adr/README.md) with the - alternatives it turned down ([docs/testing.md](docs/testing.md), - [bench-prep.md](docs/bench-sessions/bench-prep.md)). -- **Downloads anyone can check.** Signed build provenance and an SPDX - SBOM for every download, Linux core packages that build to the same - bytes, and debug symbols with each release - ([ADR-0034](docs/adr/0034-debug-symbols-and-probes.md), - [ADR-0035](docs/adr/0035-linux-downloads-sbom-reproducible.md)). +- **Vendor drivers run out of process.** Each J2534 DLL runs in a surrogate of its own architecture, so a crashing driver ends its process, not the app ([ADR-0025](docs/adr/0025-one-j2534-backend.md)). +- **Fast paths, measured.** The worker decodes with no allocation per frame; a recorded engine start replays at over 300,000 frames a second in a load test CI repeats ([load test](docs/testing.md#load-test-the-replay-fixture-through-the-bridge)). +- **Measured on a real car.** A second controller on its bus showed Havne's adapter read adding 52 ms; fixing it cut latency from 65.5-73.7 ms to 16.4 ms ([session sheet](docs/bench-sessions/2026-11-05-two-ecu-car-rerun.md)). +- **Protocol logic with no I/O, fuzzed.** The request engine, ISO-TP and the ELM327 layer take no I/O or clock, so rules are unit tests; parsers run fuzzed in CI ([ADR-0015](docs/adr/0015-request-engine.md)). +- **A user's signals are data.** Signal files are JSON that core reads from bytes and refuses at load with line and column, so every platform loads them alike ([ADR-0051](docs/adr/0051-signal-files.md)). +- **Scrubbed by construction, then checked.** An export plans the file from ISO-TP reassembly, then searches every message for the car's VIN and writes nothing on a match ([ADR-0054](docs/adr/0054-exports-and-imports.md)). +- **A stable C ABI.** Opaque handles, flat functions and POD structs with reserved room; CI compiles the headers as strict C and compares the ABI with the last release's ([ADR-0001](docs/adr/0001-qt-free-core-c-abi.md)). +- **Tested in tiers, downloads checkable.** A harness tier drives the J2534 stack against a fake driver, 32-bit included; each release carries signed provenance and an SBOM ([testing.md](docs/testing.md), [ADR-0035](docs/adr/0035-linux-downloads-sbom-reproducible.md)). ## What it does -- **Pages:** a Dashboard of gauges with shift lights and peak hold; - Live, the values and a strip chart; Diagnostics; Recordings; and a - Log of every connect, with the raw frames in developer mode, filtered - by ID or bytes and listed by ID with each one's rate. -- **Adapters:** J2534 on Windows; ELM327 over serial, Bluetooth or - WiFi, on the desktop and on Android, where sessions keep running in - the background; SocketCAN on Linux, listening through a real - controller and asking, so far, on a virtual bus - ([j2534.md](docs/j2534.md), [elm327.md](docs/elm327.md), - [linux.md](docs/linux.md)). -- **Trouble codes:** each ECU's stored, pending and permanent codes, - readiness monitors and freeze frame, generic codes named offline, and - the inspection readiness verdict; a clear asks first and saves the - report ([ADR-0037](docs/adr/0037-reading-trouble-codes.md), - [ADR-0038](docs/adr/0038-clearing-trouble-codes.md), - [ADR-0044](docs/adr/0044-trouble-code-titles.md), - [ADR-0045](docs/adr/0045-inspection-readiness.md)). -- **Profiles, chosen by the URI:** `obd2` polls every Service 01 - reading the car supports, the fast-changing ones more often; - `uds-generic` the UDS identifiers you name; `raw` logs frames; and - your signal files and plugins. The VIN, calibration IDs and each - request's reply time are read too - ([ADR-0039](docs/adr/0039-full-service01-coverage.md), - [ADR-0042](docs/adr/0042-reply-timing.md), - [ADR-0043](docs/adr/0043-vin-decode.md)). -- **Your own signals:** signal files of Service 01 PIDs and Service 22 - DIDs on up to four modules, as numbers, text, enumerations or values - computed from others (the simulated car's boost is MAP minus baro). - Write them per vehicle in Settings, where **Read once** shows a - reply's bytes beside its value, with a JSON Schema for your editor, or - import an OBDb set in Settings or with `havne-cli` - ([docs/signal-files.md](docs/signal-files.md)). -- **Plugins:** packages of signal files for one manufacturer's cars; - the car's VIN proposes the variants that fit, and the pick stays - with the vehicle ([plugins/README.md](plugins/README.md)). -- **Recording and replay:** every frame, value and event of a session. - The Recordings page pans, zooms, reads every value at a cursor, marks - what a check of the frames found and overlays a second run, or the - vehicle's baseline lined up on the engine starts; a raw recording's - frames decode through any profile; `replay://` plays a recording back - through the same decoding, with faults injected on request - ([ADR-0023](docs/adr/0023-replay-transport.md), - [ADR-0049](docs/adr/0049-recordings-in-core.md)). -- **Sharing:** a recording exported scrubbed as pcapng for Wireshark - (its ISO-TP reassembled there), CSV for a spreadsheet or pandas, or a - folder another Havne opens and replays; a car's health report (the - vehicle from its VIN, never the VIN itself, the inspection verdict, - codes, readiness and key values) from a session or a recording, in - the app or `havne-cli`; a candump log or another logger's CSV imported - as a recording ([ADR-0054](docs/adr/0054-exports-and-imports.md)). -- **`havne-cli`:** any session as JSON lines, through a signal file or - a plugin too; recordings viewed, checked, exported and imported - offline; trouble codes cleared from a script through the app's gate; - signal files checked, OBDb sets converted and plugins checked; the - simulated car served as an ELM327 adapter on a TCP port for other OBD - tools; on Linux, the simulated car or a recording answering requests - on a virtual CAN bus; and an Android phone relaying its Bluetooth - adapter to it over USB - ([ADR-0031](docs/adr/0031-command-line-client.md), - [ADR-0046](docs/adr/0046-simulated-ecu.md), - [ADR-0047](docs/adr/0047-adapter-relay.md), - [ADR-0055](docs/adr/0055-elm327-emulator.md)). -- **Python:** the `havne` package, in a wheel per platform with core - inside: sessions on every transport with their frames and values as - iterators, recordings, imports, the simulated ECU and your own - signals; examples from a PID reader to a DID scan, ISO-TP fuzzing on - a virtual bus and a notebook predicting fuel cut - ([ADR-0053](docs/adr/0053-python-bindings.md), - [python/examples/](python/examples/)). -- **A simulated vehicle:** a modeled car (gearing, airflow, tire slip, - coolant and oil heat) through a cold start, pulls onto the limiter, a - cruise and a quarter mile, its readings consistent with each other. +- **Live data:** a Dashboard built from eight kinds of gauge, Live's table and chart, and Dark, Low glare and Night themes ([ADR-0057](docs/adr/0057-dashboards.md)). +- **Adapters:** J2534 on Windows; ELM327 over serial, Bluetooth or WiFi, kept running in the background on Android; SocketCAN on Linux, asking so far on a virtual bus ([docs/linux.md](docs/linux.md)). +- **Diagnose:** each ECU's stored, pending and permanent codes with titles, readiness, the freeze frame and an inspection verdict; a clear asks first and saves the report ([ADR-0037](docs/adr/0037-reading-trouble-codes.md)). +- **Profiles, chosen by the URI:** `obd2` polls every Service 01 reading the car supports, `uds-generic` the identifiers you name, `raw` logs frames ([ADR-0039](docs/adr/0039-full-service01-coverage.md)). +- **Your own signals:** signal files and plugins for Service 01 PIDs and Service 22 DIDs on up to four modules, written in Settings or imported from an OBDb set ([signal-files.md](docs/signal-files.md)). +- **Record and review:** every frame and value of a session; the Recordings page pans, zooms, overlays a second run and shows the frames; `replay://` plays one back ([ADR-0049](docs/adr/0049-recordings-in-core.md)). +- **Analysis log:** Start log records the picked signals at the bus's own rate, and `havne-cli export` writes them as a wide CSV, a row a sweep ([ADR-0056](docs/adr/0056-analysis-log.md)). +- **Share:** `havne-cli` exports a recording scrubbed as pcapng, CSV or a folder; the app saves a health report; candump logs and other loggers' CSVs import in both ([ADR-0054](docs/adr/0054-exports-and-imports.md)). +- **`havne-cli` and Python:** any session as JSON lines or iterators, recordings viewed and exported offline, the simulated car served as an ELM327 adapter ([ADR-0031](docs/adr/0031-command-line-client.md), [ADR-0053](docs/adr/0053-python-bindings.md)). +- **A simulated vehicle:** a modeled car through a cold start, pulls onto the limiter and a quarter mile, so every page runs with no hardware. | Live view | Link health | |---|---| -| [![Live view: RPM, speed, MAF and lambda plotted through a 3rd-gear pull onto the limiter](docs/images/live.png)](docs/images/live.png) | [![Live view over J2534 with every request failing: an amber "Requests failing" banner and pill, and each signal waiting for data](docs/images/link-health.png)](docs/images/link-health.png) | +| [![Live view: a 3rd-gear pull onto the limiter](docs/images/live.png)](docs/images/live.png) | [![Live view with every request failing: an amber banner](docs/images/link-health.png)](docs/images/link-health.png) | | A 3rd-gear pull onto the limiter: rpm, speed and MAF rise together, then rpm saws while speed holds and lambda swings lean on each fuel cut | Every request refused by the fake J2534 driver: the link reads "requests failing", not idle, and the page says what to check | -![The Diagnostics page on the simulated vehicle: the inspection readiness card says it would fail an emissions inspection because an ECU commands the check-engine light on; ECU 0x7E8 lists three stored codes (P0301, P0420, U0100), three pending (P0171, C0035, B1001) and one permanent (P0420), each P and U code with its title, such as "P0301 Cylinder 1 Misfire Detected"; below, the readiness monitors, each done this drive and complete since the last clear](docs/images/diagnostics.png) +![The Diagnostics page on the simulated vehicle](docs/images/diagnostics.png) -*The Diagnostics page on the simulated vehicle: the inspection -verdict, each code with its SAE J2012 title, and the readiness -monitors.* +*Diagnostics: the inspection verdict, each code with its SAE J2012 title, the readiness monitors.* -![The Log page in developer mode on the simulated vehicle: the activity log holds two connects with their Session lines and, between them, the Delivery line of the disconnect (none dropped, the GUI thread's wait in microseconds); the pointer clicks Frames and the raw frame table streams, newest first, each frame's time, length, standard or extended ID and payload; then it clicks back to Activity](docs/images/log.gif) +![The Log page in developer mode: activity, then raw frames](docs/images/log.gif) -*The Log page in developer mode: each session as it happened, then the -frames as they arrive.* +*The Log page in developer mode: each session, then the frames.* -![The Recordings page: a recording of the simulated vehicle's third loop, warmed up, open in the viewer with its first loop, a cold start, overlaid dashed and aligned on a marker typed before each 2nd-gear pull; the list is filtered to the four plotted signals, RPM, coolant, vehicle speed and oil; RPM and speed climb to the fuel-cut limiter together in both runs while the warm run's coolant reads 201 deg F and oil 192 deg F at the cursor against the cold run's 99 and 82; under the chart the frames check found nothing in 6,501 frames](docs/images/recordings.png) +![The Recordings page: two runs overlaid](docs/images/recordings.png) -*The Recordings page: a warm loop's 2nd-gear pull with the cold -start's overlaid dashed, aligned on a marker typed while recording.* +*Recordings: a warm loop's pull with the cold start's overlaid, aligned on a marker.* ## Architecture @@ -224,10 +78,9 @@ start's overlaid dashed, aligned on a marker typed while recording.* └── ecuio-j2534-surrogate-x64.exe (64-bit drivers) ``` -Three rules shape it: **the core never links Qt**, so other front ends -can drive the same core; **the UI receives final display values**, so -decoding, scaling and units have one home; and **the C ABI is the -boundary**. [docs/architecture.md](docs/architecture.md) walks through +Three rules shape it: **the core never links Qt**; **the UI receives +final display values**, so decoding and units have one home; and **the C +ABI is the boundary**. [docs/architecture.md](docs/architecture.md) walks through it, a frame's path from transport to screen included. **Where to look in the code:** @@ -252,28 +105,14 @@ it, a frame's path from transport to screen included. Download from the [latest release](https://github.com/erickramer42/havne/releases/latest): -- **Windows 10 or 11 (x64):** unzip the zip and run `havne.exe`; Qt and - the Visual C++ runtime are inside. It isn't code-signed, so - SmartScreen may ask first (**More info**, then **Run anyway**). -- **Android 12 or later:** open the APK on the phone. It's signed with - Havne's release key, so each release installs over the last. -- **Linux (x86_64 or 64-bit ARM such as a Raspberry Pi; glibc 2.39 or - later):** make the AppImage executable and run it. - [docs/linux.md](docs/linux.md) covers what it needs, the core - packages for `havne-cli` and your own programs, serial permissions and - SocketCAN. -- **Python 3.11 or later** (Windows x64, Linux x86_64 or 64-bit ARM, - macOS 13 or later on Apple silicon): `pip install` the wheel for your - platform, then `python read_pids.py mock://demo` with - [`read_pids.py`](python/examples/read_pids.py) prints the simulated - car's engine speed, vehicle speed and coolant temperature. - -Then in Settings, tick **Developer mode** under Display, press the -`mock://demo` preset and **Connect**; with **Record sessions** on, each -run opens afterward on the Recordings page. - -To build from source you need CMake 3.21+, Qt 6.12 and a C++17 -compiler: +- **Windows 10 or 11 (x64):** unzip and run `havne.exe`. It isn't code-signed, so SmartScreen may ask first (**More info**, then **Run anyway**). +- **Android 12 or later:** open the APK on the phone; it's signed with Havne's release key, so each release installs over the last. +- **Linux (x86_64 or 64-bit ARM; glibc 2.39 or later):** make the AppImage executable and run it ([docs/linux.md](docs/linux.md)). +- **Python 3.11 or later:** `pip install` the wheel for your platform, then `python read_pids.py mock://demo` ([`read_pids.py`](python/examples/read_pids.py)) prints the simulated car's readings. + +Then in Settings, tick **Developer mode** under Advanced, press the `mock://demo` preset on Connection and **Connect**; with **Record sessions** on, each run opens afterward on the Recordings page. + +To build from source you need CMake 3.21+, Qt 6.12 and a C++17 compiler: ```sh cmake -B build -DCMAKE_PREFIX_PATH=/ @@ -281,27 +120,18 @@ cmake --build build --config Release ctest --test-dir build -C Release --output-on-failure ``` -`-DHAVNE_BUILD_CORE_ONLY=ON` builds the core, `havne-cli` and their -tests without Qt; `havne-cli stream mock://demo --values` then streams -the simulated car as JSON lines. -[docs/development.md](docs/development.md) covers the 32-bit -surrogate's second tree, Linux, macOS, Android and iOS, and -troubleshooting. +`-DHAVNE_BUILD_CORE_ONLY=ON` builds the core, `havne-cli` and their tests without Qt; `havne-cli stream mock://demo --values` then streams the simulated car as JSON lines. [docs/development.md](docs/development.md) covers the other platforms and troubleshooting. ## Status -v0.6.0, sharing and scripting (scrubbed exports and imports, a car's -health report, Python bindings, an ELM327 emulator, clearing codes from -`havne-cli`), is the latest release. Next: +v0.7.0, the dashboard and the UI, is the latest release. Next: | Version | Plan | |---|---| -| v0.7.0-v0.10.0 | Configurable dashboards and a refreshed UI; triggered logging and alerts; discovery of every module; the scan tool | +| v0.7.1-v0.10.0 | A more modern look; triggered logging and alerts; discovery of every module; the scan tool | | 1.0.0 | The finished reader: frozen and hardened, full featured on Windows, Linux and Android | -[STATUS.md](STATUS.md) holds what works, what's verified, the known -issues and the roadmap; [CHANGELOG.md](CHANGELOG.md) what each release -changed. +[STATUS.md](STATUS.md) holds what works, what's verified, the known issues and the roadmap; [CHANGELOG.md](CHANGELOG.md) what each release changed. ## Documentation diff --git a/STATUS.md b/STATUS.md index ed357da6..27e91e0c 100644 --- a/STATUS.md +++ b/STATUS.md @@ -1,6 +1,6 @@ # Havne: Project Status -**Updated:** 2026-11-07, **Version:** v0.6.0, +**Updated:** 2026-11-08, **Version:** v0.7.0, [![CI](https://github.com/erickramer42/havne/actions/workflows/ci.yml/badge.svg)](https://github.com/erickramer42/havne/actions/workflows/ci.yml) This file covers the project as it stands: what works, what comes @@ -14,8 +14,13 @@ Safety, regulatory and warranty caveats are in ## Where things stand -**Current phase: between releases; v0.7.0 is next.** v0.6.0 is out, -sharing and scripting (its section below): everything reaches +**Current phase: v0.7.0, the dashboard and the UI, is +out** (its section below). The Dashboard is built by hand +from eight kinds of gauge and saved per phone and desktop, with Low +glare and Night themes; Settings is a list of pages; an analysis log +records the signals picked on Live at their own rate, as a wide CSV; the +app imports CSV and candump logs and shows a recording's frames. v0.6.0 +is out, sharing and scripting: everything reaches `havne-cli` and Python as well as the app, a recording exports scrubbed as pcapng, CSV or a copy of its folder, a car's health goes in one file, candump logs and other loggers' CSVs import as recordings, and the @@ -209,8 +214,14 @@ background too ([roadmap](#roadmap)). adapter apart on every connection surface ([docs/j2534.md](docs/j2534.md#session-lifecycle)); all four states have shown on the VX. - - **The UI:** Dashboard gauges with peak hold and stale dimming, - Live's table and strip chart, the Log page's activity log, the + - **The UI:** the Dashboard, built in the app + ([ADR-0057](docs/adr/0057-dashboards.md)): pages of dials, rings, + bars, cells, digits, numbers, sparklines and shift lights for any + numeric signal of the profile, each with its label, range, zones, + decimals, size and place, saved as made, one set for every vehicle, + the phone's and the desktop's apart, with peak hold and stale + dimming; Dark, Low glare and Night themes; Settings as a list of + pages; Live's table and strip chart, the Log page's activity log, the Recordings page's viewer (pan, zoom, a cursor, the frames check's findings, two runs overlaid and aligned, a vehicle's baseline recording overlaid on a new run aligned on the engine starts, and a @@ -225,7 +236,8 @@ background too ([roadmap](#roadmap)). a filter (ID, data, direction, flag), a By ID view (count, rate, newest payload), selected rows copied to the clipboard as they are, and Export CSV, scrubbed by core (ADR-0054's appendix "frames in - memory"). Kept between runs: zoom, + memory"), by ID or mask, length and time, and the changed bytes + marked. Kept between runs: the theme, zoom, metric or imperial units ([ADR-0022](docs/adr/0022-display-units.md)), the last URI that connected, the Record sessions switch, the splitters' shares and @@ -314,9 +326,11 @@ background too ([roadmap](#roadmap)). Pi 3 (aarch64), with no warnings; on both, the simulated bus's cases and `havne-cli` end to end over `vcan0` (the simulated ECU answering through ISO-TP, recorded and checked) (2026-11-05, - [docs/linux.md](docs/linux.md#what-has-run-where)); not yet with an - ELM327 adapter on Linux, nor a CAN controller on a Linux machine - outside WSL. + [docs/linux.md](docs/linux.md#what-has-run-where)). A laptop on + native Ubuntu 26.04 has run the MX+ over Bluetooth, the VX in ELM + mode on USB and WiFi and the USB2CAN listening, on the test car + ([2026-11-08-linux-car](docs/bench-sessions/2026-11-08-linux-car.md)); + no requesting session has sent through a real CAN controller. - **Reply timing** ([ADR-0042](docs/adr/0042-reply-timing.md)): every requesting session measures, per request in its rotation, its outcomes, its reply latency (host clock) and its refresh interval @@ -373,6 +387,18 @@ background too ([roadmap](#roadmap)). test car through the VX: "ready", one monitor incomplete where its model year allows one ([2026-11-02-vehicle](docs/bench-sessions/2026-11-02-vehicle.md)). + - **The analysis log** ([ADR-0056](docs/adr/0056-analysis-log.md)): + the app's Start log and Stop log, and `havne-cli log`, ask the ECU + for the signals picked on Live alone, so they refresh at the bus's + own pace, into a recording that exports as one wide CSV, a row a + sweep (`ecuio_session_set_focus`, `ecuio_session_record`, + `ecuio_export_estimate`). Verified at UNIT, in the bridge, QML and CLI + tests, and on the test car over ELM327 on native Linux: the MX+ + reached 27.45 sweeps a second at one signal and 15.48 at eight, the + VX on USB 47.38 and 6.63, every reply after the connect carrying + only the picked PIDs + ([2026-11-08-linux-car](docs/bench-sessions/2026-11-08-linux-car.md)). + Left: a log through J2534 and SocketCAN, the viewer's Export. - **Evidence for field sessions:** opt-in recording of every frame, decoded value and activity line per connect ([ADR-0017](docs/adr/0017-session-recording.md)), written by core's @@ -383,13 +409,14 @@ background too ([roadmap](#roadmap)). view`, through the values as recorded or through the frames by a profile (`ecuio_recording_open_frames`, so a raw recording plots), exported by `havne-cli export` as pcapng (its frames), CSV (its - values, one row per sample) or a folder (a copy that reads and + values, a row a sweep in the wide layout) or a folder (a copy that reads and replays as the original), scrubbed by construction and checked ([ADR-0054](docs/adr/0054-exports-and-imports.md)), summed up as a scrubbed health report by `havne-cli health`, and a - `candump -L` log imported as a recording (`havne-cli import - candump`); the app exports only the Log page's frames and imports - nothing yet, and a surrogate + `candump -L` log or another logger's CSV imported as a recording + (`havne-cli import`, and the Recordings page's Import, which guesses + a CSV's map from its header); the app exports the Log page's frames + and a report, and a surrogate session log of every vendor call, with every request and reply while recording. Session time counts the machine's sleep on every platform, so a sleep is a gap on Live and in a recording, and the @@ -409,8 +436,8 @@ background too ([roadmap](#roadmap)). [desk](docs/bench-sessions/socketcan-desk-runsheet.md) sheet, and [two-ecu-car-runsheet.md](docs/bench-sessions/two-ecu-car-runsheet.md) (both ECUs in one session, the recorders on a car, a second listener). -- **Tests:** 1607 ctest cases on Windows (both trees rebuilt, - 2026-11-07), all passing but six skips (the cross-arch case and +- **Tests:** 1814 ctest cases on Windows (both trees rebuilt, + 2026-11-08), all passing but six skips (the cross-arch case and the real-car recordings' diff, run locally; three cases that run on Linux only, Read once over SocketCAN and the Python package's vcan and ISO-TP fuzzing cases; and the Wireshark export's `tshark` run, @@ -528,7 +555,9 @@ an issue is resolved it is removed, and its number is not reused. A listening session needs no flow control, so its setup still turns it off (`AT CFC0`). Untried: `STCMM`'s other modes (some acknowledge on the bus) and `STM`'s filters. To listen to - multi-frame replies, use a SocketCAN controller in listen-only mode. + multi-frame replies, use a SocketCAN controller in listen-only mode, + or the VX in ELM mode, which hears them (BENCH prep #19, + [2026-11-08-linux-car](docs/bench-sessions/2026-11-08-linux-car.md)). - **#42. Through the OBDX Pro VX, a second module's reply can be lost while the first module's segmented reply comes in.** On the test car, a session asking the engine (0x7E8) and a second module @@ -547,7 +576,8 @@ an issue is resolved it is removed, and its number is not reused. | Version | Scope | Status | |---|---|---| | v0.6.0 | Sharing and scripting: exports and imports scrubbed by construction, Python bindings, the ELM327 emulator, `havne-cli clear`, the viewer reading a recording's frames, JSON Schemas for signal files, the health report | Released | -| v0.7.0-v0.10.0 | v0.7.0, the dashboard and the UI: configurable gauges from a library, a refresh for the phone, night themes. v0.8.0, conditions: triggered logging and alerts. v0.9.0, the whole vehicle: discovery and extended sessions. v0.10.0, the scan tool, the last feature release | Planned | +| v0.7.0 | The dashboard and the UI: gauges built by hand from a library, an analysis log and a wide CSV, import in the app, themes for the dark, a phone-first Settings | Released | +| v0.7.1-v0.10.0 | v0.7.1, a more modern look, phone first: the shared controls, Night as its own control. v0.8.0, conditions: triggered logging and alerts. v0.9.0, the whole vehicle: discovery and extended sessions. v0.10.0, the scan tool, the last feature release | Planned | | 1.0.0 | The finished reader: the features above frozen and hardened, full featured on Windows, Linux and Android | Planned | Versions follow semantic versioning @@ -557,89 +587,52 @@ releases are in [CHANGELOG.md](CHANGELOG.md). The planned releases are in order and hold about three features each; a release's detail comes in here when its work starts. -### v0.6.0: sharing and scripting +### v0.7.0: the dashboard and the UI -For users who script, pen testers among them: everything reaches -`havne-cli` and Python as well as the app. A minor release +For people who watch the car while it runs, and for anyone who wants +the values of a drive in a spreadsheet. A minor release ([ADR-0048](docs/adr/0048-semantic-versioning.md)): the C ABI grows, -append-only. +append-only, and the CSV export's default changes (a breaking change +for scripts, named in CHANGELOG). - **Built:** - - the ELM327 emulator ([ADR-0055](docs/adr/0055-elm327-emulator.md)): - `havne-cli sim --elm327`, and core's simulated ECU answering with - no bus; - - `havne-cli clear --yes`, through core's clear gate; - - the viewer and `havne-cli view --frames` reading a recording's - frames through a profile; - - JSON Schemas for signal files and plugins, checked in CI; - - CI's downloads (the Windows Qt kit, Gradle's, linuxdeploy's) from - the Actions cache; - - PCAP export and candump import in core and `havne-cli`, scrubbed - by construction ([ADR-0054](docs/adr/0054-exports-and-imports.md)); - - an OBDb set imported in Settings; - - the Log page's filter, per-ID view and Export CSV, scrubbed by core - (`ecuio_scrub_frames`); - - the shared core (`ecuio`), exporting the C API and nothing else, - `ecuio_version`, and the pull queue (`ecuio/queue.h`), steps 1 and - 2 of the Python bindings - ([ADR-0053](docs/adr/0053-python-bindings.md)'s appendices); - - a recording's values exported as CSV, one row per sample, scrubbed - and checked, in core and `havne-cli export --format csv` - (ADR-0054's appendix "the CSV export as built"); - - a scrubbed copy of a recording's folder, every file rewritten by - its classes and checked, in core and `havne-cli export --format - folder` (ADR-0054's appendix "the folder export as built"); - - the `havne` Python package over the shared core, its tests in CI - (step 3 of ADR-0053; its appendix "the havne package as built"), - and a replay's end told through the pull queue - (`ECUIO_ERR_STREAM_ENDED`); - - a vehicle's baseline recording, one per vehicle, overlaid on a new - run aligned on its engine start (core's - `ECUIO_RECORDING_FIND_ENGINE_START`, the Recordings page, `havne-cli - view --align-on engine-start`; ADR-0049's appendix "a vehicle's - baseline"); - - the wheel (step 4 of ADR-0053; its appendix "the wheel as - built"): one per platform with the shared core inside, each release - job installing it into a fresh venv and running - `python/examples/read_pids.py` through it, which also reads - SocketCAN on `vcan0` and the ELM327 emulator. Left: the macOS 13.0 - build and `gh attestation verify` on a wheel run first on v0.6.0's - release candidate; - - the examples (ADR-0053's appendix "the examples as built"): a DID - scan through core's own scan, ISO-TP fuzzing of the simulated ECU - on `vcan0`, a notebook predicting fuel cut from a committed - synthetic recording; the notebook runs locally, as CI carries no - scientific stack; - - the health report (ADR-0054's appendix "the health report as - built"): one scrubbed file of a car's health in JSON or text, from - a live session or a recording (each ECU's reports rebuilt from its - replies in frames.csv), in core, `havne-cli health` and the app's - Save report on Diagnostics and in the log viewer; - - the CSV import (ADR-0054's appendix "the CSV import as built"): - another logger's CSV by a column map into a recording's folder of - values, in core, `havne-cli import csv` and Python's - `havne.import_csv` (with `havne.import_candump`); the app's - Recordings page lists a folder of values alone and the viewer opens - and plots it, saying it has no frames. Left: the app's Import - button, v0.7.0's, for both formats; until then a folder made - elsewhere is moved into the recordings folder to be listed. - -**Done when:** a Python script opens SocketCAN, decodes PIDs and prints -the values, and the same script runs on Windows against the ELM327 -emulator and on every platform against `mock://` (met: -`python/examples/read_pids.py`, through `PythonTest.test_vcan` on -`vcan0`, `PythonTest.test_read_pids` and each wheel's install check); -the wheel installs from a release's downloads and passes `gh -attestation verify` (v0.6.0's release candidate); an export of a -recording passes the leak check (met 2026-11-07: scrubbed pcapng, CSV -and folder exports of 159 real-car, bench and phone recordings hold none -of their cars' identity values, whole or in 7-byte pieces, as bytes or -hex); a recording opens in Wireshark (met: -`CliTransferRunTest.tshark`, its ISO-TP reassembled); python-OBD reads -the simulated car through the ELM327 emulator on Windows (met: -`CliElm327RunTest.PythonObdReadsIt`); a CSV from another logger plots in -the viewer (met: `QmlTest.recordings`, an import listed, opened and -plotted; `RecordingViewTest.AnImportedCsvOpensAndPlots`; -`CliTransferRunTest.csv-import`, two made-up loggers' layouts). + - the Dashboard, built in the app + ([ADR-0057](docs/adr/0057-dashboards.md)): eight kinds of gauge, + pages, edit mode, one layout for every vehicle and one per form, + saved as it is made; core names a signal file's key and a def's + range (`ecuio_signal_file_key`, `ecuio_def_range`); + - the Low glare and Night themes, with the gauges' color roles in + `Theme`; + - Settings as a list of pages, and the phone's tab bar and top bar at + a finger's size; + - the analysis log ([ADR-0056](docs/adr/0056-analysis-log.md)): a + running session's requests narrowed to picked signals + (`ecuio_session_set_focus`), a recorder attached to a running + session, `havne-cli log` and the app's Start log and Stop log, the + wide CSV as the export's default (`--rows`, `--signal`, + `--units`) with its size estimate (`ecuio_export_estimate`); it has + run on the test car through the MX+ and the VX over ELM327 on + native Linux, with the rates per signal count in ADR-0056's + appendix of 2026-11-08 + ([2026-11-08-linux-car](docs/bench-sessions/2026-11-08-linux-car.md)); + not through J2534, and no request has gone out through SocketCAN; + - the app's Import for CSV and candump logs, a CSV's map guessed from + its header (`havne-cli import csv` with no map, Python's + `havne.guess_csv_map`), and the viewer's Frames switch with + `havne-cli frames` and `havne.read_frames`; + - the Log page's ID mask, length and time filters, and By ID's + changed bytes; + - the health report naming the vehicle's baseline recording; + - the downloads' notices: Qt's, the AppImage's pinned runtime and + its sources, and no Microsoft shader DLLs in the Windows zip. +- **Left for v0.7.1:** the viewer's Export, undo and drag in edit mode, + the minimum sweep interval and the viewer's navigation aids + (ADR-0056), and a more modern look. + +**Done when:** a user builds a dashboard page from the library on the +test phone and on the desktop, it survives a restart (tested: +`QmlTest.dashedit`'s `test_aLayoutBuiltInEditModeSurvivesARestart`; the +phone's run is not filed as a session sheet), and Settings fits the test +phone with no section longer than two screens. ### Waiting on a tester: an iPhone download @@ -684,10 +677,6 @@ less, **M** a few days, **L** a week or more or an ADR first. arrow keys stepping the cursor a sample at a time; on Live, a pause that scrolls back through the buffer while the session runs. v0.5.0's computed signals want panes too. -- **Low-glare and night themes (M):** Theme roles for the analog gauge - first; warning and danger told apart by more than hue. -- **User-configurable dashboards (L):** pages built from the gauge - library; layout persistence is the new ground. - **In-vehicle displays, Android Auto and CarPlay (L, research first):** a native front end over the C ABI, only if a live-gauge app qualifies. @@ -709,10 +698,22 @@ less, **M** a few days, **L** a week or more or an ADR first. ### Performance +- **`FrameListModel` inserts a row per frame (S):** one + `beginInsertRows` for each frame of a delivery; a batch insert would + signal the view once. Measure first + ([docs/testing.md](docs/testing.md#performance)). - **Full signal sets at full rate (L):** left is the bridge's 4 KB copy per frame ([docs/testing.md](docs/testing.md#performance)). ### Toolchain +- **A Release iOS build may link Qt's `qmltooling` plugins (S):** check + whether the `.ipa` carries them and, if so, exclude them with + `qt_import_plugins(havne EXCLUDE_BY_TYPE qmltooling)`; needs a CI run + and an Apple kit. +- **The next type2-runtime pin (S):** the steps are in + [docs/development.md](docs/development.md) ("A new runtime pin"); the + newer runtime would take the release that unpacks into a 0700 folder. + - **C++20 baseline (M, an ADR first):** `std::span` and `std::format` against older toolchains dropping out; low priority. diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 5d49e2c0..31df1e8d 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -5,7 +5,8 @@ # clean (contributors without a win32 tree). Check CI invariant: this # file is app-side only, core stays Qt-free/untouched. Release builds # carry no QML debugging: stage.ps1 fails a package whose exe imports -# QQmlDebuggingEnabler or that holds qmltooling. +# QQmlDebuggingEnabler or that holds qmltooling, and sign-apk.sh an APK +# whose libhavne names it or that holds qmltooling. # 6.12 is the version CI and local builds use (macOS needs it), and # REQUIRES sets every Qt policy up to it to NEW, QTP0004 among them. @@ -43,6 +44,10 @@ qt_add_library(app_ui STATIC pluginstore.h signalstore.cpp signalstore.h + recordingimport.cpp + recordingimport.h + recordingframes.cpp + recordingframes.h recordingview.cpp recordingview.h sessionbridge.cpp @@ -51,10 +56,12 @@ qt_add_library(app_ui STATIC signalfilter.h latencystats.h urlwrite.h + windowtheme.cpp + windowtheme.h ) set_source_files_properties(qml/Theme.qml qml/ChartLayout.qml qml/VehicleBook.qml - qml/SignalForm.qml PROPERTIES + qml/DashboardBook.qml qml/SignalForm.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE ) @@ -67,11 +74,34 @@ qt_add_qml_module(app_ui qml/Main.qml qml/HomePage.qml qml/ThemedButton.qml + qml/ThemedCheckBox.qml + qml/SegmentButton.qml + qml/CsvGuessPreview.qml qml/PageHeader.qml qml/DashboardPage.qml qml/LogPage.qml + qml/FrameFilterPanel.qml + qml/FrameTable.qml + qml/FrameIdList.qml qml/RecordingsPage.qml qml/SettingsPage.qml + qml/Captioned.qml + qml/Heading.qml + qml/LabeledFlow.qml + qml/SettingsAdapter.qml + qml/SettingsAdvanced.qml + qml/SettingsList.qml + qml/SettingsOwnForm.qml + qml/SettingsSubpage.qml + qml/SettingsConnect.qml + qml/SettingsDisplay.qml + qml/SettingsOwnSignals.qml + qml/SettingsPlugins.qml + qml/SettingsProfile.qml + qml/SettingsRecording.qml + qml/SettingsSignalFiles.qml + qml/SettingsVehiclePicker.qml + qml/SettingsVinLookup.qml qml/NavButton.qml qml/Theme.qml qml/LiveViewPage.qml @@ -79,9 +109,14 @@ qt_add_qml_module(app_ui qml/ChartLayout.qml qml/StripChart.qml qml/VehicleBook.qml + qml/DashboardBook.qml qml/SignalForm.qml qml/SignalHub.qml qml/GaugeBase.qml + qml/DangerMark.qml + qml/SegmentGauge.qml + qml/SegmentReadout.qml + qml/SparkGauge.qml qml/GaugeArc.qml qml/GaugeCard.qml qml/AnalogGauge.qml @@ -118,6 +153,10 @@ if(ANDROID) # (ADR-0029 section 2; its Java half is in android/src) target_sources(app_ui PRIVATE androidsession.cpp androidsession.h) endif() +# The title bar's color (windowtheme.cpp, DwmSetWindowAttribute) +if(WIN32) + target_link_libraries(app_ui PUBLIC dwmapi) +endif() # MSVC's C4702 (unreachable code) fires inside Qt's inline headers, as # the generated QML registration code instantiates them; none of it is # this project's code. @@ -140,8 +179,6 @@ app_add_version_resource(havne havne "Havne ECU reader and logger" if(WIN32) set_target_properties(havne PROPERTIES WIN32_EXECUTABLE TRUE) - # The title bar's color (main.cpp, DwmSetWindowAttribute) - target_link_libraries(havne PRIVATE dwmapi) endif() # The name people see is capitalized: Apple's bundle, which Finder and # the home screen show (iOS's display name is Xcode's PRODUCT_NAME, the @@ -223,6 +260,13 @@ endif() if(QT_FEATURE_qml_debug) target_compile_definitions(havne PRIVATE $<$:QT_QML_DEBUG>) endif() +# Outside Debug, the APK carries no qmltooling plugins (the debug +# server's half): androiddeployqt deploys the plugin list Qt's CMake +# writes, which honors this exclusion. packaging/android/sign-apk.sh +# checks the release APK +if(ANDROID AND NOT CMAKE_BUILD_TYPE STREQUAL "Debug") + qt_import_plugins(havne EXCLUDE_BY_TYPE qmltooling) +endif() # --- Deploy Qt runtime DLLs next to the exe (Windows only) --- if(WIN32) @@ -231,9 +275,13 @@ if(WIN32) if(QT_WINDEPLOYQT_LOCATION) add_custom_command(TARGET havne POST_BUILD # Outside Debug, no qmltooling plugins: the debug server's - # half, which nothing but a QT_QML_DEBUG build loads + # half, which nothing but a QT_QML_DEBUG build loads. + # Microsoft's shader compilers stay out: Qt Quick runs without + # them, and each brings the Windows SDK's distribution terms COMMAND ${QT_WINDEPLOYQT_LOCATION} --no-compiler-runtime + --no-system-d3d-compiler + --no-system-dxc-compiler "$<$>:--skip-plugin-types;qmltooling>" --qmldir ${CMAKE_CURRENT_SOURCE_DIR}/qml $ diff --git a/app/android/assets/havne/LICENSE.txt b/app/android/assets/havne/LICENSE.txt new file mode 100644 index 00000000..0a619b54 --- /dev/null +++ b/app/android/assets/havne/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Eric Kramer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/android/assets/havne/THIRD_PARTY_NOTICES.txt b/app/android/assets/havne/THIRD_PARTY_NOTICES.txt new file mode 100644 index 00000000..11425efe --- /dev/null +++ b/app/android/assets/havne/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,169 @@ +Third-party software in this package +==================================== + +Havne itself is licensed under the MIT license (LICENSE.txt, beside +this file). This package also contains the software below, each under +its own terms. The same text ships in Havne's Linux AppImage +(usr/share/doc/havne/) and in its Android APK (assets/havne/); a +section that names one of them applies to that one alone. + + +Qt 6.12.0 +--------- + +Copyright (C) The Qt Company Ltd. and other contributors. + +Havne uses Qt under the GNU Lesser General Public License, version 3 +(licenses/LGPL-3.0.txt, which builds on licenses/GPL-3.0.txt). Qt is +linked dynamically: Qt's libraries, plugins and QML modules here are +Qt's unmodified binaries, and you may replace them with your own build +of the same Qt version. In the AppImage they are the libQt6*.so files +in usr/lib and the plugins and QML modules under usr/plugins and +usr/qml; in the APK, the libQt6*, libplugins_* and libqml_* files +under lib//, with Qt's Java classes in classes.dex. + +The source code for this Qt version is available from +https://download.qt.io/official_releases/qt/6.12/6.12.0/ and from +https://code.qt.io. Qt's own third-party components, with the copyright +lines, credits and license texts they ask for, are in +licenses/Qt-third-party.txt. + +Havne is an independent project, not affiliated with or endorsed by +The Qt Company. + + +ICU 73.2, in the AppImage +------------------------- + +The AppImage's libicudata, libicui18n and libicuuc files come with the +Qt kit Havne is built with: ICU 73.2, copyright Unicode, Inc. and +others, under the Unicode license in licenses/ICU.txt, which also +lists the third-party data and code ICU includes. Its source is at +https://github.com/unicode-org/icu/releases/tag/release-73-2. + + +System libraries, in the AppImage +--------------------------------- + +The AppImage also carries libraries from the Ubuntu release it is +built on, each under its own license; the release's SBOM +(havne-.spdx.json) names each one and its package's version. +Each package's copyright file, as Ubuntu ships it, is +usr/share/doc//copyright in the AppImage, and the license +texts those files point to in /usr/share/common-licenses are in +common-licenses/ beside this file. + + +The AppImage runtime, in the AppImage +------------------------------------- + +The AppImage begins with the AppImage type 2 runtime, which mounts or +unpacks the rest when it starts: +type2-runtime release 20251108 (commit dd6cebe) +from https://github.com/AppImage/type2-runtime, copyright probonopd and +contributors, under the MIT license in licenses/AppImage-runtime.txt. +The runtime is one static program that also contains: + + libfuse 3.15.0, with the runtime's patch to lib/mount.c, under the + GNU Lesser General Public License, version 2.1 + (licenses/LGPL-2.1.txt) + squashfuse 0.5.2, under its BSD license (licenses/squashfuse.txt) + musl libc 1.2.5, under the MIT license (licenses/musl.txt) + mimalloc 2.1.7, under the MIT license (licenses/mimalloc.txt) + zstd 1.5.6, under the BSD license of its two (licenses/zstd.txt) + zlib 1.3.1, under the zlib license (licenses/zlib.txt) + +libfuse and squashfuse are built from those releases by the runtime's +build scripts; musl, mimalloc, zstd and zlib come from Alpine Linux +3.21's packages. As LGPL-2.1 section 6 asks, the source of libfuse and +of the runtime it is linked into is attached to each Havne release +that carries an AppImage, beside the AppImage itself: +fuse-3.15.0.tar.xz (libfuse's own release) and +type2-runtime-20251108.tar.gz (the runtime at that commit, with its +libfuse patch and build scripts). With them you can rebuild the runtime +against your own libfuse and put it in place of the AppImage's first +part. They are also at https://github.com/libfuse/libfuse/releases/tag/fuse-3.15.0 +and https://github.com/AppImage/type2-runtime/releases/tag/20251108. + + +Android libraries, in the APK +----------------------------- + +The APK carries the Java and Kotlin libraries below, which Qt's +Android build takes in through Gradle, each under the Apache License, +version 2.0 (licenses/Apache-2.0.txt), as each one's Maven POM +declares: + + androidx.annotation:annotation + androidx.annotation:annotation-experimental + androidx.annotation:annotation-jvm + androidx.arch.core:core-common + androidx.arch.core:core-runtime + androidx.collection:collection + androidx.collection:collection-jvm + androidx.concurrent:concurrent-futures + androidx.core:core + androidx.core:core-viewtree + androidx.interpolator:interpolator + androidx.lifecycle:lifecycle-common + androidx.lifecycle:lifecycle-runtime + androidx.profileinstaller:profileinstaller + androidx.startup:startup-runtime + androidx.tracing:tracing + androidx.versionedparcelable:versionedparcelable + com.google.guava:listenablefuture + org.jetbrains.kotlin:kotlin-stdlib + org.jetbrains.kotlinx:kotlinx-coroutines-android + org.jetbrains.kotlinx:kotlinx-coroutines-core + org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm + org.jetbrains:annotations + org.jspecify:jspecify + +The release's SBOM names each one's version. + +The APK's libc++_shared.so is LLVM's C++ standard library from the +Android NDK, under the Apache License, version 2.0 with LLVM +Exceptions, which ask for no notice in a library's binary form. + + +Wal33D/dtc-database: trouble-code titles +---------------------------------------- + +The titles Havne shows for SAE J2012's generic powertrain and network +trouble codes come from Wal33D's dtc-database, +https://github.com/Wal33D/dtc-database (the commit is named in Havne's +source, core/src/dtc_titles_table.h), under its MIT license: + + MIT License + + Copyright (c) 2024 Wal33D (Waleed Judah) + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + +NHTSA vPIC manufacturer codes +----------------------------- + +The makes Havne shows for a VIN's manufacturer code come from the +standalone database of NHTSA's Product Information Catalog and Vehicle +Listing (vPIC), https://vpic.nhtsa.dot.gov/downloads/, a work of the +US government, whose terms of use call it public information that may +be distributed or copied. The release used is named in Havne's source +(core/src/vin_wmi_table.h). NHTSA gives no warranty of its accuracy, +and Havne is not affiliated with or endorsed by NHTSA. diff --git a/app/android/assets/havne/licenses/Apache-2.0.txt b/app/android/assets/havne/licenses/Apache-2.0.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/app/android/assets/havne/licenses/Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/app/android/assets/havne/licenses/GPL-3.0.txt b/app/android/assets/havne/licenses/GPL-3.0.txt new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/app/android/assets/havne/licenses/GPL-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/app/android/assets/havne/licenses/LGPL-3.0.txt b/app/android/assets/havne/licenses/LGPL-3.0.txt new file mode 100644 index 00000000..0a041280 --- /dev/null +++ b/app/android/assets/havne/licenses/LGPL-3.0.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/app/android/assets/havne/licenses/Qt-third-party.txt b/app/android/assets/havne/licenses/Qt-third-party.txt new file mode 100644 index 00000000..8cf8892e --- /dev/null +++ b/app/android/assets/havne/licenses/Qt-third-party.txt @@ -0,0 +1,1431 @@ +Qt's third-party components, in Qt 6.12.0 as Havne ships it +=========================================================== + +Qt's libraries, plugins and QML modules, which Havne ships unmodified, +contain the third-party code below. Each entry is one Qt lists in the +software bill of materials it publishes with Qt 6.12.0 (the sbom folder +of each Qt kit), for the Qt modules Havne's Windows, Linux and Android +packages carry: Core, Gui, Network, OpenGL, Qml and its companions, +Quick and its Controls, Dialogs, Effects, Layouts, Shapes and Templates, +Svg, Bluetooth and the folder list model. Where a line names packages, +the component is in those alone. Where its license offers a choice, the +one named here applies. + +These two credits are the ones the licenses ask for in the documentation: + + Portions of this software are copyright (C) 2026 The FreeType + Project (www.freetype.org). All rights reserved. + + This software is based in part on the work of the Independent JPEG + Group. + +The Public Suffix List data in Qt Network is under the Mozilla Public +License, version 2.0. Its source is at +https://github.com/publicsuffix/list, and the copy in Qt 6.12.0's source +(https://download.qt.io/official_releases/qt/6.12/6.12.0/). + + +Components by license +--------------------- + +Apache 2.0: + + emoji-segmenter 0.4.0 + Copyright 2019 Google LLC + + tika-mimetypes c29724782854 + Copyright 2026 The Apache Software Foundation + +BSD 2-clause: + + masm + Copyright (C) 2003-2018 Apple Inc. All rights reserved. + Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com) + Copyright (C) 2007-2009 Torch Mobile, Inc. All rights reserved. (http://www.torchmobile.com/) + Copyright (C) 2009, 2010 University of Szeged + Copyright (C) 2009-2011 STMicroelectronics. All rights reserved. + Copyright (C) 2010 MIPS Technologies, Inc. All rights reserved. + Copyright (C) 2010 Peter Varga (pvarga@inf.u-szeged.hu), University of Szeged + Copyright (C) 2010 MIPS Technologies, Inc. All rights reserved. + Copyright (C) 2010, 2011 Research In Motion Limited. All rights reserved. + Copyright (C) 2011 Google Inc. All rights reserved. + Copyright (C) 2013 Samsung Electronics. All rights reserved. + Copyright (C) 2015 Cisco Systems, Inc. All rights reserved. + Copyright (c) 2002-2009 Vivek Thampi + + pcre2-sljit 10.48 + Copyright Zoltan Herczeg + + sha3_endian 1.0.0 + Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved. + +BSD 2-clause and Imlib2: + + smooth-scaling-algorithm + Copyright (C) 2004, 2005 Daniel M. Duley. + (C) Carsten Haitzler and various contributors. + (C) Willem Monsuwe + +BSD 3-clause: + + aglfn 1.7 + Copyright 2002, 2003, 2005, 2006, 2008, 2010, 2015 Adobe Systems + + doubleconversion 3.4.0 + Copyright 2006-2012, the V8 project authors + + easing + Copyright (c) 2001 Robert Penner + + libpsl 664f3dc85259 + Copyright 2014-2016 The Chromium Authors. All rights reserved. + + rfc6234 + Copyright (c) 2011 IETF Trust and the persons identified as authors of the code. + +BSD 3-clause with PCRE2's binary-like packages exception: + + PCRE2 10.48 + Copyright (c) 1997-2007 University of Cambridge + Copyright (c) 2007-2024 Philip Hazel + Copyright (c) 2010-2024 Zoltan Herczeg + +CC0 1.0 (public domain dedication): + + blake2 ed1974ea8343 + Copyright 2012, Samuel Neves + + md4 + Written by Alexander Peslyak - better known as Solar Designer - in 2001, and placed in the public domain. There's absolutely no warranty. + + md5 + Written by Colin Plumb in 1993, no copyright is claimed. Ian Jackson . + + sha3_keccak 3.2 + Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche. + To the extent possible under law, the implementers have waived all copyright + and related or neighboring rights to the source code in this file. + + siphash + Copyright (C) 2012-2014 Jean-Philippe Aumasson + Copyright (C) 2012-2014 Daniel J. Bernstein + Copyright (C) 2016 Intel Corporation + + tlexpected 41d3e1f48d68 + To the extent possible under law, Sy Brand has waived all copyright and related or neighboring rights to the expected library. This work is published from: United Kingdom. + +FreeType License: + + FreeType 2.14.3 [APK, Windows] + Copyright (c) 2007-2014 Adobe Systems Incorporated + Copyright (c) 2004-2026 Albert Chin-A-Young + Copyright (c) 2018-2026 Armin Hasitzka, David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2000 Computing Research Labs, New Mexico State University + Copyright (c) 1996-2026 David Turner, Robert Wilhelm, Dominik Röttsches, and Werner Lemberg + Copyright (c) 2004-2026 David Turner, Robert Wilhelm, Werner Lemberg and George Williams + Copyright (c) 2022-2026 David Turner, Robert Wilhelm, Werner Lemberg, and Moazin Khatti + Copyright (c) 2008-2026 David Turner, Robert Wilhelm, Werner Lemberg, and suzuki toshiya + Copyright (c) 2003-2026 David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2005-2026 David Turner + Copyright (c) 2007-2026 Derek Clegg and Michael Toftdal + Copyright (c) 2007 Dmitry Timoshkov for Codeweavers + Copyright (c) 2001-2015 Francesco Zappa Nardelli + Copyright (c) 2005, 2007, 2008, 2013 George Williams + Copyright (c) 2013-2026 Google, Inc. Google Author(s) Behdad Esfahbod and Stuart Gill + Copyright (c) 2013-2022 Google, Inc. + Copyright (c) 2003 Huw D M Davies for Codeweavers + Copyright (c) 2010-2026 Joel Klinghed + Copyright (c) 1996-2026 Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2003-2026 Masatake YAMATO and Redhat K.K. + Copyright (c) 2004-2026 Masatake YAMATO, Redhat K.K, David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2019-2026 Nikhil Ramakrishnan, David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2009-2026 Oran Agra and Mickey Gabel + Copyright (c) 2007-2026 Rahul Bhalerao + Copyright (c) 2002-2026 Roberto Alameda + Copyright (c) 2015-2026 Werner Lemberg + Copyright (c) 2004-2026 suzuki toshiya, Masatake YAMATO, Red Hat K.K., David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2019 nyorain + Copyright (c) 2022-2026 David Turner, Robert Wilhelm, Werner Lemberg, George Williams, and Dominik Röttsches + Copyright (C) 2009, 2023 Red Hat, Inc. + + grayraster + Copyright 2000-2016 by David Turner, Robert Wilhelm, and Werner Lemberg. + +Historical Permission Notice and Disclaimer, sell variant: + + xsvg + Copyright 2002 USC/Information Sciences Institute + +Independent JPEG Group and BSD 3-clause: + + libjpeg-turbo 3.2.0 + Copyright (C) 2009-2026 D. R. Commander + Copyright (C) 1991-1998 Thomas G. Lane + Copyright (C) 2009 Pierre Ossman for Cendio AB + Copyright (C) 1999-2006 MIYASAKA Masaru + Copyright (C) 1999 Ken Murchison + Copyright (C) 2015-2016, 2018, 2022 Matthieu Darbois + Copyright (C) 2018 Matthias Räncker + Copyright (C) 2019-2020 Arm Limited + Copyright (C) 2022 Felix Hanau + Copyright (C) 1997-1998 Thomas G. Lane, Todd Newman + Copyright (C) 2021 Alex Richardson + Copyright (C) 2015, 2020 Google, Inc. + Copyright (C) 2013 Linaro Limited + Copyright (C) 2014 Olle Liljenzin + Copyright (C) 1991-2020 Thomas G. Lane, Guido Vollbeding + +International Color Consortium: + + icc-srgb-color-profile + Copyright International Color Consortium, 2015 + +libpng (older) and libpng 2.0: + + libpng 1.6.58 + Copyright (c) 1995-2026 The PNG Reference Library Authors + Copyright (c) 2000-2026 Cosmin Truta + Copyright (c) 1998-2018 Glenn Randers-Pehrson + Copyright (c) 1996-1997 Andreas Dilger + Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + Copyright (c) 2000-2017 Simon-Pierre Cadieux + Copyright (c) 2000-2017 Eric S. Raymond + Copyright (c) 2000-2017 Mans Rullgard + Copyright (c) 2000-2017 Gilles Vollant + Copyright (c) 2000-2017 James Yu + Copyright (c) 2000-2017 Mandar Sahastrabuddhe + Copyright (c) 1998-2000 Tom Lane + Copyright (c) 1998-2000 Willem van Schaik + Copyright (c) 1996-1997 John Bowler + Copyright (c) 1996-1997 Kevin Bracey + Copyright (c) 1996-1997 Sam Bushell + Copyright (c) 1996-1997 Magnus Holmgren + Copyright (c) 1996-1997 Greg Roelofs + Copyright (c) 1996-1997 Tom Tanner + Copyright (c) 1995-1996 Dave Martindale + Copyright (c) 1995-1996 Paul Schmidt + Copyright (c) 1995-1996 Tim Wegner + +MIT: + + d3d12memoryallocator v3.1.0 [Windows] + Copyright (c) 2019-2026 Advanced Micro Devices, Inc. All rights reserved. + + forkfd [APK, AppImage] + Copyright (C) 2016 Intel Corporation + Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com + + freetype-bdf [APK, Windows] + Copyright (c) 2000 Computing Research Labs, New Mexico State University + Copyright (c) 2001-2014 Francesco Zappa Nardelli + + HarfBuzz 14.5.0 + Copyright © 2010-2022 Google, Inc. + Copyright © 2015-2020 Ebrahim Byagowi + Copyright © 2019,2020 Facebook, Inc. + Copyright © 2012,2015 Mozilla Foundation + Copyright © 2011 Codethink Limited + Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) + Copyright © 2009 Keith Stribley + Copyright © 2011 Martin Hosken and SIL International + Copyright © 2007 Chris Wilson + Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod + Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. + Copyright © 1998-2005 David Turner and Werner Lemberg + Copyright © 2016 Igalia S.L. + Copyright © 2022 Matthias Clasen + Copyright © 2018,2021 Khaled Hosny + Copyright © 2018,2019,2020 Adobe, Inc + Copyright © 2013-2015 Alexei Podtelezhnikov + + md4c 0.5.3 + Copyright © 2016-2024 Martin Mitáš + + opengl-es2-headers 27673 + Copyright (c) 2013-2014 The Khronos Group Inc. + + opengl-headers 27684 + Copyright (c) 2013-2014 The Khronos Group Inc. + + pixman 0.17.12 [AppImage] + Copyright © 2009 Nokia Corporation + + rhi-miniengine-d3d12-mipmap 0aa79bad7899 + Copyright (c) 2015 Microsoft + + shadow_angular_material + Copyright (c) 2014-2016 Google, Inc + + tinycbor 7.0 + Copyright (C) 2015-2025 Intel Corporation + + vulkan-xml-spec 1.4.308 + Copyright (c) 2015-2025 The Khronos Group Inc. + + vulkanmemoryallocator 3.3.0 + Copyright (c) 2017-2025 Advanced Micro Devices, Inc. All rights reserved. + + webgradients + Copyright (c) 2017 itmeo + + yoga 2.0.1 + Copyright (c) Facebook, Inc. and its affiliates. + Copyright (c) Meta Platforms, Inc. and affiliates. + +MIT and MIT (Open Group variant): + + freetype-pcf [APK, Windows] + Copyright (c) 2001, 2012 David Turner, Robert Wilhelm, and Werner Lemberg + Copyright (c) 2000-2014 Francesco Zappa Nardelli + Copyright (c) 1990, 1994, 1998 The Open Group + +Mozilla Public License 2.0: + + psl-data 2026-05-14_0 + The list was originally provided by Jo Hermans . + It is now maintained on github (https://github.com/publicsuffix/list). + +Public domain: + + sha1 + Copyright (C) Dominik Reichl + Copyright (C) 2016 The Qt Company Ltd + +Unicode 3.0: + + unicode-character-database 36 + Copyright (C) 1991-2025 Unicode, Inc. + + unicode-cldr v48.2 + Copyright (C) 2004-2025 Unicode, Inc. + +X11 and Historical Permission Notice and Disclaimer: + + xserverhelper + Copyright (c) 1987, 1988 X Consortium + Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts. + +zlib: + + freetype-zlib [APK, Windows] + Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler + + zlib 1.3.2 [Windows] + (C) 1995-2026 Jean-loup Gailly and Mark Adler + + +License texts +------------- + +==== BSD 2-clause ==== + +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +==== BSD 3-clause ==== + +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +==== MIT ==== + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== MIT (Open Group variant) ==== + +Copyright 1990, 1994, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +==== FreeType License ==== + + The FreeType Project LICENSE + ---------------------------- + + 2006-Jan-27 + + Copyright 1996-2002, 2006 by + David Turner, Robert Wilhelm, and Werner Lemberg + + + +Introduction +============ + + The FreeType Project is distributed in several archive packages; + some of them may contain, in addition to the FreeType font engine, + various tools and contributions which rely on, or relate to, the + FreeType Project. + + This license applies to all files found in such packages, and + which do not fall under their own explicit license. The license + affects thus the FreeType font engine, the test programs, + documentation and makefiles, at the very least. + + This license was inspired by the BSD, Artistic, and IJG + (Independent JPEG Group) licenses, which all encourage inclusion + and use of free software in commercial and freeware products + alike. As a consequence, its main points are that: + + o We don't promise that this software works. However, we will be + interested in any kind of bug reports. (`as is' distribution) + + o You can use this software for whatever you want, in parts or + full form, without having to pay us. (`royalty-free' usage) + + o You may not pretend that you wrote this software. If you use + it, or only parts of it, in a program, you must acknowledge + somewhere in your documentation that you have used the + FreeType code. (`credits') + + We specifically permit and encourage the inclusion of this + software, with or without modifications, in commercial products. + We disclaim all warranties covering The FreeType Project and + assume no liability related to The FreeType Project. + + + Finally, many people asked us for a preferred form for a + credit/disclaimer to use in compliance with this license. We thus + encourage you to use the following text: + + """ + Portions of this software are copyright © The FreeType + Project (www.freetype.org). All rights reserved. + """ + + Please replace with the value from the FreeType version you + actually use. + + +Legal Terms +=========== + +0. Definitions +-------------- + + Throughout this license, the terms `package', `FreeType Project', + and `FreeType archive' refer to the set of files originally + distributed by the authors (David Turner, Robert Wilhelm, and + Werner Lemberg) as the `FreeType Project', be they named as alpha, + beta or final release. + + `You' refers to the licensee, or person using the project, where + `using' is a generic term including compiling the project's source + code as well as linking it to form a `program' or `executable'. + This program is referred to as `a program using the FreeType + engine'. + + This license applies to all files distributed in the original + FreeType Project, including all source code, binaries and + documentation, unless otherwise stated in the file in its + original, unmodified form as distributed in the original archive. + If you are unsure whether or not a particular file is covered by + this license, you must contact us to verify this. + + The FreeType Project is copyright (C) 1996-2000 by David Turner, + Robert Wilhelm, and Werner Lemberg. All rights reserved except as + specified below. + +1. No Warranty +-------------- + + THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO + USE, OF THE FREETYPE PROJECT. + +2. Redistribution +----------------- + + This license grants a worldwide, royalty-free, perpetual and + irrevocable right and license to use, execute, perform, compile, + display, copy, create derivative works of, distribute and + sublicense the FreeType Project (in both source and object code + forms) and derivative works thereof for any purpose; and to + authorize others to exercise some or all of the rights granted + herein, subject to the following conditions: + + o Redistribution of source code must retain this license file + (`FTL.TXT') unaltered; any additions, deletions or changes to + the original files must be clearly indicated in accompanying + documentation. The copyright notices of the unaltered, + original files must be preserved in all copies of source + files. + + o Redistribution in binary form must provide a disclaimer that + states that the software is based in part of the work of the + FreeType Team, in the distribution documentation. We also + encourage you to put an URL to the FreeType web page in your + documentation, though this isn't mandatory. + + These conditions apply to any software derived from or based on + the FreeType Project, not just the unmodified files. If you use + our work, you must acknowledge us. However, no fee need be paid + to us. + +3. Advertising +-------------- + + Neither the FreeType authors and contributors nor you shall use + the name of the other for commercial, advertising, or promotional + purposes without specific prior written permission. + + We suggest, but do not require, that you use one or more of the + following phrases to refer to this software in your documentation + or advertising materials: `FreeType Project', `FreeType Engine', + `FreeType library', or `FreeType Distribution'. + + As you have not signed this license, you are not required to + accept it. However, as the FreeType Project is copyrighted + material, only this license, or another one contracted with the + authors, grants you the right to use, distribute, and modify it. + Therefore, by using, distributing, or modifying the FreeType + Project, you indicate that you understand and accept all the terms + of this license. + +4. Contacts +----------- + + There are two mailing lists related to FreeType: + + o freetype@nongnu.org + + Discusses general use and applications of FreeType, as well as + future and wanted additions to the library and distribution. + If you are looking for support, start in this list if you + haven't found anything to help you in the documentation. + + o freetype-devel@nongnu.org + + Discusses bugs, as well as engine internals, design issues, + specific licenses, porting, etc. + + Our home page can be found at + + https://www.freetype.org + + +--- end of FTL.TXT --- + +==== Independent JPEG Group ==== + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + +==== Unicode 3.0 ==== + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2004-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +==== X11 ==== + +X11 License + +Copyright (C) 1996 X Consortium + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of the X Consortium shall not be used in +advertising or otherwise to promote the sale, use or other dealings in this Software +without prior written authorization from the X Consortium. + +X Window System is a trademark of X Consortium, Inc. + +==== Historical Permission Notice and Disclaimer ==== + +Historical Permission Notice and Disclaimer + +Copyright + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, provided +that the above copyright notice appear in all copies, and that both that +copyright notice and this permission notice appear in supporting +documentation , and that the name of +not be used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. +makes no representations about the suitability of this software for any +purpose. It is provided "as is" without express or implied warranty. + + DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO +EVENT SHALL BE LIABLE FOR ANY SPECIAL, INDIRECT OR +CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF +USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +==== Historical Permission Notice and Disclaimer, sell variant ==== + +Copyright 2002 USC/Information Sciences Institute + +Permission to use, copy, modify, distribute, and sell this software +and its documentation for any purpose is hereby granted without +fee, provided that the above copyright notice appear in all copies +and that both that copyright notice and this permission notice +appear in supporting documentation, and that the name of +Information Sciences Institute not be used in advertising or +publicity pertaining to distribution of the software without +specific, written prior permission. Information Sciences Institute +makes no representations about the suitability of this software for +any purpose. It is provided "as is" without express or implied +warranty. + +INFORMATION SCIENCES INSTITUTE DISCLAIMS ALL WARRANTIES WITH REGARD +TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL INFORMATION SCIENCES +INSTITUTE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA +OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +==== Imlib2 ==== + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies of the Software and its Copyright notices. In addition publicly documented acknowledgment must be given that this software has been used if no source code of this software is made available publicly. Making the source available publicly means including the source for this software with the distribution, or a method to get this software via some reasonable mechanism (electronic transfer via a network or media) as well as making an offer to supply the source on request. This Copyright notice serves as an offer to supply the source on on request as well. Instead of this, supplying acknowledgments of use of this software in either Copyright notices, Manuals, Publicity and Marketing documents or any documentation provided with any product containing this software. This License does not apply to any software that links to the libraries provided by this software (statically or dynamically), but only to the software provided. + +Please see the COPYING-PLAIN for a plain-english explanation of this notice and its intent. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== zlib ==== + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +==== libpng (older) ==== + +This copy of the libpng notices is provided for your convenience. In case of any discrepancy between this copy and the notices in the file png.h that is included in the libpng distribution, the latter shall prevail. + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: + +If you modify libpng you may insert additional notices immediately following this sentence. + +This code is released under the libpng license. + +libpng versions 1.2.6, August 15, 2004, through 1.4.5, December 9, 2010, are Copyright (c) 2004, 2006-2010 Glenn Randers-Pehrson, and are distributed according to the same disclaimer and license as libpng-1.2.5 with the following individual added to the list of Contributing Authors + +Cosmin Truta + +libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are +Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are distributed according to the same disclaimer and license as libpng-1.0.6 with the following individuals added to the list of Contributing Authors + +Simon-Pierre Cadieux +Eric S. Raymond +Gilles Vollant + +and with the following additions to the disclaimer: + +There is no warranty against interference with your enjoyment of the library or against infringement. There is no warranty that our efforts or the library will fulfill any of your particular purposes or needs. This library is provided with all faults, and the entire risk of satisfactory quality, performance, accuracy, and effort is with the user. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are distributed according to the same disclaimer and license as libpng-0.96, with the following individuals added to the list of Contributing Authors: + +Tom Lane +Glenn Randers-Pehrson +Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996, 1997 Andreas Digger +Distributed according to the same disclaimer and license as libpng-0.88, with the following individuals added to the list of Contributing Authors: + +John Bowler +Kevin Bracey +Sam Bushell +Magnus Holmgren +Greg Roelofs +Tom Tanner + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" is defined as the following set of individuals: + +Andreas Dilger +Dave Martindale +Guy Eric Schalnat +Paul Schmidt +Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing Authors and Group 42, Inc. disclaim all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. The Contributing Authors and Group 42, Inc. assume no liability for direct, indirect, incidental, special, exemplary, or consequential damages, which may result from the use of the PNG Reference Library, even if advised of the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this source code, or portions hereof, for any purpose, without fee, subject to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + 2. Altered versions must be plainly marked as such and must not be misrepresented as being the original source. + 3. This Copyright notice may not be removed or altered from any source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, without fee, and encourage the use of this source code as a component to supporting the PNG file format in commercial products. If you use this source code in a product, acknowledgment is not required but would be appreciated. + +A "png_get_copyright" function is available, for convenient use in "about" boxes and the like: + +printf("%s",png_get_copyright(NULL)); + +Also, the PNG logo (in PNG format, of course) is supplied in the files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31). + +Libpng is OSI Certified Open Source Software. OSI Certified Open Source is a certification mark of the Open Source Initiative. + +Glenn Randers-Pehrson +glennrp at users.sourceforge.net +December 9, 2010 + +==== libpng 2.0 ==== + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2024 The PNG Reference Library Authors. + * Copyright (c) 2018-2024 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, or +anyone distributing the software, be liable for any damages or +other liability, whether in contract, tort or otherwise, arising +from, out of, or in connection with the software, or the use or +other dealings in the software, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. + +==== BSD 3-clause with PCRE2's binary-like packages exception ==== + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +EXEMPTION FOR BINARY LIBRARY-LIKE PACKAGES +------------------------------------------ + +The second condition in the BSD licence (covering binary redistributions) does not apply all the way down a chain of software. If binary package A includes PCRE2, it must respect the condition, but if package B is software that includes package A, the condition is not imposed on package B unless it uses PCRE2 independently. + +==== International Color Consortium ==== + +For the file sRGB2014.icc: + +Copyright International Color Consortium, 2015 + +This profile is made available by the International Color Consortium, and may be copied, +distributed, embedded, made, used, and sold without restriction. Altered versions of this +profile shall have the original identification and copyright information removed and +shall not be misrepresented as the original profile. + +(original source location: http://www.color.org/srgbprofiles.xalter) + +==== Public domain ==== + +100% free public domain implementation of the SHA-1 algorithm +by Dominik Reichl +Web: http://www.dominik-reichl.de/ + +==== Apache 2.0 ==== + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +==== Mozilla Public License 2.0 ==== + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/app/android/src/io/github/erickramer42/havne/SessionService.java b/app/android/src/io/github/erickramer42/havne/SessionService.java index f5177492..8ca9f806 100644 --- a/app/android/src/io/github/erickramer42/havne/SessionService.java +++ b/app/android/src/io/github/erickramer42/havne/SessionService.java @@ -27,6 +27,11 @@ // notification says what is connected; a tap opens the app. // androidsession.cpp starts, updates and stops it through JNI. // +// Its static openAppSettings is not part of that: bluetoothdevices.cpp +// calls it through JNI to open Havne's page in Android's settings, where +// the Nearby devices permission is switched on after Android stopped +// asking. It needs no service running. +// // It also holds a partial wake lock while it runs: the service keeps // Android from freezing the app, not the CPU from sleeping, and with the // screen off the CPU slept about 100 s of a session, no request going out @@ -60,6 +65,22 @@ public static void stop(Context context) context.stopService(new Intent(context, SessionService.class)); } + // Havne's own page in Android's settings (Apps > Havne), where the + // Nearby devices permission is switched on once Android no longer + // shows its dialog + public static void openAppSettings(Context context) + { + try { + Intent intent = new Intent( + android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, + android.net.Uri.fromParts("package", context.getPackageName(), null)); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } catch (RuntimeException e) { + Log.w(TAG, "Android's settings didn't open: " + e); + } + } + // Android 13+ asks before an app shows notifications: once, at the // first adapter connect. Refused, the service still runs and Android // lists it in its task manager only diff --git a/app/bluetoothdevices.cpp b/app/bluetoothdevices.cpp index 8a807e64..fc076390 100644 --- a/app/bluetoothdevices.cpp +++ b/app/bluetoothdevices.cpp @@ -172,9 +172,10 @@ QString BluetoothDevices::streamName(const QString& uri) void BluetoothDevices::setStatus(const QString& status, bool warns) { - if (m_status != status || m_statusWarns != warns) { + if (m_status != status || m_statusWarns != warns || m_needsSettings) { m_status = status; m_statusWarns = warns; + m_needsSettings = false; emit statusChanged(); } } @@ -190,6 +191,8 @@ void BluetoothDevices::setScanning(bool scanning) #ifndef APP_BLUETOOTH void BluetoothDevices::refresh(bool) {} +void BluetoothDevices::userRefresh() {} +void BluetoothDevices::openSettings() {} void BluetoothDevices::scan() {} QString BluetoothDevices::prepare(const QString& uri) @@ -205,10 +208,27 @@ QString BluetoothDevices::prepare(const QString& uri) #else +// The refusal's message, and the button to Havne's page in Android's +// settings (needsSettings) +void BluetoothDevices::deniedStatus() +{ + // All three set before the one emit, so a binding never sees the + // status with the button not yet shown + m_status = tr("Allow Nearby devices for Havne: Android settings > Apps > " + "Havne > Permissions"); + m_statusWarns = true; + m_needsSettings = true; + emit statusChanged(); +} + // Android's answer on the Nearby devices permission (BLUETOOTH_CONNECT and // BLUETOOTH_SCAN, declared never for location: app/CMakeLists.txt). With // ask, an undecided one is asked, and the list or the scan runs on a yes. -bool BluetoothDevices::permitted(bool ask, bool forScan) +// After a "Don't allow" Android still shows its dialog the next time, until +// the user has refused twice or chosen not to be asked again: a tap (user) +// asks again, and only an answer of Denied sends the user to Havne's page +// in Android's settings. Seen only (no tap), a refusal just says so. +bool BluetoothDevices::permitted(bool ask, bool forScan, bool user) { QBluetoothPermission permission; permission.setCommunicationModes(QBluetoothPermission::Access); @@ -216,10 +236,11 @@ bool BluetoothDevices::permitted(bool ask, bool forScan) case Qt::PermissionStatus::Granted: return true; case Qt::PermissionStatus::Denied: - setStatus(tr("Allow Nearby devices for Havne in Android's settings to " - "reach Bluetooth adapters"), - true); - return false; + if (!(ask && user)) { + deniedStatus(); + return false; + } + break; case Qt::PermissionStatus::Undetermined: break; } @@ -235,15 +256,27 @@ bool BluetoothDevices::permitted(bool ask, bool forScan) listPaired(); } } else { - setStatus( - tr("Allow Nearby devices for Havne in Android's settings " - "to reach Bluetooth adapters"), - true); + deniedStatus(); } }); return false; } +void BluetoothDevices::userRefresh() +{ + if (permitted(true, false, true)) { + listPaired(); + } +} + +void BluetoothDevices::openSettings() +{ + const QJniObject context = QNativeInterface::QAndroidApplication::context(); + QJniObject::callStaticMethod( + "io/github/erickramer42/havne/SessionService", "openAppSettings", + "(Landroid/content/Context;)V", context.object()); +} + void BluetoothDevices::refresh(bool ask) { if (permitted(ask, false)) { @@ -275,7 +308,7 @@ void BluetoothDevices::listPaired() void BluetoothDevices::scan() { - if (!m_scanning && permitted(true, true)) { + if (!m_scanning && permitted(true, true, true)) { scanNow(); } } diff --git a/app/bluetoothdevices.h b/app/bluetoothdevices.h index c108fda6..6ece714d 100644 --- a/app/bluetoothdevices.h +++ b/app/bluetoothdevices.h @@ -45,6 +45,9 @@ class BluetoothDevices : public QObject // The status asks the user to act (Bluetooth off, the permission // refused, a failed scan), not just reports Q_PROPERTY(bool statusWarns READ statusWarns NOTIFY statusChanged) + // The permission is refused and Android won't ask: the page shows the + // way to Havne's page in Android's settings and a button to it + Q_PROPERTY(bool needsSettings READ needsSettings NOTIFY statusChanged) public: explicit BluetoothDevices(QObject* parent = nullptr); @@ -64,10 +67,16 @@ class BluetoothDevices : public QObject bool scanning() const { return m_scanning; } QString status() const { return m_status; } bool statusWarns() const { return m_statusWarns; } + bool needsSettings() const { return m_needsSettings; } // Lists the paired adapters. With ask, asks for the permission when // Android hasn't been asked yet; without, lists only once it's given Q_INVOKABLE void refresh(bool ask); + // Refresh on the user's tap: also asks again after a "Don't allow", + // which Android answers at once once it stops showing the dialog + Q_INVOKABLE void userRefresh(); + // Opens Havne's page in Android's settings (Android only) + Q_INVOKABLE void openSettings(); // Looks for BLE adapters for a few seconds; they join the list Q_INVOKABLE void scan(); @@ -92,9 +101,12 @@ class BluetoothDevices : public QObject bool m_scanning = false; QString m_status; bool m_statusWarns = false; + bool m_needsSettings = false; #ifdef APP_BLUETOOTH - // Whether Android has been asked and what it said - bool permitted(bool ask, bool forScan); + // Whether Android has been asked and what it said. user: a tap, which + // asks again after a refusal + bool permitted(bool ask, bool forScan, bool user = false); + void deniedStatus(); void listPaired(); void scanNow(); std::map m_links; // by stream name, owned (children) diff --git a/app/bridgesingleton.h b/app/bridgesingleton.h index df2e6730..71d85f82 100644 --- a/app/bridgesingleton.h +++ b/app/bridgesingleton.h @@ -10,6 +10,7 @@ #include #include "adapterrelay.h" +#include "recordingframes.h" #include "recordingview.h" #include "sessionbridge.h" @@ -69,6 +70,15 @@ struct RecordingViewForeign { QML_NAMED_ELEMENT(RecordingView) }; +// The viewer's Frames table: the rows of the part in view, read from +// frames.csv (ADR-0049's appendix "frames read back"); each page makes +// its own +struct RecordingFramesForeign { + Q_GADGET + QML_FOREIGN(RecordingFrames) + QML_NAMED_ELEMENT(RecordingFrames) +}; + // Finding a signal among many (ADR-0050): Live's list holds one, and the // Recordings page makes its own struct SignalFilterForeign { @@ -77,6 +87,15 @@ struct SignalFilterForeign { QML_NAMED_ELEMENT(SignalFilter) }; +// The bridge's Import, named so a page reads its Kind values +struct RecordingImportForeign +{ + Q_GADGET + QML_FOREIGN(RecordingImport) + QML_NAMED_ELEMENT(RecordingImport) + QML_UNCREATABLE("Bridge.recordingImport is the one import") +}; + // The bridge's model properties, typed for qmllint. Not creatable or // nameable from QML. struct FrameListModelForeign diff --git a/app/framefilter.cpp b/app/framefilter.cpp index 7d9e537b..b46c3826 100644 --- a/app/framefilter.cpp +++ b/app/framefilter.cpp @@ -3,8 +3,11 @@ #include "framefilter.h" +#include #include +#include + #include "ecuio/core.h" namespace { @@ -33,6 +36,45 @@ bool hexId(QString text, uint32_t* out) return true; } +// One length in bytes, decimal; false past what a frame holds +bool decimalLength(QString text, int* out) +{ + text = text.trimmed(); + if (text.isEmpty() || text.size() > 4) { + return false; + } + for (const QChar c : text) { + if (c < QLatin1Char('0') || c > QLatin1Char('9')) { + return false; + } + } + const int value = text.toInt(); + if (value > static_cast(ECUIO_FRAME_DATA_MAX)) { + return false; + } + *out = value; + return true; +} + +// Seconds as the table shows them ("12.5", "30", ".25"), into +// microseconds; false for a sign, an exponent or past a million hours +bool seconds(QString text, uint64_t* out) +{ + static const QRegularExpression form( + QStringLiteral("^([0-9]+(\\.[0-9]*)?|\\.[0-9]+)$")); + text = text.trimmed(); + if (!form.match(text).hasMatch()) { + return false; + } + bool ok = false; + const double value = text.toDouble(&ok); + if (!ok || value > 3.6e9) { + return false; + } + *out = static_cast(std::llround(value * 1e6)); + return true; +} + } // namespace QString FrameFilter::parseIds(const QString& text, std::vector* out) @@ -47,7 +89,25 @@ QString FrameFilter::parseIds(const QString& text, std::vector* out) if (item.isEmpty()) { return QStringLiteral("an empty item between commas"); } + if (item.contains(QLatin1Char('/'))) { + return QStringLiteral( + "\"%1\": an ID and its mask take \":\", as in 7E0:7F8") + .arg(item); + } IdRange r; + const qsizetype colon = item.indexOf(QLatin1Char(':')); + if (colon >= 0) { + if (!hexId(item.left(colon), &r.first) || + !hexId(item.mid(colon + 1), &r.mask)) { + return QStringLiteral( + "\"%1\" isn't a hex ID and mask like 7E0:7F8") + .arg(item); + } + r.last = r.first; + r.masked = true; + ranges.push_back(r); + continue; + } const qsizetype dash = item.indexOf(QLatin1Char('-')); const bool ok = dash < 0 ? hexId(item, &r.first) @@ -113,21 +173,96 @@ QString FrameFilter::parseData(const QString& text, std::vector* out, return {}; } +QString FrameFilter::parseLengths(const QString& text, + std::vector* out) +{ + out->clear(); + if (text.trimmed().isEmpty()) { + return {}; + } + std::vector ranges; + for (const QString& raw : text.split(QLatin1Char(','))) { + const QString item = raw.trimmed(); + if (item.isEmpty()) { + return QStringLiteral("an empty item between commas"); + } + LengthRange r; + const qsizetype dash = item.indexOf(QLatin1Char('-')); + const bool ok = dash < 0 + ? decimalLength(item, &r.first) + : decimalLength(item.left(dash), &r.first) && + decimalLength(item.mid(dash + 1), &r.last); + if (!ok) { + return QStringLiteral( + "\"%1\" isn't a length in bytes (up to %2) or a range " + "like 1-7") + .arg(item) + .arg(ECUIO_FRAME_DATA_MAX); + } + if (dash < 0) { + r.last = r.first; + } else if (r.last < r.first) { + return QStringLiteral("\"%1\" runs backward").arg(item); + } + ranges.push_back(r); + } + *out = std::move(ranges); + return {}; +} + +QString FrameFilter::parseTimes(const QString& text, TimeRange* out) +{ + *out = TimeRange(); + const QString t = text.trimmed(); + if (t.isEmpty()) { + return {}; + } + // Not const: each return moves it + QString shape = + QStringLiteral("\"%1\" isn't a range of seconds like 12.5-30, " + "12.5- (from then on) or -30 (up to then)") + .arg(t); + const qsizetype dash = t.indexOf(QLatin1Char('-')); + if (dash < 0 || t.indexOf(QLatin1Char('-'), dash + 1) >= 0) { + return shape; + } + const QString from = t.left(dash).trimmed(); + const QString to = t.mid(dash + 1).trimmed(); + TimeRange r; + r.set = true; + if ((from.isEmpty() && to.isEmpty()) || + (!from.isEmpty() && !seconds(from, &r.first)) || + (!to.isEmpty() && !seconds(to, &r.last))) { + return shape; + } + if (r.last < r.first) { + return QStringLiteral("\"%1\" runs backward").arg(t); + } + *out = r; + return {}; +} + int FrameFilter::terms() const { return (ids.empty() ? 0 : 1) + (data.empty() ? 0 : 1) + - (direction == AnyDirection ? 0 : 1) + (flag == AnyFlag ? 0 : 1); + (direction == AnyDirection ? 0 : 1) + (flag == AnyFlag ? 0 : 1) + + (lengths.empty() ? 0 : 1) + (time.set ? 1 : 0); } -bool FrameFilter::matches(uint32_t id, uint32_t flags, const uint8_t* payload, - int length) const +bool FrameFilter::matches(uint32_t id, uint32_t flags, uint64_t timestampUs, + const uint8_t* payload, int length) const { const bool extended = (flags & ECUIO_FRAME_FLAG_EXTENDED) != 0; if (!ids.empty()) { bool any = false; for (const IdRange& r : ids) { - if (id >= r.first && id <= r.last && - (extended || id <= kMaxStandardId)) { + const bool in = r.masked + ? (id & r.mask) == (r.first & r.mask) && + (extended || (r.first <= kMaxStandardId && + r.mask <= kMaxStandardId)) + : id >= r.first && id <= r.last && + (extended || id <= kMaxStandardId); + if (in) { any = true; break; } @@ -165,6 +300,21 @@ bool FrameFilter::matches(uint32_t id, uint32_t flags, const uint8_t* payload, default: break; } + if (time.set && (timestampUs < time.first || timestampUs > time.last)) { + return false; + } + if (!lengths.empty()) { + bool any = false; + for (const LengthRange& r : lengths) { + if (length >= r.first && length <= r.last) { + any = true; + break; + } + } + if (!any) { + return false; + } + } if (data.empty()) { return true; } diff --git a/app/framefilter.h b/app/framefilter.h index 68a882c6..135b89e3 100644 --- a/app/framefilter.h +++ b/app/framefilter.h @@ -6,11 +6,17 @@ // flags, the direction). It chooses rows to show, as a search does; it // reads no field of a payload, so decoding stays in core (rule 2). // -// ID hex IDs and ranges, commas between, "0x" optional: -// "7E8, 7E0-7EF, 0x18DAF110". An ID past 0x7FF matches only an -// extended (29-bit) frame. +// ID hex IDs, ranges and IDs under a mask, commas between, "0x" +// optional: "7E8, 7E0-7EF, 0x18DAF110, 7E0:7F8". A mask is +// candump's can_id:can_mask, the ID's bits where the mask has +// ones. An ID (or a mask) past 0x7FF matches only an extended +// (29-bit) frame. // Data hex bytes, "??" for any byte, found anywhere in the payload; // "^" first anchors them at byte 0: "^62 F1 ??". +// Length data lengths in bytes and ranges, decimal, commas between: +// "8", "1-7, 12, 64". +// Time the table's seconds, one range, both ends in it: "12.5-30", +// "12.5-" (from then on) or "-30" (up to then). // Direction every frame, the received ones, or the sent ones (an // echo of the session's own transmit, ECUIO_FRAME_FLAG_TX_ECHO). // Flags any, or one: extended, standard, CAN FD, reassembled, @@ -38,9 +44,36 @@ class FrameFilter Error = 7 }; + // first to last; or, masked, the IDs whose bits under mask are + // first's (last is first) struct IdRange { uint32_t first = 0; uint32_t last = 0; + bool masked = false; + uint32_t mask = 0; + bool operator==(const IdRange& o) const + { + return first == o.first && last == o.last && masked == o.masked && + mask == o.mask; + } + }; + struct LengthRange { + int first = 0; + int last = 0; + bool operator==(const LengthRange& o) const + { + return first == o.first && last == o.last; + } + }; + // Session time in microseconds, both ends in the range + struct TimeRange { + bool set = false; + uint64_t first = 0; + uint64_t last = UINT64_MAX; + bool operator==(const TimeRange& o) const + { + return set == o.set && first == o.first && last == o.last; + } }; // The ID field's text into ranges; "" when it parses (empty is any @@ -50,18 +83,27 @@ class FrameFilter // (empty is any payload), else why not static QString parseData(const QString& text, std::vector* out, bool* anchored); + // The length field's text into ranges; "" when it parses (empty is + // any length), else why not, naming the item + static QString parseLengths(const QString& text, + std::vector* out); + // The time field's text into a range; "" when it parses (empty is + // any time, not set), else why not + static QString parseTimes(const QString& text, TimeRange* out); std::vector ids; std::vector data; bool anchored = false; int direction = AnyDirection; int flag = AnyFlag; + std::vector lengths; + TimeRange time; // How many fields are in force: 0 is no filter, every frame shown int terms() const; bool active() const { return terms() > 0; } - // A frame as the ring holds it: its ID, its ECUIO_FRAME_FLAG_* and - // its payload - bool matches(uint32_t id, uint32_t flags, const uint8_t* payload, - int length) const; + // A frame as the ring holds it: its ID, its ECUIO_FRAME_FLAG_*, its + // session time and its payload + bool matches(uint32_t id, uint32_t flags, uint64_t timestampUs, + const uint8_t* payload, int length) const; }; diff --git a/app/healthreport.cpp b/app/healthreport.cpp index 64544500..d5473a62 100644 --- a/app/healthreport.cpp +++ b/app/healthreport.cpp @@ -68,6 +68,12 @@ QString healthSavedLine(const ecuio_health_report_t& report) "identification item", "identification items")); } +QByteArray healthBaselineArgument(const QString& folder) +{ + return folder.isEmpty() ? QByteArray() + : QDir::toNativeSeparators(folder).toUtf8(); +} + QVariantMap writeHealthReport(ecuio_health_options_t options, const QUrl& url) { // Core's own name in a folder of the app's: never the vehicle's label @@ -106,6 +112,7 @@ QVariantMap writeHealthReport(ecuio_health_options_t options, const QUrl& url) const qulonglong leftOut = report.left_out[ECUIO_EXPORT_LEFT_OUT_IDENTIFICATION]; const bool vin = (report.flags & ECUIO_HEALTH_VIN_DECODED) != 0; + const bool baseline = (report.flags & ECUIO_HEALTH_BASELINE_READ) != 0; return {{QStringLiteral("ok"), true}, {QStringLiteral("words"), QString()}, {QStringLiteral("ecus"), report.ecus}, @@ -114,6 +121,7 @@ QVariantMap writeHealthReport(ecuio_health_options_t options, const QUrl& url) {QStringLiteral("sinceCleared"), report.since_cleared}, {QStringLiteral("identificationLeftOut"), leftOut}, {QStringLiteral("vinDecoded"), vin}, + {QStringLiteral("baselineRead"), baseline}, {QStringLiteral("summary"), healthSummary(report)}, {QStringLiteral("line"), healthSavedLine(report)}}; } diff --git a/app/healthreport.h b/app/healthreport.h index ba6122f8..e6e31583 100644 --- a/app/healthreport.h +++ b/app/healthreport.h @@ -11,6 +11,7 @@ #pragma once +#include #include #include #include @@ -29,6 +30,10 @@ uint32_t healthFormatFor(const QUrl& url, int filterIndex); uint64_t healthUtcNow(); uint32_t healthLatestModelYear(); +// A baseline's folder as core takes it (UTF-8, the platform's separators), +// empty for none: baseline_folder_utf8 is then NULL +QByteArray healthBaselineArgument(const QString& folder); + // A written report's counts in words, each noun as its count wants it: // "1 ECU, 3 trouble codes, 0 key values"; and the log's line, "Health // report saved: (2 identification items left out)" @@ -37,7 +42,9 @@ QString healthSavedLine(const ecuio_health_report_t& report); // options: every field but out_path_utf8, which this sets. The result: // { ok, words, ecus, codes, values, sinceCleared, identificationLeftOut, -// vinDecoded, summary, line }, words "" on success and never a path, a +// vinDecoded, baselineRead, summary, line }, baselineRead whether core +// read the baseline named (the report says why not), words "" on success +// and never a path, a // folder's name or a value; summary healthSummary's ("" on failure); // line the log's, in the same words QVariantMap writeHealthReport(ecuio_health_options_t options, const QUrl& url); diff --git a/app/main.cpp b/app/main.cpp index 0d502d79..ac4e4493 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -2,6 +2,7 @@ // Testing: Manual smoke; BENCH (the phone run sheet); CI android-build // (compiles it) +#include #include #include #include @@ -10,18 +11,6 @@ #include #include -#ifdef Q_OS_ANDROID -#include -#include -#endif -#ifdef Q_OS_WIN -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#include -#endif - #ifdef Q_OS_ANDROID #include "androidsession.h" #endif @@ -33,52 +22,15 @@ #include "bridgesingleton.h" #include "carryover.h" #include "sessionbridge.h" +#if defined(Q_OS_ANDROID) || defined(Q_OS_WIN) +#include "windowtheme.h" +#endif #include "ecuio/version.h" // The App module is a static library (app/CMakeLists.txt); this pulls // in its plugin, which registers the module's types Q_IMPORT_QML_PLUGIN(AppPlugin) -#ifdef Q_OS_ANDROID -// Android's own window, behind Qt's, follows the phone's day/night theme -// (QtActivity's DayNight): light on a light phone. After a rotation, the -// screen Qt's window didn't reach showed white, and three-button -// navigation sat on a light scrim (docs/bench-sessions/2026-10-28-android-3.md). -// Dark like the app instead, no scrim, the navigation buttons drawn light. -static void darkenAndroidWindow() -{ - using QNativeInterface::QAndroidApplication; - QAndroidApplication::runOnAndroidMainThread([]() { - const QJniObject activity = QAndroidApplication::context(); - const QJniObject window = - activity.callObjectMethod("getWindow", "()Landroid/view/Window;"); - if (!window.isValid()) - return; - const QJniObject background("android/graphics/drawable/ColorDrawable", - "(I)V", - static_cast(0xFF14141Cu)); // Theme.bg - window.callMethod("setBackgroundDrawable", - "(Landroid/graphics/drawable/Drawable;)V", - background.object()); - if (QAndroidApplication::sdkVersion() >= 29) { - window.callMethod("setNavigationBarContrastEnforced", "(Z)V", - static_cast(false)); - } - if (QAndroidApplication::sdkVersion() >= 30) { - const QJniObject insets = window.callObjectMethod( - "getInsetsController", - "()Landroid/view/WindowInsetsController;"); - if (insets.isValid()) { - // APPEARANCE_LIGHT_NAVIGATION_BARS (0x10) off: light buttons - insets.callMethod("setSystemBarsAppearance", "(II)V", - static_cast(0), - static_cast(0x10)); - } - } - }); -} -#endif - #ifdef Q_OS_ANDROID // No drawing while the app isn't active. With the event loops kept running // in the background (ADR-0029 section 1), Qt 6.12's Android plugin, handling the @@ -99,29 +51,14 @@ class NoDrawWhileInactive : public QObject { if ((event->type() == QEvent::Expose || event->type() == QEvent::UpdateRequest) && - QGuiApplication::applicationState() != Qt::ApplicationActive) + QGuiApplication::applicationState() != Qt::ApplicationActive) { return true; + } return QObject::eventFilter(watched, event); } }; #endif -#ifdef Q_OS_WIN -// The title bar in the header's color (Theme.surface) with the app's text -// color, so the two read as one bar. Windows 11 takes both; Windows 10 -// refuses them and keeps the dark title bar the color scheme gives it -static void colorTitleBar(QWindow *window) -{ - // WId is the window's HWND held as an integer: the cast is Qt's own - // NOLINTNEXTLINE(performance-no-int-to-ptr) - const auto hwnd = reinterpret_cast(window->winId()); - const COLORREF caption = RGB(0x1e, 0x1e, 0x2e); // Theme.surface - const COLORREF text = RGB(0xe8, 0xe8, 0xf0); // Theme.text - (void)DwmSetWindowAttribute(hwnd, DWMWA_CAPTION_COLOR, &caption, sizeof caption); - (void)DwmSetWindowAttribute(hwnd, DWMWA_TEXT_COLOR, &text, sizeof text); -} -#endif - int main(int argc, char *argv[]) { #ifdef Q_OS_ANDROID @@ -129,8 +66,9 @@ int main(int argc, char *argv[]) // by an event NoDrawWhileInactive sees. The threaded loop's render // thread starts frames of its own, and one that started as the screen // went off waited there, the GUI thread waiting on it - if (!qEnvironmentVariableIsSet("QSG_RENDER_LOOP")) + if (!qEnvironmentVariableIsSet("QSG_RENDER_LOOP")) { qputenv("QSG_RENDER_LOOP", "basic"); + } #endif QGuiApplication app(argc, argv); app.setOrganizationName("Havne"); @@ -196,16 +134,15 @@ int main(int argc, char *argv[]) .arg(earlierProductName()) .arg(carriedOver)); } +#if defined(Q_OS_ANDROID) || defined(Q_OS_WIN) + if (auto *window = + qobject_cast(engine.rootObjects().constFirst())) { + if (auto* theme = engine.singletonInstance("App", "Theme")) { + new WindowTheme(theme, window); + } #ifdef Q_OS_ANDROID - darkenAndroidWindow(); - if (auto* window = - qobject_cast(engine.rootObjects().constFirst())) window->installEventFilter(new NoDrawWhileInactive(window)); #endif -#ifdef Q_OS_WIN - if (auto *window = - qobject_cast(engine.rootObjects().constFirst())) { - colorTitleBar(window); } #endif diff --git a/app/qml/AnalogGauge.qml b/app/qml/AnalogGauge.qml index fa40b6d9..f53b0b8a 100644 --- a/app/qml/AnalogGauge.qml +++ b/app/qml/AnalogGauge.qml @@ -2,6 +2,8 @@ // Testing: manual smoke: DashboardPage under mock://demo at 160 px // (numerals shrink, then thin out) through 480 px; sweep on // connect; tap clears the peak marker +// QML: QmlTest.dashboard (no negative tick count while a +// reused cell rebinds) import QtQuick import QtQuick.Shapes @@ -25,8 +27,7 @@ GaugeBase { property string caption: "" // above the hub, e.g. "×1000 r/min" property string peakLabel: qsTr("PEAK") property bool showProgress: false // lit arc from `from` to the needle - property bool showPeak: false // tell-tale marker and readout line - property color needleColor: "#ff5a5f" + property color needleColor: Theme.gaugeNeedle // Geometry, all from the square the dial fits in readonly property real size: Math.min(width, height) @@ -40,13 +41,14 @@ GaugeBase { readonly property real ringWidth: Math.max(2.5, size * 0.013) readonly property real numRadius: r * 0.63 - readonly property int majorCount: Math.round((to - from) / majorStep) + 1 - readonly property int minorCount: Math.round((to - from) / minorStep) + 1 + // None while a reused cell rebinds its ends one at a time + readonly property int majorCount: Math.max(0, Math.floor((to - from) / majorStep + 1e-9) + 1) + readonly property int minorCount: Math.max(0, Math.floor((to - from) / minorStep + 1e-9) + 1) // Numerals shrink to fit the arc between them, down to 9 px; past // that every other one (or more) is dropped readonly property real labelGap: numRadius * sweepAngle * Math.PI / 180 / Math.max(1, majorCount - 1) - readonly property real labelEm: 0.62 * String(Math.round(to / labelDivisor)).length + 0.6 + readonly property real labelEm: 0.62 * formatScale(to / labelDivisor).length + 0.6 readonly property real numSize: Math.max(9, Math.min(size * 0.07, labelGap / labelEm)) readonly property int labelEvery: Math.max(1, Math.ceil(numSize * labelEm / labelGap)) @@ -69,9 +71,9 @@ GaugeBase { anchors.centerIn: parent width: gauge.size; height: width; radius: width / 2 gradient: Gradient { - GradientStop { position: 0.0; color: "#3a3a52" } - GradientStop { position: 0.45; color: "#1b1b28" } - GradientStop { position: 1.0; color: "#2c2c42" } + GradientStop { position: 0.0; color: Theme.gaugeShade.bezelHi } + GradientStop { position: 0.45; color: Theme.gaugeFace } + GradientStop { position: 1.0; color: Theme.gaugeShade.bezelLo } } } Shape { @@ -83,8 +85,8 @@ GaugeBase { centerX: gauge.cx; centerY: gauge.cy - gauge.r * 0.35 centerRadius: gauge.r * 1.25 focalX: gauge.cx; focalY: gauge.cy - gauge.r * 0.35 - GradientStop { position: 0.0; color: "#25253a" } - GradientStop { position: 1.0; color: "#0e0e15" } + GradientStop { position: 0.0; color: Theme.gaugeShade.faceHi } + GradientStop { position: 1.0; color: Theme.gaugeShade.faceLo } } PathAngleArc { centerX: gauge.cx; centerY: gauge.cy @@ -101,7 +103,7 @@ GaugeBase { GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.tickOuter startAngle: gauge.startAngle; sweepAngle: gauge.sweepAngle - strokeColor: Qt.alpha(Theme.text, 0.16) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.16) strokeWidth: Math.max(1, gauge.size * 0.004) } GaugeArc { @@ -109,7 +111,7 @@ GaugeBase { radius: gauge.tickOuter - gauge.majorLen / 2 startAngle: gauge.angleOf(gauge.warnStart) sweepAngle: gauge.angleOf(gauge.dangerStart) - startAngle - strokeColor: Qt.alpha(Theme.warning, 0.14) + strokeColor: Qt.alpha(Theme.gaugeWarn, 0.14) strokeWidth: gauge.majorLen } GaugeArc { @@ -117,22 +119,23 @@ GaugeBase { radius: gauge.tickOuter - gauge.majorLen / 2 startAngle: gauge.angleOf(gauge.dangerStart) sweepAngle: gauge.angleOf(gauge.to) - startAngle - strokeColor: Qt.alpha(Theme.danger, 0.18) + strokeColor: Qt.alpha(Theme.gaugeDanger, 0.30) strokeWidth: gauge.majorLen } GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.tickOuter startAngle: gauge.angleOf(gauge.warnStart) sweepAngle: gauge.angleOf(gauge.dangerStart) - startAngle - strokeColor: Theme.warning + strokeColor: Theme.gaugeWarn strokeWidth: Math.max(2, gauge.size * 0.009) } GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.tickOuter startAngle: gauge.angleOf(gauge.dangerStart) sweepAngle: gauge.angleOf(gauge.to) - startAngle - strokeColor: Theme.danger - strokeWidth: Math.max(2, gauge.size * 0.009) + strokeColor: Theme.gaugeDanger + // Heavier than the warning stroke: danger is more than a hue + strokeWidth: Math.max(4, gauge.size * 0.02) } } @@ -144,7 +147,7 @@ GaugeBase { GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.ringRadius startAngle: gauge.startAngle; sweepAngle: gauge.sweepAngle - strokeColor: Qt.alpha(Theme.text, 0.06) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.06) strokeWidth: gauge.ringWidth } GaugeArc { @@ -187,8 +190,8 @@ GaugeBase { height: tick.major ? gauge.majorLen : gauge.minorLen x: gauge.cx - width / 2 y: gauge.cy - gauge.tickOuter - color: gauge.zoneColor(tick.v, tick.major ? Theme.text - : Qt.alpha(Theme.text, 0.5)) + color: gauge.zoneColor(tick.v, tick.major ? Theme.gaugeTick + : Qt.alpha(Theme.gaugeTick, 0.5)) } } } @@ -201,13 +204,13 @@ GaugeBase { readonly property real a: gauge.angleOf(v) visible: index % gauge.labelEvery === 0 - text: String(Math.round(v / gauge.labelDivisor)) + text: gauge.formatScale(v / gauge.labelDivisor) x: gauge.px(a, gauge.numRadius) - width / 2 y: gauge.py(a, gauge.numRadius) - height / 2 font.pixelSize: gauge.numSize font.weight: Font.DemiBold font.features: ({ "tnum": 1 }) - color: gauge.zoneColor(v, Theme.text) + color: gauge.zoneColor(v, Theme.gaugeTick) } } @@ -224,7 +227,7 @@ GaugeBase { readonly property real m: gauge.size * 0.02 readonly property real tip: gauge.cx + gauge.ringRadius - gauge.ringWidth strokeColor: "transparent" - fillColor: Theme.warning + fillColor: Theme.gaugeWarn startX: wedge.tip; startY: gauge.cy PathLine { x: wedge.tip + wedge.m * 1.6; y: gauge.cy - wedge.m } PathLine { x: wedge.tip + wedge.m * 1.6; y: gauge.cy + wedge.m } @@ -247,14 +250,29 @@ GaugeBase { y: gauge.cy + gauge.r * 0.2 opacity: gauge.stale ? 0.45 : 1.0 - Text { + Item { anchors.horizontalCenter: parent.horizontalCenter - text: gauge.valueText - // Sized to clear the end numerals beside it at full scale - font.pixelSize: Math.max(16, gauge.size * 0.1) - font.weight: Font.DemiBold - font.features: ({ "tnum": 1 }) - color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.text) : Theme.textDim + width: valueLabel.width + height: valueLabel.height + Text { + id: valueLabel + objectName: "readout" + text: gauge.valueText + // Sized to clear the end numerals beside it at full scale + font.pixelSize: Math.max(16, gauge.size * 0.1) + font.weight: Font.DemiBold + font.features: ({ "tnum": 1 }) + color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim + } + // Past dangerFrom, beside the value + DangerMark { + // The slot stays once a gauge has a danger zone, so the readout + // never moves as the mark appears + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: valueLabel.font.pixelSize * 0.8 + anchors { left: valueLabel.right; leftMargin: 4; verticalCenter: valueLabel.verticalCenter } + } } Text { anchors.horizontalCenter: parent.horizontalCenter @@ -273,7 +291,7 @@ GaugeBase { font.pixelSize: Math.max(9, gauge.size * 0.032) font.letterSpacing: 1 font.features: ({ "tnum": 1 }) - color: gauge.hasValue ? Theme.warning : Theme.textDim + color: gauge.hasValue ? Theme.gaugeWarn : Theme.textDim } } @@ -282,8 +300,17 @@ GaugeBase { id: needle property color tint: gauge.needleColor property bool shadow: false + property real shiftX: 0 // the shadow's offset + property real shiftY: 0 - width: gauge.width; height: gauge.height + // The box is the square whose corners lie as far from the center + // as the needle's tip, so turning it never carries a corner past + // the dial (a dial-sized box would, by up to 41%); the path + // draws beyond the box, which a Shape doesn't clip. Centered on + // the dial, so the box's center is the rotation's + width: body.len * Math.SQRT2; height: width + x: gauge.cx - width / 2 + shiftX + y: gauge.cy - height / 2 + shiftY rotation: gauge.needleAngle opacity: gauge.hasValue || gauge.sweeping ? 1.0 : 0.4 preferredRendererType: Shape.CurveRenderer @@ -299,27 +326,27 @@ GaugeBase { strokeColor: "transparent" fillColor: needle.shadow ? Qt.rgba(0, 0, 0, 0.45) : "transparent" fillGradient: needle.shadow ? null : grad - startX: gauge.cx - body.tail; startY: gauge.cy - body.tailW - PathLine { x: gauge.cx; y: gauge.cy - body.baseW } - PathLine { x: gauge.cx + body.len; y: gauge.cy - body.tipW } - PathLine { x: gauge.cx + body.len; y: gauge.cy + body.tipW } - PathLine { x: gauge.cx; y: gauge.cy + body.baseW } - PathLine { x: gauge.cx - body.tail; y: gauge.cy + body.tailW } - PathLine { x: gauge.cx - body.tail; y: gauge.cy - body.tailW } + startX: needle.width / 2 - body.tail; startY: needle.height / 2 - body.tailW + PathLine { x: needle.width / 2; y: needle.height / 2 - body.baseW } + PathLine { x: needle.width / 2 + body.len; y: needle.height / 2 - body.tipW } + PathLine { x: needle.width / 2 + body.len; y: needle.height / 2 + body.tipW } + PathLine { x: needle.width / 2; y: needle.height / 2 + body.baseW } + PathLine { x: needle.width / 2 - body.tail; y: needle.height / 2 + body.tailW } + PathLine { x: needle.width / 2 - body.tail; y: needle.height / 2 - body.tailW } } LinearGradient { id: grad - x1: gauge.cx - gauge.r * 0.18; y1: 0 - x2: gauge.cx + gauge.r * 0.80; y2: 0 - GradientStop { position: 0.0; color: "#2a2a38" } - GradientStop { position: 0.17; color: "#2a2a38" } + x1: needle.width / 2 - gauge.r * 0.18; y1: 0 + x2: needle.width / 2 + gauge.r * 0.80; y2: 0 + GradientStop { position: 0.0; color: Theme.gaugeShade.needleBase } + GradientStop { position: 0.17; color: Theme.gaugeShade.needleBase } GradientStop { position: 0.19; color: Qt.darker(needle.tint, 1.25) } GradientStop { position: 1.0; color: Qt.lighter(needle.tint, 1.2) } } } Needle { shadow: true - x: gauge.size * 0.006; y: gauge.size * 0.014 + shiftX: gauge.size * 0.006; shiftY: gauge.size * 0.014 } Needle {} @@ -327,11 +354,11 @@ GaugeBase { Rectangle { anchors.centerIn: parent width: gauge.size * 0.11; height: width; radius: width / 2 - border.color: Qt.alpha(Theme.text, 0.10) + border.color: Qt.alpha(Theme.gaugeTick, 0.10) border.width: 1 gradient: Gradient { - GradientStop { position: 0.0; color: "#4b4b63" } - GradientStop { position: 1.0; color: "#14141c" } + GradientStop { position: 0.0; color: Theme.gaugeShade.hubHi } + GradientStop { position: 1.0; color: Theme.bg } } Rectangle { anchors.centerIn: parent diff --git a/app/qml/BarGauge.qml b/app/qml/BarGauge.qml index a62e3ab7..c6fdb8ff 100644 --- a/app/qml/BarGauge.qml +++ b/app/qml/BarGauge.qml @@ -1,7 +1,5 @@ // File/layer: app/qml/BarGauge.qml | Qt6 Quick, UI layer -// Testing: manual smoke: DashboardPage under mock://demo; segment -// count follows width (phone ~30, desktop ~50); the leading -// segment fades in, so motion reads smooth at any count +// Testing: QML: QmlTest.kinds, QmlTest.gauges, QmlTest.dashboard import QtQuick @@ -15,11 +13,20 @@ GaugeBase { property real segmentWidth: 7 // minimum; segments stretch to fill property real segmentGap: 3 property var scaleMarks: [0, 25, 50, 75, 100] // value units; [] hides the scale + // Standing up (segments stacked from the bottom, the scale beside) and + // the scale's ticks on or off (ADR-0057 section 1) + property bool vertical: false + property bool marks: true - readonly property int segments: Math.max(10, Math.floor((bar.width + segmentGap) - / (segmentWidth + segmentGap))) + // The bar's length along its own direction, and its thickness across + readonly property real barLength: vertical ? bar.height : bar.width + readonly property real barThickness: vertical ? bar.width : bar.height + // At least ten when ten fit; a short bar gets as many as fit (two at + // least), never segments narrower than they are wide across + readonly property int segments: Math.max(2, Math.floor((barLength + segmentGap) + / (segmentWidth + segmentGap))) - implicitHeight: 72 + implicitHeight: vertical ? 180 : 72 Text { id: title @@ -45,13 +52,24 @@ GaugeBase { opacity: gauge.stale ? 0.45 : 1.0 Text { id: valueLabel + objectName: "readout" text: gauge.valueText font.pixelSize: 22 font.weight: Font.DemiBold font.features: ({ "tnum": 1 }) - color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.text) : Theme.textDim + color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim + } + // Past dangerFrom, beside the value + DangerMark { + // The slot stays once a gauge has a danger zone, so the readout + // never moves as the mark appears + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: 18 + anchors.verticalCenter: valueLabel.verticalCenter } Text { + objectName: "unit" visible: gauge.hasValue anchors.baseline: valueLabel.baseline text: gauge.unit @@ -60,16 +78,19 @@ GaugeBase { } } - Row { + Item { id: bar - anchors { left: parent.left; right: parent.right; top: readout.bottom; topMargin: 8 } - height: 18 - spacing: gauge.segmentGap + objectName: "bar" + x: 0 + y: readout.height + 8 + width: gauge.vertical ? Math.min(28, gauge.width * 0.4) : gauge.width + height: gauge.vertical ? Math.max(0, gauge.height - y - 14) : 18 Repeater { model: gauge.segments delegate: Rectangle { id: seg + objectName: "segment" required property int index // Zone color at the segment's midpoint; fill fraction // 0..1 so the leading segment fades rather than snaps @@ -79,10 +100,23 @@ GaugeBase { readonly property real fill: Math.max(0, Math.min(1, gauge.fraction * gauge.segments - index)) - width: (bar.width - (gauge.segments - 1) * gauge.segmentGap) / gauge.segments - height: bar.height + // The danger zone's segments carry an outline: heavier than + // the others, so the zone reads apart by more than its hue + readonly property bool inDangerZone: !isNaN(gauge.dangerFrom) + && gauge.from + (index + 0.5) / gauge.segments * (gauge.to - gauge.from) + >= gauge.dangerFrom + + readonly property real along: (gauge.barLength + - (gauge.segments - 1) * gauge.segmentGap) / gauge.segments + // Standing up the first segment is the lowest + width: gauge.vertical ? bar.width : along + height: gauge.vertical ? along : bar.height + x: gauge.vertical ? 0 : index * (along + gauge.segmentGap) + y: gauge.vertical ? bar.height - (index + 1) * along - index * gauge.segmentGap : 0 radius: 2 color: Qt.alpha(seg.lit, 0.09) + border.width: seg.inDangerZone ? 2 : 0 + border.color: Qt.alpha(Theme.gaugeDanger, 0.55) Rectangle { anchors.fill: parent @@ -97,16 +131,38 @@ GaugeBase { } } + // The held peak: a mark across the bar at its place, only when asked for + Rectangle { + objectName: "peakMark" + visible: gauge.showPeak && !isNaN(gauge.peakValue) + readonly property real at: gauge.fractionOf(isNaN(gauge.peakValue) ? gauge.from : gauge.peakValue) + color: Theme.gaugeTick // no zone's color: it sits over lit segments + radius: 1 + // Inside the track at either end + x: gauge.vertical ? bar.x - 3 : bar.x + Math.max(0, Math.min(bar.width - width, at * bar.width - width / 2)) + y: gauge.vertical ? bar.y + Math.max(0, Math.min(bar.height - height, (1 - at) * bar.height - height / 2)) + : bar.y - 3 + width: gauge.vertical ? bar.width + 6 : 3 + height: gauge.vertical ? 3 : bar.height + 6 + } + Item { - anchors { left: bar.left; right: bar.right; top: bar.bottom; topMargin: 4 } - visible: gauge.scaleMarks.length > 0 + objectName: "scaleMarks" + x: gauge.vertical ? bar.x + bar.width + 6 : bar.x + y: gauge.vertical ? bar.y : bar.y + bar.height + 4 + width: gauge.vertical ? gauge.width - x : bar.width + height: gauge.vertical ? bar.height : 12 + visible: gauge.marks && gauge.scaleMarks.length > 0 Repeater { model: gauge.scaleMarks delegate: Text { required property real modelData readonly property real f: gauge.fractionOf(modelData) - // End labels align to the bar's edges, the rest center - x: f <= 0 ? 0 : f >= 1 ? parent.width - width : f * parent.width - width / 2 + // End labels align to the bar's edges, the rest center; standing + // up the low end is at the bottom + x: gauge.vertical ? 0 : f <= 0 ? 0 : f >= 1 ? parent.width - width : f * parent.width - width / 2 + y: gauge.vertical ? (f <= 0 ? parent.height - height + : f >= 1 ? 0 : (1 - f) * parent.height - height / 2) : 0 text: gauge.formatScale(modelData) font.pixelSize: 10 font.features: ({ "tnum": 1 }) diff --git a/app/qml/Captioned.qml b/app/qml/Captioned.qml new file mode 100644 index 00000000..5bb4c2d8 --- /dev/null +++ b/app/qml/Captioned.qml @@ -0,0 +1,16 @@ +// File/layer: app/qml/Captioned.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings (test_qml) +// A form's box with its name above it: a placeholder alone goes once +// something is typed, and the box no longer says what it holds + +import QtQuick +import QtQuick.Controls + +Column { + property alias caption: captionText.text + spacing: 2 + Label { + id: captionText + color: Theme.textDim + } +} diff --git a/app/qml/CsvGuessPreview.qml b/app/qml/CsvGuessPreview.qml new file mode 100644 index 00000000..cb4dfcf8 --- /dev/null +++ b/app/qml/CsvGuessPreview.qml @@ -0,0 +1,354 @@ +// File/layer: app/qml/CsvGuessPreview.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.recordings, QmlTest.phone (test_qml) + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +// The Import panel's preview of a CSV's guessed column map (ADR-0054's +// appendix "a column map guessed from the header", section 3): the time +// column and its unit, then each header column with a checkbox, its name, +// unit and kind, and the first rows of its cells. An edit changes the map +// the import gets (mapText()); Save as map keeps it for next time. The +// cells shown are the file's text as it splits here, for looking at only: +// the import's reader is core's. +ColumnLayout { + id: preview + + // Bridge.recordingImport.guess's result, ok; null for none + property var guess: null + // s, ms or us for a time of plain numbers; "" until one is chosen + property string timeUnit: "" + // One entry a header column but the time's, in the header's order: + // { column, include, used, why, canPutBack, name, unit, kind, samples }. + // Edited in place by the rows below; replaced by load() + property var columns: [] + property int included: 0 + property bool notesOpen: false + // The words the last Save as map gave + property string saveNote: "" + property bool saveFailed: false + + readonly property bool unitReady: guess === null ? false + : guess.timeNumbers ? timeUnit !== "" + : guess.unitKnown + readonly property bool ready: guess !== null && unitReady && included > 0 + // Why Import waits, "" when it doesn't + readonly property string waiting: { + if (guess === null) + return "" + if (!unitReady) + return guess.timeNumbers + ? qsTr("Choose the time column's unit to import") + : qsTr("This file's time needs a column map that says its zone: Column map... picks one") + if (included === 0) + return qsTr("Choose a column to import") + return "" + } + + // A map was saved: the page lists the saved maps again + signal mapSaved() + + spacing: Theme.spacing + + function load(result) { + const list = [] + let time = null + for (const c of result.columns) { + if (c.isTime) { + time = c + continue + } + list.push({ column: c.column, include: c.used, used: c.used, why: c.why, + canPutBack: c.canPutBack, name: c.name, unit: c.unit, + kind: c.kind, samples: c.samples }) + } + guess = result + timeColumn = time + // Emptied first so the rows below are made anew, never kept with + // bindings an edit has replaced + columns = [] + columns = list + timeUnit = ["s", "ms", "us"].includes(result.timeUnit) ? result.timeUnit : "" + notesOpen = false + saveNote = "" + saveFailed = false + recount() + } + function clear() { + guess = null + timeColumn = null + columns = [] + timeUnit = "" + included = 0 + notesOpen = false + saveNote = "" + saveFailed = false + saveName.text = "" + } + property var timeColumn: null + + function recount() { + let n = 0 + for (const c of columns) + n += c.include ? 1 : 0 + included = n + } + + // The map text the import takes: the guess with the edits + function mapText() { + const edits = columns.map(c => ({ column: c.column, include: c.include, name: c.name, + unit: c.unit, kind: c.kind })) + return Bridge.recordingImport.composeMap(guess.mapText, edits, + guess.timeNumbers ? timeUnit : "") + } + + function saveAs(name) { + const r = Bridge.recordingImport.saveMap(name, mapText()) + saveFailed = !r.ok + saveNote = r.ok ? qsTr("Saved as %1").arg(r.name) : r.words + if (r.ok) + mapSaved() + } + + // ---- The time column and its unit ---- + Label { + objectName: "guessTime" + Layout.fillWidth: true + wrapMode: Text.WrapAnywhere + color: Theme.text + text: preview.timeColumn === null ? "" + : qsTr("Time: %1").arg(preview.timeColumn.column) + } + Label { + objectName: "guessTimeSamples" + visible: preview.timeColumn !== null + Layout.fillWidth: true + wrapMode: Text.WrapAnywhere + maximumLineCount: 2 + elide: Text.ElideRight + color: Theme.textDim + font.pixelSize: 12 + text: preview.timeColumn === null ? "" : preview.timeColumn.samples.join(" ") + } + RowLayout { + visible: preview.guess !== null && preview.guess.timeNumbers + Layout.fillWidth: true + spacing: Theme.spacing + Label { + text: qsTr("Unit") + color: Theme.textDim + font.pixelSize: 13 + } + Rectangle { + implicitWidth: unitSwitch.implicitWidth + 4 + implicitHeight: unitSwitch.implicitHeight + 4 + radius: Theme.radius + color: Theme.surface + Row { + id: unitSwitch + anchors.centerIn: parent + spacing: 2 + Repeater { + model: ["s", "ms", "us"] + SegmentButton { + required property string modelData + objectName: "guessTimeUnit_" + modelData + text: modelData + implicitWidth: Math.max(Theme.touchTarget, implicitContentWidth + 24) + implicitHeight: Theme.touchTarget + selected: preview.timeUnit === modelData + onClicked: preview.timeUnit = modelData + } + } + } + } + } + Label { + objectName: "guessTimeFixed" + visible: preview.guess !== null && !preview.guess.timeNumbers + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + font.pixelSize: 13 + text: preview.guess === null ? "" + : preview.guess.timeUnit === "iso8601" ? qsTr("Its times are dates with a UTC offset") + : preview.guess.unitKnown ? qsTr("Its unit: %1").arg(preview.guess.timeUnit) + : "" + } + Label { + objectName: "guessWaiting" + visible: preview.waiting !== "" + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.danger + font.pixelSize: 13 + text: preview.waiting + } + + // ---- The columns ---- + Repeater { + id: rows + objectName: "guessRows" + model: preview.columns.length + + Rectangle { + id: row + required property int index + readonly property var col: preview.columns[index] + // The checkbox's state, kept here so the fields follow it + property bool on: col.include + + objectName: "guessRow_" + index + Layout.fillWidth: true + implicitHeight: body.implicitHeight + 16 + radius: Theme.radius + color: Theme.surface + + ColumnLayout { + id: body + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 8 + spacing: 4 + + CheckBox { + id: includeBox + objectName: "include" + Layout.fillWidth: true + Layout.minimumHeight: Theme.touchTarget + checked: row.on + enabled: row.col.used || row.col.canPutBack + onToggled: { + row.col.include = checked + row.on = checked + preview.recount() + } + contentItem: Label { + text: row.col.column === "" ? qsTr("(no header)") : row.col.column + color: Theme.text + wrapMode: Text.WrapAnywhere + verticalAlignment: Text.AlignVCenter + leftPadding: includeBox.indicator.width + includeBox.spacing + opacity: includeBox.enabled ? 1 : 0.6 + } + } + // Why a column was left out, and whether it can be put back + Label { + objectName: "why" + visible: !row.col.used + Layout.fillWidth: true + wrapMode: Text.WordWrap + maximumLineCount: 2 + elide: Text.ElideRight + color: Theme.textDim + font.pixelSize: 12 + text: row.col.canPutBack ? qsTr("Left out: %1. Check it to put it back.").arg(row.col.why) + : qsTr("Left out: %1").arg(row.col.why) + } + RowLayout { + visible: row.on + Layout.fillWidth: true + spacing: Theme.spacing + TextField { + objectName: "name" + Layout.fillWidth: true + Layout.preferredWidth: 0 // the row's width, not its text's + Layout.preferredHeight: Theme.touchTarget + placeholderText: qsTr("Name") + text: row.col.name + onTextChanged: row.col.name = text + } + TextField { + objectName: "unit" + Layout.preferredWidth: 72 + Layout.preferredHeight: Theme.touchTarget + placeholderText: qsTr("Unit") + text: row.col.unit + onTextChanged: row.col.unit = text + } + ThemedButton { + id: kindButton + objectName: "kind" + compact: true + Layout.preferredHeight: Theme.touchTarget + Layout.minimumWidth: Theme.touchTarget + property string kind: row.col.kind + text: kind + Accessible.name: qsTr("Kind of %1: %2, press to change").arg(row.col.column).arg(kind) + onClicked: { + kind = kind === "number" ? "text" : "number" + row.col.kind = kind + } + } + } + Label { + objectName: "samples" + Layout.fillWidth: true + wrapMode: Text.WrapAnywhere + maximumLineCount: 2 + elide: Text.ElideRight + color: Theme.textDim + font.pixelSize: 12 + font.family: Theme.monoFamily + text: row.col.samples.join(" ") + } + } + } + } + + // ---- What the guess noted ---- + ThemedButton { + objectName: "guessNotesToggle" + visible: preview.guess !== null && preview.guess.notes.length > 0 + compact: true + Layout.preferredHeight: Theme.touchTarget + text: preview.notesOpen ? qsTr("Hide notes") : qsTr("Notes (%1)").arg(preview.guess === null ? 0 : preview.guess.notes.length) + onClicked: preview.notesOpen = !preview.notesOpen + } + Label { + objectName: "guessNotes" + visible: preview.notesOpen && preview.guess !== null + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + font.pixelSize: 12 + text: preview.guess === null ? "" : preview.guess.notes.join("\n") + } + + // ---- Keep the map ---- + RowLayout { + visible: preview.guess !== null + Layout.fillWidth: true + spacing: Theme.spacing + TextField { + id: saveName + objectName: "saveMapName" + Layout.fillWidth: true + Layout.preferredWidth: 0 + Layout.preferredHeight: Theme.touchTarget + placeholderText: qsTr("Name for the map") + inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText + } + ThemedButton { + objectName: "saveMapButton" + compact: true + Layout.preferredHeight: Theme.touchTarget + text: qsTr("Save as map") + enabled: preview.ready && !Bridge.recordingImport.busy + onClicked: preview.saveAs(saveName.text) + } + } + Label { + objectName: "saveMapNote" + visible: preview.saveNote !== "" + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: preview.saveFailed ? Theme.danger : Theme.success + font.pixelSize: 13 + text: preview.saveNote + } +} diff --git a/app/qml/DangerMark.qml b/app/qml/DangerMark.qml new file mode 100644 index 00000000..bea154ed --- /dev/null +++ b/app/qml/DangerMark.qml @@ -0,0 +1,48 @@ +// File/layer: app/qml/DangerMark.qml | Qt6 Quick + Shapes, UI layer +// Testing: QML: QmlTest.gauges (test_qml) + +import QtQuick +import QtQuick.Shapes + +// The mark beside a readout once its value is past dangerFrom: a filled +// triangle with an exclamation point, so danger is told from warning by +// more than hue (the low-glare and night themes draw both in warm colors). +// The gauge shows it only while it applies. +Item { + id: mark + objectName: "dangerMark" + + property real size: 16 + + implicitWidth: size + implicitHeight: size + width: size + height: size + + Accessible.role: Accessible.Indicator + Accessible.name: qsTr("Danger") + Accessible.ignored: opacity === 0 + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeColor: Theme.gaugeDanger + strokeWidth: Math.max(1, mark.size * 0.08) + joinStyle: ShapePath.RoundJoin + fillColor: Theme.gaugeDanger + startX: mark.width / 2; startY: mark.size * 0.06 + PathLine { x: mark.width - mark.size * 0.04; y: mark.height - mark.size * 0.08 } + PathLine { x: mark.size * 0.04; y: mark.height - mark.size * 0.08 } + PathLine { x: mark.width / 2; y: mark.size * 0.06 } + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + y: mark.size * 0.30 + text: "!" + font.pixelSize: mark.size * 0.62 + font.weight: Font.Bold + color: Theme.gaugeFace + } +} diff --git a/app/qml/DashboardBook.qml b/app/qml/DashboardBook.qml new file mode 100644 index 00000000..1a993685 --- /dev/null +++ b/app/qml/DashboardBook.qml @@ -0,0 +1,550 @@ +// File/layer: app/qml/DashboardBook.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.dashboardbook (test_qml) + +pragma Singleton +import QtQml + +// The dashboards (ADR-0057) as rules on one form's document, +// { format: 1, pages: [{ name, cells: [{ kind, w, h, label, refs, unit, +// options }] }] }: a form is "phone" or "desktop", each stored as its +// own text, and a page's cells are in order, placed by place(). +// +// Reading keeps what it can (section 7): a key it doesn't know, in the +// document, a page, a cell or its options, and a kind or an accent it +// doesn't know, are kept as read and written back. A known field of the +// wrong type or out of its bounds drops its cell (or its page, for the +// page's name and cells); the document's own bounds (pages, cells on a +// page, the text's size) and an unreadable or newer text give the +// built-in layout and a problem instead, the stored text left alone. A +// read that drops a page or cell names that as its problem too, since +// the next write stores the document without it. +// +// Every function takes the document and returns a new one, never +// changing what it was given. A write that would leave a document that +// doesn't read back as it is (an 11th page, a 25th cell, the last page +// removed, an option of the wrong type) returns an unchanged copy, so +// whatever the page stores reads back equal; canAddPage, canAddCell, +// canRemovePage and cellProblem give its controls their state. +QtObject { + readonly property int format: 1 + readonly property int maxPages: 10 + readonly property int maxCells: 24 + readonly property int maxRefs: 8 + readonly property int maxLabel: 40 + readonly property int maxColumns: 12 + readonly property int maxRows: 16 + readonly property int maxBytes: 65536 + + // Append-only: a name is never reused for another drawing (section 1) + readonly property var kinds: ["analog", "ring", "bar", "segments", "digital", + "seven-segment", "sparkline", "shift-light"] + // The Theme roles a cell's accent names; any other string is kept and + // draws as "accent", the gauges' default + readonly property var accents: ["accent", "info", "success"] + + // Each known option's rule, one table for every kind: a name means + // one thing in each, and a kind ignores the ones it has no use for + readonly property var optionRules: ({ + from: { type: "number" }, to: { type: "number" }, + coldBelow: { type: "number" }, warnFrom: { type: "number" }, + dangerFrom: { type: "number" }, rise: { type: "number" }, + majorStep: { type: "positive" }, minorStep: { type: "positive" }, + labelDivisor: { type: "positive" }, + decimals: { type: "whole", min: 0, max: 6 }, + count: { type: "whole", min: 1, max: 32 }, + cells: { type: "whole", min: 2, max: 64 }, + digits: { type: "whole", min: 1, max: 8 }, + window: { type: "whole", min: 10, max: 120 }, + peak: { type: "bool" }, progress: { type: "bool" }, + vertical: { type: "bool" }, marks: { type: "bool" }, + caption: { type: "text", max: 40 }, + description: { type: "text", max: 80 }, + peakLabel: { type: "text", max: 8 }, + accent: { type: "string" } + }) + + // A new gauge's range by the unit it decodes to (section 6) + readonly property var unitRanges: ({ + "RPM": [0, 8000], "km/h": [0, 260], "\u00B0C": [0, 150], "%": [0, 100], + "kPa": [0, 300], "V": [0, 16], "g/s": [0, 300], "L/h": [0, 60] + }) + + function knownKind(kind) { + return kinds.indexOf(kind) >= 0 + } + + function knownAccent(name) { + return accents.indexOf(name) >= 0 + } + + // ---- Reading and writing the stored text + + // { doc, problem, dropped }: problem "" (read), "dropped" (read, + // with pages or cells left out: dropped holds their counts, { pages, + // cells }), "none" (no stored text), "damaged" or "newer"; doc is the + // built-in layout of the form for the last three, so the page always + // has pages to show + function parse(text, form) { + if (typeof text !== "string" || text === "") + return { doc: builtIn(form), problem: "none" } + if (utf8Bytes(text) > maxBytes) + return { doc: builtIn(form), problem: "damaged" } + let d + try { + d = JSON.parse(text) + } catch (e) { + return { doc: builtIn(form), problem: "damaged" } + } + if (!isObject(d) || !Number.isInteger(d.format) || d.format < 1) + return { doc: builtIn(form), problem: "damaged" } + if (d.format > format) + return { doc: builtIn(form), problem: "newer" } + if (!Array.isArray(d.pages) || d.pages.length > maxPages + || d.pages.some(p => isObject(p) && Array.isArray(p.cells) + && p.cells.length > maxCells)) + return { doc: builtIn(form), problem: "damaged" } + const pagesRead = d.pages.length + d.pages = d.pages.filter(p => pageProblem(p) === "") + let cellsDropped = 0 + for (const p of d.pages) { + const cellsRead = p.cells.length + p.cells = p.cells.filter(c => cellProblem(c) === "") + cellsDropped += cellsRead - p.cells.length + } + // What's left must be what a write stores: with no page left, or + // past 64 KiB once written back (1e5 is written 100000), it isn't + if (documentProblem(d) !== "") + return { doc: builtIn(form), problem: "damaged" } + const pagesDropped = pagesRead - d.pages.length + if (pagesDropped > 0 || cellsDropped > 0) + return { doc: d, problem: "dropped", + dropped: { pages: pagesDropped, cells: cellsDropped } } + return { doc: d, problem: "" } + } + + function serialize(doc) { + return JSON.stringify(doc) + } + + // What the page stores on its first edit after a read: the new text, + // and the stored text to keep in
Unread ("" for none), which + // is the stored text only when it couldn't be read, was newer or + // lost a page or cell to the read + function saveTexts(problem, stored, doc) { + const keep = problem === "damaged" || problem === "newer" || problem === "dropped" + return { text: serialize(doc), unread: keep ? String(stored) : "" } + } + + // ---- The fields' rules + + // "" when a page's own fields may be kept, else why not + function pageProblem(p) { + if (!isObject(p)) + return qsTr("A page isn't an object") + if (pageNameProblem(p.name) !== "") + return pageNameProblem(p.name) + if (!Array.isArray(p.cells)) + return qsTr("A page needs a list of cells") + return "" + } + + function pageNameProblem(name) { + if (typeof name !== "string" || name.trim() === "") + return qsTr("A page's name needs at least one character") + if (codePoints(name.trim()) > maxLabel) + return qsTr("At most %1 characters").arg(maxLabel) + return "" + } + + // "" when a cell may be kept, else why not (its own fields: the + // count of cells is the page's, judged where the page is) + function cellProblem(c) { + if (!isObject(c)) + return qsTr("A gauge isn't an object") + if (typeof c.kind !== "string" || c.kind === "") + return qsTr("A gauge needs a kind") + if (!Number.isInteger(c.w) || c.w < 1 || c.w > maxColumns) + return qsTr("A gauge is 1 to %1 columns wide").arg(maxColumns) + if (!Number.isInteger(c.h) || c.h < 1 || c.h > maxRows) + return qsTr("A gauge is 1 to %1 rows high").arg(maxRows) + if (!Array.isArray(c.refs) || !c.refs.every(r => typeof r === "string")) + return qsTr("A gauge's signals are a list of references") + if (c.refs.length > maxRefs) + return qsTr("At most %1 signals").arg(maxRefs) + if (c.label !== undefined + && (typeof c.label !== "string" || codePoints(c.label) > maxLabel)) + return qsTr("A label of at most %1 characters").arg(maxLabel) + if (c.unit !== undefined && typeof c.unit !== "string") + return qsTr("A unit is text") + if (c.options === undefined) + return "" + if (!isObject(c.options)) + return qsTr("A gauge's options are an object") + for (const name in optionRules) { + if (c.options[name] !== undefined && !optionFits(optionRules[name], c.options[name])) + return qsTr("%1 isn't a value it can take").arg(name) + } + const o = c.options + if (o.from !== undefined && o.to !== undefined && o.from >= o.to) + return qsTr("The scale's start is below its end") + return "" + } + + function optionFits(rule, v) { + switch (rule.type) { + case "number": return typeof v === "number" && isFinite(v) + case "positive": return typeof v === "number" && isFinite(v) && v > 0 + case "whole": return Number.isInteger(v) && v >= rule.min && v <= rule.max + case "bool": return typeof v === "boolean" + case "text": return typeof v === "string" && codePoints(v) <= rule.max + default: return typeof v === "string" + } + } + + // "" when the whole document reads back as it is + function documentProblem(doc) { + if (!isObject(doc) || doc.format !== format || !Array.isArray(doc.pages) + || doc.pages.length < 1 || doc.pages.length > maxPages) + return "pages" + for (const p of doc.pages) { + if (pageProblem(p) !== "" || p.cells.length > maxCells + || p.cells.some(c => cellProblem(c) !== "")) + return "page" + } + return utf8Bytes(serialize(doc)) > maxBytes ? "size" : "" + } + + // The fields a stored cell may leave out, read with their defaults + function labelOf(cell) { + return cell.label === undefined ? "" : cell.label + } + function unitOf(cell) { + return cell.unit === undefined ? "" : cell.unit + } + function optionsOf(cell) { + return cell.options === undefined ? {} : cell.options + } + + // ---- The built-in layout + + function builtIn(form) { + const phone = form === "phone" + const rpm = ["id:1001", "id:7003"] + const cell = (kind, w, h, label, refs, unit, options) => + ({ kind: kind, w: w, h: h, label: label, refs: refs, unit: unit, options: options }) + const degC = "\u00B0C" + return { + format: format, + pages: [{ + name: qsTr("Engine"), + cells: [ + cell("shift-light", 12, 1, qsTr("Shift lights"), rpm.slice(), "RPM", + { from: 4500, to: 6500, count: phone ? 11 : 15 }), + cell("analog", phone ? 1 : 2, phone ? 4 : 8, qsTr("Engine speed"), rpm.slice(), + "RPM", + { from: 0, to: 8000, majorStep: 1000, minorStep: 250, + labelDivisor: 1000, dangerFrom: 6800, + caption: qsTr("\u00D71000 r/min"), peak: true, progress: true }), + // No caption: the dial shows its unit + cell("analog", phone ? 1 : 2, phone ? 4 : 8, qsTr("Vehicle speed"), + ["id:3001", "id:7004"], "km/h", + { from: 0, to: 260, majorStep: 20, minorStep: 10, peak: true, + peakLabel: qsTr("TOP") }), + cell("ring", 1, 4, qsTr("Coolant"), ["id:2001", "id:7002"], degC, + { from: 0, to: 130, coldBelow: 60, warnFrom: 105, dangerFrom: 115 }), + cell("ring", 1, 4, qsTr("Oil temp"), ["id:9001", "id:7010"], degC, + { from: 0, to: 160, coldBelow: 70, warnFrom: 125, dangerFrom: 140 }), + cell("digital", 1, 4, qsTr("IAT"), ["id:5001", "id:7005"], degC, + { from: 0, to: 120, warnFrom: 55, dangerFrom: 70, + description: qsTr("Intake air temperature") }), + cell("digital", 1, 4, qsTr("MAF"), ["id:8001", "id:7009"], "g/s", + { from: 0, to: 300, description: qsTr("Mass air flow"), + accent: "info" }), + cell("bar", phone ? 1 : 2, 2, qsTr("Throttle"), ["id:4001", "id:7006"], "%", + { from: 0, to: 100, accent: "success" }), + cell("bar", phone ? 1 : 2, 2, qsTr("Engine load"), ["id:6001", "id:7001"], "%", + { from: 0, to: 100 }) + ] + }] + } + } + + function reset(form) { + return builtIn(form) + } + + // ---- Placement (section 4) + + // [{ x, y, w, h }] in the cells' order: each at the first free block + // of its span, rows top to bottom, columns left to right; a span + // wider than the grid takes the whole row + function place(cells, columns) { + // A width not yet laid out (0 / 0) gives no count: one column + const cols = isFinite(columns) ? Math.max(1, Math.floor(columns)) : 1 + const taken = [] // taken[y][x] + const free = (x, y, w, h) => { + for (let r = y; r < y + h; ++r) { + for (let c = x; c < x + w; ++c) { + if (taken[r] && taken[r][c]) + return false + } + } + return true + } + const out = [] + for (const cell of cells) { + const w = Math.min(cell.w, cols) + const h = cell.h + let spot = null + for (let y = 0; spot === null; ++y) { + for (let x = 0; x + w <= cols; ++x) { + if (free(x, y, w, h)) { + spot = { x: x, y: y, w: w, h: h } + break + } + } + } + for (let r = spot.y; r < spot.y + h; ++r) { + taken[r] = taken[r] || [] + for (let c = spot.x; c < spot.x + w; ++c) + taken[r][c] = true + } + out.push(spot) + } + return out + } + + // { from, to } for a new gauge: by the unit it decodes to, then the + // field's range (finite, lo below hi), then 0 to 100. Never NaN, so a + // layout never stores one + function defaultRange(unit, lo, hi) { + const byUnit = unitRanges[unit] + if (byUnit !== undefined && Object.prototype.hasOwnProperty.call(unitRanges, unit)) + return { from: byUnit[0], to: byUnit[1] } + if (typeof lo === "number" && typeof hi === "number" && isFinite(lo) && isFinite(hi) + && lo < hi) + return { from: lo, to: hi } + return { from: 0, to: 100 } + } + + // ---- Writes: each returns a new document, or an unchanged copy + + function canAddPage(doc) { + return documentProblem(doc) === "" && doc.pages.length < maxPages + } + function canRemovePage(doc) { + return documentProblem(doc) === "" && doc.pages.length > 1 + } + function canAddCell(doc, page) { + return documentProblem(doc) === "" && hasPage(doc, page) + && doc.pages[page].cells.length < maxCells + } + + function addCell(doc, page, cell) { + return write(doc, d => { + if (!hasPage(d, page) || !plain(cell)) + return false + d.pages[page].cells.push(cell) + return true + }) + } + + function removeCell(doc, page, index) { + return write(doc, d => { + if (!hasCell(d, page, index)) + return false + d.pages[page].cells.splice(index, 1) + return true + }) + } + + // The cell at from goes to place to (0 the start, the count less one + // the end): earlier, later, to the start and to the end are each one + function moveCell(doc, page, from, to) { + return write(doc, d => { + if (!hasCell(d, page, from) || !hasCell(d, page, to)) + return false + const cells = d.pages[page].cells + cells.splice(to, 0, cells.splice(from, 1)[0]) + return true + }) + } + + // The span, rounded and clamped to 1 to 12 columns and 1 to 16 rows + function resizeCell(doc, page, index, w, h) { + return write(doc, d => { + if (!hasCell(d, page, index) || typeof w !== "number" || typeof h !== "number" + || !isFinite(w) || !isFinite(h)) + return false + const c = d.pages[page].cells[index] + c.w = clamp(Math.round(w), 1, maxColumns) + c.h = clamp(Math.round(h), 1, maxRows) + return true + }) + } + + // label, refs and unit, merged; null removes label or unit, and a key + // holding undefined is left out of the change. The kind + // and the span aren't changed here (a new kind is a new cell) + function setCell(doc, page, index, fields) { + return write(doc, d => { + if (!hasCell(d, page, index) || !isObject(fields) || !plain(fields)) + return false + const c = d.pages[page].cells[index] + for (const k in fields) { + if (k !== "label" && k !== "refs" && k !== "unit") + return false + if (fields[k] === undefined) + continue + if (fields[k] === null) + delete c[k] + else + c[k] = fields[k] + } + return true + }) + } + + // Merged into the cell's options; null removes a key, and a key + // holding undefined is left out of the change. Keys this version + // doesn't know are kept, as read + function setOptions(doc, page, index, changes) { + return write(doc, d => { + if (!hasCell(d, page, index) || !isObject(changes) || !plain(changes)) + return false + const c = d.pages[page].cells[index] + const o = c.options === undefined ? {} : c.options + if (!isObject(o)) + return false + for (const k in changes) { + if (changes[k] === undefined) + continue + if (changes[k] === null) + delete o[k] + else + o[k] = changes[k] + } + c.options = o + return true + }) + } + + function addPage(doc, name) { + return write(doc, d => { + if (pageNameProblem(name) !== "") + return false + d.pages.push({ name: name.trim(), cells: [] }) + return true + }) + } + + function renamePage(doc, page, name) { + return write(doc, d => { + if (!hasPage(d, page) || pageNameProblem(name) !== "") + return false + d.pages[page].name = name.trim() + return true + }) + } + + function movePage(doc, from, to) { + return write(doc, d => { + if (!hasPage(d, from) || !hasPage(d, to)) + return false + d.pages.splice(to, 0, d.pages.splice(from, 1)[0]) + return true + }) + } + + // Never the last page: a form holds 1 to 10 + function removePage(doc, page) { + return write(doc, d => { + if (!hasPage(d, page)) + return false + d.pages.splice(page, 1) + return true + }) + } + + // ---- Helpers + + // change(copy) edits a copy and says whether it applies. The result is + // the copy as stored text reads it back (a key holding undefined left + // out, nothing shared with the caller's arguments), kept only when the + // change applies and that reads back as it is + function write(doc, change) { + if (documentProblem(doc) !== "") + return copy(doc) + const d = copy(doc) + if (!change(d)) + return copy(doc) + const out = copy(d) + return documentProblem(out) === "" ? out : copy(doc) + } + + // Whether a value a write is given is one stored text holds as it is: + // null, a boolean, a finite number, text, or a list or a plain object + // of those (an object's key holding undefined is left out). A + // function, NaN, a list holding undefined or an object of a class (a + // Date, which stored text holds as a string) isn't, and its write is + // refused + function plain(v) { + if (v === null || typeof v === "boolean" || typeof v === "string") + return true + if (typeof v === "number") + return isFinite(v) + if (Array.isArray(v)) + return v.every(e => plain(e)) + if (isObject(v) && Object.getPrototypeOf(v) === Object.prototype) + return Object.keys(v).every(k => v[k] === undefined || plain(v[k])) + return false + } + + function copy(v) { + return v === undefined ? undefined : JSON.parse(JSON.stringify(v)) + } + + function hasPage(doc, page) { + return Number.isInteger(page) && page >= 0 && page < doc.pages.length + } + + function hasCell(doc, page, index) { + return hasPage(doc, page) && Number.isInteger(index) && index >= 0 + && index < doc.pages[page].cells.length + } + + function isObject(v) { + return v !== null && typeof v === "object" && !Array.isArray(v) + } + + function clamp(v, lo, hi) { + return Math.min(hi, Math.max(lo, v)) + } + + // A label's length as a reader counts it: a character outside the + // BMP (an emoji) is one, not its two UTF-16 units + function codePoints(s) { + return s.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "_").length + } + + // The text's size as stored, in UTF-8 bytes (a lone surrogate as the + // three of its replacement character) + function utf8Bytes(s) { + let n = 0 + for (let i = 0; i < s.length; ++i) { + const u = s.charCodeAt(i) + if (u < 0x80) { + n += 1 + } else if (u < 0x800) { + n += 2 + } else if (u >= 0xD800 && u <= 0xDBFF && i + 1 < s.length + && s.charCodeAt(i + 1) >= 0xDC00 && s.charCodeAt(i + 1) <= 0xDFFF) { + n += 4 + ++i + } else { + n += 3 + } + } + return n + } +} diff --git a/app/qml/DashboardPage.qml b/app/qml/DashboardPage.qml index 1879eb9d..09dc02cd 100644 --- a/app/qml/DashboardPage.qml +++ b/app/qml/DashboardPage.qml @@ -1,13 +1,20 @@ // File/layer: app/qml/DashboardPage.qml | Qt6 Quick, UI layer -// Testing: QML: QmlTest.phone, QmlTest.dashboard, QmlTest.linkhealth -// (test_qml); Manual smoke +// Testing: QML: QmlTest.dashboard, QmlTest.dashedit, QmlTest.phone, +// QmlTest.linkhealth (test_qml); Manual smoke +import QtCore import QtQuick import QtQuick.Controls import QtQuick.Layouts pragma ComponentBehavior: Bound +// The Dashboard (ADR-0057): one form's pages of gauges, drawn from the +// form's document. DashboardBook holds the document's rules; this page +// reads it, places each page's cells on a grid and binds each cell's +// gauge to the first of its refs the session has. Edit mode (section 5) +// changes the document through DashboardBook's writes and stores each +// change as it's made. Page { id: root background: Rectangle { color: Theme.bg } @@ -16,96 +23,373 @@ Page { readonly property real margin: Theme.pageMargin readonly property real gap: compact ? 10 : 16 + // The platform's form, never the window's width (section 4) + property string form: Theme.mobile ? "phone" : "desktop" + SignalHub { id: hub } - // One gauge input: the first of `ids` (core's def IDs, from - // Bridge.gaugeSignals) the active profile provides, whatever it names - // the signal. Unit and decimals are - // core's display strings. `high` and `low` are the last window's, - // for the gauges' holds. `note` explains an empty gauge instead of - // showing a fake zero. - component Tap: QtObject { - required property var ids - readonly property SignalHub.Entry entry: hub.lookup(ids) - readonly property bool live: Bridge.connected && entry !== null && entry.hasValue - readonly property real value: entry ? entry.value : 0 - readonly property real high: entry ? entry.windowHigh : 0 - readonly property real low: entry ? entry.windowLow : 0 - readonly property bool stale: live && entry.ageMs > Theme.staleMs - readonly property string unit: entry ? entry.unit : "" - readonly property int decimals: entry ? entry.decimals : 0 - readonly property string note: !Bridge.connected ? qsTr("no session") - : entry === null ? qsTr("not in profile") - : !entry.hasValue ? qsTr("waiting for data") - : "" - } - - Tap { id: rpm; ids: Bridge.gaugeSignals.rpm } - Tap { id: speed; ids: Bridge.gaugeSignals.speed } - Tap { id: coolant; ids: Bridge.gaugeSignals.coolant } - Tap { id: oil; ids: Bridge.gaugeSignals.oil } - Tap { id: iat; ids: Bridge.gaugeSignals.iat } - Tap { id: maf; ids: Bridge.gaugeSignals.maf } - Tap { id: throttle; ids: Bridge.gaugeSignals.throttle } - Tap { id: load; ids: Bridge.gaugeSignals.load } - - // Sizes for the gauge arrangements below - QtObject { - id: fit - readonly property real w: column.width - readonly property real g: root.gap - readonly property bool narrow: w < 760 - // Narrower still, the two dials stack; above it they share the - // row, so a phone upright (about 360 px) sees both at once - readonly property bool oneDial: w < 320 - readonly property real shiftHeight: root.compact ? 40 : 48 - readonly property real barHeight: 96 - // Everything but the dials and tiles: the page margins, the - // header, the shift lights, the bars and the column's three gaps - readonly property real fixedHeight: 2 * root.margin + header.implicitHeight - + 3 * g + shiftHeight + barHeight - // The stacked arrangement at full size decides whether the page - // needs the wide one - readonly property real stackedHeight: fixedHeight - + Math.min((w - g) / 2 * 0.88, 380) + g - + Math.min((w - 3 * g) / 4 * 1.05, 220) - readonly property bool wide: w >= 900 && stackedHeight > flick.height - - readonly property int tileColumns: wide || narrow ? 2 : 4 - readonly property real tileCell: ((wide ? (w - 2 * g) / 3 : w) - (tileColumns - 1) * g) - / tileColumns - // Wide: the two tile rows share what the page has left, down to a - // floor below which the page scrolls instead - readonly property real tileHeight: wide - ? Math.max(120, Math.min(tileCell * 1.05, 220, (flick.height - fixedHeight - g) / 2)) - : Math.min(tileCell * 1.05, 220) - readonly property real dialWidth: wide ? (w - 2 * g) / 3 : oneDial ? w : (w - g) / 2 - // At most what the page shows, so a phone on its side sees a - // whole dial; below the floor the page scrolls instead - readonly property real dialHeight: wide ? 2 * tileHeight + g - : Math.min(dialWidth * 0.88, 380, - Math.max(160, flick.height - 2 * root.margin)) + // One document per form, and the page last shown on each + Settings { + id: store + objectName: "dashStore" + category: "dashboards" + property string phone: "" + property string desktop: "" + property int phonePage: 0 + property int desktopPage: 0 + // A stored text that couldn't be read, kept by the first edit + property string phoneUnread: "" + property string desktopUnread: "" + } + // The last URI that connected (SettingsPage's), whose profile's + // signals Add offers when there's no session + Settings { + id: sessionStore + category: "session" + property string uri: "" + } + + // The stored text read: the document, or the built-in layout with + // the reason when there is none or it can't be used + readonly property var parsed: DashboardBook.parse(storedText, form) + property var doc: parsed.doc + readonly property string problem: parsed.problem + // What a "dropped" read left out, in words + readonly property string droppedWords: { + const d = parsed.dropped + if (!d) + return "" + const words = [] + if (d.pages > 0) + words.push(d.pages === 1 ? qsTr("1 page") : qsTr("%1 pages").arg(d.pages)) + if (d.cells > 0) + words.push(d.cells === 1 ? qsTr("1 gauge") : qsTr("%1 gauges").arg(d.cells)) + return words.join(qsTr(" and ")) + } + readonly property var pages: doc && Array.isArray(doc.pages) ? doc.pages : [] + property bool problemDismissed: false + // A different stored text is a different problem, so its line shows again + readonly property string storedText: form === "phone" ? store.phone : store.desktop + onStoredTextChanged: problemDismissed = false + + // ---- Edit mode (section 5). Each edit is stored as it's made, so + // Done only leaves edit mode and nothing waits to be saved + + property bool editing: false + property int selected: -1 // the cell edited, on the page shown + property string panel: "" // "", "cell", "add", "signal" + property string addKind: "" // Add's kind; "" when changing a cell's signal + property bool moreShown: false + property bool confirmReset: false + property bool confirmRemovePage: false + + // The kinds this page draws, in the order Add offers them, and the + // component that makes each (a cell's and Add's preview); null for + // a kind this version doesn't draw + readonly property var drawnKinds: ["analog", "ring", "bar", "segments", "digital", + "seven-segment", "sparkline", "shift-light"] + function kindComponent(kind) { + return kind === "analog" ? analogKind + : kind === "ring" ? ringKind + : kind === "bar" ? barKind + : kind === "digital" ? digitalKind + : kind === "shift-light" ? shiftKind + : kind === "segments" ? segmentsKind + : kind === "seven-segment" ? readoutKind + : kind === "sparkline" ? sparkKind + : null + } + // The kinds that draw a peak, so the panel offers Peak hold only there + readonly property var peakKinds: ["analog", "ring", "bar", "segments"] + readonly property var kindNames: ({ + "analog": qsTr("Dial"), "ring": qsTr("Ring"), "bar": qsTr("Bar"), + "digital": qsTr("Number"), "shift-light": qsTr("Shift lights"), + "segments": qsTr("Cells"), "seven-segment": qsTr("Digits"), "sparkline": qsTr("Sparkline") + }) + // A new gauge's span: columns, and rows of a quarter column + readonly property var newSpans: ({ + "analog": [1, 4], "ring": [1, 4], "bar": [2, 2], "digital": [1, 4], + "shift-light": [12, 1], "segments": [2, 3], "seven-segment": [1, 2], "sparkline": [2, 3] + }) + + readonly property string formKey: form === "phone" ? "phone" : "desktop" + readonly property var shownCells: pages[pageIndex] && Array.isArray(pages[pageIndex].cells) + ? pages[pageIndex].cells : [] + readonly property var selectedCell: editing && selected >= 0 && selected < shownCells.length + ? shownCells[selected] : null + onSelectedCellChanged: if (selectedCell === null && panel === "cell") panel = "" + + function startEditing() { + editing = true + } + function stopEditing() { + commitTyping() + editing = false + selected = -1 + panel = "" + moreShown = false + confirmReset = false + confirmRemovePage = false + } + + // Takes the focus off a text field, so the field commits what was + // typed to the cell or page it was typed for before the selection or + // the page changes (a tap on a cell and a swipe take no focus). Its + // fields exist only in edit mode, and outside it the focus is left + // where it is. The field's own focus goes: the page is a focus scope, + // so focusing the page would give it back to the field + function commitTyping() { + if (!editing) + return + const f = Window.activeFocusItem + if (f !== null && (f instanceof TextInput || f instanceof TextEdit)) + f.focus = false + // qmllint disable missing-property + Qt.inputMethod.hide() + // qmllint enable missing-property + } + + // Stores next as this form's document, unless it's the same (a + // refused write gives an equal copy). The first edit after a stored + // text that couldn't be used keeps that text in Unread + function edit(next) { + if (DashboardBook.serialize(next) === DashboardBook.serialize(doc)) + return false + const texts = DashboardBook.saveTexts(problem, store[formKey], next) + if (texts.unread !== "") + store[formKey + "Unread"] = texts.unread + store[formKey] = texts.text + doc = next + return true } + // Back to the built-in layout: nothing stored, so a later version's + // built-in layout reaches it + function resetForm() { + const texts = DashboardBook.saveTexts(problem, store[formKey], doc) + if (texts.unread !== "") + store[formKey + "Unread"] = texts.unread + store[formKey] = "" + doc = DashboardBook.reset(form) + confirmReset = false + moreShown = false + selected = -1 + panel = "" + goTo(0) + } + + function select(i) { + commitTyping() + selected = i + panel = "cell" + } + + // ---- Add: a kind, then a signal + + property var profileRows: [] + function refreshRows() { + profileRows = Bridge.profileSignals(Bridge.connected ? Bridge.currentUri : sessionStore.uri) + } + // The rows a gauge of `kind` can show: numbers with references, an + // enumeration only on a digital tile + function pickable(kind) { + return profileRows.filter(r => r.ref !== "" && !r.isText && (!r.isEnum || kind === "digital")) + } + function startAdd() { + if (!DashboardBook.canAddCell(doc, pageIndex)) + return + commitTyping() + selected = -1 + addKind = "" + panel = "add" + } + function pickKind(kind) { + addKind = kind + refreshRows() + panel = "signal" + } + function changeSignal() { + addKind = "" + refreshRows() + panel = "signal" + } + // The picked ref and its counterparts in the other built-in set + function counterparts(ref) { + const sets = Bridge.gaugeSignals + for (const key in sets) { + const refs = sets[key] + if (refs.indexOf(ref) >= 0) + return [ref].concat(refs.filter(r => r !== ref)) + } + return [ref] + } + function labelFor(row) { + return Array.from(String(row.name)).slice(0, DashboardBook.maxLabel).join("") + } + // A new gauge's cell (section 5): the row's name, its unit and range + // as core decodes them (section 6), no zones; decimals follow the row + function newCell(kind, row) { + const span = newSpans[kind] ?? [1, 4] + const r = DashboardBook.defaultRange(row.decodedUnit, row.decodedLow, row.decodedHigh) + return { kind: kind, w: span[0], h: span[1], label: labelFor(row), + refs: counterparts(row.ref), unit: row.decodedUnit, + options: { from: r.from, to: r.to } } + } + function pickSignal(row) { + if (addKind !== "") { + if (edit(DashboardBook.addCell(doc, pageIndex, newCell(addKind, row)))) { + addKind = "" + select(shownCells.length - 1) + } + return + } + if (selected < 0) + return + // Another signal: its name, unit and range, and none of the old + // signal's zones, steps, words or decimals, which were its own + const r = DashboardBook.defaultRange(row.decodedUnit, row.decodedLow, row.decodedHigh) + let next = DashboardBook.setCell(doc, pageIndex, selected, { + refs: counterparts(row.ref), unit: row.decodedUnit, label: labelFor(row) }) + next = DashboardBook.setOptions(next, pageIndex, selected, { + from: r.from, to: r.to, coldBelow: null, warnFrom: null, dangerFrom: null, + majorStep: null, minorStep: null, labelDivisor: null, caption: null, + description: null, peakLabel: null, decimals: null }) + edit(next) + panel = "cell" + } + Connections { + target: Bridge + enabled: root.panel === "signal" + function onConnectedChanged() { root.refreshRows() } + function onUnitSystemChanged() { root.refreshRows() } + } + + // ---- The cell's panel + + function setOptions(changes) { + return edit(DashboardBook.setOptions(doc, pageIndex, selected, changes)) + } + function setLabel(text) { + return edit(DashboardBook.setCell(doc, pageIndex, selected, + { label: text === "" ? null : text })) + } + function resize(w, h) { + return edit(DashboardBook.resizeCell(doc, pageIndex, selected, w, h)) + } + // Earlier, later, to the start and to the end: the cell's place in + // the order, which both forms' grids follow + function moveTo(to) { + const t = Math.max(0, Math.min(shownCells.length - 1, to)) + if (edit(DashboardBook.moveCell(doc, pageIndex, selected, t))) + selected = t + } + function removeCell(i) { + commitTyping() + if (!edit(DashboardBook.removeCell(doc, pageIndex, i))) + return + if (selected === i) { + selected = -1 + panel = "" + } else if (selected > i) { + --selected + } + } + + // ---- The pages' edits + + function addPage() { + if (edit(DashboardBook.addPage(doc, qsTr("Page %1").arg(pages.length + 1)))) + goTo(pages.length - 1) + } + function movePage(by) { + const to = pageIndex + by + if (edit(DashboardBook.movePage(doc, pageIndex, to))) + goTo(to) + } + // Another page takes this one's index, so nothing stays selected + function removePage() { + confirmRemovePage = false + selected = -1 + panel = "" + addKind = "" + edit(DashboardBook.removePage(doc, pageIndex)) + } + + // ---- Pages + + property int pageIndex: 0 + property bool restored: false + function goTo(i) { + const n = Math.max(1, pages.length) + const to = Math.max(0, Math.min(n - 1, Math.round(i))) + if (to !== pageIndex) + commitTyping() + pageIndex = to + } + onPagesChanged: goTo(pageIndex) + // A page change closes whatever panel was open + onPageIndexChanged: { + selected = -1 + panel = "" + addKind = "" + if (swipe.count > pageIndex && swipe.currentIndex !== pageIndex) + swipe.setCurrentIndex(pageIndex) + if (!restored) return + if (form === "phone") store.phonePage = pageIndex + else store.desktopPage = pageIndex + } + + // Left and Right on the desktop form, never while a text field has + // the focus (an editable one keeps them; a read-only one would pass + // them on, though they move its cursor) + readonly property bool typing: { + const f = Window.activeFocusItem + return f !== null && (f instanceof TextInput || f instanceof TextEdit) + } + readonly property bool pageKeys: visible && form === "desktop" && pages.length > 1 && !typing + Shortcut { + sequence: "Left" + enabled: root.pageKeys + onActivated: root.goTo(root.pageIndex - 1) + } + Shortcut { + sequence: "Right" + enabled: root.pageKeys + onActivated: root.goTo(root.pageIndex + 1) + } + + // ---- The sweep and the peaks, on every page + + signal sweepRequested() + signal peaksResetRequested() + // Ignition-style sweep, once per session, the first time the page // is on screen while connected property bool sweptThisSession: false + // When the sweep was last requested (ms since the epoch) and how long + // it plays. A gauge that finishes loading within that time of it + // plays its own, so a page loaded between frames sweeps too. + property double sweptAt: 0 + property int sweepMs: 1550 + function sweepIsOn() { return Date.now() - sweptAt < sweepMs } function maybeSweep() { if (!Bridge.connected) { sweptThisSession = false + sweptAt = 0 return } if (!visible || sweptThisSession) return sweptThisSession = true - for (const g of [shiftLights, tach, speedo, coolantRing, oilRing]) g.sweep() - } - function resetPeaks() { - for (const g of [tach, speedo, coolantRing, oilRing, iatTile, mafTile, - throttleBar, loadBar]) - g.resetPeaks() + sweptAt = Date.now() + sweepRequested() } + function resetPeaks() { peaksResetRequested() } onVisibleChanged: maybeSweep() - Component.onCompleted: maybeSweep() + Component.onCompleted: { + goTo(form === "phone" ? store.phonePage : store.desktopPage) + restored = true + maybeSweep() + } Connections { target: Bridge function onConnectedChanged() { @@ -116,266 +400,1278 @@ Page { function onUnitSystemChanged() { root.resetPeaks() } } - // Scale ends and zones are written once, in the decoded units, and - // shown in the current unit system through core (ADR-0022). Reading - // Bridge.unitSystem here makes each binding follow a change. - readonly property string degC: "°C" + // ---- Units + + // Scale ends and zones are written in the unit the signal decodes + // to and shown in the current unit system through core (ADR-0022). + // Reading Bridge.unitSystem here makes each binding follow a change. function shown(unit, v) { return Bridge.unitSystem === 0 ? v : Bridge.displayValue(unit, v) } function shownUnit(unit) { return Bridge.unitSystem === 0 ? unit : Bridge.displayUnit(unit) } + // A number typed in the unit shown, in the unit stored. Each of + // core's conversions is linear, so two points give it back; six + // decimals drop the arithmetic's noise (212 deg F is 100 deg C) + function stored(unit, v) { + if (Bridge.unitSystem === 0) + return v + const a = Bridge.displayValue(unit, 0), b = Bridge.displayValue(unit, 1) + const x = b !== a ? (v - a) / (b - a) : v + return Math.round(x * 1e6) / 1e6 + } + // A number for a field: at most four decimals, none trailing + function fieldText(v) { + return typeof v === "number" && isFinite(v) ? String(Number(v.toFixed(4))) : "" + } + // A round tick spacing near `step`: 1, 2 or 5 times a power of ten + function niceStep(step) { + if (!(step > 0) || !isFinite(step)) return 1 + const p = Math.pow(10, Math.floor(Math.log(step) / Math.LN10)) + const m = step / p + return (m < 1.5 ? 1 : m < 3.5 ? 2 : m < 7.5 ? 5 : 10) * p + } - Flickable { - id: flick - anchors.fill: parent - contentWidth: width - contentHeight: column.implicitHeight + 2 * root.margin - clip: true - // Shown whenever there's more below, not only while scrolling, so - // a short window says it scrolls - ScrollBar.vertical: ScrollBar { - policy: flick.contentHeight > flick.height ? ScrollBar.AlwaysOn : ScrollBar.AsNeeded - } - - ColumnLayout { - id: column - x: (flick.width - width) / 2 - y: root.margin - width: Math.min(flick.width - 2 * root.margin, 1400) - spacing: root.gap - - // ---- Header: title, link state, peak reset - PageHeader { - id: header - title: qsTr("Dashboard") - - Rectangle { - objectName: "linkDot" - implicitWidth: 8; implicitHeight: 8 // layout-managed - radius: 4 - color: Theme.linkColor(Bridge.linkState) - } - Label { - objectName: "linkLabel" - Layout.fillWidth: true - elide: Text.ElideMiddle - // Short statuses come from Theme.linkLabel; "ok" keeps - // the richer URI text. Long-form detail (episode - // counts, error codes) stays in LiveView's banner. - text: Bridge.linkState === "ok" - ? qsTr("Live · %1").arg(Bridge.uriLabel) - : Theme.linkLabel(Bridge.linkState) - font.pixelSize: 13 - color: Theme.linkColor(Bridge.linkState) + // ---- A cell: its gauge's inputs, from the cell and its entry + + component Cell: GaugeCard { + id: card + required property var cell + // On a page two or more away from the one shown, the gauge loads + // between frames, so a full document doesn't hold back the first + // one; on the page shown and its neighbors (a swipe drags one in) + // it finishes at once + property bool later: false + // Whether this card's page is the one on screen and the app is + // active: the sparkline samples only then (a SwipeView keeps its + // neighbors visible) + property bool shown: true + property int pageNo: -1 + property int cellIndex: -1 + readonly property bool editable: root.editing && pageNo === root.pageIndex + + // The sweep plays on the dials, the cells and the shift lights only + function sweep() { + if (gauge.item && kind !== "bar" && kind !== "digital" + && kind !== "seven-segment" && kind !== "sparkline") + (gauge.item as GaugeBase).sweep() + } + + readonly property string kind: cell && typeof cell.kind === "string" ? cell.kind : "" + readonly property var options: cell && cell.options ? cell.options : ({}) + readonly property string cellUnit: cell && typeof cell.unit === "string" ? cell.unit : "" + readonly property string label: cell && typeof cell.label === "string" ? cell.label : "" + readonly property SignalHub.Entry entry: hub.lookup(cell && cell.refs ? cell.refs : []) + + readonly property bool hasValue: Bridge.connected && entry !== null && entry.hasValue + readonly property real value: entry ? entry.value : 0 + readonly property real windowHigh: entry ? entry.windowHigh : 0 + readonly property real windowLow: entry ? entry.windowLow : 0 + readonly property bool stale: hasValue && entry.ageMs > Theme.staleMs + // An enumeration's label, which only `digital` is offered + readonly property string valueLabel: entry && entry.isEnum ? entry.label : "" + + // The row's unit against the one the cell was made for (section 6) + readonly property string expectedUnit: root.shownUnit(cellUnit) + readonly property bool mismatch: entry !== null && entry.unit !== "" + && expectedUnit !== "" && entry.unit !== expectedUnit + readonly property string unit: entry && entry.unit !== "" ? entry.unit : expectedUnit + readonly property int decimals: options.decimals !== undefined ? options.decimals + : entry ? entry.decimals : 0 + + // Section 3: the first state that applies + readonly property string note: { + let words = "" + if (!Bridge.connected) words = qsTr("no session") + else if (entry === null) words = qsTr("not in this profile: %1").arg(label) + else if (entry.hidden) words = qsTr("not supported by this car") + else if (entry.refusedCode !== "") words = qsTr("refused (%1)").arg(entry.refusedCode) + else if (!entry.hasValue) words = qsTr("waiting for data") + return words !== "" && mismatch ? qsTr("%1 (expected %2)").arg(words).arg(expectedUnit) + : words + } + + function opt(name, fallback) { + return options[name] !== undefined ? options[name] : fallback + } + // A zone in the unit shown; none under another unit's row + function zone(name) { + return mismatch || options[name] === undefined ? NaN + : root.shown(cellUnit, options[name]) + } + + // The scale: the stored ends shown in the current units (a + // dial's converted end snapped to its major step), or the row's + // own range under another unit. A step that would draw more + // ticks than a face holds gives a round one instead. + readonly property var axis: { + let a = 0, b = 100 + let snap = false + const d = DashboardBook.defaultRange(cellUnit) + const f = opt("from", d.from), t = opt("to", d.to) + if (mismatch) { + const lo = entry.rangeLow, hi = entry.rangeHigh + if (isFinite(lo) && isFinite(hi) && lo < hi) { + a = lo + b = hi } - ThemedButton { - text: qsTr("Reset peaks") - onClicked: root.resetPeaks() + } else { + a = root.shown(cellUnit, f) + b = root.shown(cellUnit, t) + snap = kind === "analog" && Bridge.unitSystem !== 0 + } + if (!(a < b)) b = a + 1 + let major = opt("majorStep", NaN) + if (!(major > 0) || (b - a) / major > 40) + major = root.niceStep((b - a) / 8) + if (snap) { + const sa = a !== f ? Math.round(a / major) * major : a + const sb = b !== t ? Math.round(b / major) * major : b + if (sa < sb) { + a = sa + b = sb } } + let minor = opt("minorStep", major / 2) + if (!(minor > 0) || (b - a) / minor > 200) + minor = major / 2 + return { from: a, to: b, major: major, minor: minor } + } + readonly property real from: axis.from + readonly property real to: axis.to + readonly property real majorStep: axis.major + readonly property real minorStep: axis.minor + readonly property real coldBelow: zone("coldBelow") + readonly property real warnFrom: zone("warnFrom") + readonly property real dangerFrom: zone("dangerFrom") + readonly property color accent: { + const a = opt("accent", "accent") + return a === "info" ? Theme.info : a === "success" ? Theme.success + : Theme.gaugeValue + } - // ---- Gauges, in one of three arrangements: - // - stacked: the two dials side by side, the four tiles in a - // row below them, then the two bars; - // - narrow (a phone): one dial per row, the tiles 2 x 2, one - // bar per row; - // - wide, when the stacked arrangement would overflow a short, - // wide page (a 1080p laptop at 150 % scaling): the two dials - // and the tiles, 2 x 2, side by side in one row sized to the - // page's height. - // Each grid holds only single-cell items, so uniformCellWidths - // keeps its columns equal. - GaugeCard { - Layout.fillWidth: true - Layout.preferredHeight: fit.shiftHeight - padding: 8 - ShiftLightBar { - id: shiftLights - anchors.fill: parent - count: root.compact ? 11 : 15 - ledSpacing: root.compact ? 6 : 10 - label: qsTr("Shift lights") - value: rpm.value; windowHigh: rpm.high; windowLow: rpm.low - hasValue: rpm.live; stale: rpm.stale - from: 4500; to: 6500 + // Each kind's own + readonly property real labelDivisor: opt("labelDivisor", 1) + readonly property string caption: opt("caption", unit) + readonly property string peakLabel: opt("peakLabel", qsTr("PEAK")) + readonly property bool showPeak: opt("peak", false) + // The new kinds' own options (ADR-0057 section 1): the cells' count + // and curve, the digits, the sparkline's window, the bar standing up + // and its ticks + readonly property int cells: opt("cells", 24) + readonly property real rise: opt("rise", 1.6) + readonly property int digits: opt("digits", 4) + readonly property int windowS: opt("window", 30) + readonly property bool vertical: opt("vertical", false) + readonly property bool marks: opt("marks", true) + readonly property bool showProgress: opt("progress", false) + readonly property string description: opt("description", "") + readonly property var scaleMarks: { + const marks = [] + for (let i = 0; i <= 4; ++i) + marks.push(from + (to - from) * i / 4) + return marks + } + readonly property int count: opt("count", root.compact ? 11 : 15) + readonly property real ledSpacing: root.compact ? 6 : 10 + + readonly property bool drawn: gauge.sourceComponent !== null + padding: kind === "shift-light" ? 8 : kind === "bar" ? 14 : 12 + + readonly property var shared: ["value", "windowHigh", "windowLow", "hasValue", "stale", + "from", "to", "label", "unit", "note", "decimals", + "coldBelow", "warnFrom", "dangerFrom", "accent", "showPeak"] + readonly property var own: ({ + "analog": ["majorStep", "minorStep", "labelDivisor", "caption", "peakLabel", + "showProgress"], + "bar": ["scaleMarks", "vertical", "marks"], + "segments": ["cells", "rise"], + "seven-segment": ["digits"], + "sparkline": ["windowS", "shown"], + "digital": ["description", "valueLabel", "shown"], + "shift-light": ["count", "ledSpacing"] + }) + + // A held peak, low and trace belong to the signal that made them: + // a cell that shows another signal starts them again + onEntryChanged: if (gauge.item) (gauge.item as GaugeBase).resetPeaks() + + Loader { + id: gauge + objectName: "gauge" + anchors.fill: parent + asynchronous: card.later + sourceComponent: root.kindComponent(card.kind) + onLoaded: { + const g = item + for (const name of card.shared.concat(card.own[card.kind] ?? [])) + g[name] = Qt.binding(() => card[name]) + if (root.sweepIsOn()) card.sweep() + } + Connections { + target: root + function onSweepRequested() { card.sweep() } + function onPeaksResetRequested() { + if (gauge.item) (gauge.item as GaugeBase).resetPeaks() } } + } - GridLayout { - id: dials - objectName: "dialGrid" - Layout.fillWidth: true - columns: fit.wide ? 3 : fit.oneDial ? 1 : 2 - columnSpacing: root.gap - rowSpacing: root.gap - uniformCellWidths: true + // In edit mode a tap opens the cell's panel; on the phone a long + // press starts edit mode at the cell + TapHandler { + objectName: "cellTap" + onTapped: if (card.editable) root.select(card.cellIndex) + onLongPressed: { + if (root.form !== "phone" || card.pageNo !== root.pageIndex) + return + root.startEditing() + root.select(card.cellIndex) + } + } + // The outline and Remove exist only while the cell is editable + Loader { + z: 2 + active: card.editable && root.selected === card.cellIndex + anchors.fill: parent + anchors.margins: -card.padding + 2 + sourceComponent: Rectangle { + objectName: "cellSelected" + color: "transparent" + border.color: Theme.primary + border.width: 2 + radius: Theme.radius + } + } + Loader { + z: 3 + active: card.editable + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: -card.padding + 2 + width: Theme.touchTarget + height: Theme.touchTarget + sourceComponent: ThemedButton { + objectName: "cellRemove" + compact: true + text: "\u00D7" + Accessible.name: qsTr("Remove %1").arg(card.label) + onClicked: root.removeCell(card.cellIndex) + } + } + + // A kind this version doesn't draw, kept so it can be removed + Label { + objectName: "unknownKind" + visible: !card.drawn + anchors.centerIn: parent + width: parent.width + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.WordWrap + text: qsTr("a gauge this version of Havne doesn't have") + color: Theme.textDim + font.pixelSize: 13 + } + } + + // ---- Edit mode's panels + + // A number option, typed in the unit shown when `converted`; empty + // removes it when `clearable`, else puts the shown value back + component OptionField: TextField { + id: field + required property string option + property bool converted: true + property bool clearable: true + property real fallback: NaN + readonly property var cell: root.selectedCell + readonly property var value: { + const o = cell && cell.options ? cell.options[field.option] : undefined + return o !== undefined ? o : field.fallback + } + readonly property string shownText: cell === null ? "" + : root.fieldText(converted ? root.shown(cell.unit ?? "", value) : value) + Layout.fillWidth: true + Layout.preferredHeight: Theme.touchTarget + text: shownText + inputMethodHints: Qt.ImhFormattedNumbersOnly + onEditingFinished: { + const t = text.trim() + if (t === "" && clearable) { + root.setOptions({ [option]: null }) + } else { + const v = Number(t) + if (t !== "" && isFinite(v)) + root.setOptions({ [option]: converted ? root.stored(cell.unit ?? "", v) : v }) + } + text = Qt.binding(() => field.shownText) + } + } + + component Caption: Label { + color: Theme.textDim + font.pixelSize: 13 + } + + Component { + id: cellPanel + GaugeCard { + id: panelCard + objectName: "dashCellPanel" + readonly property real touchMin: Theme.touchTarget + readonly property var cell: root.selectedCell + readonly property string kind: cell ? cell.kind : "" + readonly property string unitShown: cell ? root.shownUnit(cell.unit ?? "") : "" + readonly property var range: DashboardBook.defaultRange(cell ? cell.unit ?? "" : "") + // The row the cell shows, whose decimals it uses until it has its own + readonly property SignalHub.Entry entry: hub.lookup(cell && cell.refs ? cell.refs : []) + readonly property bool phone: root.form === "phone" + implicitHeight: panelColumn.implicitHeight + 2 * padding + padding: 12 + + ColumnLayout { + id: panelColumn + width: parent.width + spacing: 8 - GaugeCard { - objectName: "tachCard" + RowLayout { Layout.fillWidth: true - Layout.preferredHeight: fit.dialHeight - AnalogGauge { - id: tach - anchors.fill: parent - label: qsTr("Engine speed") - caption: qsTr("×1000 r/min") - unit: rpm.unit || qsTr("RPM") - decimals: rpm.decimals - value: rpm.value; windowHigh: rpm.high; windowLow: rpm.low - hasValue: rpm.live; stale: rpm.stale; note: rpm.note - from: 0; to: 8000 - majorStep: 1000; minorStep: 250; labelDivisor: 1000 - // Danger from the shift point (6800), so the red - // zone is entered before the 7000 limiter cuts in - dangerFrom: 6800 - showProgress: true - showPeak: true + Label { + Layout.fillWidth: true + elide: Text.ElideRight + font.pixelSize: 15 + font.bold: true + color: Theme.text + text: (root.kindNames[panelCard.kind] ?? panelCard.kind) + ": " + + (panelCard.cell && panelCard.cell.label ? panelCard.cell.label : "") } - } - GaugeCard { - Layout.fillWidth: true - Layout.preferredHeight: fit.dialHeight - AnalogGauge { - id: speedo - anchors.fill: parent - label: qsTr("Vehicle speed") - caption: speed.unit || root.shownUnit("km/h") - unit: speed.unit || root.shownUnit("km/h") - decimals: speed.decimals - value: speed.value; windowHigh: speed.high; windowLow: speed.low - hasValue: speed.live; stale: speed.stale; note: speed.note - // Round ends in either system: 260 km/h, 160 mph - from: 0; to: Bridge.unitSystem === 0 ? 260 : 160 - majorStep: 20; minorStep: 10 - showPeak: true - peakLabel: qsTr("TOP") + ThemedButton { + objectName: "panelClose" + text: qsTr("Close") + onClicked: { + root.commitTyping() + root.panel = "" + } } } - // The tiles: four in a row below the dials, or 2 x 2 GridLayout { - Layout.columnSpan: fit.wide ? 1 : dials.columns Layout.fillWidth: true - columns: fit.tileColumns - columnSpacing: root.gap - rowSpacing: root.gap - uniformCellWidths: true + columns: panelCard.phone ? 2 : 4 + columnSpacing: 8 + rowSpacing: 8 - GaugeCard { + Caption { text: qsTr("Label") } + TextField { + id: labelField + objectName: "panelLabel" Layout.fillWidth: true - Layout.preferredHeight: fit.tileHeight - RingGauge { - id: coolantRing - anchors.fill: parent - label: qsTr("Coolant") - unit: coolant.unit || root.shownUnit(root.degC) - decimals: coolant.decimals - value: coolant.value; windowHigh: coolant.high; windowLow: coolant.low - hasValue: coolant.live; stale: coolant.stale - note: coolant.note - // From 0 deg C, so a cold engine at ambient reads on - // the scale instead of pinning at its start - from: root.shown(root.degC, 0); to: root.shown(root.degC, 130) - coldBelow: root.shown(root.degC, 60) - warnFrom: root.shown(root.degC, 105) - dangerFrom: root.shown(root.degC, 115) + Layout.preferredHeight: Theme.touchTarget + maximumLength: DashboardBook.maxLabel + text: panelCard.cell && panelCard.cell.label ? panelCard.cell.label : "" + onEditingFinished: { + root.setLabel(text) + text = Qt.binding(() => panelCard.cell && panelCard.cell.label + ? panelCard.cell.label : "") } } - GaugeCard { + Caption { text: qsTr("Signal") } + ThemedButton { + objectName: "panelSignal" Layout.fillWidth: true - Layout.preferredHeight: fit.tileHeight - RingGauge { - id: oilRing - anchors.fill: parent - label: qsTr("Oil temp") - unit: oil.unit || root.shownUnit(root.degC) - decimals: oil.decimals - value: oil.value; windowHigh: oil.high; windowLow: oil.low - hasValue: oil.live; stale: oil.stale - note: oil.note - // From 0 deg C, like coolant - from: root.shown(root.degC, 0); to: root.shown(root.degC, 160) - coldBelow: root.shown(root.degC, 70) - warnFrom: root.shown(root.degC, 125) - dangerFrom: root.shown(root.degC, 140) - } + text: qsTr("Change signal") + onClicked: root.changeSignal() + } + + Caption { text: qsTr("From (%1)").arg(panelCard.unitShown) } + OptionField { + objectName: "panelFrom" + option: "from" + clearable: false + fallback: panelCard.range.from + } + Caption { text: qsTr("To (%1)").arg(panelCard.unitShown) } + OptionField { + objectName: "panelTo" + option: "to" + clearable: false + fallback: panelCard.range.to + } + + Caption { text: qsTr("Cold below") } + OptionField { objectName: "panelColdBelow"; option: "coldBelow" } + Caption { text: qsTr("Warning from") } + OptionField { objectName: "panelWarnFrom"; option: "warnFrom" } + Caption { text: qsTr("Danger from") } + OptionField { objectName: "panelDangerFrom"; option: "dangerFrom" } + + Caption { text: qsTr("Decimals") } + SpinBox { + objectName: "panelDecimals" + Accessible.name: qsTr("Decimals") + Layout.preferredHeight: Theme.touchTarget + from: 0 + to: 6 + value: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.decimals !== undefined + ? panelCard.cell.options.decimals + : panelCard.entry ? panelCard.entry.decimals : 0 + onValueModified: root.setOptions({ decimals: value }) + } + + Caption { text: qsTr("Width") } + SpinBox { + objectName: "panelW" + Accessible.name: qsTr("Width") + Layout.preferredHeight: Theme.touchTarget + from: 1 + to: DashboardBook.maxColumns + value: panelCard.cell ? panelCard.cell.w : 1 + onValueModified: root.resize(value, panelCard.cell.h) + } + Caption { text: qsTr("Height") } + SpinBox { + objectName: "panelH" + Accessible.name: qsTr("Height") + Layout.preferredHeight: Theme.touchTarget + from: 1 + to: DashboardBook.maxRows + value: panelCard.cell ? panelCard.cell.h : 1 + onValueModified: root.resize(panelCard.cell.w, value) + } + + Caption { + visible: root.peakKinds.indexOf(panelCard.kind) >= 0 + text: qsTr("Peak hold") + } + Switch { + objectName: "panelPeak" + Accessible.name: qsTr("Peak hold") + visible: root.peakKinds.indexOf(panelCard.kind) >= 0 + implicitHeight: Math.max(implicitIndicatorHeight + topPadding + bottomPadding, + Theme.touchTarget) + checked: panelCard.cell && panelCard.cell.options + ? panelCard.cell.options.peak === true : false + onToggled: root.setOptions({ peak: checked }) } - GaugeCard { + + // The kind's own + Caption { visible: panelCard.kind === "analog"; text: qsTr("Major step") } + OptionField { + objectName: "panelMajorStep" + visible: panelCard.kind === "analog" + option: "majorStep" + converted: false + } + Caption { visible: panelCard.kind === "analog"; text: qsTr("Caption") } + TextField { + objectName: "panelCaption" + visible: panelCard.kind === "analog" Layout.fillWidth: true - Layout.preferredHeight: fit.tileHeight - DigitalGauge { - id: iatTile - anchors.fill: parent - label: qsTr("IAT") - description: qsTr("Intake air temperature") - unit: iat.unit || root.shownUnit(root.degC) - decimals: iat.decimals - value: iat.value; windowHigh: iat.high; windowLow: iat.low - hasValue: iat.live; stale: iat.stale; note: iat.note - from: root.shown(root.degC, 0); to: root.shown(root.degC, 120) - warnFrom: root.shown(root.degC, 55) - dangerFrom: root.shown(root.degC, 70) + Layout.preferredHeight: Theme.touchTarget + maximumLength: 40 + readonly property string current: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.caption + ? panelCard.cell.options.caption : "" + text: current + onEditingFinished: { + root.setOptions({ caption: text === "" ? null : text }) + text = Qt.binding(() => current) } } - GaugeCard { + Caption { visible: panelCard.kind === "digital"; text: qsTr("Description") } + TextField { + objectName: "panelDescription" + visible: panelCard.kind === "digital" Layout.fillWidth: true - Layout.preferredHeight: fit.tileHeight - DigitalGauge { - id: mafTile - anchors.fill: parent - label: qsTr("MAF") - description: qsTr("Mass air flow") - unit: maf.unit || root.shownUnit("g/s") - decimals: maf.decimals - value: maf.value; windowHigh: maf.high; windowLow: maf.low - hasValue: maf.live; stale: maf.stale; note: maf.note - from: 0; to: root.shown("g/s", 300) - accent: Theme.info + Layout.preferredHeight: Theme.touchTarget + maximumLength: 80 + readonly property string current: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.description + ? panelCard.cell.options.description : "" + text: current + onEditingFinished: { + root.setOptions({ description: text === "" ? null : text }) + text = Qt.binding(() => current) } } + Caption { visible: panelCard.kind === "segments"; text: qsTr("Cells") } + SpinBox { + objectName: "panelCells" + Accessible.name: qsTr("Cells") + visible: panelCard.kind === "segments" + Layout.preferredHeight: Theme.touchTarget + from: 2 + to: 64 + value: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.cells !== undefined + ? panelCard.cell.options.cells : 24 + onValueModified: root.setOptions({ cells: value }) + } + Caption { visible: panelCard.kind === "segments"; text: qsTr("Curve") } + OptionField { + objectName: "panelRise" + Accessible.name: qsTr("Curve") + visible: panelCard.kind === "segments" + option: "rise" + converted: false + fallback: 1.6 + } + Caption { visible: panelCard.kind === "seven-segment"; text: qsTr("Digits") } + SpinBox { + objectName: "panelDigits" + Accessible.name: qsTr("Digits") + visible: panelCard.kind === "seven-segment" + Layout.preferredHeight: Theme.touchTarget + from: 1 + to: 8 + value: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.digits !== undefined + ? panelCard.cell.options.digits : 4 + onValueModified: root.setOptions({ digits: value }) + } + Caption { visible: panelCard.kind === "sparkline"; text: qsTr("Window (s)") } + SpinBox { + objectName: "panelWindow" + Accessible.name: qsTr("Window (s)") + visible: panelCard.kind === "sparkline" + Layout.preferredHeight: Theme.touchTarget + from: 10 + to: 120 + stepSize: 10 + value: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.window !== undefined + ? panelCard.cell.options.window : 30 + onValueModified: root.setOptions({ window: value }) + } + Caption { visible: panelCard.kind === "bar"; text: qsTr("Standing up") } + Switch { + objectName: "panelVertical" + Accessible.name: qsTr("Standing up") + visible: panelCard.kind === "bar" + implicitHeight: Math.max(implicitIndicatorHeight + topPadding + bottomPadding, + Theme.touchTarget) + checked: panelCard.cell && panelCard.cell.options + ? panelCard.cell.options.vertical === true : false + onToggled: { + // Standing up is a tall, narrow bar: the default + // span follows the toggle, and a size the user + // chose stays + // (the resize rebinds this switch, so its state is read first) + const on = checked + const c = panelCard.cell + if (c && on && c.w === 2 && c.h === 2) + root.resize(1, 4) + else if (c && !on && c.w === 1 && c.h === 4) + root.resize(2, 2) + root.setOptions({ vertical: on }) + } + } + Caption { visible: panelCard.kind === "bar"; text: qsTr("Scale marks") } + Switch { + objectName: "panelMarks" + Accessible.name: qsTr("Scale marks") + visible: panelCard.kind === "bar" + implicitHeight: Math.max(implicitIndicatorHeight + topPadding + bottomPadding, + Theme.touchTarget) + checked: panelCard.cell && panelCard.cell.options + ? panelCard.cell.options.marks !== false : true + onToggled: root.setOptions({ marks: checked }) + } + Caption { visible: panelCard.kind === "shift-light"; text: qsTr("Lights") } + SpinBox { + objectName: "panelCount" + Accessible.name: qsTr("Lights") + visible: panelCard.kind === "shift-light" + Layout.preferredHeight: Theme.touchTarget + from: 1 + to: 32 + value: panelCard.cell && panelCard.cell.options + && panelCard.cell.options.count !== undefined + ? panelCard.cell.options.count : 15 + onValueModified: root.setOptions({ count: value }) + } + } + + // The order: both forms' grids follow it + GridLayout { + Layout.fillWidth: true + columns: panelCard.phone ? 2 : 4 + columnSpacing: 8 + rowSpacing: 8 + ThemedButton { + objectName: "panelEarlier" + Layout.fillWidth: true + enabled: root.selected > 0 + text: qsTr("Move earlier") + onClicked: root.moveTo(root.selected - 1) + } + ThemedButton { + objectName: "panelLater" + Layout.fillWidth: true + enabled: root.selected < root.shownCells.length - 1 + text: qsTr("Move later") + onClicked: root.moveTo(root.selected + 1) + } + ThemedButton { + objectName: "panelStart" + Layout.fillWidth: true + enabled: root.selected > 0 + text: qsTr("To the start") + onClicked: root.moveTo(0) + } + ThemedButton { + objectName: "panelEnd" + Layout.fillWidth: true + enabled: root.selected < root.shownCells.length - 1 + text: qsTr("To the end") + onClicked: root.moveTo(root.shownCells.length - 1) + } } } + } + } - GridLayout { - Layout.fillWidth: true - columns: fit.narrow ? 1 : 2 - columnSpacing: root.gap - rowSpacing: root.gap - uniformCellWidths: true + // Add's kinds, each with a still preview + Component { + id: addPanel + GaugeCard { + objectName: "dashAddPanel" + readonly property real touchMin: Theme.touchTarget + implicitHeight: addColumn.implicitHeight + 2 * padding + padding: 12 + ColumnLayout { + id: addColumn + width: parent.width + spacing: 8 + RowLayout { + Layout.fillWidth: true + Label { + Layout.fillWidth: true + font.pixelSize: 15 + font.bold: true + color: Theme.text + text: qsTr("Add a gauge: its kind") + } + ThemedButton { + objectName: "addClose" + text: qsTr("Close") + onClicked: { + root.commitTyping() + root.panel = "" + } + } + } + Flow { + Layout.fillWidth: true + spacing: 8 + Repeater { + model: root.drawnKinds + ColumnLayout { + id: kindTile + required property string modelData + // Comparisons, not an indexOf on an array literal: the QML + // compiler's C++ for that narrows qsizetype to int, which + // Xcode's -Wshorten-64-to-32 rejects + readonly property bool wide: modelData === "bar" + || modelData === "shift-light" + || modelData === "segments" + || modelData === "sparkline" + spacing: 4 + Loader { + objectName: "preview_" + kindTile.modelData + Layout.preferredWidth: kindTile.wide ? 200 : 120 + Layout.preferredHeight: kindTile.modelData === "shift-light" ? 40 + : kindTile.modelData === "segments" + || kindTile.modelData === "sparkline" ? 100 + : kindTile.wide || kindTile.modelData === "seven-segment" ? 70 + : 120 + sourceComponent: root.kindComponent(kindTile.modelData) + // Still: 60 percent of a 0 to 100 range, never live + onLoaded: { + const g = item as GaugeBase + g.from = 0 + g.to = 100 + g.hasValue = true + g.value = 60 + g.label = root.kindNames[kindTile.modelData] + // A sparkline's still is a made-up trace, and it + // takes no samples of its own + if (kindTile.modelData === "sparkline") { + const spark = item as SparkGauge + spark.shown = false + spark.windowS = 12 // 120 points at 10 Hz fill the box + spark.history = Array.from({ length: 120 }, + (_, i) => 55 + 25 * Math.sin(i / 10)) + } + } + } + ThemedButton { + objectName: "addKind_" + kindTile.modelData + Layout.fillWidth: true + text: root.kindNames[kindTile.modelData] + onClicked: root.pickKind(kindTile.modelData) + } + } + } + } + } + } + } - GaugeCard { + // A signal for Add's kind, or the edited cell's new one: the session's + // rows with references, or those of the last URI that connected + Component { + id: signalPanel + GaugeCard { + id: signalCard + objectName: "dashSignalPanel" + readonly property real touchMin: Theme.touchTarget + // The rows the bar leaves: every filter property shares one + // change signal, so reading active re-filters on any change + readonly property var offered: root.pickable(root.addKind !== "" ? root.addKind + : root.selectedCell ? root.selectedCell.kind : "") + readonly property var rows: { + const f = rowFilter + const all = offered + if (!f.active) + return all + return all.filter(r => f.matches(r.name, r.unit, r.group, false)) + } + implicitHeight: signalColumn.implicitHeight + 2 * padding + padding: 12 + SignalFilter { id: rowFilter } + ColumnLayout { + id: signalColumn + width: parent.width + spacing: 8 + RowLayout { Layout.fillWidth: true - Layout.preferredHeight: fit.barHeight - padding: 14 - BarGauge { - id: throttleBar - anchors.fill: parent - label: qsTr("Throttle") - unit: throttle.unit || "%" - decimals: throttle.decimals - value: throttle.value; windowHigh: throttle.high; windowLow: throttle.low - hasValue: throttle.live; stale: throttle.stale - note: throttle.note - accent: Theme.success + Label { + Layout.fillWidth: true + font.pixelSize: 15 + font.bold: true + color: Theme.text + elide: Text.ElideRight + text: root.addKind !== "" + ? qsTr("Add a gauge: a signal for the %1").arg(root.kindNames[root.addKind]) + : qsTr("A signal for this gauge") } + ThemedButton { + objectName: "signalBack" + text: qsTr("Back") + onClicked: root.panel = root.addKind !== "" ? "add" : "cell" + } + } + // The text alone: a Popup doesn't take the page's zoom, and + // Plotted only means nothing to a gauge + SignalFilterBar { + objectName: "signalFilter" + Layout.fillWidth: true + filter: rowFilter + filterButtonShown: false } - GaugeCard { + Label { + objectName: "signalNone" + visible: signalCard.rows.length === 0 Layout.fillWidth: true - Layout.preferredHeight: fit.barHeight - padding: 14 - BarGauge { - id: loadBar - anchors.fill: parent - label: qsTr("Engine load") - unit: load.unit || "%" - decimals: load.decimals - value: load.value; windowHigh: load.high; windowLow: load.low - hasValue: load.live; stale: load.stale; note: load.note + wrapMode: Text.WordWrap + color: Theme.textDim + text: signalCard.offered.length > 0 ? qsTr("No signal matches.") + : Bridge.connected ? qsTr("This session's profile has no signal a gauge can show.") + : qsTr("No signals: connect, or choose a profile in Settings.") + } + Flow { + Layout.fillWidth: true + spacing: 8 + Repeater { + model: signalCard.rows + ThemedButton { + required property var modelData + objectName: "pickSignal_" + modelData.ref + text: modelData.unit !== "" ? qsTr("%1 (%2)").arg(modelData.name).arg(modelData.unit) + : modelData.name + onClicked: root.pickSignal(modelData) + } } } } } } + + Component { id: analogKind; AnalogGauge {} } + Component { id: ringKind; RingGauge {} } + Component { id: barKind; BarGauge {} } + Component { id: digitalKind; DigitalGauge {} } + Component { id: shiftKind; ShiftLightBar {} } + Component { id: segmentsKind; SegmentGauge {} } + Component { id: readoutKind; SegmentReadout {} } + Component { id: sparkKind; SparkGauge {} } + + // The link's dot and words + Component { + id: linkState + RowLayout { + spacing: 10 + Rectangle { + objectName: "linkDot" + implicitWidth: 8; implicitHeight: 8 // layout-managed + radius: 4 + color: Theme.linkColor(Bridge.linkState) + } + Label { + objectName: "linkLabel" + Layout.fillWidth: true + elide: Text.ElideMiddle + // Short statuses come from Theme.linkLabel; "ok" keeps + // the richer URI text. Long-form detail (episode + // counts, error codes) stays in LiveView's banner. + text: Bridge.linkState === "ok" + ? qsTr("Live · %1").arg(Bridge.uriLabel) + : Theme.linkLabel(Bridge.linkState) + font.pixelSize: 13 + color: Theme.linkColor(Bridge.linkState) + } + } + } + + // ---- The header: title, link state, peak reset; the desktop's + // page buttons; why the stored layout isn't shown + + ColumnLayout { + id: topBar + x: (root.width - width) / 2 + y: root.margin + width: Math.max(0, root.width - 2 * root.margin) + spacing: root.gap / 2 + + PageHeader { + id: header + Layout.fillWidth: true + title: qsTr("Dashboard") + // At a narrow width the row's buttons are compact, the link + // state gives way first and the title last, so the row fits + // whatever the font's widths + titleShrinks: true + // Reset peaks and Edit at a phone's touch size + readonly property real touchMin: Theme.touchTarget + + // The desktop's link state follows the title; the phone's + // row has no room for it beside Reset peaks and Edit, so it + // takes a line of its own below, except on its side, where + // the row has the width and the line's height is the + // gauges'. No width of its own: it takes what the title and + // buttons leave + Loader { + objectName: "linkInRow" + Layout.fillWidth: true + Layout.preferredWidth: 0 + active: root.form !== "phone" || Theme.shortLayout + visible: active + sourceComponent: linkState + } + Item { + Layout.fillWidth: true + visible: root.form === "phone" && !Theme.shortLayout + } + ThemedButton { + objectName: "resetPeaks" + compact: root.compact + text: qsTr("Reset peaks") + onClicked: root.resetPeaks() + } + ThemedButton { + objectName: "dashEdit" + compact: root.compact + visible: !root.editing + text: qsTr("Edit") + onClicked: root.startEditing() + } + } + + Loader { + objectName: "linkLine" + Layout.fillWidth: true + active: root.form === "phone" && !Theme.shortLayout + visible: active + sourceComponent: linkState + } + + // What the log did without being asked: Start log's refusal, or + // an end the user didn't ask for (a failed write, the session's + // end), in words beside a warning dot, until Dismiss or the next + // log. Start log sits in Main's header, so the bridge holds the + // words (Bridge.logNotice) and this page shows them + RowLayout { + objectName: "dashLogNotice" + Layout.fillWidth: true + visible: Bridge.logNotice !== "" + spacing: 10 + Rectangle { + implicitWidth: 8; implicitHeight: 8 // layout-managed + radius: 4 + color: Theme.warning + } + Label { + objectName: "dashLogNoticeText" + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.text + font.pixelSize: 13 + text: Bridge.logNotice + } + ThemedButton { + objectName: "dashLogNoticeDismiss" + compact: true + text: qsTr("Dismiss") + Accessible.name: qsTr("Dismiss the log's notice") + onClicked: Bridge.clearLogNotice() + } + } + + // Edit mode's bar: three buttons, compact on the phone, so its + // row holds them + RowLayout { + objectName: "dashEditBar" + readonly property real touchMin: Theme.touchTarget + Layout.fillWidth: true + visible: root.editing + spacing: 8 + ThemedButton { + objectName: "dashDone" + compact: root.form === "phone" + highlighted: true + text: qsTr("Done") + onClicked: root.stopEditing() + } + ThemedButton { + objectName: "dashAdd" + compact: root.form === "phone" + enabled: DashboardBook.canAddCell(root.doc, root.pageIndex) + text: qsTr("Add gauge") + onClicked: root.startAdd() + } + ThemedButton { + objectName: "dashMore" + compact: root.form === "phone" + highlighted: root.moreShown + text: qsTr("Pages") + onClicked: { + root.moreShown = !root.moreShown + root.confirmReset = false + root.confirmRemovePage = false + } + } + Item { Layout.fillWidth: true } + } + + // The pages' controls and Reset, in the page (never a menu) + Flow { + objectName: "dashMoreRow" + readonly property real touchMin: Theme.touchTarget + Layout.fillWidth: true + visible: root.editing && root.moreShown && !root.confirmReset && !root.confirmRemovePage + spacing: 8 + TextField { + id: pageName + objectName: "moreRename" + width: Math.min(220, parent.width) + height: Theme.touchTarget + maximumLength: DashboardBook.maxLabel + text: root.pages[root.pageIndex] ? root.pages[root.pageIndex].name : "" + placeholderText: qsTr("Page name") + Accessible.name: qsTr("This page's name") + onEditingFinished: { + root.edit(DashboardBook.renamePage(root.doc, root.pageIndex, text)) + text = Qt.binding(() => root.pages[root.pageIndex] + ? root.pages[root.pageIndex].name : "") + } + } + ThemedButton { + objectName: "moreAddPage" + enabled: DashboardBook.canAddPage(root.doc) + text: qsTr("Add page") + onClicked: root.addPage() + } + ThemedButton { + objectName: "moreLeft" + enabled: root.pageIndex > 0 + text: qsTr("Move page left") + onClicked: root.movePage(-1) + } + ThemedButton { + objectName: "moreRight" + enabled: root.pageIndex < root.pages.length - 1 + text: qsTr("Move page right") + onClicked: root.movePage(1) + } + ThemedButton { + objectName: "moreRemovePage" + enabled: DashboardBook.canRemovePage(root.doc) + text: qsTr("Remove page") + onClicked: root.confirmRemovePage = true + } + ThemedButton { + objectName: "moreReset" + text: qsTr("Reset") + onClicked: root.confirmReset = true + } + } + RowLayout { + objectName: "dashRemovePageConfirm" + readonly property real touchMin: Theme.touchTarget + Layout.fillWidth: true + visible: root.editing && root.confirmRemovePage + spacing: 8 + Label { + objectName: "removePageQuestion" + Layout.fillWidth: true + Layout.minimumWidth: 0 + wrapMode: Text.WordWrap + color: Theme.warning + font.pixelSize: 13 + text: qsTr("Remove the page \"%1\" and its gauges?") + .arg(root.pages[root.pageIndex] ? root.pages[root.pageIndex].name : "") + } + ThemedButton { + objectName: "removePageConfirm" + compact: root.form === "phone" + text: qsTr("Remove") + onClicked: root.removePage() + } + ThemedButton { + objectName: "removePageKeep" + compact: root.form === "phone" + text: qsTr("Keep") + onClicked: root.confirmRemovePage = false + } + } + RowLayout { + objectName: "dashResetConfirm" + readonly property real touchMin: Theme.touchTarget + Layout.fillWidth: true + visible: root.editing && root.confirmReset + spacing: 8 + Label { + Layout.fillWidth: true + Layout.minimumWidth: 0 + wrapMode: Text.WordWrap + color: Theme.warning + font.pixelSize: 13 + text: qsTr("Replace this form's pages with the built-in layout?") + } + ThemedButton { + objectName: "resetConfirm" + compact: root.form === "phone" + text: qsTr("Reset") + onClicked: root.resetForm() + } + ThemedButton { + objectName: "resetKeep" + compact: root.form === "phone" + text: qsTr("Keep") + onClicked: root.confirmReset = false + } + } + + Flow { + objectName: "dashPageButtons" + Layout.fillWidth: true + visible: root.form === "desktop" && root.pages.length > 1 + spacing: 6 + Repeater { + model: root.pages.length + ThemedButton { + required property int index + objectName: "dashPageButton_" + index + compact: true + highlighted: index === root.pageIndex + text: root.pages[index] && root.pages[index].name + ? root.pages[index].name : qsTr("Page %1").arg(index + 1) + onClicked: root.goTo(index) + } + } + } + + RowLayout { + objectName: "dashProblem" + Layout.fillWidth: true + visible: (root.problem === "damaged" || root.problem === "newer" + || root.problem === "dropped") && !root.problemDismissed + Label { + objectName: "dashProblemText" + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.warning + font.pixelSize: 13 + text: root.problem === "newer" + ? qsTr("The saved dashboard was made by a newer version of Havne. " + + "This shows the built-in one; the saved one is kept.") + : root.problem === "dropped" + ? qsTr("Part of the saved dashboard couldn't be read: %1 left out. " + + "The saved text is kept.").arg(root.droppedWords) + : qsTr("The saved dashboard couldn't be read. " + + "This shows the built-in one; the saved text is kept.") + } + ThemedButton { + objectName: "dashProblemDismiss" + compact: true + text: qsTr("Dismiss") + onClicked: root.problemDismissed = true + } + } + } + + // ---- The pages: one SwipeView, swiped on the phone form, moved by + // the buttons and keys on the desktop form + + SwipeView { + id: swipe + objectName: "dashPages" + anchors.left: parent.left + anchors.right: parent.right + anchors.top: topBar.bottom + anchors.bottom: indicator.visible ? indicator.top : parent.bottom + clip: true + interactive: root.form === "phone" + // The page shown goes in once every page is in: the first page + // added makes the index 0, which would override a stored one + onCountChanged: { + if (count === root.pages.length && currentIndex !== root.pageIndex) + setCurrentIndex(root.pageIndex) + } + onCurrentIndexChanged: { + if (count === root.pages.length && currentIndex >= 0) { + if (currentIndex !== root.pageIndex) + root.commitTyping() + root.pageIndex = currentIndex + } + } + + Repeater { + model: root.pages.length + + Flickable { + id: pageView + required property int index + readonly property var page: root.pages[index] + readonly property var cells: page && Array.isArray(page.cells) ? page.cells : [] + objectName: "dashPage_" + index + clip: true + contentWidth: width + contentHeight: grid.y + grid.height + root.margin + // Shown whenever there's more below, not only while + // scrolling, so a short window says it scrolls + ScrollBar.vertical: ScrollBar { + policy: pageView.contentHeight > pageView.height ? ScrollBar.AlwaysOn + : ScrollBar.AsNeeded + } + + // The grid (section 4): the phone's 2 columns upright and + // 4 on its side, the desktop's one per 220 px from 2 to 12 + readonly property real gridWidth: Math.max(0, width - 2 * root.margin) + readonly property int columns: root.form === "phone" + ? (root.width > root.height ? 4 : 2) + : Math.max(2, Math.min(12, Math.round(gridWidth / 220))) + readonly property real columnWidth: Math.max(0, (gridWidth - (columns - 1) + * root.gap) / columns) + readonly property bool shown: index === root.pageIndex + // In edit mode the page ends with a "+" cell while it has room + readonly property bool addCell: root.editing && shown + && DashboardBook.canAddCell(root.doc, index) + readonly property var placed: addCell ? cells.concat([{ w: 1, h: 2 }]) : cells + readonly property var boxes: DashboardBook.place(placed, columns) + readonly property int tallest: placed.reduce((m, c) => Math.max(m, c.h), 1) + // The row unit is a quarter of a column, so h = 4w is + // square; never so tall that the tallest cell overflows + // what the page shows, down to a floor of 160 px, below + // which the page scrolls instead + readonly property real pitch: Math.max(1, Math.min( + (columnWidth + root.gap) / 4, + (Math.max(160, height - 2 * root.margin) + root.gap) / tallest)) + readonly property int rows: boxes.reduce((m, b) => Math.max(m, b.y + b.h), 0) + + // The edit panel, in the page above its grid (never a Popup) + Loader { + id: panelHost + objectName: "dashPanel" + x: (pageView.width - width) / 2 + y: root.margin + width: pageView.gridWidth + active: root.editing && pageView.shown && root.panel !== "" + sourceComponent: root.panel === "cell" ? cellPanel + : root.panel === "add" ? addPanel + : root.panel === "signal" ? signalPanel : null + onLoaded: pageView.contentY = 0 + } + + Label { + objectName: "dashEmptyPage" + visible: pageView.cells.length === 0 && !root.editing + x: root.margin + y: root.margin + width: pageView.gridWidth + wrapMode: Text.WordWrap + color: Theme.textDim + text: qsTr("No gauges on this page. Edit adds them.") + } + + Item { + id: grid + x: (pageView.width - width) / 2 + y: root.margin + (panelHost.item ? (panelHost.item as Item).height + root.gap : 0) + width: pageView.gridWidth + height: Math.max(0, pageView.rows * pageView.pitch - root.gap) + + Repeater { + model: pageView.cells.length + + Cell { + required property int index + readonly property var box: pageView.boxes[index] + objectName: "dashCell_" + pageView.index + "_" + index + cell: pageView.cells[index] + pageNo: pageView.index + cellIndex: index + later: pageView !== null && Math.abs(pageView.index - root.pageIndex) > 1 + // qmllint disable missing-property + shown: pageView !== null && pageView.index === root.pageIndex + && Qt.application.state !== Qt.ApplicationSuspended + && Qt.application.state !== Qt.ApplicationHidden + // qmllint enable missing-property + x: box ? box.x * (pageView.columnWidth + root.gap) : 0 + y: box ? box.y * pageView.pitch : 0 + width: box ? box.w * pageView.columnWidth + (box.w - 1) * root.gap : 0 + height: box ? Math.max(0, box.h * pageView.pitch - root.gap) : 0 + } + } + + ThemedButton { + readonly property var box: pageView.boxes[pageView.cells.length] + objectName: "dashAddCell_" + pageView.index + visible: pageView.addCell + x: box ? box.x * (pageView.columnWidth + root.gap) : 0 + y: box ? box.y * pageView.pitch : 0 + width: box ? pageView.columnWidth : 0 + height: box ? Math.max(Theme.touchTarget, box.h * pageView.pitch - root.gap) : 0 + text: "+" + font.pixelSize: 28 + Accessible.name: qsTr("Add a gauge") + onClicked: root.startAdd() + } + } + } + } + } + + PageIndicator { + id: indicator + objectName: "dashIndicator" + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + visible: root.form === "phone" && root.pages.length > 1 + count: swipe.count + currentIndex: swipe.currentIndex + } } diff --git a/app/qml/DiagnosticsPage.qml b/app/qml/DiagnosticsPage.qml index 14840eed..77f7af89 100644 --- a/app/qml/DiagnosticsPage.qml +++ b/app/qml/DiagnosticsPage.qml @@ -27,6 +27,12 @@ Page { signal connectRequested() readonly property var ecus: Bridge.diagnostics + // The vehicles, Settings' VehicleBook document (Main binds it): the + // report names the picked vehicle's baseline recording by its start, + // never its folder (ADR-0049's appendix "a vehicle's baseline") + property var vehicles: VehicleBook.empty() + readonly property var pickedVehicle: VehicleBook.picked(vehicles) + readonly property string baselineFolder: pickedVehicle !== null ? pickedVehicle.baseline : "" // Read again needs a session and a read that has settled readonly property bool canReadAgain: Bridge.connected && ecus.some(e => e.asked && e.complete) @@ -75,9 +81,9 @@ Page { } // The health report to url, its format by the dialog's filter or the - // file's name; true when written + // file's name, naming the picked vehicle's baseline; true when written function saveReportTo(url, filterIndex) { - const r = Bridge.saveHealthReport(url, filterIndex) + const r = Bridge.saveHealthReport(url, filterIndex, baselineFolder) reportFailed = !r.ok reportNote = r.ok ? qsTr("Report saved: %1").arg(r.summary) : qsTr("Report not saved: %1").arg(r.words) diff --git a/app/qml/DigitalGauge.qml b/app/qml/DigitalGauge.qml index b14de59d..8beec674 100644 --- a/app/qml/DigitalGauge.qml +++ b/app/qml/DigitalGauge.qml @@ -17,6 +17,9 @@ GaugeBase { property string description: "" // second line under the label property int historyLength: 80 // samples at the 10 Hz clock below property var history: [] + // Whether the page holding this tile is on screen: a tile on another + // page takes no samples (its trace picks up where it stopped) + property bool shown: true // Clear with the peaks, so a new session draws a fresh trace onPeaksReset: history = [] @@ -26,7 +29,8 @@ GaugeBase { Timer { interval: 100 repeat: true - running: gauge.hasValue && gauge.visible + objectName: "sampler" + running: gauge.hasValue && gauge.visible && gauge.shown onTriggered: { const h = gauge.history.slice(1 - gauge.historyLength) h.push(gauge.value) @@ -36,7 +40,7 @@ GaugeBase { readonly property bool roomy: height >= 160 readonly property color levelColor: gauge.hasValue - ? gauge.zoneColor(gauge.value, Theme.text) + ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim // Polyline for the sparkline, newest sample on the right edge. @@ -91,6 +95,7 @@ GaugeBase { // Live dot: zone color while fresh, hollow without data Rectangle { id: status + objectName: "statusDot" anchors { right: parent.right; top: parent.top; topMargin: 3 } width: 8; height: 8; radius: 4 color: gauge.hasValue && !gauge.stale ? gauge.zoneColor(gauge.value, Theme.success) @@ -106,13 +111,24 @@ GaugeBase { opacity: gauge.stale ? 0.45 : 1.0 Text { id: readout + objectName: "readout" text: gauge.valueText font.pixelSize: Math.max(18, Math.min(valueBand.height * 0.9, gauge.width * 0.24)) font.weight: Font.DemiBold font.features: ({ "tnum": 1 }) color: gauge.levelColor } + // Past dangerFrom, beside the value + DangerMark { + // The slot stays once a gauge has a danger zone, so the readout + // never moves as the mark appears + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: Math.max(14, readout.font.pixelSize * 0.55) + anchors.verticalCenter: readout.verticalCenter + } Text { + objectName: "unit" visible: gauge.hasValue anchors.baseline: readout.baseline text: gauge.unit @@ -138,7 +154,7 @@ GaugeBase { [Qt.point(width, height)]) ShapePath { // baseline - strokeColor: Qt.alpha(Theme.text, 0.06) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.06) strokeWidth: 1 fillColor: "transparent" startX: 0; startY: trace.height - 0.5 diff --git a/app/qml/FrameFilterPanel.qml b/app/qml/FrameFilterPanel.qml new file mode 100644 index 00000000..c0bdfea2 --- /dev/null +++ b/app/qml/FrameFilterPanel.qml @@ -0,0 +1,218 @@ +// File/layer: app/qml/FrameFilterPanel.qml | Qt Quick, UI layer +// Testing: QML: QmlTest.log, QmlTest.recordings, QmlTest.phone (test_qml) + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +// The filter's fields over a FrameListModel (framefilter.h): the columns a +// bus is read by. The Log page and the recording viewer share it. +GridLayout { + id: panel + objectName: "filterPanel" + Layout.fillWidth: true + columns: 2 + columnSpacing: Theme.spacing + rowSpacing: Theme.spacing / 2 + + // The FrameListModel the fields filter + required property var frames + // FrameFilter::Direction's order: All, Received, Sent + property int direction: 0 + + // The fields to the model, which keeps the last good part of a field + // that doesn't parse and says why + function apply() { + const r = panel.frames.setFilter(filterIds.text, filterData.text, + panel.direction, filterFlag.currentIndex, + filterLengths.text, filterTimes.text) + filterIdsProblem.text = r.ids + filterDataProblem.text = r.data + filterLengthsProblem.text = r.lengths + filterTimesProblem.text = r.times + } + + function clear() { + filterIds.text = "" + filterData.text = "" + filterLengths.text = "" + filterTimes.text = "" + filterFlag.currentIndex = 0 + panel.direction = 0 + apply() + } + + // One ID's frames alone. The ID filter takes a number of either + // width, so the row's own width is the flag: a standard 0x7E8 leaves + // an extended 0x7E8 out, as an extended one leaves the standard one out + function showId(id, extended) { + filterIds.text = id.toString(16).toUpperCase() + filterFlag.currentIndex = extended ? 1 : 2 // Extended (29-bit), Standard (11-bit) + apply() + } + + Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 13 } + TextField { + id: filterIds + objectName: "filterIds" + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + placeholderText: qsTr("7E8, 7E0-7EF") + font.family: Theme.monoFamily + inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText + onTextEdited: panel.apply() + } + Item { visible: filterIdsProblem.visible } // the label column, empty + Label { + id: filterIdsProblem + objectName: "filterIdsProblem" + visible: text !== "" + color: Theme.warning + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + } + + Label { text: qsTr("Data"); color: Theme.textDim; font.pixelSize: 13 } + TextField { + id: filterData + objectName: "filterData" + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + placeholderText: qsTr("^62 F1 ??") + font.family: Theme.monoFamily + inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText + onTextEdited: panel.apply() + } + Item { visible: filterDataProblem.visible } // the label column, empty + Label { + id: filterDataProblem + objectName: "filterDataProblem" + visible: text !== "" + color: Theme.warning + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + } + + // The data length in bytes, and a span of the table's seconds + Label { text: qsTr("Length"); color: Theme.textDim; font.pixelSize: 13 } + RowLayout { + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + spacing: Theme.spacing + TextField { + id: filterLengths + objectName: "filterLengths" + Layout.fillWidth: true + Layout.preferredWidth: 0 // half the row, not its text's + placeholderText: qsTr("8, 1-7") + font.family: Theme.monoFamily + inputMethodHints: Qt.ImhPreferNumbers | Qt.ImhNoPredictiveText + onTextEdited: panel.apply() + } + Label { text: qsTr("Time"); color: Theme.textDim; font.pixelSize: 13 } + TextField { + id: filterTimes + objectName: "filterTimes" + Layout.fillWidth: true + Layout.preferredWidth: 0 // half the row, not its text's + placeholderText: qsTr("12.5-30") + font.family: Theme.monoFamily + inputMethodHints: Qt.ImhFormattedNumbersOnly | Qt.ImhNoPredictiveText + onTextEdited: panel.apply() + } + } + Item { visible: filterLengthsProblem.visible } // the label column, empty + Label { + id: filterLengthsProblem + objectName: "filterLengthsProblem" + visible: text !== "" + color: Theme.warning + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + } + Item { visible: filterTimesProblem.visible } // the label column, empty + Label { + id: filterTimesProblem + objectName: "filterTimesProblem" + visible: text !== "" + color: Theme.warning + font.pixelSize: 12 + wrapMode: Text.Wrap + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + } + + Flow { + Layout.columnSpan: 2 + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + spacing: Theme.spacing + + Rectangle { + implicitWidth: directionSwitch.implicitWidth + 4 + implicitHeight: directionSwitch.implicitHeight + 4 + radius: Theme.radius + color: Theme.surface + + Row { + id: directionSwitch + anchors.centerIn: parent + spacing: 2 + Repeater { + model: [qsTr("All"), qsTr("Received"), qsTr("Sent")] + SegmentButton { + required property string modelData + required property int index + objectName: "direction_" + index + text: modelData + selected: panel.direction === index + onClicked: { + panel.direction = index + panel.apply() + } + } + } + } + } + ComboBox { + id: filterFlag + objectName: "filterFlag" + // FrameFilter::Flag's order + model: [qsTr("Any flag"), qsTr("Extended (29-bit)"), + qsTr("Standard (11-bit)"), qsTr("CAN FD"), + qsTr("Reassembled"), qsTr("Truncated"), + qsTr("After a loss"), qsTr("Error")] + implicitHeight: Theme.controlHeight + onActivated: panel.apply() + } + ThemedButton { + objectName: "filterClear" + text: qsTr("Clear the filter") + enabled: panel.frames.filterTerms > 0 || filterIds.text !== "" + || filterData.text !== "" || filterLengths.text !== "" + || filterTimes.text !== "" + onClicked: panel.clear() + } + } + // No transport reports the frames it sends yet, so Sent + // shows none: said, so an empty table doesn't read as lost + Label { + objectName: "sentNote" + visible: panel.direction === 2 + Layout.columnSpan: 2 + Layout.fillWidth: true + Layout.preferredWidth: 0 // the panel's width, not its text's + text: qsTr("No adapter reports the frames the session sends yet, so Sent shows none") + color: Theme.textDim + font.pixelSize: 12 + wrapMode: Text.Wrap + } +} diff --git a/app/qml/FrameIdList.qml b/app/qml/FrameIdList.qml new file mode 100644 index 00000000..e700df72 --- /dev/null +++ b/app/qml/FrameIdList.qml @@ -0,0 +1,159 @@ +// File/layer: app/qml/FrameIdList.qml | Qt Quick, UI layer +// Testing: QML: QmlTest.log, QmlTest.recordings, QmlTest.phone (test_qml) + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +// One row per ID over the frames a table shows (FrameIdModel), the bytes +// that changed from the ID's frame before marked. +Rectangle { + id: idTable + // The FrameIdModel: one row per ID over the frames a table shows + required property var ids + // True while the list is in view: it reads the model again twice a + // second then + property bool refreshing: false + // Shown while there is no row + property string emptyText: "" + // A row tapped + signal idTapped(var id, bool extended) + + // Frames a second, as the rows show them + function rateText(rate) { + return rate <= 0 ? "-" : rate < 10 ? rate.toFixed(1) + "/s" : Math.round(rate) + "/s" + } + + // A row's payload with the bytes that changed from the frame before + // marked, as styled text: the payload's spaced hex and the changed + // positions, both from the model + function markedPayload(hex, changed) { + if (!changed || changed.length === 0) + return hex + const bytes = hex.split(" ") + for (const at of changed) { + if (at < bytes.length) + bytes[at] = "" + bytes[at] + "" + } + return bytes.join(" ") + } + + Layout.fillWidth: true + Layout.fillHeight: true + radius: Theme.radius + color: Theme.surface + clip: true + + // Read again twice a second while it shows (FrameIdModel) + Timer { + interval: 500 + repeat: true + running: idTable.refreshing && idTable.visible + onTriggered: idTable.ids.refresh() + } + + Rectangle { + id: idHeader + anchors { top: parent.top; left: parent.left; right: parent.right } + height: 32 + z: 2 + color: Theme.elevated + + RowLayout { + anchors.fill: parent + anchors.leftMargin: 12 + anchors.rightMargin: 12 + spacing: 8 + // Widths MUST match the delegate's columns below + Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 12; + Layout.preferredWidth: 104 } // a 29-bit ID and its E + Label { text: qsTr("Frames"); color: Theme.textDim; font.pixelSize: 12; + Layout.preferredWidth: 52 } + Label { text: qsTr("Rate"); color: Theme.textDim; font.pixelSize: 12; + Layout.preferredWidth: 52 } + Label { text: qsTr("Last payload"); color: Theme.textDim; font.pixelSize: 12; + Layout.fillWidth: true; elide: Text.ElideRight } + } + } + + ListView { + id: idList + objectName: "idList" + anchors { top: idHeader.bottom; left: parent.left + right: parent.right; bottom: parent.bottom } + anchors.margins: 4 + clip: true + model: idTable.ids + ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } + + delegate: Rectangle { + id: idRow + readonly property bool narrow: ListView.view !== null + && ListView.view.width < 480 + width: ListView.view !== null ? ListView.view.width : 0 + height: Math.max(Theme.rowHeight, idPayload.implicitHeight + 8) + radius: 4 + color: "transparent" + + required property var model + required property int index + + // A tap reads this ID's frames: the filter takes it + MouseArea { + objectName: "idRowArea" + anchors.fill: parent + onClicked: idTable.idTapped(idRow.model.arbId, idRow.model.extended) + } + + RowLayout { + anchors.fill: parent + anchors.leftMargin: 8 + anchors.rightMargin: 8 + spacing: 8 + Label { + text: "0x" + idRow.model.arbId.toString(16).toUpperCase() + + (idRow.model.extended ? " E" : "") + color: Theme.text + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: 104 + elide: Text.ElideRight + } + Label { + text: idRow.model.frames + color: Theme.textDim + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: 52 + } + Label { + text: idTable.rateText(idRow.model.rate) + color: Theme.textDim + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: 52 + } + // The bytes that changed from the ID's frame + // before, in the warning color and bold + Label { + id: idPayload + objectName: "idPayload" + text: idTable.markedPayload(idRow.model.payloadHex, + idRow.model.changedBytes) + textFormat: Text.StyledText + color: Theme.text + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.fillWidth: true + wrapMode: idRow.narrow ? Text.Wrap : Text.NoWrap // between bytes + elide: idRow.narrow ? Text.ElideNone : Text.ElideRight + } + } + } + + Label { + anchors.centerIn: parent + visible: idList.count === 0 + text: idTable.emptyText + color: Theme.textDim + } + } +} diff --git a/app/qml/FrameTable.qml b/app/qml/FrameTable.qml new file mode 100644 index 00000000..6d637b42 --- /dev/null +++ b/app/qml/FrameTable.qml @@ -0,0 +1,271 @@ +// File/layer: app/qml/FrameTable.qml | Qt Quick, UI layer +// Testing: QML: QmlTest.log, QmlTest.recordings, QmlTest.phone (test_qml) + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +// A FrameListModel's rows as a table. The Log page's live frames and the +// recording viewer's frames share it; what a tap does is the user's. +Rectangle { + id: table + // The FrameListModel the rows come from + required property var frames + // True for the live session: new rows land at one end and the view + // follows them. A recording's rows are a fixed set + property bool live: true + // Shown while the table has no rows + property string emptyText: "" + // A phone's width: the table leaves out DLC, narrows its columns and + // wraps the payload under itself rather than cut it off + readonly property bool narrowTable: frameList.width < 480 // the rows' narrow too + // The wide table's Flags column + readonly property int flagsWidth: 96 + // A row tapped: its index, the keyboard modifiers held and its time in + // microseconds, as the table shows it + signal rowClicked(int index, int modifiers, real timestampUs) + + Layout.fillWidth: true + Layout.fillHeight: true + radius: Theme.radius + color: Theme.surface + clip: true + + // Column header + Rectangle { + id: columnHeader + anchors { top: parent.top; left: parent.left; right: parent.right } + height: 32 + z: 2 + color: Theme.elevated + + RowLayout { + anchors.fill: parent + anchors.leftMargin: 12 + anchors.rightMargin: 12 + spacing: 8 + + // Widths MUST match delegate columns below. The time's + // header is the order: a tap turns it, and goes to the + // newest row (a new order resets the model, which + // leaves the view where it was) + AbstractButton { + id: orderToggle + objectName: "orderToggle" + Layout.preferredWidth: table.narrowTable ? 64 : 96 + Layout.fillHeight: true + Accessible.name: table.frames.newestFirst + ? qsTr("Time, newest first") : qsTr("Time, oldest first") + contentItem: Label { + text: (table.frames.newestFirst ? qsTr("Time ↓") : qsTr("Time ↑")) + + (table.narrowTable ? "" : qsTr(" (s)")) + color: Theme.text + font.pixelSize: 12 + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + background: Rectangle { + color: "transparent" + border.width: orderToggle.visualFocus ? 2 : 0 + border.color: Theme.text + } + onClicked: { + table.frames.newestFirst = !table.frames.newestFirst + Qt.callLater(table.live ? frameList.jumpToLatest : frameList.positionViewAtBeginning) + } + } + Label { text: qsTr("DLC"); color: Theme.textDim; font.pixelSize: 12; + visible: !table.narrowTable + Layout.preferredWidth: 36 } + Label { text: qsTr("Ext"); color: Theme.textDim; font.pixelSize: 12; + Layout.preferredWidth: table.narrowTable ? 20 : 36 } + // Fits a 29-bit ID ("0x18FF0C00") in the mono face + Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 12; + Layout.preferredWidth: table.narrowTable ? 80 : 96 } + Label { text: qsTr("Payload"); color: Theme.textDim; font.pixelSize: 12; + Layout.fillWidth: true } + Label { text: qsTr("Flags"); color: Theme.textDim; font.pixelSize: 12; + visible: !table.narrowTable + Layout.preferredWidth: table.flagsWidth } + } + } + + ListView { + id: frameList + objectName: "frameList" + anchors { top: columnHeader.bottom; left: parent.left + right: parent.right; bottom: parent.bottom } + anchors.margins: 4 + clip: true + model: table.frames // the bridge's FrameListModel + + // Oldest-first reads as a tail: new rows land at the + // bottom, and the view follows them while it's at the + // end. Scrolling up stops following; scrolling back to + // the end, or "Latest", resumes it. Newest-first needs no + // follow, since new rows land at the top. + property bool follow: true + readonly property bool tailing: !table.frames.newestFirst + + // The newest row: the top in newest-first order, the end + // in oldest-first. Position first, then follow: + // positioning cancels a flick still coasting, and that + // flick's movementEnded would otherwise clear follow + // before the view reaches the end. + function jumpToLatest() { + if (tailing) + positionViewAtEnd() + else + positionViewAtBeginning() + follow = true + } + // Named, so Qt.callLater folds a burst of frames into one + // reposition per event-loop turn. Re-checks follow: a + // scroll may have started since the call was queued. + function followTail() { if (follow) jumpToLatest() } + + onCountChanged: { + if (count === 0) follow = true // cleared or new session + else if (table.live && tailing && follow) Qt.callLater(frameList.followTail) + } + // User scrolling decides. Following stops as a drag, flick + // or wheel starts, or the next frame would pull the view + // back to the end; where the scroll comes to rest decides + // whether it resumes. positionViewAtEnd emits neither. + onMovementStarted: follow = false + onMovementEnded: follow = atYEnd + + ScrollBar.vertical: ScrollBar { + policy: ScrollBar.AsNeeded + onPressedChanged: frameList.follow = !pressed && frameList.atYEnd + } + + delegate: Rectangle { + id: frameRow + // The page's narrowTable, read through the view + readonly property bool narrow: ListView.view !== null + && ListView.view.width < 480 + width: ListView.view !== null ? ListView.view.width : 0 + // Narrow, a long payload wraps onto more lines, its + // flags under it + height: narrow ? Math.max(26, payloadColumn.implicitHeight + 8) : 26 + radius: 4 + color: frameRow.model.selected ? Qt.alpha(Theme.info, 0.22) : "transparent" + + required property var model // role access + required property int index + + // A tap is the table's user's to answer (rowClicked); a drag + // still scrolls + MouseArea { + objectName: "frameRowArea" + anchors.fill: parent + onClicked: mouse => table.rowClicked(frameRow.index, mouse.modifiers, + frameRow.model.timestampUs) + } + + RowLayout { + anchors.fill: parent + // Under the column headers: theirs is 12 px in, + // the list's 4 + anchors.leftMargin: 8 + anchors.rightMargin: 8 + spacing: 8 + + // Roles from FrameListModel::roleNames(): the model + // registers "arbId": bind exactly that name. A + // misspelled role is undefined at runtime, not a + // build error: the column would render empty and + // throw per delegate. + Label { + // Session-relative us, shown as s.mmm + text: (frameRow.model.timestampUs / 1e6).toFixed(3) + color: Theme.textDim + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: frameRow.narrow ? 64 : 96 + elide: Text.ElideRight + } + Label { + text: frameRow.model.dlc + visible: !frameRow.narrow + color: Theme.text + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: 36 + } + Label { + text: frameRow.model.extended ? "E" : "-" + color: frameRow.model.extended ? Theme.success : Theme.textDim + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: frameRow.narrow ? 20 : 36 + } + Label { + // Role name is "arbId" (a quint32): hex-format + // it for display. + text: "0x" + frameRow.model.arbId.toString(16).toUpperCase() + color: Theme.textDim + font.family: Theme.monoFamily; font.pixelSize: 12 + Layout.preferredWidth: frameRow.narrow ? 80 : 96 + elide: Text.ElideRight + } + Column { + id: payloadColumn + Layout.fillWidth: true + Label { + id: payloadLabel + width: parent.width + text: frameRow.model.payloadHex // spaced uppercase bytes, from the bridge + color: Theme.text + font.family: Theme.monoFamily; font.pixelSize: 12 + wrapMode: frameRow.narrow ? Text.WrapAnywhere : Text.NoWrap + elide: frameRow.narrow ? Text.ElideNone : Text.ElideRight + } + // A phone's flags, under the payload + Label { + objectName: "rowFlagsNarrow" + width: parent.width + visible: frameRow.narrow && text !== "" + text: frameRow.model.flagsText + color: Theme.textDim + font.pixelSize: 11 + elide: Text.ElideRight + } + } + Label { + objectName: "rowFlags" + visible: !frameRow.narrow + text: frameRow.model.flagsText + color: Theme.textDim + font.pixelSize: 12 + Layout.preferredWidth: table.flagsWidth + elide: Text.ElideRight + } + } + } + + // ---- Empty state ---- + Label { + anchors.centerIn: parent + width: Math.min(implicitWidth, parent.width - 16) + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + visible: frameList.count === 0 + text: table.emptyText + color: Theme.textDim + } + } + + // Back to the newest row after a scroll away (and following + // again, oldest-first); on a phone there's no scroll bar to + // drag + ThemedButton { + objectName: "latestButton" + anchors { right: parent.right; bottom: parent.bottom; margins: 12 } + z: 3 + visible: table.live && frameList.count > 0 + && (frameList.tailing ? !frameList.follow : !frameList.atYBeginning) + text: frameList.tailing ? qsTr("Latest ↓") : qsTr("Latest ↑") + onClicked: frameList.jumpToLatest() + } +} diff --git a/app/qml/GaugeBase.qml b/app/qml/GaugeBase.qml index d9adfd51..3ac6ca2a 100644 --- a/app/qml/GaugeBase.qml +++ b/app/qml/GaugeBase.qml @@ -1,7 +1,5 @@ // File/layer: app/qml/GaugeBase.qml | Qt6 Quick, UI layer -// Testing: manual smoke via DashboardPage under mock://demo, needles -// ease between batches, sweep once per session, peaks reset; -// test_qml (tst_dashboard.qml) the held peak of a replay +// Testing: QML: QmlTest.kinds, QmlTest.gauges, QmlTest.dashboard import QtQuick @@ -29,7 +27,11 @@ Item { property real coldBelow: NaN property real warnFrom: NaN property real dangerFrom: NaN - property color accent: Qt.lighter(Theme.primary, 1.3) // normal-zone color + property color accent: Theme.gaugeValue // normal-zone color + // The hold shown: a kind with a scale marks its peak on it (the dial's + // tell-tale, the bar's and the ring's mark, the cells' notch); off by + // default. Reset peaks clears it + property bool showPeak: false // A little over one batch interval, so motion never stalls between // samples. Shift lights want less. @@ -38,7 +40,13 @@ Item { // Drawn position 0..1: the eased value, or the sweep while it plays readonly property real fraction: Math.max(sweepPos, fractionOf(smoothed)) readonly property bool sweeping: sweepAnim.running - readonly property string valueText: hasValue ? format(value) : qsTr("—") + // Past dangerFrom: the readout gains a DangerMark and the zone's stroke + // is heavier, so danger is more than a hue + readonly property bool inDanger: hasValue && !isNaN(dangerFrom) && value >= dangerFrom + // An enumeration's label, shown in place of the number + property string valueLabel: "" + readonly property string valueText: hasValue ? (valueLabel !== "" ? valueLabel : format(value)) + : qsTr("—") property real peakValue: NaN property real lowValue: NaN @@ -47,11 +55,19 @@ Item { function fractionOf(v) { return Math.max(0, Math.min(1, (v - from) / (to - from))) } function format(v) { return Number(v).toLocaleString(Qt.locale(), 'f', decimals) } - // Scale labels are whole numbers, whatever the readout's decimals - function formatScale(v) { return Number(v).toLocaleString(Qt.locale(), 'f', 0) } + // Scale labels carry only the decimals the value needs: none for a + // whole number, up to two under 10 and one under 100, whatever the + // readout's decimals + function formatScale(v) { + const n = Number(v) + const most = Math.abs(n) < 10 ? 2 : Math.abs(n) < 100 ? 1 : 0 + let d = 0 + while (d < most && Math.abs(n - Number(n.toFixed(d))) > 1e-9) ++d + return n.toLocaleString(Qt.locale(), 'f', d) + } function zoneColor(v, normal) { - if (!isNaN(dangerFrom) && v >= dangerFrom) return Theme.danger - if (!isNaN(warnFrom) && v >= warnFrom) return Theme.warning + if (!isNaN(dangerFrom) && v >= dangerFrom) return Theme.gaugeDanger + if (!isNaN(warnFrom) && v >= warnFrom) return Theme.gaugeWarn if (!isNaN(coldBelow) && v < coldBelow) return Theme.info return normal } diff --git a/app/qml/Heading.qml b/app/qml/Heading.qml new file mode 100644 index 00000000..c0e6bf27 --- /dev/null +++ b/app/qml/Heading.qml @@ -0,0 +1,14 @@ +// File/layer: app/qml/Heading.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings (test_qml) +// The heading of a Settings part + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +Label { + color: Theme.text + font.pixelSize: 16 + font.weight: Font.DemiBold + Layout.topMargin: Theme.spacing +} diff --git a/app/qml/HomePage.qml b/app/qml/HomePage.qml index 917f31e8..67ccd778 100644 --- a/app/qml/HomePage.qml +++ b/app/qml/HomePage.qml @@ -37,6 +37,7 @@ Rectangle { // from 6.5. No numerals or readout; at this size they'd crowd it. Rectangle { id: logo + objectName: "homeLogo" implicitWidth: 96; implicitHeight: 96 // layout-managed: implicit, not width/height radius: Theme.radius color: Theme.surface @@ -48,8 +49,8 @@ Rectangle { readonly property real cy: height / 2 readonly property real r: 38 readonly property real tickOuter: r * 0.76 - readonly property color litColor: rpm >= redline ? Theme.danger - : rpm >= 4500 ? Theme.warning + readonly property color litColor: rpm >= redline ? Theme.gaugeDanger + : rpm >= 4500 ? Theme.gaugeWarn : Theme.success property real rpm: 800 @@ -83,7 +84,7 @@ Rectangle { anchors.fill: parent preferredRendererType: Shape.CurveRenderer ShapePath { - strokeColor: Qt.alpha(Theme.text, 0.12) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.12) strokeWidth: 1 fillGradient: RadialGradient { centerX: logo.cx; centerY: logo.cy - logo.r * 0.35 @@ -109,13 +110,13 @@ Rectangle { centerX: logo.cx; centerY: logo.cy; radius: logo.tickOuter - 3 startAngle: logo.angleOf(logo.redline) sweepAngle: logo.angleOf(logo.maxRpm) - startAngle - strokeColor: Qt.alpha(Theme.danger, logo.rpm >= logo.redline ? 0.6 : 0.22) + strokeColor: Qt.alpha(Theme.gaugeDanger, logo.rpm >= logo.redline ? 0.6 : 0.22) strokeWidth: 6 } GaugeArc { centerX: logo.cx; centerY: logo.cy; radius: logo.r * 0.88 startAngle: logo.angleOf(0); sweepAngle: 270 - strokeColor: Qt.alpha(Theme.text, 0.08) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.08) strokeWidth: 3 } GaugeArc { @@ -145,8 +146,8 @@ Rectangle { height: tick.major ? 6 : 3.5 x: logo.cx - width / 2 y: logo.cy - logo.tickOuter - color: tick.v >= logo.redline ? Theme.danger - : tick.major ? Theme.text : Qt.alpha(Theme.text, 0.5) + color: tick.v >= logo.redline ? Theme.gaugeDanger + : tick.major ? Theme.gaugeTick : Qt.alpha(Theme.gaugeTick, 0.5) } } } @@ -170,7 +171,7 @@ Rectangle { readonly property real len: logo.r * 0.80 readonly property real tail: logo.r * 0.18 strokeColor: "transparent" - fillColor: Theme.danger + fillColor: Theme.gaugeDanger startX: logo.cx - needle.tail; startY: logo.cy - 1 PathLine { x: logo.cx; y: logo.cy - 1.6 } PathLine { x: logo.cx + needle.len; y: logo.cy - 0.4 } diff --git a/app/qml/LabeledFlow.qml b/app/qml/LabeledFlow.qml new file mode 100644 index 00000000..a8f8444c --- /dev/null +++ b/app/qml/LabeledFlow.qml @@ -0,0 +1,22 @@ +// File/layer: app/qml/LabeledFlow.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings (test_qml) +// A caption, then buttons that wrap: a row of them would hold the +// page at its natural width, past a phone's. The caption is the +// flow's first item, so a wrapped button has the whole width + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +Flow { + property alias label: caption.text + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + id: caption + visible: text !== "" + color: Theme.textDim + topPadding: 8 + } +} diff --git a/app/qml/LogPage.qml b/app/qml/LogPage.qml index e9d75eeb..a04bc800 100644 --- a/app/qml/LogPage.qml +++ b/app/qml/LogPage.qml @@ -19,62 +19,33 @@ Pane { // raw frame table instead (Theme.developerMode) property string view: "activity" readonly property bool showingFrames: Theme.developerMode && view === "frames" - // A phone's width: the table leaves out DLC, narrows its columns and - // wraps the payload under itself rather than cut it off - readonly property bool narrowTable: frameList.width < 480 // the rows' narrow too - readonly property int maxLogLines: 200 // ---- The Frames view's table (framefilter.h) ---- - // By ID instead of the frames; the filter's panel open; its - // direction (FrameFilter::Direction's order) + // By ID instead of the frames; the filter's panel open property bool byId: false property bool filterOpen: false // Export CSV's last answer: the counts, or why nothing was written property string exportNote: "" property bool exportFailed: false - property int filterDirection: 0 - // The wide table's Flags column - readonly property int flagsWidth: 96 - - // The filter's fields to the model, which keeps the last good part of - // a field that doesn't parse and says why - function applyFilter() { - const r = Bridge.model.setFilter(filterIds.text, filterData.text, - page.filterDirection, filterFlag.currentIndex) - filterIdsProblem.text = r.ids - filterDataProblem.text = r.data - } - function clearFilter() { - filterIds.text = "" - filterData.text = "" - filterFlag.currentIndex = 0 - page.filterDirection = 0 - applyFilter() - } + // The filter's fields to the model (FrameFilterPanel) + function applyFilter() { filterPanel.apply() } function showById() { page.byId = true Bridge.frameIds.refresh() } - // A By ID row tapped: the table of that ID's frames alone. The ID - // filter takes a number of either width, so the row's own width is - // the flag: a standard 0x7E8's tap leaves an extended 0x7E8 out, as - // an extended one's leaves the standard one out + // A By ID row tapped: the table of that ID's frames alone function showIdFrames(id, extended) { - filterIds.text = id.toString(16).toUpperCase() - filterFlag.currentIndex = extended ? 1 : 2 // Extended (29-bit), Standard (11-bit) - applyFilter() + filterPanel.showId(id, extended) page.filterOpen = true page.byId = false } // Frames a second, as the By ID view shows them - function rateText(rate) { - return rate <= 0 ? "-" : rate < 10 ? rate.toFixed(1) + "/s" : Math.round(rate) + "/s" - } + function rateText(rate) { return idTable.rateText(rate) } // Each line is stamped with local time in the surrogate session // log's format (HH:MM:SS.mmm), so the two line up, and a disconnect @@ -123,36 +94,6 @@ Pane { return r.ok } - // One option of a two-option toggle. Both options stay visible and - // the current one is filled, so it doesn't read as a dropdown. - component SegmentButton: AbstractButton { - id: seg - property bool selected: false - - implicitWidth: segLabel.implicitWidth + 24 - implicitHeight: 30 - hoverEnabled: true - Accessible.checkable: true - Accessible.checked: seg.selected - - background: Rectangle { - radius: Theme.radius - 2 - color: seg.selected ? Theme.elevatedLight - : seg.hovered ? Qt.alpha(Theme.text, 0.05) - : "transparent" - border.width: seg.visualFocus ? 2 : 0 - border.color: Theme.text - } - contentItem: Text { - id: segLabel - text: seg.text - font.pixelSize: 13 - color: seg.selected ? Theme.text : Theme.textDim - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - } - ColumnLayout { anchors.fill: parent spacing: Theme.spacing @@ -377,124 +318,10 @@ Pane { } // ---- The filter: the columns a bus is read by ---- - GridLayout { - objectName: "filterPanel" + FrameFilterPanel { + id: filterPanel visible: page.filterOpen - Layout.fillWidth: true - columns: 2 - columnSpacing: Theme.spacing - rowSpacing: Theme.spacing / 2 - - Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 13 } - TextField { - id: filterIds - objectName: "filterIds" - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - placeholderText: qsTr("7E8, 7E0-7EF") - font.family: Theme.monoFamily - inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText - onTextEdited: page.applyFilter() - } - Item { visible: filterIdsProblem.visible } // the label column, empty - Label { - id: filterIdsProblem - objectName: "filterIdsProblem" - visible: text !== "" - color: Theme.warning - font.pixelSize: 12 - wrapMode: Text.Wrap - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - } - - Label { text: qsTr("Data"); color: Theme.textDim; font.pixelSize: 13 } - TextField { - id: filterData - objectName: "filterData" - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - placeholderText: qsTr("^62 F1 ??") - font.family: Theme.monoFamily - inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText - onTextEdited: page.applyFilter() - } - Item { visible: filterDataProblem.visible } // the label column, empty - Label { - id: filterDataProblem - objectName: "filterDataProblem" - visible: text !== "" - color: Theme.warning - font.pixelSize: 12 - wrapMode: Text.Wrap - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - } - - Flow { - Layout.columnSpan: 2 - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - spacing: Theme.spacing - - Rectangle { - implicitWidth: directionSwitch.implicitWidth + 4 - implicitHeight: directionSwitch.implicitHeight + 4 - radius: Theme.radius - color: Theme.surface - - Row { - id: directionSwitch - anchors.centerIn: parent - spacing: 2 - Repeater { - model: [qsTr("All"), qsTr("Received"), qsTr("Sent")] - SegmentButton { - required property string modelData - required property int index - objectName: "direction_" + index - text: modelData - selected: page.filterDirection === index - onClicked: { - page.filterDirection = index - page.applyFilter() - } - } - } - } - } - ComboBox { - id: filterFlag - objectName: "filterFlag" - // FrameFilter::Flag's order - model: [qsTr("Any flag"), qsTr("Extended (29-bit)"), - qsTr("Standard (11-bit)"), qsTr("CAN FD"), - qsTr("Reassembled"), qsTr("Truncated"), - qsTr("After a loss"), qsTr("Error")] - implicitHeight: Theme.controlHeight - onActivated: page.applyFilter() - } - ThemedButton { - objectName: "filterClear" - text: qsTr("Clear the filter") - enabled: Bridge.model.filterTerms > 0 || filterIds.text !== "" - || filterData.text !== "" - onClicked: page.clearFilter() - } - } - // No transport reports the frames it sends yet, so Sent - // shows none: said, so an empty table doesn't read as lost - Label { - objectName: "sentNote" - visible: page.filterDirection === 2 - Layout.columnSpan: 2 - Layout.fillWidth: true - Layout.preferredWidth: 0 // the panel's width, not its text's - text: qsTr("No adapter reports the frames the session sends yet, so Sent shows none") - color: Theme.textDim - font.pixelSize: 12 - wrapMode: Text.Wrap - } + frames: Bridge.model } // ---- Status and bridge counters, wrapping on a phone ---- @@ -571,375 +398,33 @@ Pane { } // ---- Frame table ---- - Rectangle { + FrameTable { visible: !page.byId - Layout.fillWidth: true - Layout.fillHeight: true - radius: Theme.radius - color: Theme.surface - clip: true - - // Column header - Rectangle { - id: columnHeader - anchors { top: parent.top; left: parent.left; right: parent.right } - height: 32 - z: 2 - color: Theme.elevated - - RowLayout { - anchors.fill: parent - anchors.leftMargin: 12 - anchors.rightMargin: 12 - spacing: 8 - - // Widths MUST match delegate columns below. The time's - // header is the order: a tap turns it, and goes to the - // newest row (a new order resets the model, which - // leaves the view where it was) - AbstractButton { - id: orderToggle - objectName: "orderToggle" - Layout.preferredWidth: page.narrowTable ? 64 : 96 - Layout.fillHeight: true - Accessible.name: Bridge.model.newestFirst - ? qsTr("Time, newest first") : qsTr("Time, oldest first") - contentItem: Label { - text: (Bridge.model.newestFirst ? qsTr("Time ↓") : qsTr("Time ↑")) - + (page.narrowTable ? "" : qsTr(" (s)")) - color: Theme.text - font.pixelSize: 12 - verticalAlignment: Text.AlignVCenter - elide: Text.ElideRight - } - background: Rectangle { - color: "transparent" - border.width: orderToggle.visualFocus ? 2 : 0 - border.color: Theme.text - } - onClicked: { - Bridge.model.newestFirst = !Bridge.model.newestFirst - Qt.callLater(frameList.jumpToLatest) - } - } - Label { text: qsTr("DLC"); color: Theme.textDim; font.pixelSize: 12; - visible: !page.narrowTable - Layout.preferredWidth: 36 } - Label { text: qsTr("Ext"); color: Theme.textDim; font.pixelSize: 12; - Layout.preferredWidth: page.narrowTable ? 20 : 36 } - // Fits a 29-bit ID ("0x18FF0C00") in the mono face - Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 12; - Layout.preferredWidth: page.narrowTable ? 80 : 96 } - Label { text: qsTr("Payload"); color: Theme.textDim; font.pixelSize: 12; - Layout.fillWidth: true } - Label { text: qsTr("Flags"); color: Theme.textDim; font.pixelSize: 12; - visible: !page.narrowTable - Layout.preferredWidth: page.flagsWidth } - } - } - - ListView { - id: frameList - objectName: "frameList" - anchors { top: columnHeader.bottom; left: parent.left - right: parent.right; bottom: parent.bottom } - anchors.margins: 4 - clip: true - model: Bridge.model // the bridge's FrameListModel - - // Oldest-first reads as a tail: new rows land at the - // bottom, and the view follows them while it's at the - // end. Scrolling up stops following; scrolling back to - // the end, or "Latest", resumes it. Newest-first needs no - // follow, since new rows land at the top. - property bool follow: true - readonly property bool tailing: !Bridge.model.newestFirst - - // The newest row: the top in newest-first order, the end - // in oldest-first. Position first, then follow: - // positioning cancels a flick still coasting, and that - // flick's movementEnded would otherwise clear follow - // before the view reaches the end. - function jumpToLatest() { - if (tailing) - positionViewAtEnd() - else - positionViewAtBeginning() - follow = true - } - // Named, so Qt.callLater folds a burst of frames into one - // reposition per event-loop turn. Re-checks follow: a - // scroll may have started since the call was queued. - function followTail() { if (follow) jumpToLatest() } - - onCountChanged: { - if (count === 0) follow = true // cleared or new session - else if (tailing && follow) Qt.callLater(frameList.followTail) - } - // User scrolling decides. Following stops as a drag, flick - // or wheel starts, or the next frame would pull the view - // back to the end; where the scroll comes to rest decides - // whether it resumes. positionViewAtEnd emits neither. - onMovementStarted: follow = false - onMovementEnded: follow = atYEnd - - ScrollBar.vertical: ScrollBar { - policy: ScrollBar.AsNeeded - onPressedChanged: frameList.follow = !pressed && frameList.atYEnd - } - - delegate: Rectangle { - id: frameRow - // The page's narrowTable, read through the view - readonly property bool narrow: ListView.view !== null - && ListView.view.width < 480 - width: ListView.view !== null ? ListView.view.width : 0 - // Narrow, a long payload wraps onto more lines, its - // flags under it - height: narrow ? Math.max(26, payloadColumn.implicitHeight + 8) : 26 - radius: 4 - color: frameRow.model.selected ? Qt.alpha(Theme.info, 0.22) : "transparent" - - required property var model // role access - required property int index - - // A tap selects the row or lets it go; a - // shift-click selects from the last row tapped to - // this one. A drag still scrolls - MouseArea { - objectName: "frameRowArea" - anchors.fill: parent - onClicked: mouse => { - if (mouse.modifiers & Qt.ShiftModifier) - Bridge.model.selectThrough(frameRow.index) - else - Bridge.model.toggleSelected(frameRow.index) - } - } - - RowLayout { - anchors.fill: parent - // Under the column headers: theirs is 12 px in, - // the list's 4 - anchors.leftMargin: 8 - anchors.rightMargin: 8 - spacing: 8 - - // Roles from FrameListModel::roleNames(): the model - // registers "arbId": bind exactly that name. A - // misspelled role is undefined at runtime, not a - // build error: the column would render empty and - // throw per delegate. - Label { - // Session-relative us, shown as s.mmm - text: (frameRow.model.timestampUs / 1e6).toFixed(3) - color: Theme.textDim - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: frameRow.narrow ? 64 : 96 - elide: Text.ElideRight - } - Label { - text: frameRow.model.dlc - visible: !frameRow.narrow - color: Theme.text - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: 36 - } - Label { - text: frameRow.model.extended ? "E" : "-" - color: frameRow.model.extended ? Theme.success : Theme.textDim - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: frameRow.narrow ? 20 : 36 - } - Label { - // Role name is "arbId" (a quint32): hex-format - // it for display. - text: "0x" + frameRow.model.arbId.toString(16).toUpperCase() - color: Theme.textDim - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: frameRow.narrow ? 80 : 96 - elide: Text.ElideRight - } - Column { - id: payloadColumn - Layout.fillWidth: true - Label { - id: payloadLabel - width: parent.width - text: frameRow.model.payloadHex // spaced uppercase bytes, from the bridge - color: Theme.text - font.family: Theme.monoFamily; font.pixelSize: 12 - wrapMode: frameRow.narrow ? Text.WrapAnywhere : Text.NoWrap - elide: frameRow.narrow ? Text.ElideNone : Text.ElideRight - } - // A phone's flags, under the payload - Label { - objectName: "rowFlagsNarrow" - width: parent.width - visible: frameRow.narrow && text !== "" - text: frameRow.model.flagsText - color: Theme.textDim - font.pixelSize: 11 - elide: Text.ElideRight - } - } - Label { - objectName: "rowFlags" - visible: !frameRow.narrow - text: frameRow.model.flagsText - color: Theme.textDim - font.pixelSize: 12 - Layout.preferredWidth: page.flagsWidth - elide: Text.ElideRight - } - } - } - - // ---- Empty state ---- - Label { - anchors.centerIn: parent - width: Math.min(implicitWidth, parent.width - 16) - wrapMode: Text.Wrap - horizontalAlignment: Text.AlignHCenter - visible: frameList.count === 0 - text: !Bridge.connected && Bridge.model.heldCount === 0 - ? qsTr("No session: connect one from Settings") - : Bridge.model.heldCount > 0 ? qsTr("No frame the filter shows") - : Bridge.logPaused ? qsTr("Paused") - : qsTr("Waiting for frames…") - color: Theme.textDim - } - } - - // Back to the newest row after a scroll away (and following - // again, oldest-first); on a phone there's no scroll bar to - // drag - ThemedButton { - objectName: "latestButton" - anchors { right: parent.right; bottom: parent.bottom; margins: 12 } - z: 3 - visible: frameList.count > 0 - && (frameList.tailing ? !frameList.follow : !frameList.atYBeginning) - text: frameList.tailing ? qsTr("Latest ↓") : qsTr("Latest ↑") - onClicked: frameList.jumpToLatest() + frames: Bridge.model // the bridge's FrameListModel + emptyText: !Bridge.connected && Bridge.model.heldCount === 0 + ? qsTr("No session: connect one from Settings") + : Bridge.model.heldCount > 0 ? qsTr("No frame the filter shows") + : Bridge.logPaused ? qsTr("Paused") + : qsTr("Waiting for frames…") + // A tap selects the row or lets it go; a shift-click + // selects from the last row tapped to this one + onRowClicked: (index, modifiers, timestampUs) => { + if (modifiers & Qt.ShiftModifier) + Bridge.model.selectThrough(index) + else + Bridge.model.toggleSelected(index) } } // ---- By ID: one row per ID over the frames the table shows ---- - Rectangle { + FrameIdList { + id: idTable visible: page.byId - Layout.fillWidth: true - Layout.fillHeight: true - radius: Theme.radius - color: Theme.surface - clip: true - - // Read again twice a second while it shows (FrameIdModel) - Timer { - interval: 500 - repeat: true - running: page.visible && page.showingFrames && page.byId - onTriggered: Bridge.frameIds.refresh() - } - - Rectangle { - id: idHeader - anchors { top: parent.top; left: parent.left; right: parent.right } - height: 32 - z: 2 - color: Theme.elevated - - RowLayout { - anchors.fill: parent - anchors.leftMargin: 12 - anchors.rightMargin: 12 - spacing: 8 - // Widths MUST match the delegate's columns below - Label { text: qsTr("ID"); color: Theme.textDim; font.pixelSize: 12; - Layout.preferredWidth: 104 } // a 29-bit ID and its E - Label { text: qsTr("Frames"); color: Theme.textDim; font.pixelSize: 12; - Layout.preferredWidth: 52 } - Label { text: qsTr("Rate"); color: Theme.textDim; font.pixelSize: 12; - Layout.preferredWidth: 52 } - Label { text: qsTr("Last payload"); color: Theme.textDim; font.pixelSize: 12; - Layout.fillWidth: true; elide: Text.ElideRight } - } - } - - ListView { - id: idList - objectName: "idList" - anchors { top: idHeader.bottom; left: parent.left - right: parent.right; bottom: parent.bottom } - anchors.margins: 4 - clip: true - model: Bridge.frameIds - ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } - - delegate: Rectangle { - id: idRow - readonly property bool narrow: ListView.view !== null - && ListView.view.width < 480 - width: ListView.view !== null ? ListView.view.width : 0 - height: Math.max(Theme.rowHeight, idPayload.implicitHeight + 8) - radius: 4 - color: "transparent" - - required property var model - required property int index - - // A tap reads this ID's frames: the filter takes it - MouseArea { - objectName: "idRowArea" - anchors.fill: parent - onClicked: page.showIdFrames(idRow.model.arbId, idRow.model.extended) - } - - RowLayout { - anchors.fill: parent - anchors.leftMargin: 8 - anchors.rightMargin: 8 - spacing: 8 - Label { - text: "0x" + idRow.model.arbId.toString(16).toUpperCase() - + (idRow.model.extended ? " E" : "") - color: Theme.text - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: 104 - elide: Text.ElideRight - } - Label { - text: idRow.model.frames - color: Theme.textDim - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: 52 - } - Label { - text: page.rateText(idRow.model.rate) - color: Theme.textDim - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.preferredWidth: 52 - } - Label { - id: idPayload - text: idRow.model.payloadHex - color: Theme.text - font.family: Theme.monoFamily; font.pixelSize: 12 - Layout.fillWidth: true - wrapMode: idRow.narrow ? Text.Wrap : Text.NoWrap // between bytes - elide: idRow.narrow ? Text.ElideNone : Text.ElideRight - } - } - } - - Label { - anchors.centerIn: parent - visible: idList.count === 0 - text: Bridge.model.heldCount > 0 ? qsTr("No frame the filter shows") - : qsTr("No frames yet") - color: Theme.textDim - } - } + ids: Bridge.frameIds + refreshing: page.visible && page.showingFrames && page.byId + emptyText: Bridge.model.heldCount > 0 ? qsTr("No frame the filter shows") + : qsTr("No frames yet") + onIdTapped: (id, extended) => page.showIdFrames(id, extended) } } } diff --git a/app/qml/Main.qml b/app/qml/Main.qml index aca7d38c..cbc830f8 100644 --- a/app/qml/Main.qml +++ b/app/qml/Main.qml @@ -53,15 +53,47 @@ ApplicationWindow { palette.disabled.text: Theme.textDim palette.disabled.buttonText: Theme.textDim + // A phone keeps its tab bar upright and on its side: the form follows + // the platform (ADR-0057), not a width that a turn would cross. + // testMobile stands in for Theme.mobile in a test. A tablet (a short + // side of 600 dp or more) and a desktop go by the layout's width + property bool testMobile: false + // The short side is the window's own dp, not the layout's: a phone + // zoomed out is still a phone + readonly property bool phoneForm: (Theme.mobile || testMobile) + && Math.min(root.width, root.height) < 600 // The layout width, after the zoom - readonly property bool isCompact: zoomRoot.width < 720 - // A phone on its side, or a window as short - readonly property bool isShort: zoomRoot.height < 480 + readonly property bool isCompact: phoneForm || zoomRoot.width < 720 + // A phone on its side, or a window as short (the bars' insets apart) + readonly property bool isShort: zoomRoot.height - zoomRoot.insetTop - zoomRoot.insetBottom < 480 Binding { target: Theme; property: "dense"; value: root.isCompact || root.isShort } Binding { target: Theme; property: "shortLayout"; value: root.isShort } + Binding { target: Theme; property: "compact"; value: root.isCompact } + + // The system's bars over the window, per side: Qt's safe area, or a + // test's stand-in where larger (a test can't set SafeArea). The + // header and the tab bar paint theirs in their own color. + // The window's own safe area (an item's SafeArea reads its own overlap) + // testWindowSafe stands in for it where larger (a test's window has no + // bars), so zoomRoot's reach over them can be pinned + property var testWindowSafe: ({ left: 0, top: 0, right: 0, bottom: 0 }) + readonly property var windowSafe: { + const s = SafeArea.margins + const t = testWindowSafe + return { left: Math.max(s.left, t.left), top: Math.max(s.top, t.top), + right: Math.max(s.right, t.right), bottom: Math.max(s.bottom, t.bottom) } + } + property var testInsets: ({ left: 0, top: 0, right: 0, bottom: 0 }) + readonly property var insets: { + const s = SafeArea.margins + const t = testInsets + return { left: Math.max(s.left, t.left), top: Math.max(s.top, t.top), + right: Math.max(s.right, t.right), bottom: Math.max(s.bottom, t.bottom) } + } readonly property int currentPage: stack.currentIndex // Page indices, in the order of the sidebar, stack and tab bar + readonly property int recordingsPage: 5 readonly property int settingsPage: 6 function gotoPage(index) { stack.currentIndex = index } @@ -75,6 +107,26 @@ ApplicationWindow { settingsView.pickRecording(uri) gotoPage(settingsPage) } + // A log's time as m:ss, or h:mm:ss past an hour; 0:00 for a value + // that isn't a time + function logTimeText(ms) { + const s = Number.isFinite(ms) ? Math.max(0, Math.floor(ms / 1000)) : 0 + const two = n => (n < 10 ? "0" : "") + n + return s >= 3600 ? Math.floor(s / 3600) + ":" + two(Math.floor(s / 60) % 60) + ":" + two(s % 60) + : Math.floor(s / 60) + ":" + two(s % 60) + } + // After Stop log the log opens in the viewer (ADR-0056 section 1); a + // log the session's end or a failed write closed leaves the page as + // it is, since the driver may be reading Live + Connections { + target: Bridge + function onLogStopped(folder, byUser) { + if (!byUser) + return + root.gotoPage(root.recordingsPage) + recordingsView.openFolder(folder) + } + } // ---- Zoom (Theme.zoom), units (Bridge.unitSystem) and developer mode // (Theme.developerMode), kept between runs @@ -133,7 +185,7 @@ ApplicationWindow { : o === Qt.InvertedLandscapeOrientation ? "landscape, inverted" : "unknown" } readonly property string displayLine: { - const s = zoomRoot.safe + const s = root.insets return "Display: screen " + Screen.width + " × " + Screen.height + " (" + orientationName(Screen.orientation) + ", " + Screen.devicePixelRatio + "x)" + ", available " + Screen.desktopAvailableWidth + " × " + Screen.desktopAvailableHeight @@ -151,16 +203,26 @@ ApplicationWindow { // The whole UI, laid out at the window's size divided by the zoom and // scaled by it, so pages reflow as if the window were that size. // Shapes and text are vector-drawn, so they stay sharp at any zoom. - // It keeps out of the safe area's margins: Android draws the window - // under its status and navigation bars (edge to edge), where the - // window's color shows; elsewhere the margins are 0. + // It keeps out of the insets' sides; at the top and the bottom the + // header and the tab bar reach the window's edge and pad their insets + // in their own color (Android can draw the window under its status + // and navigation bars, edge to edge; elsewhere the insets are 0). Item { id: zoomRoot - readonly property var safe: parent.SafeArea.margins - x: safe.left - y: safe.top - width: (parent.width - safe.left - safe.right) / Theme.zoom - height: (parent.height - safe.top - safe.bottom) / Theme.zoom + objectName: "zoomRoot" + readonly property var safe: root.insets + // The top and bottom insets in the layout's units + readonly property real insetTop: safe.top / Theme.zoom + readonly property real insetBottom: safe.bottom / Theme.zoom + // ApplicationWindow's content item already lies inside Qt's safe + // area, so this item reaches back out over the top and bottom + // bars (the header and the tab bar paint them) and takes no side + // inset a second time + readonly property var qtSafe: root.windowSafe + x: 0 + y: -qtSafe.top + width: parent.width / Theme.zoom + height: (parent.height + qtSafe.top + qtSafe.bottom) / Theme.zoom scale: Theme.zoom transformOrigin: Item.TopLeft @@ -169,8 +231,11 @@ ApplicationWindow { spacing: 0 ToolBar { + objectName: "headerBar" Layout.fillWidth: true - Layout.preferredHeight: Theme.toolBarHeight + Layout.preferredHeight: Theme.toolBarHeight + zoomRoot.insetTop + // The row below pads the inset itself; the style would pad it too + topPadding: 0 background: Rectangle { color: Theme.surface Rectangle { // 2px accent underline @@ -180,15 +245,20 @@ ApplicationWindow { } RowLayout { id: headerRow + objectName: "headerRow" anchors.fill: parent + anchors.topMargin: zoomRoot.insetTop anchors.leftMargin: 16 anchors.rightMargin: 16 spacing: 12 - // The name gives way to Mark on a phone's width + // The name gives way to Mark or the log's controls on a + // phone's width Label { + id: headerTitle objectName: "headerTitle" - visible: !markButton.visible || headerRow.width >= 420 + visible: !(markButton.visible || startLogButton.visible || Bridge.logActive) + || headerRow.width >= 420 text: qsTr("Havne") font.pixelSize: 16 font.weight: Font.DemiBold @@ -232,6 +302,7 @@ ApplicationWindow { color: pill.tone text: Bridge.connecting ? qsTr("Connecting…") : Bridge.disconnecting ? qsTr("Disconnecting…") + : !headerTitle.visible ? Theme.linkShortLabel(Bridge.linkState) : Bridge.connected ? qsTr("%1 · %2").arg(Theme.linkLabel(Bridge.linkState)) .arg(Bridge.uriLabel) @@ -248,18 +319,55 @@ ApplicationWindow { ThemedButton { id: markButton objectName: "markButton" - visible: Bridge.recordingActive + visible: Bridge.recordingActive && !Bridge.logActive text: Bridge.markCount > 0 ? qsTr("Mark (%1)").arg(Bridge.markCount) : qsTr("Mark") Accessible.name: qsTr("Mark the recording") onClicked: Bridge.mark() } + // The analysis log (ADR-0056 section 1): Live's ticked rows, + // recorded from now on and asked alone until Stop log. A + // replay plays a recording already; Record sessions' own + // recorder is the session's one + ThemedButton { + id: startLogButton + objectName: "startLogButton" + visible: Bridge.connected && !Bridge.recordingActive + && !Bridge.currentUri.toLowerCase().startsWith("replay://") + enabled: !Bridge.disconnecting && Bridge.signalModel.subscribedCount > 0 + text: qsTr("Start log") + Accessible.name: qsTr("Start a log of the ticked signals") + onClicked: Bridge.startLog() + } + // While a log runs: its time over its folder's size, two + // short lines, so a ten-hour log's readout fits beside + // the name at 420 px + Label { + objectName: "logReadout" + visible: Bridge.logActive + text: qsTr("%1\n%2 MB").arg(root.logTimeText(Bridge.logElapsedMs)) + .arg((Bridge.logBytes / (1024 * 1024)).toFixed(1)) + horizontalAlignment: Text.AlignRight + font.pixelSize: 12 + color: Theme.text + } + ThemedButton { + objectName: "stopLogButton" + visible: Bridge.logActive + enabled: !Bridge.disconnecting + text: qsTr("Stop log") + onClicked: Bridge.stopLog() + } + // Settings owns connecting: this button opens it, or ends the // session from any page. On Settings itself, its Connect // button is the one to use. + // A log's Stop log takes its place while the log runs ThemedButton { - visible: Bridge.connected || root.currentPage !== root.settingsPage + objectName: "disconnectButton" + visible: !Bridge.logActive + && (Bridge.connected || root.currentPage !== root.settingsPage) // A teardown can take seconds with a wedged adapter; no // connect starts until it ends enabled: !Bridge.connecting && !Bridge.disconnecting @@ -335,10 +443,13 @@ ApplicationWindow { } DiagnosticsPage { objectName: "diagnosticsPage" + // The report names the picked vehicle's baseline + vehicles: settingsView.vehicles onConnectRequested: root.openConnect() } LogPage { objectName: "logPage" } RecordingsPage { + id: recordingsView objectName: "recordingsPage" // A vehicle's baseline: Settings keeps the vehicles vehicles: settingsView.vehicles @@ -352,19 +463,32 @@ ApplicationWindow { } } + // A phone's tab bar: targets a touch's size at its top (each tab + // keeps its own height), then a gap and the system's bottom + // inset, all in the bar's color, so a tap low on a tab never + // reaches Back or Home beside it TabBar { id: tabBar objectName: "tabBar" visible: root.isCompact Layout.fillWidth: true + Layout.preferredHeight: Theme.touchTarget + Theme.barGap + zoomRoot.insetBottom + spacing: 0 + // The bar's height already holds the bottom inset, painted in + // its color: the style pads none of it again + topPadding: 0 + bottomPadding: 0 + leftPadding: 0 + rightPadding: 0 currentIndex: stack.currentIndex onCurrentIndexChanged: stack.currentIndex = currentIndex - background: Rectangle { color: Theme.surface } + background: Rectangle { objectName: "tabBarBackground"; color: Theme.surface } // per-button styling since TabBar doesn't propagate backgrounds component ThemedTabButton: TabButton { id: btn + implicitHeight: Theme.touchTarget contentItem: Label { text: btn.text // 13px keeps "Settings" inside a fifth of a 375pt phone @@ -401,6 +525,13 @@ ApplicationWindow { ThemedTabButton { text: qsTr("Recs") } ThemedTabButton { text: qsTr("Settings") } } + // With no tab bar (the sidebar's width), the pages keep off + // the bottom inset + Item { + visible: !tabBar.visible + Layout.fillWidth: true + Layout.preferredHeight: zoomRoot.insetBottom + } } } @@ -410,7 +541,8 @@ ApplicationWindow { function show() { opacity = 1; zoomBadgeTimer.restart() } anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom - anchors.bottomMargin: 24 + zoomRoot.safe.bottom + // The content item lies inside the system's bars already + anchors.bottomMargin: 24 width: zoomBadgeLabel.implicitWidth + 32 height: 36 radius: 18 @@ -459,9 +591,10 @@ ApplicationWindow { visible: Theme.developerMode anchors.right: parent.right anchors.bottom: parent.bottom - anchors.rightMargin: 8 + zoomRoot.safe.right - // Above the tab bar on a phone, so it covers none of the tabs - anchors.bottomMargin: 8 + zoomRoot.safe.bottom + (tabBar.visible ? tabBar.height : 0) + anchors.rightMargin: 8 + // Above the tab bar on a phone, so it covers none of the tabs: the + // bar's part under the navigation bar lies outside this item's parent + anchors.bottomMargin: 8 + (tabBar.visible ? tabBar.height * Theme.zoom - root.windowSafe.bottom : 0) width: frameRateLabel.implicitWidth + 12 height: frameRateLabel.implicitHeight + 6 radius: 4 diff --git a/app/qml/PageHeader.qml b/app/qml/PageHeader.qml index a713c0ba..2e3aa682 100644 --- a/app/qml/PageHeader.qml +++ b/app/qml/PageHeader.qml @@ -1,6 +1,6 @@ // File/layer: app/qml/PageHeader.qml | Qt6 Quick, UI layer -// Testing: manual smoke: Dashboard, Live, Log and Settings open with -// it, the titles aligned at Theme.pageMargin +// Testing: QML: QmlTest.phone (test_qml); manual smoke: the titles +// aligned at Theme.pageMargin import QtQuick import QtQuick.Controls @@ -11,11 +11,21 @@ import QtQuick.Layouts RowLayout { id: header property string title: "" + // The title gives way, eliding, when the row's other items leave it + // less than its width; it never grows past its own width. Off, the + // title keeps its width and the row's fill items give way alone. + property bool titleShrinks: false Layout.fillWidth: true spacing: 10 Label { + Layout.fillWidth: header.titleShrinks + // A whole pixel: the layout rounds a fractional maximum down, which + // leaves the text short of its own width and elides a title that fits + Layout.maximumWidth: header.titleShrinks ? Math.ceil(implicitWidth) + : Number.POSITIVE_INFINITY + elide: header.titleShrinks ? Text.ElideRight : Text.ElideNone text: header.title font.pixelSize: 20 font.weight: Font.DemiBold diff --git a/app/qml/RecordingsPage.qml b/app/qml/RecordingsPage.qml index f0bf9544..38b0d691 100644 --- a/app/qml/RecordingsPage.qml +++ b/app/qml/RecordingsPage.qml @@ -46,6 +46,28 @@ Page { onBaselineFolderChanged: checkBaseline() readonly property int recordingsListed: 20 + + // Import: another logger's file made a recording. The file picked, its + // kind (RecordingImport.Kind: guessed from its first line, switched + // here), a CSV's column map, and the last import's words: what it + // made, or why not + property url importFile: "" + property int importKind: RecordingImport.Csv + property url importMap: "" + property bool importOpen: false + // A CSV with no column map file is imported through the map guessed + // from its header (CsvGuessPreview); picking a map file skips the guess + property bool importGuessing: false + readonly property bool importUsesGuess: importKind === RecordingImport.Csv + && importMap.toString() === "" + && guessPreview.guess !== null + // [{ name, url }]: the maps kept under the settings folder's maps/ + property var savedMaps: [] + // After a candump import is refused, the interface field shows: core + // names a log's interfaces when it has several + property bool importAsksInterface: false + property string importNote: "" + property bool importFailed: false // [{ title, uri, folder, source, profile }] (Bridge.recentRecordings) property var recordings: [] property string openedTitle: "" @@ -90,6 +112,24 @@ Page { // the cursor's time (NaN for none) property real viewT0: 0 property real viewT1: 1000 + // What the signal area shows: the values at the cursor, or the frames + // of the part in view (a recording with a frames.csv). The values each + // time a recording opens + property string detailView: "values" + readonly property bool framesShown: detailView === "frames" + && recording.state === RecordingView.Open + && recording.hasFrames + // The Frames view's By ID table and filter panel + property bool framesById: false + property bool framesFilterOpen: false + onViewT0Changed: refillFramesSoon() + onViewT1Changed: refillFramesSoon() + onFramesShownChanged: { + if (framesShown) + refillFrames() + else + viewFrames.clear() + } property real cursorMs: NaN readonly property bool hasCursor: !isNaN(cursorMs) // Signal index -> plotted, from the recording's default at the open @@ -210,6 +250,78 @@ Page { checkBaseline() } + // A URL's last part, as the picker named it (a content:// URI's too) + function fileNameOf(url) { + const text = decodeURIComponent(url.toString()) + return text.substring(text.lastIndexOf("/") + 1) + } + + // A file picked to import: its kind guessed, the rest asked for + function chooseImportFile(url) { + importFile = url + importKind = Bridge.recordingImport.guessKind(url) + importMap = "" + importAsksInterface = false + importInterface.text = "" + importNote = "" + importFailed = false + importOpen = true + savedMaps = Bridge.recordingImport.savedMaps() + guessImportFile() + } + + // A CSV's map guessed from its header, unless a map file is chosen + function guessImportFile() { + guessPreview.clear() + if (importKind !== RecordingImport.Csv || importMap.toString() !== "") + return + importGuessing = Bridge.recordingImport.guess(importFile, "") + } + + // A map file chosen (the dialog, or one saved earlier) instead of the + // guess + function chooseImportMap(url) { + importMap = url + importNote = "" + importFailed = false + guessPreview.clear() + } + + // Back to the guess after a map file was chosen + function useTheGuess() { + importMap = "" + importNote = "" + importFailed = false + guessImportFile() + } + + readonly property bool importReady: importKind === RecordingImport.Candump + || importMap.toString() !== "" + || (importUsesGuess && guessPreview.ready) + + function startImport() { + importNote = "" + importFailed = false + if (importUsesGuess) { + Bridge.recordingImport.startWithMap(importFile, guessPreview.mapText()) + return + } + Bridge.recordingImport.start(importFile, importKind, importMap, + importKind === RecordingImport.Candump + ? importInterface.text : "") + } + + // What an import made, in words + function importedWords(result) { + if (importKind === RecordingImport.Candump) + return qsTr("Imported %1 frames over %2 s") + .arg(result.frames).arg((result.durationUs / 1e6).toFixed(1)) + return result.columnsIgnored > 0 + ? qsTr("Imported %1 values; columns ignored: %2") + .arg(result.values).arg(result.columnsIgnored) + : qsTr("Imported %1 values").arg(result.values) + } + function checkBaseline() { // Not a ternary of the map and ({}): qmlcachegen 6.12.0 crashes on it if (baselineFolder === "") { @@ -243,6 +355,18 @@ Page { recording.open(row.folder) } + // A folder just recorded (a stopped log), opened from the list as a + // tap on its row would; one the list can't show stays on the list + function openFolder(folder) { + if (viewing) + backToList() + else + refresh() + const row = Bridge.recordingRow(folder) + if (row.folder !== undefined) + open(row) + } + // Seconds to the ms with no trailing zeros, as core's replay takes them function secondsText(ms) { return String(Number((ms / 1000).toFixed(3))) @@ -262,6 +386,8 @@ Page { function backToList() { recording.close() + viewFrames.clear() + detailView = "values" stopComparing() alignChoice.currentIndex = 0 alignOn = "start" @@ -288,6 +414,18 @@ Page { : durationMs() } + // The Frames view's rows again for the part in view, once it has rested + // for settleMs: a drag or a pinch asks for none until it stops + function refillFramesSoon() { + if (framesShown) + framesRefill.restart() + } + function refillFrames() { + framesRefill.stop() + if (framesShown) + viewFrames.load(recording.folder, viewT0, viewT1) + } + // The view, kept inside the axis and no narrower than minSpanMs. // A change within settleMs of the last is the view moving (a drag, a // pinch, the wheel): the chart draws it without antialiasing until the @@ -639,6 +777,24 @@ Page { : qsTr("Frames check: %1 findings").arg(n) } + // Import's file and a CSV's column map + FileDialog { + id: importDialog + title: qsTr("Import a log") + fileMode: FileDialog.OpenFile + nameFilters: [qsTr("Logs (*.csv *.log *.txt)"), qsTr("All files (*)")] + currentFolder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation) + onAccepted: root.chooseImportFile(importDialog.selectedFile) + } + FileDialog { + id: mapDialog + title: qsTr("The logger's column map") + fileMode: FileDialog.OpenFile + nameFilters: [qsTr("Column maps (*.json)"), qsTr("All files (*)")] + currentFolder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation) + onAccepted: root.chooseImportMap(mapDialog.selectedFile) + } + // Save report's file: text first, the one a shop or a buyer reads FileDialog { id: reportDialog @@ -663,10 +819,11 @@ Page { // The whole recording's health report to url, its format by the // dialog's filter or the file's name (ADR-0054's appendix "the health - // report as built"); the view's zoom never narrows it. The result - // comes back in onReportSaved; false when none started + // report as built"), naming the picked vehicle's baseline; the view's + // zoom never narrows it. The result comes back in onReportSaved; false + // when none started function saveReportTo(url, filterIndex) { - const started = recording.saveHealthReport(url, filterIndex) + const started = recording.saveHealthReport(url, filterIndex, baselineFolder) if (started) { reportFailed = false reportNote = qsTr("Saving the report…") @@ -700,6 +857,10 @@ Page { rows += s.samples root.rowsPerSecond = rows / (root.durationMs() / 1000) root.cursorMs = NaN + root.detailView = "values" + root.framesById = false + root.framesFilterOpen = false + framesFilterPanel.clear() root.showAll() } onSignalListChanged: { @@ -732,6 +893,35 @@ Page { } } + Connections { + target: Bridge.recordingImport + function onGuessFinished(result) { + root.importGuessing = false + // The panel was closed, or a map file chosen, meanwhile + if (!root.importOpen || root.importMap.toString() !== "" + || root.importKind !== RecordingImport.Csv) + return + if (result.ok) { + guessPreview.load(result) + } else { + root.importFailed = true + root.importNote = qsTr("%1. Column map... picks a map instead.").arg(result.words) + } + } + function onFinished(result) { + root.importFailed = !result.ok + if (result.ok) { + root.importNote = root.importedWords(result) + root.importOpen = false + root.refresh() + } else { + root.importNote = result.words + if (root.importKind === RecordingImport.Candump) + root.importAsksInterface = true + } + } + } + Connections { target: Bridge // A recording that ended joins the list @@ -749,6 +939,14 @@ Page { onTriggered: chart.moving = false } + // The part in view's frames (ADR-0049's appendix "frames read back") + RecordingFrames { id: viewFrames } + Timer { + id: framesRefill + interval: root.settleMs + onTriggered: root.refillFrames() + } + FrameAnimation { running: root.frameTesting onTriggered: { @@ -796,7 +994,202 @@ Page { height: scroller.contentHeight - 2 * Theme.pageMargin spacing: 10 - PageHeader { title: qsTr("Recordings"); visible: !root.chartMaximized } + PageHeader { + title: qsTr("Recordings") + visible: !root.chartMaximized + Item { Layout.fillWidth: true } + ThemedButton { + objectName: "importButton" + visible: !root.viewing + text: qsTr("Import") + enabled: !Bridge.recordingImport.busy + onClicked: importDialog.open() + } + } + + // ---- Import: the file picked, its kind, a CSV's column map ---- + ColumnLayout { + objectName: "importPanel" + visible: root.importOpen && !root.viewing + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "importFileName" + Layout.fillWidth: true + wrapMode: Text.WrapAnywhere + color: Theme.text + text: qsTr("Import %1").arg(root.fileNameOf(root.importFile)) + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + Rectangle { + implicitWidth: kindSwitch.implicitWidth + 4 + implicitHeight: kindSwitch.implicitHeight + 4 + radius: Theme.radius + color: Theme.surface + Row { + id: kindSwitch + anchors.centerIn: parent + spacing: 2 + SegmentButton { + objectName: "importKind_csv" + text: qsTr("CSV") + selected: root.importKind === RecordingImport.Csv + enabled: !Bridge.recordingImport.busy + onClicked: { + root.importKind = RecordingImport.Csv + if (guessPreview.guess === null && !root.importGuessing) + root.guessImportFile() + } + } + SegmentButton { + objectName: "importKind_candump" + text: qsTr("candump") + selected: root.importKind === RecordingImport.Candump + enabled: !Bridge.recordingImport.busy + onClicked: { + root.importKind = RecordingImport.Candump + root.importNote = "" + } + } + } + } + Label { + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + font.pixelSize: 12 + text: qsTr("Guessed from its first line") + } + } + + // A CSV's columns come through the logger's column map + RowLayout { + visible: root.importKind === RecordingImport.Csv + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "importMapButton" + text: qsTr("Column map...") + enabled: !Bridge.recordingImport.busy + onClicked: mapDialog.open() + } + Label { + objectName: "importMapName" + Layout.fillWidth: true + wrapMode: Text.WrapAnywhere + color: root.importMap.toString() !== "" ? Theme.text : Theme.textDim + text: root.importMap.toString() !== "" ? root.fileNameOf(root.importMap) + : qsTr("Guessed from the header") + } + } + // A map kept earlier, or back to the guess + RowLayout { + visible: root.importKind === RecordingImport.Csv + && (root.savedMaps.length > 0 || root.importMap.toString() !== "") + Layout.fillWidth: true + spacing: Theme.spacing + ComboBox { + id: savedMapChoice + objectName: "savedMaps" + visible: root.savedMaps.length > 0 + Layout.fillWidth: true + Layout.preferredWidth: 0 + Layout.preferredHeight: Theme.touchTarget + enabled: !Bridge.recordingImport.busy + model: [qsTr("Saved maps...")].concat(root.savedMaps.map(m => m.name)) + currentIndex: 0 + onActivated: index => { + if (index > 0) + root.chooseImportMap(root.savedMaps[index - 1].url) + currentIndex = 0 + } + } + ThemedButton { + objectName: "useTheGuess" + visible: root.importMap.toString() !== "" + compact: true + Layout.preferredHeight: Theme.touchTarget + text: qsTr("Use the guess") + enabled: !Bridge.recordingImport.busy + onClicked: root.useTheGuess() + } + } + Label { + objectName: "importGuessing" + visible: root.importGuessing + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + text: qsTr("Reading the file's header...") + } + CsvGuessPreview { + id: guessPreview + objectName: "guessPreview" + visible: root.importKind === RecordingImport.Csv && root.importMap.toString() === "" + Layout.fillWidth: true + onMapSaved: root.savedMaps = Bridge.recordingImport.savedMaps() + } + + // A candump log's bus, once core has said the log holds several + RowLayout { + visible: root.importKind === RecordingImport.Candump && root.importAsksInterface + Layout.fillWidth: true + spacing: Theme.spacing + Label { text: qsTr("Interface"); color: Theme.textDim; font.pixelSize: 13 } + TextField { + id: importInterface + objectName: "importInterface" + Layout.fillWidth: true + Layout.preferredWidth: 0 // the row's width, not its text's + placeholderText: qsTr("can0") + font.family: Theme.monoFamily + inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText + enabled: !Bridge.recordingImport.busy + } + } + + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "importStart" + text: qsTr("Import") + highlighted: true + enabled: !Bridge.recordingImport.busy && root.importReady + onClicked: root.startImport() + } + ThemedButton { + objectName: "importCancel" + text: qsTr("Cancel") + enabled: !Bridge.recordingImport.busy + onClicked: { + root.importOpen = false + root.importNote = "" + } + } + Label { + objectName: "importBusy" + visible: Bridge.recordingImport.busy + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + text: root.importGuessing ? qsTr("Reading...") : qsTr("Importing...") + } + } + } + + // The last import's words: what it made, or why not + Label { + objectName: "importNote" + visible: root.importNote !== "" && !root.viewing + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: root.importFailed ? Theme.danger : Theme.success + text: root.importNote + } // ---- The list ---- Label { @@ -1012,6 +1405,34 @@ Page { text: qsTr("Save report…") onClicked: reportDialog.open() } + // The signal area's two views: the values at the cursor, or the + // frames in view. Hidden for a recording with no frames.csv + Rectangle { + visible: recording.state === RecordingView.Open && recording.hasFrames + && !root.chartMaximized + implicitWidth: detailSwitch.implicitWidth + 4 + implicitHeight: detailSwitch.implicitHeight + 4 + radius: Theme.radius + color: Theme.surface + + Row { + id: detailSwitch + anchors.centerIn: parent + spacing: 2 + SegmentButton { + objectName: "detailView_values" + text: qsTr("Values") + selected: !root.framesShown + onClicked: root.detailView = "values" + } + SegmentButton { + objectName: "detailView_frames" + text: qsTr("Frames") + selected: root.framesShown + onClicked: root.detailView = "frames" + } + } + } Label { objectName: "reportNote" Layout.fillWidth: true @@ -1167,9 +1588,112 @@ Page { text: root.compareStatus } + // ---- The frames of the part in view, read from frames.csv ---- + ColumnLayout { + objectName: "viewerFrames" + visible: root.framesShown && !root.chartMaximized + Layout.fillWidth: true + spacing: Theme.spacing + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + + Rectangle { + implicitWidth: framesTableSwitch.implicitWidth + 4 + implicitHeight: framesTableSwitch.implicitHeight + 4 + radius: Theme.radius + color: Theme.surface + + Row { + id: framesTableSwitch + anchors.centerIn: parent + spacing: 2 + SegmentButton { + objectName: "framesTable_frames" + text: qsTr("Frames") + selected: !root.framesById + onClicked: root.framesById = false + } + SegmentButton { + objectName: "framesTable_byId" + text: qsTr("By ID") + selected: root.framesById + onClicked: { + root.framesById = true + viewFrames.ids.refresh() + } + } + } + } + ThemedButton { + objectName: "framesFilterToggle" + text: viewFrames.frames.filterTerms > 0 + ? qsTr("Filter (%1)").arg(viewFrames.frames.filterTerms) + : qsTr("Filter") + highlighted: root.framesFilterOpen + onClicked: root.framesFilterOpen = !root.framesFilterOpen + } + } + + FrameFilterPanel { + id: framesFilterPanel + visible: root.framesFilterOpen + frames: viewFrames.frames + } + + // How many rows the part in view has, and when it has more than + // the table holds, where the table begins + Label { + objectName: "framesWords" + Layout.fillWidth: true + Layout.preferredWidth: 0 + wrapMode: Text.WordWrap + color: viewFrames.error !== "" ? Theme.danger : Theme.textDim + font.pixelSize: 13 + text: viewFrames.error !== "" ? viewFrames.error + : viewFrames.loading ? qsTr("Reading the frames…") + : viewFrames.note !== "" ? viewFrames.note + : viewFrames.frames.filterTerms > 0 + ? qsTr("Showing %1 of %2 frames").arg(viewFrames.frames.count) + .arg(viewFrames.frames.heldCount) + : viewFrames.rows === 1 ? qsTr("1 frame in view") + : qsTr("%1 frames in view").arg(viewFrames.rows) + } + + // A fixed height: the page scrolls and the table scrolls inside + FrameTable { + objectName: "viewerFrameTable" + visible: !root.framesById + Layout.preferredHeight: 280 + live: false + frames: viewFrames.frames + emptyText: viewFrames.loading ? qsTr("Reading the frames…") + : viewFrames.frames.heldCount > 0 ? qsTr("No frame the filter shows") + : qsTr("No frame in view") + // A tap puts the chart's cursor at the frame's time, whether + // or not a signal has a sample there + onRowClicked: (index, modifiers, timestampUs) => root.setCursor(timestampUs / 1000) + } + FrameIdList { + objectName: "viewerFrameIds" + visible: root.framesById + Layout.preferredHeight: 280 + ids: viewFrames.ids + refreshing: root.framesById && root.framesShown + emptyText: viewFrames.frames.heldCount > 0 ? qsTr("No frame the filter shows") + : qsTr("No frame in view") + onIdTapped: (id, extended) => { + framesFilterPanel.showId(id, extended) + root.framesFilterOpen = true + root.framesById = false + } + } + } + SignalFilterBar { objectName: "recordingFilter" - visible: recording.state === RecordingView.Open && !root.chartMaximized + visible: recording.state === RecordingView.Open && !root.chartMaximized && !root.framesShown Layout.fillWidth: true filter: signalFilter codes: recording.signalList.map(s => s.group) @@ -1180,7 +1704,7 @@ Page { ListView { id: signalRows objectName: "signalRows" - visible: recording.state === RecordingView.Open && !root.chartMaximized + visible: recording.state === RecordingView.Open && !root.chartMaximized && !root.framesShown Layout.fillWidth: true Layout.preferredHeight: count * root.rowHeight Layout.maximumHeight: Math.max(root.rowHeight, column.height * 0.3) @@ -1263,7 +1787,7 @@ Page { // the chart draws: the chart keeps every ticked signal (ADR-0050) Label { objectName: "filterCount" - visible: recording.state === RecordingView.Open && signalFilter.active && !root.chartMaximized + visible: recording.state === RecordingView.Open && signalFilter.active && !root.chartMaximized && !root.framesShown Layout.fillWidth: true wrapMode: Text.WordWrap color: Theme.textDim diff --git a/app/qml/RingGauge.qml b/app/qml/RingGauge.qml index e0543ba5..2bd29d0b 100644 --- a/app/qml/RingGauge.qml +++ b/app/qml/RingGauge.qml @@ -1,6 +1,5 @@ // File/layer: app/qml/RingGauge.qml | Qt6 Quick + Shapes, UI layer -// Testing: manual smoke: DashboardPage under mock://demo; coolant -// crosses cold -> normal during warm-up; legible at 140 px +// Testing: QML: QmlTest.kinds, QmlTest.gauges, QmlTest.dashboard import QtQuick import QtQuick.Shapes @@ -53,29 +52,30 @@ GaugeBase { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.zoneRadius startAngle: gauge.angleOf(gauge.coldEnd) sweepAngle: Math.max(0, gauge.angleOf(gauge.warnStart) - startAngle - gauge.gapDeg) - strokeColor: Qt.alpha(Theme.text, 0.14) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.14) strokeWidth: gauge.zoneWidth } GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.zoneRadius startAngle: gauge.angleOf(gauge.warnStart) sweepAngle: Math.max(0, gauge.angleOf(gauge.dangerStart) - startAngle - gauge.gapDeg) - strokeColor: Theme.warning + strokeColor: Theme.gaugeWarn strokeWidth: gauge.zoneWidth } GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.zoneRadius startAngle: gauge.angleOf(gauge.dangerStart) sweepAngle: gauge.endAngle - startAngle - strokeColor: Theme.danger - strokeWidth: gauge.zoneWidth + strokeColor: Theme.gaugeDanger + // Heavier than the warning strip: danger is more than a hue + strokeWidth: gauge.zoneWidth * 2 } // Track GaugeArc { centerX: gauge.cx; centerY: gauge.cy; radius: gauge.rr startAngle: gauge.startAngle; sweepAngle: gauge.sweepAngle - strokeColor: Qt.alpha(Theme.text, 0.07) + strokeColor: Qt.alpha(Theme.gaugeTick, 0.07) strokeWidth: gauge.ringWidth capStyle: ShapePath.RoundCap } @@ -103,13 +103,25 @@ GaugeBase { } } + // The held peak: a small mark on the zone strip at its angle, only when + // asked for + Rectangle { + objectName: "peakMark" + visible: gauge.showPeak && !isNaN(gauge.peakValue) + readonly property real a: gauge.angleOf(isNaN(gauge.peakValue) ? gauge.from : gauge.peakValue) + width: gauge.zoneWidth * 2.6; height: width; radius: width / 2 + x: gauge.px(a, gauge.zoneRadius) - width / 2 + y: gauge.py(a, gauge.zoneRadius) - height / 2 + color: Theme.gaugeTick // no zone's color: it sits on the strip + } + // Tip knob Rectangle { visible: gauge.hasValue || gauge.sweeping width: gauge.ringWidth * 0.46; height: width; radius: width / 2 x: gauge.px(gauge.valueAngle, gauge.rr) - width / 2 y: gauge.py(gauge.valueAngle, gauge.rr) - height / 2 - color: Qt.alpha("white", 0.92) + color: Qt.alpha(Theme.gaugeTick, 0.92) } // Range ends under the arc tips @@ -140,13 +152,24 @@ GaugeBase { spacing: gauge.rr * 0.03 Text { id: readout + objectName: "readout" text: gauge.valueText font.pixelSize: Math.max(16, gauge.rr * 0.5) font.weight: Font.DemiBold font.features: ({ "tnum": 1 }) - color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.text) : Theme.textDim + color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim + } + // Past dangerFrom, beside the value + DangerMark { + // The slot stays once a gauge has a danger zone, so the readout + // never moves as the mark appears + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: Math.max(12, gauge.rr * 0.3) + anchors.verticalCenter: readout.verticalCenter } Text { + objectName: "unit" visible: gauge.hasValue anchors.baseline: readout.baseline text: gauge.unit diff --git a/app/qml/SegmentButton.qml b/app/qml/SegmentButton.qml new file mode 100644 index 00000000..e6438122 --- /dev/null +++ b/app/qml/SegmentButton.qml @@ -0,0 +1,35 @@ +// File/layer: app/qml/SegmentButton.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.log, QmlTest.recordings, QmlTest.phone (test_qml) + +import QtQuick +import QtQuick.Controls + +// One option of a toggle of a few. Every option stays visible and the +// current one is filled, so it doesn't read as a dropdown. +AbstractButton { + id: seg + property bool selected: false + + implicitWidth: segLabel.implicitWidth + 24 + implicitHeight: 30 + hoverEnabled: true + Accessible.checkable: true + Accessible.checked: seg.selected + + background: Rectangle { + radius: Theme.radius - 2 + color: seg.selected ? Theme.elevatedLight + : seg.hovered ? Qt.alpha(Theme.text, 0.05) + : "transparent" + border.width: seg.visualFocus ? 2 : 0 + border.color: Theme.text + } + contentItem: Text { + id: segLabel + text: seg.text + font.pixelSize: 13 + color: seg.selected ? Theme.text : Theme.textDim + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } +} diff --git a/app/qml/SegmentGauge.qml b/app/qml/SegmentGauge.qml new file mode 100644 index 00000000..20756ebf --- /dev/null +++ b/app/qml/SegmentGauge.qml @@ -0,0 +1,167 @@ +// File/layer: app/qml/SegmentGauge.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.kinds, QmlTest.dashboard + +import QtQuick + +pragma ComponentBehavior: Bound + +// A tachometer's cells (ADR-0057 section 1): `cells` Rectangles in a row +// along a rising curve, each taller than the one before, lit up to the +// value. A card too narrow for them draws as many as fit at a pitch of +// 3 px plus the gap (`drawn`), so a 64-cell option on a phone's narrow card +// shows fewer, wider cells and never a collapsed row. The cell's color is +// its zone's (warm, then danger past dangerFrom, the danger cells outlined +// like the bar's), the leading cell fades in as the value reaches it, and a +// held peak is a notch over its cell. Static items built for a size; per +// frame only the opacities change. +GaugeBase { + id: gauge + + // How many cells (2 to 64), and the curve's steepness: 0 gives cells + // of one height, 1 a straight rise, more a curve that climbs late + property int cells: 24 + property real rise: 1.6 + + readonly property int count: Math.max(2, Math.min(64, Math.round(cells))) + readonly property real curve: Math.max(0, Math.min(4, rise)) + readonly property real cellGap: width > 240 ? 3 : 2 + // The cells that fit at a pitch of at least 3 px + readonly property int drawn: Math.max(2, Math.min(count, + Math.floor((field.width + cellGap) / (cellGap + 3)))) + // The room above the tallest cell, for the peak's notch + readonly property real headroom: 7 + + // A cell's height as a fraction of the cells' room: 0.2 for the first, + // 1 for the last + function heightOf(i) { + return 0.2 + 0.8 * (curve === 0 ? 1 : Math.pow(i / (drawn - 1), curve)) + } + function valueAt(i) { return from + (i + 0.5) / drawn * (to - from) } + + implicitHeight: 96 + + Text { + id: title + anchors { left: parent.left; top: parent.top } + text: gauge.label + font.pixelSize: 12 + font.weight: Font.DemiBold + font.letterSpacing: 1.2 + font.capitalization: Font.AllUppercase + color: Theme.textDim + } + Text { + anchors { left: title.right; leftMargin: 10; baseline: title.baseline } + visible: !gauge.hasValue + text: gauge.note + font.pixelSize: 11 + color: Qt.alpha(Theme.textDim, 0.7) + } + Row { + id: readout + anchors { right: parent.right; top: parent.top } + spacing: 3 + opacity: gauge.stale ? 0.45 : 1.0 + Text { + id: valueLabel + objectName: "readout" + text: gauge.valueText + font.pixelSize: 22 + font.weight: Font.DemiBold + font.features: ({ "tnum": 1 }) + color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim + } + // Past dangerFrom, beside the value; its slot stays + DangerMark { + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: 18 + anchors.verticalCenter: valueLabel.verticalCenter + } + Text { + objectName: "unit" + visible: gauge.hasValue + anchors.baseline: valueLabel.baseline + text: gauge.unit + font.pixelSize: 12 + color: Theme.textDim + } + } + + Item { + id: field + objectName: "cellField" + anchors { left: parent.left; right: parent.right; top: readout.bottom; topMargin: 8 + bottom: ends.top; bottomMargin: 4 } + + Repeater { + model: gauge.drawn + delegate: Rectangle { + id: cell + required property int index + objectName: "cell" + readonly property color lit: gauge.zoneColor(gauge.valueAt(index), gauge.accent) + readonly property real fill: Math.max(0, Math.min(1, + gauge.fraction * gauge.drawn - index)) + readonly property bool inDangerZone: !isNaN(gauge.dangerFrom) + && gauge.valueAt(index) >= gauge.dangerFrom + + width: (field.width - (gauge.drawn - 1) * gauge.cellGap) / gauge.drawn + height: (field.height - gauge.headroom) * gauge.heightOf(index) + x: index * (width + gauge.cellGap) + y: field.height - height + radius: 2 + color: Qt.alpha(cell.lit, 0.09) + border.width: cell.inDangerZone ? 2 : 0 + border.color: Qt.alpha(Theme.gaugeDanger, 0.55) + + Rectangle { + anchors.fill: parent + radius: parent.radius + opacity: cell.fill + gradient: Gradient { + GradientStop { position: 0.0; color: Qt.lighter(cell.lit, 1.25) } + GradientStop { position: 1.0; color: cell.lit } + } + } + } + } + + // The held peak: a notch over the cell it reached + Rectangle { + objectName: "peakNotch" + readonly property int at: isNaN(gauge.peakValue) ? 0 + : Math.max(0, Math.min(gauge.drawn - 1, + Math.floor(gauge.fractionOf(gauge.peakValue) * gauge.drawn))) + visible: gauge.showPeak && !isNaN(gauge.peakValue) + width: (field.width - (gauge.drawn - 1) * gauge.cellGap) / gauge.drawn + height: 3 + radius: 1 + x: at * (width + gauge.cellGap) + y: field.height - (field.height - gauge.headroom) * gauge.heightOf(at) - 6 + // The tick color, which no zone's cell shares + color: Theme.gaugeTick + } + } + + Item { + id: ends + anchors { left: parent.left; right: parent.right; bottom: parent.bottom } + height: scaleFrom.implicitHeight + Text { + id: scaleFrom + anchors.left: parent.left + text: gauge.formatScale(gauge.from) + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + color: Qt.alpha(Theme.textDim, 0.8) + } + Text { + anchors.right: parent.right + text: gauge.formatScale(gauge.to) + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + color: Qt.alpha(Theme.textDim, 0.8) + } + } +} diff --git a/app/qml/SegmentReadout.qml b/app/qml/SegmentReadout.qml new file mode 100644 index 00000000..37589020 --- /dev/null +++ b/app/qml/SegmentReadout.qml @@ -0,0 +1,167 @@ +// File/layer: app/qml/SegmentReadout.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.kinds, QmlTest.dashboard + +import QtQuick + +pragma ComponentBehavior: Bound + +// Digits of seven segments (ADR-0057 section 1), the unlit segments faint, +// the unit beside. It has no scale to color, so it colors its digits by the +// zones instead: lit in the gauge's accent, warm past warnFrom, danger past +// dangerFrom (with the mark beside the unit). A value too long for `digits` +// (or past 1e15, or infinite) shows dashes in every digit, never a wrong +// number; no value shows blanks; a minus zero shows 0. The unit's box is +// always laid out and sized from the card, never from the digits, so the +// first value never resizes them. A digit is seven static segments whose +// opacity follows the character. +GaugeBase { + id: gauge + + // How many digits (1 to 8) + property int digits: 4 + + readonly property int count: Math.max(1, Math.min(8, Math.round(digits))) + + function dashes() { + const out = [] + for (let i = 0; i < count; ++i) + out.push({ ch: "-", dp: false }) + return out + } + + // What the digits show, one entry per digit, right aligned: the + // character ("0" to "9", "-" or " ") and whether its point is lit + readonly property var shown: { + const blank = [] + for (let i = 0; i < count; ++i) + blank.push({ ch: " ", dp: false }) + if (!hasValue || isNaN(value)) + return blank + if (Math.abs(value) >= 1e15) // also Infinity: more than any digits show + return dashes() + let text = Number(value).toFixed(decimals) + if (/^-0(\.0+)?$/.test(text)) + text = text.slice(1) // a minus zero is a zero + const chars = [] + for (const c of text) { + if (c === ".") + chars[chars.length - 1].dp = true + else + chars.push({ ch: c, dp: false }) + } + if (chars.length > count) + return dashes() + while (chars.length < count) + chars.unshift({ ch: " ", dp: false }) + return chars + } + + // The segments each character lights, a to g clockwise from the top, + // g the middle bar + readonly property var lit: ({ + "0": "abcdef", "1": "bc", "2": "abdeg", "3": "abcdg", "4": "bcfg", + "5": "acdfg", "6": "acdefg", "7": "abc", "8": "abcdefg", "9": "abcdfg", + "-": "g", " ": "" + }) + readonly property color digitColor: hasValue ? zoneColor(value, accent) : Theme.textDim + + // The unit's box: always there, its size from the card + readonly property real unitPx: Math.max(11, Math.min(16, height * 0.16)) + readonly property real markPx: Math.max(12, Math.min(18, height * 0.2)) + + implicitHeight: 64 + + Text { + id: title + anchors { left: parent.left; top: parent.top } + text: gauge.label + font.pixelSize: 12 + font.weight: Font.DemiBold + font.letterSpacing: 1.2 + font.capitalization: Font.AllUppercase + color: Theme.textDim + } + Text { + anchors { left: title.right; leftMargin: 10; baseline: title.baseline } + visible: !gauge.hasValue + text: gauge.note + font.pixelSize: 11 + color: Qt.alpha(Theme.textDim, 0.7) + } + + Row { + id: row + objectName: "digits" + anchors { left: parent.left; top: title.bottom; topMargin: 6 } + // The room left of the unit's box, divided among the digits (each a + // little over half its height wide), at most the card's own height + readonly property real digitH: Math.max(8, Math.min(gauge.height - title.height - 14, + (gauge.width - unitBox.width - 14) / (gauge.count * 0.62))) + height: digitH + spacing: digitH * 0.14 + opacity: gauge.stale ? 0.45 : 1.0 + + Repeater { + model: gauge.count + delegate: Item { + id: digit + required property int index + objectName: "digit" + // The model can outrun `shown` by a binding when `digits` changes + readonly property var entry: gauge.shown[index] ?? ({ ch: " ", dp: false }) + readonly property string on: gauge.lit[entry.ch] ?? "" + readonly property real t: Math.max(2, row.digitH * 0.12) + readonly property real w: row.digitH * 0.5 + width: w + height: row.digitH + + // One segment: a rounded bar whose opacity is its state + component Seg: Rectangle { + required property string name + radius: digit.t / 2 + color: gauge.digitColor + opacity: digit.on.indexOf(name) >= 0 ? 1.0 : 0.08 + } + readonly property real half: (height - 3 * t) / 2 + + Seg { name: "a"; x: digit.t; y: 0; width: digit.w - 2 * digit.t; height: digit.t } + Seg { name: "b"; x: digit.w - digit.t; y: digit.t; width: digit.t; height: digit.half + digit.t / 2 } + Seg { name: "c"; x: digit.w - digit.t; y: digit.t + digit.half + digit.t / 2; width: digit.t; height: digit.half + digit.t / 2 } + Seg { name: "d"; x: digit.t; y: digit.height - digit.t; width: digit.w - 2 * digit.t; height: digit.t } + Seg { name: "e"; x: 0; y: digit.t + digit.half + digit.t / 2; width: digit.t; height: digit.half + digit.t / 2 } + Seg { name: "f"; x: 0; y: digit.t; width: digit.t; height: digit.half + digit.t / 2 } + Seg { name: "g"; x: digit.t; y: digit.t + digit.half; width: digit.w - 2 * digit.t; height: digit.t } + Rectangle { // the decimal point + objectName: "point" + width: digit.t * 1.1; height: width; radius: width / 2 + x: digit.w + row.spacing / 2 - width / 2 + y: digit.height - height + color: gauge.digitColor + opacity: digit.entry.dp ? 1.0 : 0.0 + } + } + } + } + + Row { + id: unitBox + objectName: "unitBox" + anchors { right: parent.right; bottom: row.bottom } + spacing: 4 + opacity: gauge.stale ? 0.45 : 1.0 + Text { + objectName: "unit" + // Kept laid out without a value, so the digits keep their size + opacity: gauge.hasValue ? 1 : 0 + text: gauge.unit + font.pixelSize: gauge.unitPx + color: Theme.textDim + } + // Past dangerFrom, beside the unit; its slot stays + DangerMark { + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: gauge.markPx + } + } +} diff --git a/app/qml/SettingsAdapter.qml b/app/qml/SettingsAdapter.qml new file mode 100644 index 00000000..3aa75054 --- /dev/null +++ b/app/qml/SettingsAdapter.qml @@ -0,0 +1,300 @@ +// File/layer: app/qml/SettingsAdapter.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The adapter list and the presets: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + objectName: "adapterSection" + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + + // ---- Adapters: J2534 interfaces and serial ports ---- + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "deviceCount" + text: root.host.devices.length === 0 + ? qsTr("None found: install a Pass-Thru driver (Windows), plug in " + + "or pair an ELM327 adapter, or pick one below") + : qsTr("J2534 interfaces: %1, serial ports: %2%3; select one to " + + "put its URI in the field above, then Connect") + .arg(root.host.j2534Devices.length).arg(root.host.serialPorts.length) + .arg((root.host.canInterfaces.length > 0 + ? qsTr(", CAN interfaces: %1").arg(root.host.canInterfaces.length) + : "") + + (Bluetooth.available || root.host.bluetoothAdapters.length > 0 + ? qsTr(", Bluetooth: %1").arg(root.host.bluetoothAdapters.length) + : "")) + color: root.host.devices.length === 0 ? Theme.textDim : Theme.text + wrapMode: Text.WordWrap + Layout.fillWidth: true + } + ThemedButton { + text: qsTr("Refresh") + onClicked: { + root.host.refreshDevices() + Bluetooth.userRefresh() + } + } + } + + // ---- Bluetooth (Android): why the list is short, and a + // scan for BLE adapters, which aren't paired ---- + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + visible: Bluetooth.available + + Label { + objectName: "bluetoothStatus" + text: Bluetooth.status !== "" + ? Bluetooth.status + : qsTr("Paired adapters are listed; pair one in Android's " + + "Bluetooth settings") + color: Bluetooth.statusWarns ? Theme.warning : Theme.textDim + wrapMode: Text.WordWrap + Layout.fillWidth: true + } + ThemedButton { + objectName: "bleScanButton" + text: Bluetooth.scanning ? qsTr("Scanning…") : qsTr("Scan for BLE") + enabled: root.host.idle && !Bluetooth.scanning + onClicked: Bluetooth.scan() + } + } + // Android won't show its dialog: Havne's own page in its settings + ThemedButton { + objectName: "bluetoothSettingsButton" + text: qsTr("Open settings") + visible: Bluetooth.available && Bluetooth.needsSettings + onClicked: Bluetooth.openSettings() + } + + // Sized to its rows up to deviceRowsShown, then it scrolls + ListView { + id: deviceList + objectName: "deviceList" + // No current row: ListView gives a current one a default + // highlight, which animates to its size and, after the + // section opened at a phone's width, lay past the edge + currentIndex: -1 + highlightFollowsCurrentItem: false + Layout.fillWidth: true + Layout.preferredHeight: contentHeight + Layout.maximumHeight: root.host.deviceRowsShown * (root.host.deviceRowHeight + spacing) - spacing + visible: count > 0 + clip: true + spacing: 2 + boundsBehavior: Flickable.StopAtBounds + model: root.host.devices + + ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } + + delegate: Rectangle { + id: row + required property var modelData + width: deviceList.width + height: root.host.deviceRowHeight + radius: Theme.radius + color: mouse.containsMouse ? Theme.elevatedLight : Theme.elevated + border.width: root.host.isChosen(row.modelData.base) ? 2 : 0 + border.color: Theme.primary + + MouseArea { + id: mouse + objectName: "deviceRowArea" + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + enabled: root.host.idle + onClicked: { + root.host.fillUri(row.modelData.base) + root.host.showUriField() + } + } + + ColumnLayout { + anchors.fill: parent + anchors.margins: Theme.spacing + spacing: 2 + + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "deviceTitle" + text: row.modelData.title + color: root.host.idle ? Theme.text : Theme.textDim + } + Label { + objectName: "deviceVersions" + visible: text !== "" + text: row.modelData.versions === "" + ? "" : qsTr("last seen: %1").arg(row.modelData.versions) + color: Theme.textDim + font.pointSize: 8 + elide: Text.ElideRight + horizontalAlignment: Text.AlignRight + rightPadding: Theme.spacing // clear of the list's scroll bar + Layout.fillWidth: true + } + } + Label { + objectName: "deviceDetail" + text: row.modelData.detail + color: Theme.textDim + font.pointSize: 8 + elide: Text.ElideMiddle + Layout.fillWidth: true + } + } + } + } + + // ---- Relay (the phone, developer mode; ADR-0047): the + // selected Bluetooth adapter relayed to a computer over USB, + // for havne-cli there ---- + ColumnLayout { + objectName: "relayBox" + visible: Relay.available && Theme.developerMode + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "relayStatus" + text: Relay.running + ? Relay.status + : qsTr("Relay to a computer over USB: select a paired adapter above, " + + "Relay, then on the computer adb forward tcp:%1 tcp:%1 " + + "and havne-cli on elm327://127.0.0.1:%1") + .arg(Relay.defaultPort) + color: Relay.running ? Theme.text : Theme.textDim + wrapMode: Text.WordWrap + Layout.fillWidth: true + } + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "relayTraffic" + visible: Relay.running + text: qsTr("%1 from the adapter, %2 to it") + .arg(root.host.byteText(Relay.bytesIn)) + .arg(root.host.byteText(Relay.bytesOut)) + color: Theme.textDim + // Beside the button on a phone's width + wrapMode: Text.WordWrap + Layout.fillWidth: true + } + ThemedButton { + objectName: "relayButton" + text: Relay.running ? qsTr("Stop relaying") : qsTr("Relay") + // Not beside a session: the adapter takes one link + enabled: Relay.running + || (root.host.idle && /^elm327:\/\/bt:/i.test(root.host.uriField.text)) + onClicked: { + if (Relay.running) { + Relay.stop() + return + } + const why = Relay.start(root.host.uriField.text) + root.host.errorLabel.text = why + root.host.errorLabel.visible = why !== "" + } + } + } + } + + // ---- Presets: the URI's base, for what the list doesn't show. Closed + // until the row is tapped: five buttons would fill a phone's page ---- + property bool presetsOpen: false + // A J2534 interface is a Windows driver + property bool j2534Offered: Qt.platform.os === "windows" + LabeledFlow { + ThemedButton { + objectName: "presetsToggle" + // Expanded or not, for a screen reader + Accessible.role: Accessible.Button + Accessible.checkable: true + Accessible.checked: root.presetsOpen + text: root.presetsOpen ? qsTr("Not listed: hide") : qsTr("Not listed: show") + onClicked: root.presetsOpen = !root.presetsOpen + } + Repeater { + model: [ + { name: "mock", uri: "mock://demo", label: "mock://demo", hint: "" }, + // A bare j2534:// opens the first discovered device + { name: "j2534", uri: "j2534://", label: qsTr("j2534:// (first device)"), hint: "" }, + // elm327:// takes no first port: the user picks one + // from the list above or types a WiFi adapter's + // address (core's refusal says so) + { name: "elm327", uri: "elm327://", label: qsTr("elm327:// (type an address)"), hint: "" }, + // WiFi adapters aren't listed (ADR-0026's appendix + // "WiFi over TCP"): the two common addresses, so a + // phone needn't type one + { name: "wifi_obdx", uri: "elm327://192.168.4.1:23", + label: qsTr("WiFi: OBDX"), hint: "192.168.4.1:23" }, + { name: "wifi_elm", uri: "elm327://192.168.0.10:35000", + label: qsTr("WiFi: other adapters"), hint: "192.168.0.10:35000" } + ] + ThemedButton { + id: preset + required property var modelData + objectName: "preset_" + modelData.name + text: modelData.label + Accessible.name: modelData.hint !== "" ? modelData.label + " " + modelData.hint + : modelData.label + // Wraps rather than run past a narrow page's edge + // (Linux's font at 320 px did) + width: Math.min(implicitWidth, parent.width) + // The mock is a developer's tool, not a device + visible: root.presetsOpen + && (modelData.name !== "mock" || Theme.developerMode) + && (modelData.name !== "j2534" || root.j2534Offered) + enabled: root.host.idle + onClicked: { + root.host.fillUri(modelData.uri) + root.host.showUriField() + } + // The name, and the address smaller under it. The width is + // stated, so the children's (the item's) don't feed back + contentItem: Item { + implicitWidth: Math.max(nameText.implicitWidth, hintText.implicitWidth) + implicitHeight: nameText.height + (hintText.visible ? hintText.height : 0) + Text { + id: nameText + width: parent.width + text: preset.text + font.pixelSize: 14 + color: Theme.text + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + } + Text { + id: hintText + y: nameText.height + width: parent.width + visible: preset.modelData.hint !== "" + text: preset.modelData.hint + font.pixelSize: 11 + color: Theme.textDim + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + } + } + } + } + } +} diff --git a/app/qml/SettingsAdvanced.qml b/app/qml/SettingsAdvanced.qml new file mode 100644 index 00000000..4e6e9406 --- /dev/null +++ b/app/qml/SettingsAdvanced.qml @@ -0,0 +1,36 @@ +// File/layer: app/qml/SettingsAdvanced.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// Developer mode: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + // Developer mode (Theme.developerMode); Main.qml stores it + ThemedCheckBox { + id: developerBox + objectName: "developerBox" + text: qsTr("Developer mode: the mock:// preset, and the raw frames on the Log page") + checked: Theme.developerMode + Layout.fillWidth: true + onToggled: { + Theme.developerMode = checked + checked = Qt.binding(() => Theme.developerMode) + } + contentItem: Label { + text: developerBox.text + color: Theme.text + leftPadding: developerBox.indicator.width + developerBox.spacing + verticalAlignment: Text.AlignVCenter + wrapMode: Text.WordWrap + } + } +} diff --git a/app/qml/SettingsConnect.qml b/app/qml/SettingsConnect.qml new file mode 100644 index 00000000..b238656e --- /dev/null +++ b/app/qml/SettingsConnect.qml @@ -0,0 +1,95 @@ +// File/layer: app/qml/SettingsConnect.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The connect bar (the status line, the URI field and Connect): one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + property alias uriField: uriField + property alias errorLabel: errorLabel + + Label { + objectName: "sessionStatus" + text: Bridge.connected + ? qsTr("Connected: %1").arg(Bridge.currentUri) + : Bridge.connecting ? qsTr("Connecting…") + : Bridge.disconnecting ? qsTr("Disconnecting…") + : qsTr("Not connected") + color: Theme.linkColor(Bridge.linkState) + // A long URI breaks anywhere: unwrapped, it widened the + // page past a phone's edge once connected + wrapMode: Text.WrapAnywhere + Layout.fillWidth: true + } + + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + + TextField { + id: uriField + objectName: "uriField" + Layout.fillWidth: true + // ?poll= replaces the profile's PID rotation. Raw on an + // adapter listens to the engine ECU, so ?poll= alone + // asks it; under the obd2 default it also decodes. + // A WiFi adapter is typed: nothing lists it (ADR-0026's + // appendix "WiFi over TCP") + placeholderText: qsTr("URI, e.g. mock://demo, elm327://COM5, " + + "elm327://192.168.0.10:35000 or " + + "j2534://Vendor?profile=raw&poll=0x0C") + enabled: root.host.idle + color: Theme.text + // A URI, not prose: a phone's keyboard capitalized + // "Replay://" into a scheme core doesn't know + inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText + // Any text the page didn't compose is read back + onTextChanged: { + if (!root.host.composing) + root.host.readChoices() + } + onAccepted: root.host.requestConnect(text) + } + + ThemedButton { + objectName: "connectButton" + text: Bridge.connected ? qsTr("Disconnect") + : Bridge.connecting ? qsTr("Connecting…") + : Bridge.disconnecting ? qsTr("Disconnecting…") + : qsTr("Connect") + highlighted: !Bridge.connected + // Disconnect is always offered; Connect only while idle + // with a URI to connect + // and no relay holds the adapter (ADR-0047) + enabled: Bridge.connected + || (root.host.idle && uriField.text !== "" && !Relay.running) + onClicked: { + if (Bridge.connected) { + Bridge.disconnectSession() + errorLabel.visible = false + } else { + root.host.requestConnect(uriField.text) + } + } + } + } + + Label { + id: errorLabel + objectName: "errorLabel" + visible: false + color: Theme.danger + wrapMode: Text.WrapAnywhere + Layout.fillWidth: true + text: "" + } +} diff --git a/app/qml/SettingsDisplay.qml b/app/qml/SettingsDisplay.qml new file mode 100644 index 00000000..1615d484 --- /dev/null +++ b/app/qml/SettingsDisplay.qml @@ -0,0 +1,106 @@ +// File/layer: app/qml/SettingsDisplay.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// Zoom and units: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + // The whole UI's zoom; Main.qml applies and stores it + // One row of four: a button never wraps alone onto a second line + ColumnLayout { + Layout.fillWidth: true + spacing: Theme.spacing + Label { + text: qsTr("Display size:") + color: Theme.textDim + } + RowLayout { + spacing: Theme.spacing + ThemedButton { + id: smaller + compact: true + implicitWidth: Math.max(40, Theme.touchTarget) + text: "−" + Accessible.name: qsTr("Smaller") + enabled: Theme.zoom > Theme.zoomSteps[0] + 0.001 + onClicked: Theme.stepZoom(-1) + } + Label { + Layout.preferredWidth: Math.max(52, implicitWidth) + Layout.preferredHeight: smaller.height + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + text: qsTr("%1 %").arg(Math.round(Theme.zoom * 100)) + color: Theme.text + } + ThemedButton { + compact: true + implicitWidth: Math.max(40, Theme.touchTarget) + text: "+" + Accessible.name: qsTr("Larger") + enabled: Theme.zoom < Theme.zoomSteps[Theme.zoomSteps.length - 1] - 0.001 + onClicked: Theme.stepZoom(1) + } + ThemedButton { + text: qsTr("Reset") + enabled: Math.abs(Theme.zoom - 1) > 0.001 + onClicked: Theme.zoom = 1 + } + } + } + // A phone has no keyboard to zoom with + Label { + visible: !Theme.mobile + text: qsTr("or Ctrl + / Ctrl − / Ctrl 0") + color: Theme.textDim + wrapMode: Text.WordWrap + Layout.fillWidth: true + } + + // The theme: Dark, or Low glare and Night (amber and red on near black) + // for a cabin after dark. Takes effect at once; Theme.qml stores it. + LabeledFlow { + label: qsTr("Theme:") + Repeater { + model: Theme.themeNames + ThemedButton { + required property string modelData + objectName: "theme_" + modelData + text: Theme.themeLabel(modelData) + highlighted: Theme.active === modelData + onClicked: Theme.theme = modelData + } + } + } + + // Units: what the pages show, converted in core (ADR-0022); + // recordings keep the decoded values. Main.qml stores it. + // Takes effect at once, connected or not. + LabeledFlow { + label: qsTr("Units:") + Repeater { + model: [ + { system: 0, name: "metric", label: qsTr("Metric (km/h, °C)") }, + { system: 1, name: "imperial", label: qsTr("Imperial (mph, °F)") } + ] + ThemedButton { + required property var modelData + // A long label wraps rather than run past a phone's edge + width: Math.min(implicitWidth, parent.width) + objectName: "units_" + modelData.name + text: modelData.label + highlighted: Bridge.unitSystem === modelData.system + onClicked: Bridge.unitSystem = modelData.system + } + } + } +} diff --git a/app/qml/SettingsList.qml b/app/qml/SettingsList.qml new file mode 100644 index 00000000..a11ea090 --- /dev/null +++ b/app/qml/SettingsList.qml @@ -0,0 +1,50 @@ +// File/layer: app/qml/SettingsList.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The list of Settings' pages, each row with its summary on the right + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +// pages: [{ key, title, summary }]; current is the key shown (the wide +// layout's selection, "" on a phone's list) +ColumnLayout { + id: list + property var pages: [] + property string current: "" + signal chosen(string key) + spacing: 0 + + Repeater { + model: list.pages + ThemedButton { + id: row + required property var modelData + objectName: "settingsRow_" + modelData.key + Layout.fillWidth: true + Layout.preferredHeight: Theme.touchTarget + highlighted: list.current === modelData.key + Accessible.name: modelData.title + onClicked: list.chosen(modelData.key) + contentItem: RowLayout { + spacing: 10 + Label { + text: row.modelData.title + color: Theme.text + font.pixelSize: 16 + font.weight: Font.DemiBold + } + Label { + objectName: "settingsRowSummary" + text: row.modelData.summary + color: Theme.textDim + elide: Text.ElideRight + horizontalAlignment: Text.AlignRight + Layout.fillWidth: true + } + } + } + } +} diff --git a/app/qml/SettingsOwnForm.qml b/app/qml/SettingsOwnForm.qml new file mode 100644 index 00000000..81e499d0 --- /dev/null +++ b/app/qml/SettingsOwnForm.qml @@ -0,0 +1,288 @@ +// File/layer: app/qml/SettingsOwnForm.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The form for a vehicle's own signal (Add a signal, Edit): a page of its own in Settings + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + property alias formName: formName + property alias formRx: formRx + property alias formTx: formTx + property alias formNumber: formNumber + property alias formByte: formByte + property alias formBits: formBits + property alias formBit: formBit + property alias formBytes: formBytes + property alias formSigned: formSigned + property alias formScale: formScale + property alias formOffset: formOffset + property alias formUnit: formUnit + property alias formDecimals: formDecimals + property alias formValues: formValues + + objectName: "signalForm" + visible: root.host.pickedVehicle !== null + Layout.fillWidth: true + spacing: Theme.spacing + + Flow { + id: formNameRow + Layout.fillWidth: true + spacing: Theme.spacing + Captioned { + caption: qsTr("Name") + TextField { + id: formName + objectName: "formName" + placeholderText: qsTr("Name") + width: Math.min(formNameRow.width, Theme.controlHeight * 8) + } + } + Captioned { + caption: qsTr("Reply ID") + TextField { + id: formRx + objectName: "formRx" + text: "7E8" + placeholderText: qsTr("Reply ID") + width: Theme.controlHeight * 3 + } + } + Captioned { + caption: qsTr("Request ID") + TextField { + id: formTx + objectName: "formTx" + placeholderText: qsTr("Request ID") + width: Theme.controlHeight * 3 + } + } + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + Repeater { + model: [{ name: "01", label: qsTr("01 PID") }, { name: "22", label: qsTr("22 DID") }] + ThemedButton { + required property var modelData + objectName: "formService_" + modelData.name + text: modelData.label + highlighted: root.host.formService === modelData.name + onClicked: root.host.formService = modelData.name + } + } + Captioned { + caption: root.host.formService === "22" ? qsTr("DID") : qsTr("PID") + TextField { + id: formNumber + objectName: "formNumber" + placeholderText: root.host.formService === "22" ? qsTr("DID, 4 hex digits") + : qsTr("PID, 2 hex digits") + width: Theme.controlHeight * 5 + } + } + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + Repeater { + model: SignalForm.kinds + ThemedButton { + required property string modelData + objectName: "formKind_" + modelData + text: modelData + highlighted: root.host.formKind === modelData + onClicked: root.host.formKind = modelData + } + } + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + Captioned { + caption: qsTr("Byte") + TextField { + id: formByte + objectName: "formByte" + text: "0" + placeholderText: qsTr("Byte") + width: Theme.controlHeight * 2.5 + } + } + Captioned { + caption: qsTr("Bits") + visible: root.host.formKind === "number" || root.host.formKind === "enum" + TextField { + id: formBits + objectName: "formBits" + text: "8" + placeholderText: qsTr("Bits") + width: Theme.controlHeight * 2.5 + } + } + Captioned { + caption: qsTr("Start bit") + visible: root.host.formKind === "number" || root.host.formKind === "enum" + TextField { + id: formBit + objectName: "formBit" + placeholderText: qsTr("Bit") + width: Theme.controlHeight * 2.5 + } + } + Captioned { + caption: qsTr("Bytes") + visible: !(root.host.formKind === "number" || root.host.formKind === "enum") + TextField { + id: formBytes + objectName: "formBytes" + placeholderText: qsTr("Bytes (all)") + width: Theme.controlHeight * 3 + } + } + Repeater { + model: root.host.formKind === "number" || root.host.formKind === "enum" ? ["be", "le"] : [] + ThemedButton { + required property string modelData + objectName: "formOrder_" + modelData + text: modelData + highlighted: root.host.formOrder === modelData + onClicked: root.host.formOrder = modelData + } + } + ThemedCheckBox { + id: formSigned + objectName: "formSigned" + visible: root.host.formKind === "number" + text: qsTr("Signed") + } + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + visible: root.host.formKind === "number" + Captioned { + caption: qsTr("Scale") + TextField { + id: formScale + objectName: "formScale" + placeholderText: qsTr("Scale (1)") + width: Theme.controlHeight * 3 + } + } + Captioned { + caption: qsTr("Offset") + TextField { + id: formOffset + objectName: "formOffset" + placeholderText: qsTr("Offset (0)") + width: Theme.controlHeight * 3 + } + } + Captioned { + caption: qsTr("Unit") + TextField { + id: formUnit + objectName: "formUnit" + placeholderText: qsTr("Unit") + width: Theme.controlHeight * 3 + } + } + Captioned { + caption: qsTr("Decimals") + TextField { + id: formDecimals + objectName: "formDecimals" + placeholderText: qsTr("Decimals") + width: Theme.controlHeight * 3 + } + } + } + + TextField { + id: formValues + objectName: "formValues" + visible: root.host.formKind === "enum" + placeholderText: qsTr("Values: 0=Park, 1=Reverse, 2=Neutral") + Layout.fillWidth: true + } + + LabeledFlow { + label: qsTr("Group:") + Repeater { + model: SignalForm.groups + ThemedButton { + required property string modelData + objectName: "formGroup_" + (modelData === "" ? "other" : modelData) + text: modelData === "" ? qsTr("other") : modelData + highlighted: root.host.formGroup === modelData + onClicked: root.host.formGroup = modelData + } + } + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "formReadOnce" + text: Bridge.readingOnce ? qsTr("Reading...") : qsTr("Read once") + enabled: root.host.idle && !Bridge.readingOnce && root.host.confirming === "" + onClicked: root.host.readOnceDraft() + } + ThemedButton { + objectName: "formSave" + text: qsTr("Save") + enabled: root.host.idle && root.host.confirming === "" + onClicked: { + if (root.host.saveDraft()) { + // Saved: the form empties for the next, and Signals shows the note + const note = root.host.formNote + root.host.clearForm() + root.host.formNote = note + root.host.back() + } + } + } + ThemedButton { + objectName: "formClear" + text: qsTr("Clear") + onClicked: root.host.clearForm() + } + } + + Label { + objectName: "formReadResult" + visible: text !== "" + text: root.host.readResultText(root.host.readResult) + color: root.host.readResult !== null && root.host.readResult.ok ? Theme.text : Theme.warning + wrapMode: Text.WrapAnywhere + Layout.fillWidth: true + } + Label { + objectName: "formProblem" + visible: text !== "" + text: root.host.formProblem + color: Theme.warning + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Label { + objectName: "formNote" + visible: text !== "" + text: root.host.formNote + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } +} diff --git a/app/qml/SettingsOwnSignals.qml b/app/qml/SettingsOwnSignals.qml new file mode 100644 index 00000000..f2a78915 --- /dev/null +++ b/app/qml/SettingsOwnSignals.qml @@ -0,0 +1,84 @@ +// File/layer: app/qml/SettingsOwnSignals.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The vehicle's own signals and Add a signal: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + objectName: "settingsOwnSignalsPart" + visible: root.host.pickedVehicle !== null + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + + // ---- The vehicle's own signals (ADR-0051's form) ---- + Label { + objectName: "ownSignalsTitle" + visible: root.host.pickedVehicle !== null + text: qsTr("Your own signals") + color: Theme.text + font.bold: true + } + + Repeater { + model: root.host.ownSignals + RowLayout { + id: ownRow + required property var modelData + required property int index + objectName: "ownSignal_" + index + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "ownSignalText" + text: qsTr("%1: %2").arg(ownRow.modelData.name, + SignalForm.describe(root.host.ownFile, ownRow.modelData)) + color: Theme.text + wrapMode: Text.Wrap + Layout.fillWidth: true + } + ThemedButton { + objectName: "ownEdit_" + ownRow.index + text: qsTr("Edit") + enabled: root.host.confirming === "" + onClicked: { + root.host.editOwnSignal(ownRow.modelData.key) + root.host.openOwnForm() + } + } + ThemedButton { + objectName: "ownRemove_" + ownRow.index + text: qsTr("Remove") + enabled: root.host.idle && root.host.confirming === "" + onClicked: root.host.removeOwnSignal(ownRow.modelData.key) + } + } + } + + Label { + objectName: "ownSignalsNote" + visible: text !== "" + text: root.host.formNote + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + ThemedButton { + objectName: "ownAdd" + text: qsTr("Add a signal") + enabled: root.host.confirming === "" + onClicked: { + // A new signal starts from an empty form, not the last one edited + root.host.clearForm() + root.host.openOwnForm() + } + } +} diff --git a/app/qml/SettingsPage.qml b/app/qml/SettingsPage.qml index 80e29617..ac480e17 100644 --- a/app/qml/SettingsPage.qml +++ b/app/qml/SettingsPage.qml @@ -1,14 +1,11 @@ // File/layer: app/qml/SettingsPage.qml | Qt6 Quick, UI layer -// Testing: UNIT: SignalsTest (test_signals); BRIDGE: BridgeTest -// (test_bridge); QML: QmlTest.settings, QmlTest.linkhealth, -// QmlTest.log, QmlTest.phone (test_qml); Manual smoke +// Testing: QML: QmlTest.settings, QmlTest.linkhealth, QmlTest.log, +// QmlTest.phone (test_qml) import QtCore import QtQuick import QtQuick.Controls -import QtQuick.Dialogs import QtQuick.Layouts -import QtQuick.Shapes pragma ComponentBehavior: Bound @@ -17,6 +14,28 @@ Pane { padding: 0 background: Rectangle { color: Theme.bg } + property alias uriField: settingsConnect.uriField + property alias errorLabel: settingsConnect.errorLabel + property alias vehicleLabelField: settingsVehiclePicker.vehicleLabelField + property alias obdbYearField: settingsSignalFiles.obdbYearField + property alias saveDialog: settingsSignalFiles.saveDialog + property alias formName: settingsOwnForm.formName + property alias formRx: settingsOwnForm.formRx + property alias formTx: settingsOwnForm.formTx + property alias formNumber: settingsOwnForm.formNumber + property alias formByte: settingsOwnForm.formByte + property alias formBits: settingsOwnForm.formBits + property alias formBit: settingsOwnForm.formBit + property alias formBytes: settingsOwnForm.formBytes + property alias formSigned: settingsOwnForm.formSigned + property alias formScale: settingsOwnForm.formScale + property alias formOffset: settingsOwnForm.formOffset + property alias formUnit: settingsOwnForm.formUnit + property alias formDecimals: settingsOwnForm.formDecimals + property alias formValues: settingsOwnForm.formValues + property alias vinLookupField: settingsVinLookup.vinLookupField + property alias didField: settingsProfile.didField + readonly property int deviceRowHeight: 56 readonly property int deviceRowsShown: 4 // the list scrolls past this @@ -440,7 +459,13 @@ Pane { chooseProfile(profile) } - // The picked vehicle's variant as What to read offers it: null for + // The Signals row's summary: a count of files, one or many (no + // translation is loaded to pick a plural form) + function filesSummary(n) { + return n === 1 ? qsTr("1 file") : qsTr("%1 files").arg(n) + } + + // The picked vehicle's variant as the Profile buttons offer it: null for // none, or one no plugin loaded registers function pluginChoice() { if (pickedVehicle === null || pickedVehicle.plugin === "") @@ -527,7 +552,7 @@ Pane { // The vehicle a Read once was asked for: its reply shows only there property string readOnceFor: "" - // The form and the section's notes are the picked vehicle's: a pick, + // The form and the page's notes are the picked vehicle's: a pick, // New, Duplicate, Forget or a car recognized starts them afresh, and a // question asked about the last one goes with it readonly property string pickedId: pickedVehicle !== null ? pickedVehicle.id : "" @@ -742,7 +767,7 @@ Pane { uriField.text = pickedVehicle.uri } - // A change of the list from the section's buttons: the field empties + // A change of the list from the page's buttons: the field empties // for the next label function changeVehicles(doc) { confirming = "" @@ -786,113 +811,92 @@ Pane { // rewrite the grayed field under the connect in flight. readonly property bool idle: !Bridge.connected && !Bridge.connecting && !Bridge.disconnecting - component Heading: Label { - color: Theme.text - font.pixelSize: 16 - font.weight: Font.DemiBold - Layout.topMargin: Theme.spacing - } - - // A form's box with its name above it: a placeholder alone goes once - // something is typed, and the box no longer says what it holds - component Captioned: Column { - property alias caption: captionText.text - spacing: 2 - Label { - id: captionText - color: Theme.textDim + // ---- Navigation: the list of pages, and the page shown. A phone shows + // one at a time (the list is the root, a page pushes over it); 900 and + // wider shows the list at the left and a page beside it. The pages are + // all made once and shown or hidden, so the state in them (a typed + // URI, a half-filled form) survives a visit elsewhere ---- + property string pageKey: "" // "" is the list, on a phone + readonly property bool twoPane: width >= 900 + readonly property string shownKey: twoPane && pageKey === "" ? "connection" : pageKey + readonly property var pageList: [ + { key: "connection", title: qsTr("Connection"), + summary: (devices.length === 0 ? qsTr("none found") : qsTr("%1 found").arg(devices.length)) + + " · " + profileLabel() }, + { key: "vehicle", title: qsTr("Vehicle"), + summary: (pickedVehicle !== null ? pickedVehicle.label : qsTr("None")) + + (vehicles.list.length > 0 ? qsTr(" · %1 saved").arg(vehicles.list.length) : "") }, + { key: "signals", title: qsTr("Signals"), + summary: pickedVehicle === null ? qsTr("pick a vehicle") + : filesSummary(pickedVehicle.signals.length + (pickedVehicle.own !== "" ? 1 : 0)) }, + { key: "recording", title: qsTr("Recording"), + summary: Bridge.recordingActive ? qsTr("recording") : Bridge.recording ? qsTr("on") : qsTr("off") }, + { key: "display", title: qsTr("Display"), + summary: qsTr("%1 %").arg(Math.round(Theme.zoom * 100)) + + (Bridge.unitSystem === 1 ? qsTr(" · imperial") : qsTr(" · metric")) }, + { key: "advanced", title: qsTr("Advanced"), + summary: Theme.developerMode ? qsTr("developer mode") : qsTr("off") } + ] + + function open(key) { + pageKey = key + } + // Back from a page: the form returns to Signals, the rest to the list + function back() { + pageKey = pageKey === "ownform" ? "signals" : "" + } + // The form for a new signal (Add a signal), as a page of its own + function openOwnForm() { + open("ownform") + } + // The phone's Bluetooth permission is asked for when what to connect to + // is seen: Connection is the page shown and Settings is on screen. Not + // at launch, and not when the width crosses 900 while Settings is + // hidden. bluetoothAsks counts the asks + property int bluetoothAsks: 0 + function askBluetoothIfSeen() { + if (visible && shownKey === "connection") { + ++bluetoothAsks + Bluetooth.refresh(true) } } - - // A caption, then buttons that wrap: a row of them would hold the - // page at its natural width, past a phone's. The caption is the - // flow's first item, so a wrapped button has the whole width - component LabeledFlow: Flow { - property alias label: caption.text - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - id: caption - visible: text !== "" - color: Theme.textDim - topPadding: 8 + // Back from Android's settings (or any other app) with Connection + // shown: the permission may have changed there, so the message and the + // Open settings button follow it with no tap. Reads the answer only: + // never an ask, never a scan. bluetoothRechecks counts them + property int bluetoothRechecks: 0 + function recheckBluetoothIfSeen() { + if (visible && shownKey === "connection") { + ++bluetoothRechecks + Bluetooth.refresh(false) } } - - // The page is the connect bar, then five sections, each folded - // until its heading is pressed: what to connect to, the vehicle, what - // to read, recording and the display. Unfolded, the page ran to - // several screens on a phone and an adapter sat at its bottom. Each - // heading says what its section holds now, so the page reads folded - // (docs/bench-sessions/2026-10-28-android-5.md) - component Section: ColumnLayout { - id: section - property string title - property string summary - property bool open: false - default property alias content: body.data - Layout.fillWidth: true - spacing: Theme.spacing * 2 - - ThemedButton { - objectName: section.objectName + "Heading" - Layout.fillWidth: true - Accessible.name: section.title - onClicked: section.open = !section.open - contentItem: RowLayout { - spacing: 10 - // Drawn, not a glyph: Android's fonts have no ▸ or ▾, - // which showed as a box - Shape { - objectName: "sectionChevron" - Layout.preferredWidth: 10 - Layout.preferredHeight: 10 - rotation: section.open ? 90 : 0 - preferredRendererType: Shape.CurveRenderer - ShapePath { - strokeColor: Theme.text - strokeWidth: 1.5 - fillColor: "transparent" - capStyle: ShapePath.RoundCap - joinStyle: ShapePath.RoundJoin - startX: 3.5; startY: 1 - PathLine { x: 7.5; y: 5 } - PathLine { x: 3.5; y: 9 } - } - } - Label { - text: section.title - color: Theme.text - font.pixelSize: 16 - font.weight: Font.DemiBold - } - Label { - objectName: "sectionSummary" - text: section.summary - color: Theme.textDim - elide: Text.ElideRight - horizontalAlignment: Text.AlignRight - Layout.fillWidth: true - } - } + // qmllint disable missing-property + Connections { + target: Qt.application + function onStateChanged() { + if (Qt.application.state === Qt.ApplicationActive) + page.recheckBluetoothIfSeen() } - - ColumnLayout { - id: body - visible: section.open - Layout.fillWidth: true - Layout.leftMargin: Theme.spacing - Layout.bottomMargin: Theme.spacing - spacing: Theme.spacing * 2 + } + // qmllint enable missing-property + onShownKeyChanged: askBluetoothIfSeen() + onVisibleChanged: askBluetoothIfSeen() + + // A best-effort back key: where Qt delivers it, it repeats the back + // arrow. Nothing relies on it + focus: true + Keys.onBackPressed: event => { + if (!twoPane && pageKey !== "") { + back() + event.accepted = true } } // Connect... on Home, Live or the header lands here: what to connect to - // is open, folded or not before function showAdapters() { - adapterSection.open = true - flick.contentY = 0 + open("connection") + connectionPage.contentY = 0 } function profileLabel() { @@ -918,6 +922,8 @@ Pane { // needs nothing typed. Set like typed text, so the profile row and the // DID field read it function pickRecording(uri) { + // The field is on Connection, which a phone may not be showing + open("connection") uriField.text = uri showUriField() } @@ -932,9 +938,10 @@ Pane { // Connect and the error line under them when they're above the view, // as on a phone, where the pick otherwise seems to do nothing function showUriField() { - const top = uriField.mapToItem(column, 0, 0).y + column.y - Theme.spacing - if (top < flick.contentY) - flick.contentY = Math.max(0, top) + const body = connectionPage.body + const top = uriField.mapToItem(body, 0, 0).y + body.y - Theme.spacing + if (top < connectionPage.contentY) + connectionPage.contentY = Math.max(0, top) } // The URI is composed from three choices, so none of it needs typing: @@ -1201,7 +1208,7 @@ Pane { useSignalFiles() loadPlugins() refreshDevices() - Bluetooth.refresh(false) // asked for when Adapter first opens + Bluetooth.refresh(false) // asked for when Connection first opens // Set like typed text, so the profile row and the DID field read // it back if (uriField.text === "") @@ -1217,8 +1224,8 @@ Pane { page.readResult = result } function onConnectResult(uri, error) { - errorLabel.text = error - errorLabel.visible = (error !== "") + page.errorLabel.text = error + page.errorLabel.visible = (error !== "") if (error === "") { sessionSettings.uri = uri page.rememberVersions(uri, Bridge.adapterVersions) @@ -1265,1416 +1272,166 @@ Pane { } } - // Scrolls when the content doesn't fit (a short laptop screen); - // otherwise the activity log takes the height that's left - Flickable { - id: flick - objectName: "settingsFlick" + RowLayout { anchors.fill: parent - contentWidth: width - contentHeight: column.height + 2 * Theme.pageMargin - clip: true - boundsBehavior: Flickable.StopAtBounds - ScrollBar.vertical: ScrollBar { - policy: flick.contentHeight > flick.height ? ScrollBar.AlwaysOn : ScrollBar.AsNeeded + spacing: 0 + + SettingsList { + objectName: "settingsSideList" + visible: page.twoPane + Layout.preferredWidth: 200 + // A nested layout fills its row by default, which would leave + // the pages beside it no width + Layout.fillWidth: false + Layout.fillHeight: true + Layout.alignment: Qt.AlignTop + Layout.margins: Theme.pageMargin + pages: page.pageList + current: page.shownKey + onChosen: key => page.open(key) } - ColumnLayout { - id: column - objectName: "settingsColumn" - x: Theme.pageMargin - y: Theme.pageMargin - width: flick.width - 2 * Theme.pageMargin - // Its content's height: stretched to the page, a layout spreads - // the spare height between the folded headings - height: implicitHeight - spacing: Theme.spacing * 2 - - PageHeader { title: qsTr("Settings") } - - // ---- Connection ---- - Heading { text: qsTr("Connection") } - - Label { - objectName: "sessionStatus" - text: Bridge.connected - ? qsTr("Connected: %1").arg(Bridge.currentUri) - : Bridge.connecting ? qsTr("Connecting…") - : Bridge.disconnecting ? qsTr("Disconnecting…") - : qsTr("Not connected") - color: Theme.linkColor(Bridge.linkState) - // A long URI breaks anywhere: unwrapped, it widened the - // page past a phone's edge once connected - wrapMode: Text.WrapAnywhere - Layout.fillWidth: true - } + Item { + Layout.fillWidth: true + Layout.fillHeight: true - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing + // The list, a phone's root + SettingsSubpage { + objectName: "settingsListPage" + anchors.fill: parent + visible: !page.twoPane && page.pageKey === "" + title: qsTr("Settings") - TextField { - id: uriField - objectName: "uriField" + SettingsList { + objectName: "settingsList" Layout.fillWidth: true - // ?poll= replaces the profile's PID rotation. Raw on an - // adapter listens to the engine ECU, so ?poll= alone - // asks it; under the obd2 default it also decodes. - // A WiFi adapter is typed: nothing lists it (ADR-0026's - // appendix "WiFi over TCP") - placeholderText: qsTr("URI, e.g. mock://demo, elm327://COM5, " - + "elm327://192.168.0.10:35000 or " - + "j2534://Vendor?profile=raw&poll=0x0C") - enabled: page.idle - color: Theme.text - // A URI, not prose: a phone's keyboard capitalized - // "Replay://" into a scheme core doesn't know - inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText - // Any text the page didn't compose is read back - onTextChanged: { - if (!page.composing) - page.readChoices() - } - onAccepted: page.requestConnect(text) + pages: page.pageList + onChosen: key => page.open(key) } - - ThemedButton { - objectName: "connectButton" - text: Bridge.connected ? qsTr("Disconnect") - : Bridge.connecting ? qsTr("Connecting…") - : Bridge.disconnecting ? qsTr("Disconnecting…") - : qsTr("Connect") - highlighted: !Bridge.connected - // Disconnect is always offered; Connect only while idle - // with a URI to connect - // and no relay holds the adapter (ADR-0047) - enabled: Bridge.connected - || (page.idle && uriField.text !== "" && !Relay.running) - onClicked: { - if (Bridge.connected) { - Bridge.disconnectSession() - errorLabel.visible = false - } else { - page.requestConnect(uriField.text) - } - } - } - } - - Label { - id: errorLabel - objectName: "errorLabel" - visible: false - color: Theme.danger - wrapMode: Text.WrapAnywhere - Layout.fillWidth: true - text: "" } - // ---- Adapter: what to connect to, found or typed ---- - Section { - id: adapterSection - objectName: "adapterSection" - title: qsTr("Adapter") - summary: page.devices.length === 0 ? qsTr("none found") - : qsTr("%1 found").arg(page.devices.length) - // The phone's Bluetooth permission is asked for here, when - // the list is first wanted, not at launch - onOpenChanged: if (open) Bluetooth.refresh(true) - - // ---- Adapters: J2534 interfaces and serial ports ---- - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "deviceCount" - text: page.devices.length === 0 - ? qsTr("None found: install a Pass-Thru driver (Windows), plug in " - + "or pair an ELM327 adapter, or pick one below") - : qsTr("J2534 interfaces: %1, serial ports: %2%3; select one to " - + "put its URI in the field above, then Connect") - .arg(page.j2534Devices.length).arg(page.serialPorts.length) - .arg((page.canInterfaces.length > 0 - ? qsTr(", CAN interfaces: %1").arg(page.canInterfaces.length) - : "") - + (Bluetooth.available || page.bluetoothAdapters.length > 0 - ? qsTr(", Bluetooth: %1").arg(page.bluetoothAdapters.length) - : "")) - color: page.devices.length === 0 ? Theme.textDim : Theme.text - wrapMode: Text.WordWrap - Layout.fillWidth: true - } - ThemedButton { - text: qsTr("Refresh") - onClicked: { - page.refreshDevices() - Bluetooth.refresh(true) - } - } + SettingsSubpage { + id: connectionPage + objectName: "settingsConnectionPage" + anchors.fill: parent + visible: page.shownKey === "connection" + title: qsTr("Connection") + backShown: !page.twoPane + onBackRequested: page.back() + + SettingsConnect { + id: settingsConnect + host: page } - // ---- Bluetooth (Android): why the list is short, and a - // scan for BLE adapters, which aren't paired ---- - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing - visible: Bluetooth.available - - Label { - objectName: "bluetoothStatus" - text: Bluetooth.status !== "" - ? Bluetooth.status - : qsTr("Paired adapters are listed; pair one in Android's " - + "Bluetooth settings") - color: Bluetooth.statusWarns ? Theme.warning : Theme.textDim - wrapMode: Text.WordWrap - Layout.fillWidth: true - } - ThemedButton { - objectName: "bleScanButton" - text: Bluetooth.scanning ? qsTr("Scanning…") : qsTr("Scan for BLE") - enabled: page.idle && !Bluetooth.scanning - onClicked: Bluetooth.scan() - } + SettingsAdapter { + id: settingsAdapter + host: page } - // Sized to its rows up to deviceRowsShown, then it scrolls - ListView { - id: deviceList - objectName: "deviceList" - // No current row: ListView gives a current one a default - // highlight, which animates to its size and, after the - // section opened at a phone's width, lay past the edge - currentIndex: -1 - highlightFollowsCurrentItem: false - Layout.fillWidth: true - Layout.preferredHeight: contentHeight - Layout.maximumHeight: page.deviceRowsShown * (page.deviceRowHeight + spacing) - spacing - visible: count > 0 - clip: true - spacing: 2 - boundsBehavior: Flickable.StopAtBounds - model: page.devices - - ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } - - delegate: Rectangle { - id: row - required property var modelData - width: deviceList.width - height: page.deviceRowHeight - radius: Theme.radius - color: mouse.containsMouse ? Theme.elevatedLight : Theme.elevated - border.width: page.isChosen(row.modelData.base) ? 2 : 0 - border.color: Theme.primary - - MouseArea { - id: mouse - objectName: "deviceRowArea" - anchors.fill: parent - hoverEnabled: true - cursorShape: Qt.PointingHandCursor - enabled: page.idle - onClicked: { - page.fillUri(row.modelData.base) - page.showUriField() - } - } - - ColumnLayout { - anchors.fill: parent - anchors.margins: Theme.spacing - spacing: 2 - - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "deviceTitle" - text: row.modelData.title - color: page.idle ? Theme.text : Theme.textDim - } - Label { - objectName: "deviceVersions" - visible: text !== "" - text: row.modelData.versions === "" - ? "" : qsTr("last seen: %1").arg(row.modelData.versions) - color: Theme.textDim - font.pointSize: 8 - elide: Text.ElideRight - horizontalAlignment: Text.AlignRight - rightPadding: Theme.spacing // clear of the list's scroll bar - Layout.fillWidth: true - } - } - Label { - objectName: "deviceDetail" - text: row.modelData.detail - color: Theme.textDim - font.pointSize: 8 - elide: Text.ElideMiddle - Layout.fillWidth: true - } - } - } - } - - // ---- Relay (the phone, developer mode; ADR-0047): the - // selected Bluetooth adapter relayed to a computer over USB, - // for havne-cli there ---- - ColumnLayout { - objectName: "relayBox" - visible: Relay.available && Theme.developerMode - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "relayStatus" - text: Relay.running - ? Relay.status - : qsTr("Relay to a computer over USB: select a paired adapter above, " - + "Relay, then on the computer adb forward tcp:%1 tcp:%1 " - + "and havne-cli on elm327://127.0.0.1:%1") - .arg(Relay.defaultPort) - color: Relay.running ? Theme.text : Theme.textDim - wrapMode: Text.WordWrap - Layout.fillWidth: true - } - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "relayTraffic" - visible: Relay.running - text: qsTr("%1 from the adapter, %2 to it") - .arg(page.byteText(Relay.bytesIn)) - .arg(page.byteText(Relay.bytesOut)) - color: Theme.textDim - // Beside the button on a phone's width - wrapMode: Text.WordWrap - Layout.fillWidth: true - } - ThemedButton { - objectName: "relayButton" - text: Relay.running ? qsTr("Stop relaying") : qsTr("Relay") - // Not beside a session: the adapter takes one link - enabled: Relay.running - || (page.idle && /^elm327:\/\/bt:/i.test(uriField.text)) - onClicked: { - if (Relay.running) { - Relay.stop() - return - } - const why = Relay.start(uriField.text) - errorLabel.text = why - errorLabel.visible = why !== "" - } - } - } - } - - // ---- Presets: the URI's base, for what the list doesn't show ---- - LabeledFlow { - label: qsTr("Not listed:") - Repeater { - model: [ - { name: "mock", uri: "mock://demo", label: "mock://demo" }, - // A bare j2534:// opens the first discovered device - { name: "j2534", uri: "j2534://", label: qsTr("j2534:// (first device)") }, - // elm327:// takes no first port: the user picks one - // from the list above or types a WiFi adapter's - // address (core's refusal says so) - { name: "elm327", uri: "elm327://", label: qsTr("elm327:// (a port above, or an address)") }, - // WiFi adapters aren't listed (ADR-0026's appendix - // "WiFi over TCP"): the two common addresses, so a - // phone needn't type one - { name: "wifi_obdx", uri: "elm327://192.168.4.1:23", - label: qsTr("WiFi: OBDX (192.168.4.1:23)") }, - { name: "wifi_elm", uri: "elm327://192.168.0.10:35000", - label: qsTr("WiFi: most others (192.168.0.10:35000)") } - ] - ThemedButton { - required property var modelData - objectName: "preset_" + modelData.name - text: modelData.label - // Wraps rather than run past a narrow page's edge - // (Linux's font at 320 px did) - width: Math.min(implicitWidth, parent.width) - // The mock is a developer's tool, not a device - visible: modelData.name !== "mock" || Theme.developerMode - enabled: page.idle - onClicked: { - page.fillUri(modelData.uri) - page.showUriField() - } - } - } + SettingsProfile { + id: settingsProfile + host: page } } - // ---- Vehicle ---- - Section { - id: vehicleSection - objectName: "vehicleSection" + SettingsSubpage { + objectName: "settingsVehiclePage" + anchors.fill: parent + visible: page.shownKey === "vehicle" title: qsTr("Vehicle") - summary: (page.pickedVehicle !== null ? page.pickedVehicle.label : qsTr("None")) - + (page.vehicles.list.length > 0 - ? qsTr(" · %1 saved").arg(page.vehicles.list.length) : "") - - // ---- Vehicle (ADR-0027): picked before a connect, its - // connection filling the field; every change to the list is - // made here. Locked while a session is up or in flight ---- - LabeledFlow { - label: qsTr("Vehicle:") - - ThemedButton { - objectName: "vehicle_none" - text: qsTr("None") - highlighted: page.pickedVehicle === null - enabled: page.idle - onClicked: page.pickVehicle("") - } - // Keyed by the count, not the list: each change makes a - // new list, and a list model would rebuild every - // button (losing focus) for a pick or a rename - Repeater { - model: page.vehicles.list.length - ThemedButton { - required property int index - // Undefined for a moment when the list shrinks, - // before the button goes - readonly property var vehicle: page.vehicles.list[index] - objectName: "vehicle_" + (vehicle?.id ?? "") - text: vehicle?.label ?? "" - // A long label wraps rather than run past a phone's edge - width: Math.min(implicitWidth, parent.width) - highlighted: vehicle !== undefined && page.vehicles.picked === vehicle.id - enabled: page.idle - onClicked: page.pickVehicle(vehicle.id) - } - } - } - - Label { - objectName: "vehicleVinPickNote" - visible: page.vinPickNote !== "" - text: page.vinPickNote - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - visible: page.confirming === "" - - TextField { - id: vehicleLabelField - objectName: "vehicleLabelField" - width: Math.min(300, parent.width) - enabled: page.idle - placeholderText: qsTr("Label") - } - ThemedButton { - objectName: "vehicleNew" - text: qsTr("New") - enabled: page.idle && VehicleBook.labelProblem(page.vehicles, page.newLabel, "") === "" - onClicked: page.changeVehicles(VehicleBook.add(page.vehicles, page.newLabel)) - } - ThemedButton { - objectName: "vehicleDuplicate" - text: qsTr("Duplicate") - enabled: page.idle && page.pickedVehicle !== null - && VehicleBook.labelProblem(page.vehicles, page.copyLabel, "") === "" - onClicked: page.duplicateVehicle() - } - ThemedButton { - objectName: "vehicleRename" - text: qsTr("Rename") - enabled: page.idle && page.pickedVehicle !== null && page.typedLabel !== "" - && page.typedLabel !== page.pickedVehicle.label - && VehicleBook.labelProblem(page.vehicles, page.typedLabel, - page.pickedVehicle.id) === "" - onClicked: page.changeVehicles(VehicleBook.rename(page.vehicles, page.typedLabel)) - } - ThemedButton { - objectName: "vehicleForgetVin" - text: qsTr("Forget the VIN") - enabled: page.idle && page.pickedVehicle !== null && page.pickedVehicle.vinKey !== "" - onClicked: page.changeVehicles(VehicleBook.forgetVin(page.vehicles)) - } - ThemedButton { - objectName: "vehicleForget" - text: qsTr("Forget") - enabled: page.idle && page.pickedVehicle !== null - onClicked: page.confirming = "forget" - } - ThemedButton { - objectName: "vehicleForgetAll" - text: qsTr("Forget all vehicles") - enabled: page.idle && page.vehicles.list.length > 0 - onClicked: page.confirming = "forgetAll" - } - } - - // With the field empty, the defaults New and Duplicate take - Label { - objectName: "vehicleLabelHint" - visible: page.typedLabel === "" && page.confirming === "" - text: page.pickedVehicle === null - ? qsTr("Left empty, New makes “%1”").arg(VehicleBook.defaultNewLabel(page.vehicles)) - : qsTr("Left empty, New makes “%1” and Duplicate “%2”") - .arg(VehicleBook.defaultNewLabel(page.vehicles), - VehicleBook.defaultCopyLabel(page.vehicles, page.pickedVehicle.label)) - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - // Why a typed label can't be used - Label { - objectName: "vehicleLabelProblem" - visible: text !== "" && page.confirming === "" - text: page.typedLabel === "" ? "" - : VehicleBook.labelProblem(page.vehicles, page.typedLabel, - page.pickedVehicle !== null ? page.pickedVehicle.id : "") - color: Theme.warning - } - - // A removal asks once, in place - Flow { - visible: page.confirming !== "" - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "vehicleConfirmText" - text: page.confirming === "forgetAll" ? qsTr("Forget all vehicles?") - : page.confirmingFile() !== null - ? qsTr("Remove %1? It was written here, and no other copy exists") - .arg(page.confirmingFile().name) - : page.pickedVehicle !== null ? qsTr("Forget %1?").arg(page.pickedVehicle.label) - : "" - color: Theme.text - wrapMode: Text.Wrap - width: Math.min(implicitWidth, parent.width) - } - ThemedButton { - objectName: "vehicleConfirm" - text: page.confirmingFile() !== null ? qsTr("Remove") : qsTr("Forget") - highlighted: true - enabled: page.idle - onClicked: { - const file = page.confirmingFile() - if (file !== null) - page.dropSignalFile(file.sha256) - else - page.forgetVehicles(page.confirming === "forgetAll") - } - } - ThemedButton { - objectName: "vehicleCancel" - text: qsTr("Cancel") - onClicked: page.confirming = "" - } - } - - // ---- The picked vehicle's signal files (ADR-0051) ---- - Label { - objectName: "signalFilesTitle" - visible: page.pickedVehicle !== null - text: qsTr("Signal files") - color: Theme.text - font.bold: true - } - - Repeater { - model: page.pickedVehicle !== null ? page.pickedVehicle.signals : [] - // The file's line at the page's width, its buttons under - // it, so a phone's narrow page never squeezes the line - ColumnLayout { - id: fileRow - required property var modelData - required property int index - objectName: "signalFile_" + index - Layout.fillWidth: true - spacing: Theme.spacing / 2 - - Label { - objectName: "signalFileText" - text: page.signalFileText(fileRow.modelData) - color: page.signalOk(fileRow.modelData.sha256) ? Theme.text - : Theme.warning - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - ThemedButton { - objectName: "signalSave_" + fileRow.index - width: Math.min(implicitWidth, parent.width) - text: qsTr("Save a copy") - // Reads the copy alone, so a session may run - enabled: page.confirming === "" - onClicked: page.saveSignalFileAs(fileRow.modelData) - } - ThemedButton { - objectName: "signalRemove_" + fileRow.index - width: Math.min(implicitWidth, parent.width) - text: qsTr("Remove") - enabled: page.idle && page.confirming === "" - onClicked: page.removeSignalFile(fileRow.modelData.sha256) - } - } - } - } - - Label { - objectName: "signalFilesNone" - visible: page.pickedVehicle !== null && page.pickedVehicle.signals.length === 0 - text: qsTr("None yet. Import adds a file of your own signals, each " - + "then a profile under What to read") - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - Flow { - visible: page.pickedVehicle !== null - Layout.fillWidth: true - spacing: Theme.spacing - ThemedButton { - objectName: "signalImport" - text: qsTr("Import a signal file") - enabled: page.idle && page.confirming === "" - onClicked: importDialog.open() - } - // An OBDb set (ADR-0051's appendix of 2026-11-06): - // its report shows before the file is kept - ThemedButton { - objectName: "obdbImport" - text: qsTr("Import an OBDb set") - enabled: page.idle && page.confirming === "" - onClicked: { - if (obdbYearField.text.trim() === "") { - const y = page.obdbVinYear() - obdbYearField.text = y > 0 ? String(y) : "" - } - obdbDialog.open() - } - } - } + backShown: !page.twoPane + onBackRequested: page.back() - LabeledFlow { - visible: page.pickedVehicle !== null - label: qsTr("OBDb model year:") - TextField { - id: obdbYearField - objectName: "obdbYearField" - width: Math.min(120, parent.width) - maximumLength: 4 - placeholderText: qsTr("from the VIN") - inputMethodHints: Qt.ImhDigitsOnly - } + SettingsVehiclePicker { + id: settingsVehiclePicker + host: page } - Label { - objectName: "signalProblem" - visible: text !== "" - text: page.signalProblem - color: Theme.warning - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Label { - objectName: "signalNote" - visible: text !== "" - text: page.signalNote - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - // The OBDb import's report, before the file is kept: what - // converted, each field that differs, each signal left out - ColumnLayout { - objectName: "obdbReport" - visible: page.obdbShown - spacing: Theme.spacing / 2 - Layout.fillWidth: true - - Label { - objectName: "obdbSummary" - text: page.obdbSummary(page.obdbReport) - color: Theme.text - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Label { - visible: page.obdbReport !== null && page.obdbReport.changed.length > 0 - text: qsTr("Differs from OBDb:") - color: Theme.text - font.bold: true - } - Repeater { - objectName: "obdbChanged" - model: page.obdbReport !== null - ? page.obdbReport.changed.slice(0, page.obdbRowsShown) : [] - Label { - required property var modelData - text: qsTr("%1, %2: %3") - .arg(modelData.key !== "" ? modelData.key : modelData.signal) - .arg(modelData.field).arg(modelData.text) - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - } - Label { - objectName: "obdbChangedMore" - readonly property int more: page.obdbReport === null ? 0 - : page.obdbReport.changed.length - page.obdbRowsShown - visible: more > 0 - text: qsTr("and %1 more").arg(more) - color: Theme.textDim - } - Label { - visible: page.obdbReport !== null && page.obdbReport.skipped.length > 0 - text: qsTr("Left out:") - color: Theme.text - font.bold: true - } - Repeater { - objectName: "obdbSkipped" - model: page.obdbReport !== null - ? page.obdbReport.skipped.slice(0, page.obdbRowsShown) : [] - Label { - required property var modelData - text: qsTr("%1 (line %2): %3") - .arg(modelData.signal !== "" ? modelData.signal : qsTr("the set")) - .arg(modelData.line).arg(modelData.text) - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - } - Label { - objectName: "obdbSkippedMore" - readonly property int more: page.obdbReport === null ? 0 - : page.obdbReport.skipped.length - page.obdbRowsShown - visible: more > 0 - text: qsTr("and %1 more").arg(more) - color: Theme.textDim - } - Repeater { - objectName: "obdbFileNotes" - model: page.obdbReport !== null ? page.obdbReport.file : [] - Label { - required property var modelData - text: modelData.field !== "" - ? qsTr("The set's %1: %2").arg(modelData.field).arg(modelData.text) - : qsTr("The set: %1").arg(modelData.text) - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - } - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - ThemedButton { - objectName: "obdbKeep" - text: page.obdbReplaces !== "" ? qsTr("Keep, replacing the earlier") - : qsTr("Keep") - highlighted: true - enabled: page.idle && page.confirming === "" - onClicked: page.keepObdb() - } - ThemedButton { - objectName: "obdbDiscard" - text: qsTr("Discard") - onClicked: page.discardObdb() - } - } - } - - FileDialog { - id: importDialog - title: qsTr("Import a signal file") - nameFilters: [qsTr("Signal files (*.json)"), qsTr("All files (*)")] - onAccepted: page.importSignalFile(importDialog.selectedFile) - } - FileDialog { - id: obdbDialog - title: qsTr("Import an OBDb set") - nameFilters: [qsTr("OBDb signal sets (*.json)"), qsTr("All files (*)")] - onAccepted: page.previewObdb(obdbDialog.selectedFile) - } - FileDialog { - id: saveDialog - title: qsTr("Save a copy of the signal file") - fileMode: FileDialog.SaveFile - defaultSuffix: "json" - nameFilters: [qsTr("Signal files (*.json)"), qsTr("All files (*)")] - currentFolder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation) - onAccepted: page.saveSignalFileTo(page.savingSha, saveDialog.selectedFile) - } - - // ---- The app's plugins (ADR-0052): every vehicle's, the - // picked one's variant proposed by its VIN ---- - Label { - objectName: "pluginsTitle" - text: qsTr("Plugins") - color: Theme.text - font.bold: true - } - - Repeater { - model: page.pluginList - RowLayout { - id: pluginRow - required property var modelData - required property int index - objectName: "plugin_" + index - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "pluginText" - text: page.pluginText(pluginRow.modelData) - color: pluginRow.modelData.ok ? Theme.text : Theme.warning - wrapMode: Text.Wrap - Layout.fillWidth: true - } - ThemedButton { - objectName: "pluginRemove_" + pluginRow.index - text: qsTr("Remove") - enabled: page.idle && page.confirming === "" - onClicked: page.removePlugin(pluginRow.modelData.sha256) - } - } - } - - Label { - objectName: "pluginsNone" - visible: page.pluginList.length === 0 - text: qsTr("None yet. A plugin (a .havne-plugin.json file) holds signals " - + "for the cars its manufacturer codes and model years name") - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - ThemedButton { - objectName: "pluginImport" - text: qsTr("Import a plugin") - enabled: page.idle && page.confirming === "" - onClicked: pluginDialog.open() - } - } - - Label { - objectName: "pluginProblem" - visible: text !== "" - text: page.pluginProblem - color: Theme.warning - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Label { - objectName: "pluginNote" - visible: text !== "" - text: page.pluginNote - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - // The variants the VIN proposes for the picked vehicle; the - // user picks one (ADR-0052 section 5) - Label { - objectName: "pluginMatchesText" - visible: page.pickedVehicle !== null && page.pluginList.length > 0 - text: page.pluginMatches.length > 0 - ? qsTr("For this car, by its VIN:") - : qsTr("No match yet: plugins are proposed once the car's VIN is " - + "read, or one is typed in the VIN lookup") - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Flow { - visible: page.pickedVehicle !== null - Layout.fillWidth: true - spacing: Theme.spacing - Repeater { - model: page.pickedVehicle !== null ? page.pluginMatches : [] - ThemedButton { - required property var modelData - required property int index - objectName: "pluginMatch_" + index - width: Math.min(implicitWidth, parent.width) - text: qsTr("%1: %2").arg(modelData.name, modelData.variant) - highlighted: page.pickedVehicle !== null - && page.pickedVehicle.plugin === modelData.profile - enabled: page.idle - onClicked: page.pickPluginVariant(modelData.profile) - } - } - } - - FileDialog { - id: pluginDialog - title: qsTr("Import a plugin") - nameFilters: [qsTr("Plugins (*.havne-plugin.json)"), qsTr("All files (*)")] - onAccepted: page.importPlugin(pluginDialog.selectedFile) - } - - // ---- The vehicle's own signals (ADR-0051's form) ---- - Label { - objectName: "ownSignalsTitle" - visible: page.pickedVehicle !== null - text: qsTr("Your own signals") - color: Theme.text - font.bold: true + SettingsVinLookup { + id: settingsVinLookup + host: page } + } - Repeater { - model: page.ownSignals - RowLayout { - id: ownRow - required property var modelData - required property int index - objectName: "ownSignal_" + index - Layout.fillWidth: true - spacing: Theme.spacing - - Label { - objectName: "ownSignalText" - text: qsTr("%1: %2").arg(ownRow.modelData.name, - SignalForm.describe(page.ownFile, ownRow.modelData)) - color: Theme.text - wrapMode: Text.Wrap - Layout.fillWidth: true - } - ThemedButton { - objectName: "ownEdit_" + ownRow.index - text: qsTr("Edit") - enabled: page.confirming === "" - onClicked: page.editOwnSignal(ownRow.modelData.key) - } - ThemedButton { - objectName: "ownRemove_" + ownRow.index - text: qsTr("Remove") - enabled: page.idle && page.confirming === "" - onClicked: page.removeOwnSignal(ownRow.modelData.key) - } - } + SettingsSubpage { + objectName: "settingsSignalsPage" + anchors.fill: parent + visible: page.shownKey === "signals" + title: qsTr("Signals") + backShown: !page.twoPane + onBackRequested: page.back() + + SettingsSignalFiles { + id: settingsSignalFiles + host: page } - ColumnLayout { - objectName: "signalForm" - visible: page.pickedVehicle !== null - Layout.fillWidth: true - spacing: Theme.spacing - - Flow { - id: formNameRow - Layout.fillWidth: true - spacing: Theme.spacing - Captioned { - caption: qsTr("Name") - TextField { - id: formName - objectName: "formName" - placeholderText: qsTr("Name") - width: Math.min(formNameRow.width, Theme.controlHeight * 8) - } - } - Captioned { - caption: qsTr("Reply ID") - TextField { - id: formRx - objectName: "formRx" - text: "7E8" - placeholderText: qsTr("Reply ID") - width: Theme.controlHeight * 3 - } - } - Captioned { - caption: qsTr("Request ID") - TextField { - id: formTx - objectName: "formTx" - placeholderText: qsTr("Request ID") - width: Theme.controlHeight * 3 - } - } - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - Repeater { - model: [{ name: "01", label: qsTr("01 PID") }, { name: "22", label: qsTr("22 DID") }] - ThemedButton { - required property var modelData - objectName: "formService_" + modelData.name - text: modelData.label - highlighted: page.formService === modelData.name - onClicked: page.formService = modelData.name - } - } - Captioned { - caption: page.formService === "22" ? qsTr("DID") : qsTr("PID") - TextField { - id: formNumber - objectName: "formNumber" - placeholderText: page.formService === "22" ? qsTr("DID, 4 hex digits") - : qsTr("PID, 2 hex digits") - width: Theme.controlHeight * 5 - } - } - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - Repeater { - model: SignalForm.kinds - ThemedButton { - required property string modelData - objectName: "formKind_" + modelData - text: modelData - highlighted: page.formKind === modelData - onClicked: page.formKind = modelData - } - } - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - Captioned { - caption: qsTr("Byte") - TextField { - id: formByte - objectName: "formByte" - text: "0" - placeholderText: qsTr("Byte") - width: Theme.controlHeight * 2.5 - } - } - Captioned { - caption: qsTr("Bits") - visible: page.formKind === "number" || page.formKind === "enum" - TextField { - id: formBits - objectName: "formBits" - text: "8" - placeholderText: qsTr("Bits") - width: Theme.controlHeight * 2.5 - } - } - Captioned { - caption: qsTr("Start bit") - visible: page.formKind === "number" || page.formKind === "enum" - TextField { - id: formBit - objectName: "formBit" - placeholderText: qsTr("Bit") - width: Theme.controlHeight * 2.5 - } - } - Captioned { - caption: qsTr("Bytes") - visible: !(page.formKind === "number" || page.formKind === "enum") - TextField { - id: formBytes - objectName: "formBytes" - placeholderText: qsTr("Bytes (all)") - width: Theme.controlHeight * 3 - } - } - Repeater { - model: page.formKind === "number" || page.formKind === "enum" ? ["be", "le"] : [] - ThemedButton { - required property string modelData - objectName: "formOrder_" + modelData - text: modelData - highlighted: page.formOrder === modelData - onClicked: page.formOrder = modelData - } - } - CheckBox { - id: formSigned - objectName: "formSigned" - visible: page.formKind === "number" - text: qsTr("Signed") - } - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - visible: page.formKind === "number" - Captioned { - caption: qsTr("Scale") - TextField { - id: formScale - objectName: "formScale" - placeholderText: qsTr("Scale (1)") - width: Theme.controlHeight * 3 - } - } - Captioned { - caption: qsTr("Offset") - TextField { - id: formOffset - objectName: "formOffset" - placeholderText: qsTr("Offset (0)") - width: Theme.controlHeight * 3 - } - } - Captioned { - caption: qsTr("Unit") - TextField { - id: formUnit - objectName: "formUnit" - placeholderText: qsTr("Unit") - width: Theme.controlHeight * 3 - } - } - Captioned { - caption: qsTr("Decimals") - TextField { - id: formDecimals - objectName: "formDecimals" - placeholderText: qsTr("Decimals") - width: Theme.controlHeight * 3 - } - } - } - - TextField { - id: formValues - objectName: "formValues" - visible: page.formKind === "enum" - placeholderText: qsTr("Values: 0=Park, 1=Reverse, 2=Neutral") - Layout.fillWidth: true - } - - LabeledFlow { - label: qsTr("Group:") - Repeater { - model: SignalForm.groups - ThemedButton { - required property string modelData - objectName: "formGroup_" + (modelData === "" ? "other" : modelData) - text: modelData === "" ? qsTr("other") : modelData - highlighted: page.formGroup === modelData - onClicked: page.formGroup = modelData - } - } - } - - Flow { - Layout.fillWidth: true - spacing: Theme.spacing - ThemedButton { - objectName: "formReadOnce" - text: Bridge.readingOnce ? qsTr("Reading...") : qsTr("Read once") - enabled: page.idle && !Bridge.readingOnce && page.confirming === "" - onClicked: page.readOnceDraft() - } - ThemedButton { - objectName: "formSave" - text: qsTr("Save") - enabled: page.idle && page.confirming === "" - onClicked: page.saveDraft() - } - ThemedButton { - objectName: "formClear" - text: qsTr("Clear") - onClicked: page.clearForm() - } - } - - Label { - objectName: "formReadResult" - visible: text !== "" - text: page.readResultText(page.readResult) - color: page.readResult !== null && page.readResult.ok ? Theme.text : Theme.warning - wrapMode: Text.WrapAnywhere - Layout.fillWidth: true - } - Label { - objectName: "formProblem" - visible: text !== "" - text: page.formProblem - color: Theme.warning - wrapMode: Text.Wrap - Layout.fillWidth: true - } - Label { - objectName: "formNote" - visible: text !== "" - text: page.formNote - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true - } + SettingsPlugins { + id: settingsPlugins + host: page } - // ---- A VIN looked up (ADR-0043): decoded here, never kept ---- - LabeledFlow { - label: qsTr("Look up a VIN:") - - TextField { - id: vinLookupField - objectName: "vinLookupField" - width: Math.min(300, parent.width) - maximumLength: 32 - placeholderText: qsTr("17 characters") - inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText | Qt.ImhSensitiveData - // A typed VIN proposes plugins too (ADR-0052 section 5) - onTextChanged: page.refreshMatches() - } - } - - Label { - readonly property string summary: Bridge.describeVin(vinLookupField.text) - objectName: "vinLookupResult" - visible: summary !== "" - text: summary.charAt(0).toUpperCase() + summary.slice(1) - color: Theme.text - wrapMode: Text.Wrap - Layout.fillWidth: true - } - - Label { - objectName: "vinLookupHint" - text: qsTr("By 49 CFR 565 and NHTSA's vPIC list (%1), on this device; the VIN isn't saved. The connected car's goes in the activity log.") - .arg(Bridge.vinSource()) - color: Theme.textDim - wrapMode: Text.Wrap - Layout.fillWidth: true + SettingsOwnSignals { + id: settingsOwnSignals + host: page } } - // ---- What to read: the profile ---- - Section { - id: profileSection - objectName: "profileSection" - title: qsTr("What to read") - summary: page.profileLabel() - - // ---- Profile: the URI's query (ADR-0013, ADR-0020) ---- - // The chosen button is drawn as the primary color - LabeledFlow { - label: qsTr("Profile:") - Repeater { - model: page.profiles - ThemedButton { - required property var modelData - objectName: "profile_" + modelData.name - text: modelData.label - highlighted: page.profileChoice === modelData.name - enabled: page.idle - onClicked: page.chooseProfile(modelData.name) - } - } - } - - Label { - objectName: "profileHint" - Layout.fillWidth: true - wrapMode: Text.WordWrap - color: Theme.textDim - text: page.profileHint() - } - - RowLayout { - objectName: "didRow" - Layout.fillWidth: true - spacing: Theme.spacing - visible: page.profileChoice === "uds-generic" - Label { text: qsTr("DIDs:"); color: Theme.textDim } - TextField { - id: didField - objectName: "didField" - Layout.fillWidth: true - // The ?did= grammar as core reads it (ADR-0020); the - // text goes into the URI as typed, so core's words - // name any mistake. The validator admits only the - // grammar's characters, so a query metacharacter (&, - // =, ?, #) can't split the URI into other keys. - placeholderText: qsTr("1E1C:u16, F190:text, 7E9:1E1C, 1E00-1EFF; " - + "[ecu:]DID[-DID][:hex|text|u8…u32|i8…i32]") - validator: RegularExpressionValidator { regularExpression: /[0-9A-Za-z:,\-\s]*/ } - inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText - enabled: page.idle - color: Theme.text - onTextChanged: { - if (!page.syncing && page.profileChoice === "uds-generic") - page.recompose() - } - onAccepted: page.requestConnect(uriField.text) - } + SettingsSubpage { + objectName: "settingsOwnFormPage" + anchors.fill: parent + visible: page.shownKey === "ownform" + title: qsTr("Add a signal") + backName: qsTr("Back to Signals") + backShown: true + onBackRequested: page.back() + + SettingsOwnForm { + id: settingsOwnForm + host: page } } - // ---- Recording ---- - Section { - id: recordingSection - objectName: "recordingSection" + SettingsSubpage { + objectName: "settingsRecordingPage" + anchors.fill: parent + visible: page.shownKey === "recording" title: qsTr("Recording") - summary: Bridge.recordingActive ? qsTr("recording") : Bridge.recording ? qsTr("on") : qsTr("off") + backShown: !page.twoPane + onBackRequested: page.back() - // ---- Recording (ADR-0017) ---- - // Off until switched on, and kept between runs. It takes effect - // at the next connect, so it's fixed while a session is up and - // each recording covers a whole session. - RowLayout { - Layout.fillWidth: true - spacing: Theme.spacing - - CheckBox { - id: recordBox - objectName: "recordBox" - text: qsTr("Record sessions") - checked: Bridge.recording - enabled: page.idle - // The bridge decides; the binding comes back either way - onToggled: { - Bridge.recording = checked - checked = Qt.binding(() => Bridge.recording) - } - contentItem: Label { - text: recordBox.text - color: recordBox.enabled ? Theme.text : Theme.textDim - leftPadding: recordBox.indicator.width + recordBox.spacing - verticalAlignment: Text.AlignVCenter - } - } - Label { - objectName: "recordStatus" - Layout.fillWidth: true - elide: Text.ElideMiddle - color: Bridge.recordingActive ? Theme.success : Theme.textDim - text: Bridge.recordingActive - ? qsTr("Recording to %1").arg(Bridge.recordingFolder) - : Bridge.recording && page.replayInField - ? qsTr("Replays aren't recorded") - : Bridge.recordingFolder !== "" - ? qsTr("Last: %1").arg(Bridge.recordingFolder) - : Bridge.recording - ? qsTr("Frames, values and events, from the next connect") - : "" - } - // A phone has no app that opens the app's own folders - ThemedButton { - text: qsTr("Open folder") - visible: Bridge.recordingFolder !== "" && !Theme.mobile - onClicked: Qt.openUrlExternally(Bridge.recordingFolderUrl) - } + SettingsRecording { + id: settingsRecording + host: page } } - // ---- Display ---- - Section { - id: displaySection - objectName: "displaySection" + SettingsSubpage { + objectName: "settingsDisplayPage" + anchors.fill: parent + visible: page.shownKey === "display" title: qsTr("Display") - summary: qsTr("%1 %").arg(Math.round(Theme.zoom * 100)) - + (Bridge.unitSystem === 1 ? qsTr(" · imperial") : qsTr(" · metric")) - + (Theme.developerMode ? qsTr(" · developer mode") : "") - - // The whole UI's zoom; Main.qml applies and stores it - LabeledFlow { - label: qsTr("Display size:") - ThemedButton { - id: smaller - text: "−" - Accessible.name: qsTr("Smaller") - enabled: Theme.zoom > Theme.zoomSteps[0] + 0.001 - onClicked: Theme.stepZoom(-1) - } - Label { - width: Math.max(52, implicitWidth) - height: smaller.height - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - text: qsTr("%1 %").arg(Math.round(Theme.zoom * 100)) - color: Theme.text - } - ThemedButton { - text: "+" - Accessible.name: qsTr("Larger") - enabled: Theme.zoom < Theme.zoomSteps[Theme.zoomSteps.length - 1] - 0.001 - onClicked: Theme.stepZoom(1) - } - ThemedButton { - text: qsTr("Reset") - enabled: Math.abs(Theme.zoom - 1) > 0.001 - onClicked: Theme.zoom = 1 - } - } - // A phone has no keyboard to zoom with - Label { - visible: !Theme.mobile - text: qsTr("or Ctrl + / Ctrl − / Ctrl 0") - color: Theme.textDim - wrapMode: Text.WordWrap - Layout.fillWidth: true - } + backShown: !page.twoPane + onBackRequested: page.back() - // Units: what the pages show, converted in core (ADR-0022); - // recordings keep the decoded values. Main.qml stores it. - // Takes effect at once, connected or not. - LabeledFlow { - label: qsTr("Units:") - Repeater { - model: [ - { system: 0, name: "metric", label: qsTr("Metric (km/h, °C)") }, - { system: 1, name: "imperial", label: qsTr("Imperial (mph, °F)") } - ] - ThemedButton { - required property var modelData - objectName: "units_" + modelData.name - text: modelData.label - highlighted: Bridge.unitSystem === modelData.system - onClicked: Bridge.unitSystem = modelData.system - } - } + SettingsDisplay { + id: settingsDisplay + host: page } + } - // Developer mode (Theme.developerMode); Main.qml stores it - CheckBox { - id: developerBox - objectName: "developerBox" - text: qsTr("Developer mode: the mock:// preset, and the raw frames on the Log page") - checked: Theme.developerMode - Layout.fillWidth: true - onToggled: { - Theme.developerMode = checked - checked = Qt.binding(() => Theme.developerMode) - } - contentItem: Label { - text: developerBox.text - color: Theme.text - leftPadding: developerBox.indicator.width + developerBox.spacing - verticalAlignment: Text.AlignVCenter - wrapMode: Text.WordWrap - } + SettingsSubpage { + objectName: "settingsAdvancedPage" + anchors.fill: parent + visible: page.shownKey === "advanced" + title: qsTr("Advanced") + backShown: !page.twoPane + onBackRequested: page.back() + + SettingsAdvanced { + id: settingsAdvanced + host: page } } } diff --git a/app/qml/SettingsPlugins.qml b/app/qml/SettingsPlugins.qml new file mode 100644 index 00000000..902fdf35 --- /dev/null +++ b/app/qml/SettingsPlugins.qml @@ -0,0 +1,130 @@ +// File/layer: app/qml/SettingsPlugins.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The app's plugins and the VIN's variant matches: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Dialogs +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + // ---- The app's plugins (ADR-0052): every vehicle's, the + // picked one's variant proposed by its VIN ---- + Label { + objectName: "pluginsTitle" + text: qsTr("Plugins") + color: Theme.text + font.bold: true + } + + Repeater { + model: root.host.pluginList + RowLayout { + id: pluginRow + required property var modelData + required property int index + objectName: "plugin_" + index + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "pluginText" + text: root.host.pluginText(pluginRow.modelData) + color: pluginRow.modelData.ok ? Theme.text : Theme.warning + wrapMode: Text.Wrap + Layout.fillWidth: true + } + ThemedButton { + objectName: "pluginRemove_" + pluginRow.index + text: qsTr("Remove") + enabled: root.host.idle && root.host.confirming === "" + onClicked: root.host.removePlugin(pluginRow.modelData.sha256) + } + } + } + + Label { + objectName: "pluginsNone" + visible: root.host.pluginList.length === 0 + text: qsTr("None yet. A plugin (a .havne-plugin.json file) holds signals " + + "for the cars its manufacturer codes and model years name") + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "pluginImport" + text: qsTr("Import a plugin") + enabled: root.host.idle && root.host.confirming === "" + onClicked: pluginDialog.open() + } + } + + Label { + objectName: "pluginProblem" + visible: text !== "" + text: root.host.pluginProblem + color: Theme.warning + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Label { + objectName: "pluginNote" + visible: text !== "" + text: root.host.pluginNote + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + // The variants the VIN proposes for the picked vehicle; the + // user picks one (ADR-0052 section 5) + Label { + objectName: "pluginMatchesText" + visible: root.host.pickedVehicle !== null && root.host.pluginList.length > 0 + text: root.host.pluginMatches.length > 0 + ? qsTr("For this car, by its VIN:") + : qsTr("No match yet: plugins are proposed once the car's VIN is " + + "read, or one is typed in the VIN lookup") + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Flow { + visible: root.host.pickedVehicle !== null + Layout.fillWidth: true + spacing: Theme.spacing + Repeater { + model: root.host.pickedVehicle !== null ? root.host.pluginMatches : [] + ThemedButton { + required property var modelData + required property int index + objectName: "pluginMatch_" + index + width: Math.min(implicitWidth, parent.width) + text: qsTr("%1: %2").arg(modelData.name, modelData.variant) + highlighted: root.host.pickedVehicle !== null + && root.host.pickedVehicle.plugin === modelData.profile + enabled: root.host.idle + onClicked: root.host.pickPluginVariant(modelData.profile) + } + } + } + + FileDialog { + id: pluginDialog + title: qsTr("Import a plugin") + nameFilters: [qsTr("Plugins (*.havne-plugin.json)"), qsTr("All files (*)")] + onAccepted: root.host.importPlugin(pluginDialog.selectedFile) + } +} diff --git a/app/qml/SettingsProfile.qml b/app/qml/SettingsProfile.qml new file mode 100644 index 00000000..ed1b44c3 --- /dev/null +++ b/app/qml/SettingsProfile.qml @@ -0,0 +1,72 @@ +// File/layer: app/qml/SettingsProfile.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The profile buttons (what to read): one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + property alias didField: didField + + // ---- Profile: the URI's query (ADR-0013, ADR-0020) ---- + // The chosen button is drawn as the primary color + LabeledFlow { + label: qsTr("Profile:") + Repeater { + model: root.host.profiles + ThemedButton { + required property var modelData + objectName: "profile_" + modelData.name + text: modelData.label + highlighted: root.host.profileChoice === modelData.name + enabled: root.host.idle + onClicked: root.host.chooseProfile(modelData.name) + } + } + } + + Label { + objectName: "profileHint" + Layout.fillWidth: true + wrapMode: Text.WordWrap + color: Theme.textDim + text: root.host.profileHint() + } + + RowLayout { + objectName: "didRow" + Layout.fillWidth: true + spacing: Theme.spacing + visible: root.host.profileChoice === "uds-generic" + Label { text: qsTr("DIDs:"); color: Theme.textDim } + TextField { + id: didField + objectName: "didField" + Layout.fillWidth: true + // The ?did= grammar as core reads it (ADR-0020); the + // text goes into the URI as typed, so core's words + // name any mistake. The validator admits only the + // grammar's characters, so a query metacharacter (&, + // =, ?, #) can't split the URI into other keys. + placeholderText: qsTr("1E1C:u16, F190:text, 7E9:1E1C, 1E00-1EFF; " + + "[ecu:]DID[-DID][:hex|text|u8…u32|i8…i32]") + validator: RegularExpressionValidator { regularExpression: /[0-9A-Za-z:,\-\s]*/ } + inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText + enabled: root.host.idle + color: Theme.text + onTextChanged: { + if (!root.host.syncing && root.host.profileChoice === "uds-generic") + root.host.recompose() + } + onAccepted: root.host.requestConnect(root.host.uriField.text) + } + } +} diff --git a/app/qml/SettingsRecording.qml b/app/qml/SettingsRecording.qml new file mode 100644 index 00000000..c96b551b --- /dev/null +++ b/app/qml/SettingsRecording.qml @@ -0,0 +1,65 @@ +// File/layer: app/qml/SettingsRecording.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The recording switch and where recordings go: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + // ---- Recording (ADR-0017) ---- + // Off until switched on, and kept between runs. It takes effect + // at the next connect, so it's fixed while a session is up and + // each recording covers a whole session. + RowLayout { + Layout.fillWidth: true + spacing: Theme.spacing + + ThemedCheckBox { + id: recordBox + objectName: "recordBox" + text: qsTr("Record sessions") + checked: Bridge.recording + enabled: root.host.idle + // The bridge decides; the binding comes back either way + onToggled: { + Bridge.recording = checked + checked = Qt.binding(() => Bridge.recording) + } + contentItem: Label { + text: recordBox.text + color: recordBox.enabled ? Theme.text : Theme.textDim + leftPadding: recordBox.indicator.width + recordBox.spacing + verticalAlignment: Text.AlignVCenter + } + } + Label { + objectName: "recordStatus" + Layout.fillWidth: true + elide: Text.ElideMiddle + color: Bridge.recordingActive ? Theme.success : Theme.textDim + text: Bridge.recordingActive + ? qsTr("Recording to %1").arg(Bridge.recordingFolder) + : Bridge.recording && root.host.replayInField + ? qsTr("Replays aren't recorded") + : Bridge.recordingFolder !== "" + ? qsTr("Last: %1").arg(Bridge.recordingFolder) + : Bridge.recording + ? qsTr("Frames, values and events, from the next connect") + : "" + } + // A phone has no app that opens the app's own folders + ThemedButton { + text: qsTr("Open folder") + visible: Bridge.recordingFolder !== "" && !Theme.mobile + onClicked: Qt.openUrlExternally(Bridge.recordingFolderUrl) + } + } +} diff --git a/app/qml/SettingsSignalFiles.qml b/app/qml/SettingsSignalFiles.qml new file mode 100644 index 00000000..aaeaef6d --- /dev/null +++ b/app/qml/SettingsSignalFiles.qml @@ -0,0 +1,265 @@ +// File/layer: app/qml/SettingsSignalFiles.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The picked vehicle's signal files and the imports: one part of SettingsPage, which holds the state + +import QtCore +import QtQuick +import QtQuick.Controls +import QtQuick.Dialogs +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + objectName: "settingsSignalFilesPart" + visible: root.host.pickedVehicle !== null + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + property alias obdbYearField: obdbYearField + property alias saveDialog: saveDialog + + // ---- The picked vehicle's signal files (ADR-0051) ---- + Label { + objectName: "signalFilesTitle" + visible: root.host.pickedVehicle !== null + text: qsTr("Signal files") + color: Theme.text + font.bold: true + } + + Repeater { + model: root.host.pickedVehicle !== null ? root.host.pickedVehicle.signals : [] + // The file's line at the page's width, its buttons under + // it, so a phone's narrow page never squeezes the line + ColumnLayout { + id: fileRow + required property var modelData + required property int index + objectName: "signalFile_" + index + Layout.fillWidth: true + spacing: Theme.spacing / 2 + + Label { + objectName: "signalFileText" + text: root.host.signalFileText(fileRow.modelData) + color: root.host.signalOk(fileRow.modelData.sha256) ? Theme.text + : Theme.warning + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "signalSave_" + fileRow.index + width: Math.min(implicitWidth, parent.width) + text: qsTr("Save a copy") + // Reads the copy alone, so a session may run + enabled: root.host.confirming === "" + onClicked: root.host.saveSignalFileAs(fileRow.modelData) + } + ThemedButton { + objectName: "signalRemove_" + fileRow.index + width: Math.min(implicitWidth, parent.width) + text: qsTr("Remove") + enabled: root.host.idle && root.host.confirming === "" + onClicked: root.host.removeSignalFile(fileRow.modelData.sha256) + } + } + } + } + + Label { + objectName: "signalFilesNone" + visible: root.host.pickedVehicle !== null && root.host.pickedVehicle.signals.length === 0 + text: qsTr("None yet. Import adds a file of your own signals, each " + + "then a profile under Profile") + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + Flow { + visible: root.host.pickedVehicle !== null + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "signalImport" + text: qsTr("Import a signal file") + enabled: root.host.idle && root.host.confirming === "" + onClicked: importDialog.open() + } + // An OBDb set (ADR-0051's appendix of 2026-11-06): + // its report shows before the file is kept + ThemedButton { + objectName: "obdbImport" + text: qsTr("Import an OBDb set") + enabled: root.host.idle && root.host.confirming === "" + onClicked: { + if (obdbYearField.text.trim() === "") { + const y = root.host.obdbVinYear() + obdbYearField.text = y > 0 ? String(y) : "" + } + obdbDialog.open() + } + } + } + + LabeledFlow { + visible: root.host.pickedVehicle !== null + label: qsTr("OBDb model year:") + TextField { + id: obdbYearField + objectName: "obdbYearField" + width: Math.min(120, parent.width) + maximumLength: 4 + placeholderText: qsTr("from the VIN") + inputMethodHints: Qt.ImhDigitsOnly + } + } + + Label { + objectName: "signalProblem" + visible: text !== "" + text: root.host.signalProblem + color: Theme.warning + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Label { + objectName: "signalNote" + visible: text !== "" + text: root.host.signalNote + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + // The OBDb import's report, before the file is kept: what + // converted, each field that differs, each signal left out + ColumnLayout { + objectName: "obdbReport" + visible: root.host.obdbShown + spacing: Theme.spacing / 2 + Layout.fillWidth: true + + Label { + objectName: "obdbSummary" + text: root.host.obdbSummary(root.host.obdbReport) + color: Theme.text + wrapMode: Text.Wrap + Layout.fillWidth: true + } + Label { + visible: root.host.obdbReport !== null && root.host.obdbReport.changed.length > 0 + text: qsTr("Differs from OBDb:") + color: Theme.text + font.bold: true + } + Repeater { + objectName: "obdbChanged" + model: root.host.obdbReport !== null + ? root.host.obdbReport.changed.slice(0, root.host.obdbRowsShown) : [] + Label { + required property var modelData + text: qsTr("%1, %2: %3") + .arg(modelData.key !== "" ? modelData.key : modelData.signal) + .arg(modelData.field).arg(modelData.text) + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + Label { + objectName: "obdbChangedMore" + readonly property int more: root.host.obdbReport === null ? 0 + : root.host.obdbReport.changed.length - root.host.obdbRowsShown + visible: more > 0 + text: qsTr("and %1 more").arg(more) + color: Theme.textDim + } + Label { + visible: root.host.obdbReport !== null && root.host.obdbReport.skipped.length > 0 + text: qsTr("Left out:") + color: Theme.text + font.bold: true + } + Repeater { + objectName: "obdbSkipped" + model: root.host.obdbReport !== null + ? root.host.obdbReport.skipped.slice(0, root.host.obdbRowsShown) : [] + Label { + required property var modelData + text: qsTr("%1 (line %2): %3") + .arg(modelData.signal !== "" ? modelData.signal : qsTr("the set")) + .arg(modelData.line).arg(modelData.text) + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + Label { + objectName: "obdbSkippedMore" + readonly property int more: root.host.obdbReport === null ? 0 + : root.host.obdbReport.skipped.length - root.host.obdbRowsShown + visible: more > 0 + text: qsTr("and %1 more").arg(more) + color: Theme.textDim + } + Repeater { + objectName: "obdbFileNotes" + model: root.host.obdbReport !== null ? root.host.obdbReport.file : [] + Label { + required property var modelData + text: modelData.field !== "" + ? qsTr("The set's %1: %2").arg(modelData.field).arg(modelData.text) + : qsTr("The set: %1").arg(modelData.text) + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + } + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + ThemedButton { + objectName: "obdbKeep" + text: root.host.obdbReplaces !== "" ? qsTr("Keep, replacing the earlier") + : qsTr("Keep") + highlighted: true + enabled: root.host.idle && root.host.confirming === "" + onClicked: root.host.keepObdb() + } + ThemedButton { + objectName: "obdbDiscard" + text: qsTr("Discard") + onClicked: root.host.discardObdb() + } + } + } + + FileDialog { + id: importDialog + title: qsTr("Import a signal file") + nameFilters: [qsTr("Signal files (*.json)"), qsTr("All files (*)")] + onAccepted: root.host.importSignalFile(importDialog.selectedFile) + } + FileDialog { + id: obdbDialog + title: qsTr("Import an OBDb set") + nameFilters: [qsTr("OBDb signal sets (*.json)"), qsTr("All files (*)")] + onAccepted: root.host.previewObdb(obdbDialog.selectedFile) + } + FileDialog { + id: saveDialog + title: qsTr("Save a copy of the signal file") + fileMode: FileDialog.SaveFile + defaultSuffix: "json" + nameFilters: [qsTr("Signal files (*.json)"), qsTr("All files (*)")] + currentFolder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation) + onAccepted: root.host.saveSignalFileTo(root.host.savingSha, saveDialog.selectedFile) + } +} diff --git a/app/qml/SettingsSubpage.qml b/app/qml/SettingsSubpage.qml new file mode 100644 index 00000000..e7452aa9 --- /dev/null +++ b/app/qml/SettingsSubpage.qml @@ -0,0 +1,54 @@ +// File/layer: app/qml/SettingsSubpage.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// One page of Settings: a scrolling column under a header with a back arrow + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +// The page's controls go in as children. The back arrow shows on a phone +// (when the page was pushed over the list), where it is the way back; +// nothing else depends on it, the back key only repeats it +Flickable { + id: flick + property string title + property bool backShown: false + property string backName: qsTr("Back to Settings") + signal backRequested + default property alias content: column.data + + // The buttons inside take at least this height (ThemedButton) + readonly property Item body: column + readonly property real touchMin: Theme.touchTarget + contentWidth: width + contentHeight: column.height + 2 * Theme.pageMargin + clip: true + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar { + policy: flick.contentHeight > flick.height ? ScrollBar.AlwaysOn : ScrollBar.AsNeeded + } + + ColumnLayout { + id: column + objectName: flick.objectName + "Column" + x: Theme.pageMargin + y: Theme.pageMargin + width: flick.width - 2 * Theme.pageMargin + // Its content's height, not the page's + height: implicitHeight + spacing: Theme.spacing * 2 + + PageHeader { + title: flick.title + ThemedButton { + objectName: "settingsBack" + visible: flick.backShown + text: "<" + Accessible.name: flick.backName + implicitWidth: Theme.touchTarget + implicitHeight: Theme.touchTarget + onClicked: flick.backRequested() + } + } + } +} diff --git a/app/qml/SettingsVehiclePicker.qml b/app/qml/SettingsVehiclePicker.qml new file mode 100644 index 00000000..35d32fb7 --- /dev/null +++ b/app/qml/SettingsVehiclePicker.qml @@ -0,0 +1,210 @@ +// File/layer: app/qml/SettingsVehiclePicker.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The vehicle picker, its label and the list edits: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + property alias vehicleLabelField: vehicleLabelField + // Whether the row of the less common actions shows + property bool moreShown: false + + // ---- Vehicle (ADR-0027): picked before a connect, its + // connection filling the field; every change to the list is + // made here. Locked while a session is up or in flight ---- + LabeledFlow { + label: qsTr("Vehicle:") + + ThemedButton { + objectName: "vehicle_none" + text: qsTr("None") + highlighted: root.host.pickedVehicle === null + enabled: root.host.idle + onClicked: root.host.pickVehicle("") + } + // Keyed by the count, not the list: each change makes a + // new list, and a list model would rebuild every + // button (losing focus) for a pick or a rename + Repeater { + model: root.host.vehicles.list.length + ThemedButton { + required property int index + // Undefined for a moment when the list shrinks, + // before the button goes + readonly property var vehicle: root.host.vehicles.list[index] + objectName: "vehicle_" + (vehicle?.id ?? "") + text: vehicle?.label ?? "" + // A long label wraps rather than run past a phone's edge + width: Math.min(implicitWidth, parent.width) + highlighted: vehicle !== undefined && root.host.vehicles.picked === vehicle.id + enabled: root.host.idle + onClicked: root.host.pickVehicle(vehicle.id) + } + } + } + + Label { + objectName: "vehicleVinPickNote" + visible: root.host.vinPickNote !== "" + text: root.host.vinPickNote + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + Flow { + Layout.fillWidth: true + spacing: Theme.spacing + visible: root.host.confirming === "" + + TextField { + id: vehicleLabelField + objectName: "vehicleLabelField" + width: Math.min(300, parent.width) + enabled: root.host.idle + placeholderText: qsTr("Label") + } + ThemedButton { + objectName: "vehicleNew" + text: qsTr("New") + enabled: root.host.idle && VehicleBook.labelProblem(root.host.vehicles, root.host.newLabel, "") === "" + onClicked: root.host.changeVehicles(VehicleBook.add(root.host.vehicles, root.host.newLabel)) + } + ThemedButton { + objectName: "vehicleDuplicate" + text: qsTr("Duplicate") + enabled: root.host.idle && root.host.pickedVehicle !== null + && VehicleBook.labelProblem(root.host.vehicles, root.host.copyLabel, "") === "" + onClicked: root.host.duplicateVehicle() + } + ThemedButton { + objectName: "vehicleMore" + text: qsTr("More") + enabled: root.host.idle + highlighted: root.moreShown + onClicked: root.moreShown = !root.moreShown + } + } + + // The destructive actions apart from New, in a row of their own under + // the page's zoom (a Popup menu keeps the window's scale and the + // Basic style's row height), each still confirming + Flow { + id: moreRow + objectName: "vehicleMoreRow" + Layout.fillWidth: true + spacing: Theme.spacing + visible: root.moreShown && root.host.confirming === "" + + ThemedButton { + objectName: "vehicleRename" + text: qsTr("Rename") + enabled: root.host.idle && root.host.pickedVehicle !== null && root.host.typedLabel !== "" + && root.host.typedLabel !== root.host.pickedVehicle.label + && VehicleBook.labelProblem(root.host.vehicles, root.host.typedLabel, + root.host.pickedVehicle.id) === "" + onClicked: { + root.moreShown = false + root.host.changeVehicles(VehicleBook.rename(root.host.vehicles, root.host.typedLabel)) + } + } + ThemedButton { + objectName: "vehicleForgetVin" + text: qsTr("Forget the VIN") + enabled: root.host.idle && root.host.pickedVehicle !== null && root.host.pickedVehicle.vinKey !== "" + onClicked: { + root.moreShown = false + root.host.changeVehicles(VehicleBook.forgetVin(root.host.vehicles)) + } + } + ThemedButton { + objectName: "vehicleForget" + text: qsTr("Forget") + enabled: root.host.idle && root.host.pickedVehicle !== null + onClicked: { + root.moreShown = false + root.host.confirming = "forget" + } + } + ThemedButton { + objectName: "vehicleForgetAll" + text: qsTr("Forget all vehicles") + enabled: root.host.idle && root.host.vehicles.list.length > 0 + onClicked: { + root.moreShown = false + root.host.confirming = "forgetAll" + } + } + } + + // With the field empty, the defaults New and Duplicate take + Label { + objectName: "vehicleLabelHint" + visible: root.host.typedLabel === "" && root.host.confirming === "" + text: root.host.pickedVehicle === null + ? qsTr("Left empty, New makes “%1”").arg(VehicleBook.defaultNewLabel(root.host.vehicles)) + : qsTr("Left empty, New makes “%1” and Duplicate “%2”") + .arg(VehicleBook.defaultNewLabel(root.host.vehicles), + VehicleBook.defaultCopyLabel(root.host.vehicles, root.host.pickedVehicle.label)) + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + // Why a typed label can't be used + Label { + objectName: "vehicleLabelProblem" + visible: text !== "" && root.host.confirming === "" + text: root.host.typedLabel === "" ? "" + : VehicleBook.labelProblem(root.host.vehicles, root.host.typedLabel, + root.host.pickedVehicle !== null ? root.host.pickedVehicle.id : "") + color: Theme.warning + } + + // A removal asks once, in place + Flow { + visible: root.host.confirming !== "" + Layout.fillWidth: true + spacing: Theme.spacing + + Label { + objectName: "vehicleConfirmText" + text: root.host.confirming === "forgetAll" ? qsTr("Forget all vehicles?") + : root.host.confirmingFile() !== null + ? qsTr("Remove %1? It was written here, and no other copy exists") + .arg(root.host.confirmingFile().name) + : root.host.pickedVehicle !== null ? qsTr("Forget %1?").arg(root.host.pickedVehicle.label) + : "" + color: Theme.text + wrapMode: Text.Wrap + width: Math.min(implicitWidth, parent.width) + } + ThemedButton { + objectName: "vehicleConfirm" + text: root.host.confirmingFile() !== null ? qsTr("Remove") : qsTr("Forget") + highlighted: true + enabled: root.host.idle + onClicked: { + const file = root.host.confirmingFile() + if (file !== null) + root.host.dropSignalFile(file.sha256) + else + root.host.forgetVehicles(root.host.confirming === "forgetAll") + } + } + ThemedButton { + objectName: "vehicleCancel" + text: qsTr("Cancel") + onClicked: root.host.confirming = "" + } + } +} diff --git a/app/qml/SettingsVinLookup.qml b/app/qml/SettingsVinLookup.qml new file mode 100644 index 00000000..e3b6fafd --- /dev/null +++ b/app/qml/SettingsVinLookup.qml @@ -0,0 +1,53 @@ +// File/layer: app/qml/SettingsVinLookup.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) +// The VIN lookup: one part of SettingsPage, which holds the state + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts + +pragma ComponentBehavior: Bound + +ColumnLayout { + id: root + required property SettingsPage host + Layout.fillWidth: true + spacing: Theme.spacing * 2 + + property alias vinLookupField: vinLookupField + + // ---- A VIN looked up (ADR-0043): decoded here, never kept ---- + LabeledFlow { + label: qsTr("Look up a VIN:") + + TextField { + id: vinLookupField + objectName: "vinLookupField" + width: Math.min(300, parent.width) + maximumLength: 32 + placeholderText: qsTr("17 characters") + inputMethodHints: Qt.ImhPreferUppercase | Qt.ImhNoPredictiveText | Qt.ImhSensitiveData + // A typed VIN proposes plugins too (ADR-0052 section 5) + onTextChanged: root.host.refreshMatches() + } + } + + Label { + readonly property string summary: Bridge.describeVin(vinLookupField.text) + objectName: "vinLookupResult" + visible: summary !== "" + text: summary.charAt(0).toUpperCase() + summary.slice(1) + color: Theme.text + wrapMode: Text.Wrap + Layout.fillWidth: true + } + + Label { + objectName: "vinLookupHint" + text: qsTr("By 49 CFR 565 and NHTSA's vPIC list (%1), on this device; the VIN isn't saved. The connected car's goes in the activity log.") + .arg(Bridge.vinSource()) + color: Theme.textDim + wrapMode: Text.Wrap + Layout.fillWidth: true + } +} diff --git a/app/qml/ShiftLightBar.qml b/app/qml/ShiftLightBar.qml index 036830fd..26efa958 100644 --- a/app/qml/ShiftLightBar.qml +++ b/app/qml/ShiftLightBar.qml @@ -22,7 +22,7 @@ GaugeBase { property bool flashOn: false Timer { id: flasher - interval: 70 + interval: 167 // a flash of 3 Hz at most repeat: true running: gauge.shiftNow onTriggered: gauge.flashOn = !gauge.flashOn @@ -40,11 +40,12 @@ GaugeBase { model: gauge.count delegate: Item { id: slot + objectName: "slot" required property int index readonly property real pos: (index + 1) / gauge.count readonly property color hue: pos <= 0.4 ? Theme.success - : pos <= 0.74 ? Theme.warning - : Theme.danger + : pos <= 0.74 ? Theme.gaugeWarn + : Theme.gaugeDanger readonly property bool lit: gauge.shiftNow ? gauge.flashOn : gauge.fraction >= pos - 1e-6 readonly property color glow: gauge.shiftNow ? Theme.info : hue @@ -67,7 +68,7 @@ GaugeBase { Rectangle { // specular highlight x: parent.width * 0.24; y: parent.height * 0.14 width: parent.width * 0.42; height: width * 0.55; radius: height / 2 - color: Qt.alpha("white", slot.lit ? 0.45 : 0.07) + color: Qt.alpha(Theme.gaugeTick, slot.lit ? 0.45 : 0.07) } } } diff --git a/app/qml/SignalFilterBar.qml b/app/qml/SignalFilterBar.qml index 59ae8933..18295f3e 100644 --- a/app/qml/SignalFilterBar.qml +++ b/app/qml/SignalFilterBar.qml @@ -1,6 +1,6 @@ // File/layer: app/qml/SignalFilterBar.qml | Qt6 Quick, UI layer // Testing: BRIDGE: BridgeTest (test_bridge); QML: QmlTest.liveview, -// QmlTest.recordings, QmlTest.phone (test_qml) +// QmlTest.recordings, QmlTest.dashedit, QmlTest.phone (test_qml) pragma ComponentBehavior: Bound @@ -19,6 +19,9 @@ RowLayout { required property SignalFilter filter // The groups' codes among the list's rows property var codes: [] + // False leaves the text field alone, with no Filter button and so no + // popup (a list the groups and Plotted only don't apply to) + property bool filterButtonShown: true readonly property var choices: bar.filter.groupChoices(bar.codes) // The popup's content, which lives in the window's overlay @@ -39,6 +42,7 @@ RowLayout { ThemedButton { id: filterButton objectName: "filterButton" + visible: bar.filterButtonShown text: qsTr("Filter") // Lit while the popup's choices narrow the list highlighted: bar.filter.plottedOnly || bar.filter.groups.length > 0 diff --git a/app/qml/SignalHub.qml b/app/qml/SignalHub.qml index 871e95a8..b47cf1dd 100644 --- a/app/qml/SignalHub.qml +++ b/app/qml/SignalHub.qml @@ -3,19 +3,24 @@ import QtQuick -// ID-keyed view of Bridge.signalModel. The model is keyed by row; a -// gauge wants "the RPM signal" by core's stable def ID, whatever the -// set names it (Bridge.gaugeSignals). Each row is mirrored into an -// Entry whose required properties re-bind on the model's dataChanged, -// the same path LiveView's delegates use. byId is replaced, never -// mutated, so lookup() bindings re-run when rows come and go (a -// profile switch resets the model). +// Ref-keyed view of Bridge.signalModel. The model is keyed by row; a +// gauge wants "the RPM signal" by its ref (ADR-0057: `id:` for core's +// def ID in the mock and obd2 sets and a file's extends base, `key:` +// for a signal file's own def), whatever the set names it +// (Bridge.gaugeSignals). Each row is mirrored into an Entry whose +// required properties re-bind on the model's dataChanged, the same path +// LiveView's delegates use. A row whose ref is "" (uds-generic's, or any +// other set's) has no entry in byRef. byRef is replaced, never mutated, +// so lookup() bindings re-run when rows come and go (a profile switch +// resets the model). Instantiator { id: hub component Entry: QtObject { required property int id // core's def ID + required property string ref // ADR-0057's ref, "" for none required property string name + required property string label // an enum value's label, "" none required property string unit // as displayed, from core required property double value required property double windowHigh // the last window's highest @@ -23,9 +28,16 @@ Instantiator { required property int decimals // core's decimal_places required property bool hasValue required property double ageMs // -1 = never arrived + required property bool hidden // the ECU lacks it + required property string refusedCode // the ECU's refusal ("7F 22 31"), "" none + required property bool isText + required property bool isEnum + // The def's range as displayed; NaN for no range (test with isNaN) + required property double rangeLow + required property double rangeHigh } - property var byId: ({}) + property var byRef: ({}) model: Bridge.signalModel delegate: Entry {} @@ -34,22 +46,24 @@ Instantiator { // delegate's Entry, which says so to the type checker onObjectAdded: (index, object) => { const entry = object as Entry - const m = Object.assign({}, hub.byId) - m[entry.id] = entry - hub.byId = m + if (entry.ref === "") return + const m = Object.assign({}, hub.byRef) + m[entry.ref] = entry + hub.byRef = m } onObjectRemoved: (index, object) => { const entry = object as Entry - if (hub.byId[entry.id] !== entry) return - const m = Object.assign({}, hub.byId) - delete m[entry.id] - hub.byId = m + if (entry.ref === "" || hub.byRef[entry.ref] !== entry) return + const m = Object.assign({}, hub.byRef) + delete m[entry.ref] + hub.byRef = m } - // First of `ids` the active signal set provides, else null - function lookup(ids) { - for (const id of ids ?? []) { - const e = byId[id] + // First of `refs` the active signal set provides, else null + function lookup(refs) { + for (const ref of refs ?? []) { + if (!Object.prototype.hasOwnProperty.call(byRef, ref)) continue + const e = byRef[ref] if (e) return e } return null diff --git a/app/qml/SparkGauge.qml b/app/qml/SparkGauge.qml new file mode 100644 index 00000000..5c87eaa5 --- /dev/null +++ b/app/qml/SparkGauge.qml @@ -0,0 +1,222 @@ +// File/layer: app/qml/SparkGauge.qml | Qt6 Quick + Shapes, UI layer +// Testing: QML: QmlTest.kinds, QmlTest.dashboard + +import QtQuick +import QtQuick.Shapes + +// One trace over a window (ADR-0057 section 1): the newest value at its end, +// the window's low and high as a scale. DigitalGauge's ShapePath trace with +// a longer window: at 10 Hz at most 1,200 samples, drawn as about one point +// per 1.5 px of width. It samples only while its page is the one shown and +// the app is active (`shown`, from the dashboard: a SwipeView keeps its +// neighbors visible, so `visible` alone would not stop them), and it starts +// its trace again when it stops being shown, on Reset peaks (a connect, a +// change of units) and never keeps a value that is not a number. The trace +// is a glance, Live's chart is the record. +GaugeBase { + id: gauge + + // The window in seconds (10 to 120) + property int windowS: 30 + // Whether the dashboard's page holding this gauge is the one on screen + // and the app is active + property bool shown: true + + readonly property int span: Math.max(10, Math.min(120, Math.round(windowS))) + readonly property int historyLength: span * 10 + property var history: [] + + onPeaksReset: history = [] + onShownChanged: if (!shown) history = [] + onVisibleChanged: if (!visible) history = [] + + // One sample every 100 ms while a value is coming: a value that holds + // still still advances the trace, so the x axis stays time + Timer { + interval: 100 + repeat: true + running: gauge.hasValue && gauge.visible && gauge.shown + onTriggered: gauge.takeSample() + } + function takeSample() { + if (!isFinite(value)) + return + const h = history.slice(1 - historyLength) + h.push(value) + history = h + } + + // The window's own low and high, padded to at least 4 % of full scale + // so idle noise doesn't fill the box + readonly property var extent: { + if (history.length < 1) + return { lo: from, hi: to } + let lo = Infinity, hi = -Infinity + for (const v of history) { + if (v < lo) lo = v + if (v > hi) hi = v + } + const minSpan = (to - from) * 0.04 + if (hi - lo < minSpan) { + const mid = (hi + lo) / 2 + lo = mid - minSpan / 2 + hi = mid + minSpan / 2 + } + return { lo: lo, hi: hi } + } + + // The trace's points for a box, newest at the right edge, one point per + // 1.5 px at most (the newest kept), and the area under them for the fill + // (the same points between two corners). A flat range draws a midline + function buildTrace(w, h) { + const n = history.length + if (n < 2 || w <= 0) + return { points: [], area: [] } + const step = w / (historyLength - 1) + const stride = Math.max(1, Math.ceil(n / (w / 1.5 + 1))) + const range = extent.hi - extent.lo + const points = [] + for (let i = n - 1; i >= 0; i -= stride) { + const y = range > 0 && isFinite(range) + ? h - 2 - (history[i] - extent.lo) / range * (h - 4) : h / 2 + points.push(Qt.point(w - (n - 1 - i) * step, y)) + } + points.reverse() + const area = [Qt.point(points[0].x, h)] + for (const p of points) + area.push(p) + area.push(Qt.point(w, h)) + return { points: points, area: area } + } + // The points alone, as the tests and the trace read them + function tracePoints(w, h) { return buildTrace(w, h).points } + + implicitHeight: 96 + + Text { + id: title + anchors { left: parent.left; top: parent.top } + text: gauge.label + font.pixelSize: 12 + font.weight: Font.DemiBold + font.letterSpacing: 1.2 + font.capitalization: Font.AllUppercase + color: Theme.textDim + } + Text { + anchors { left: title.right; leftMargin: 10; baseline: title.baseline } + visible: !gauge.hasValue + text: gauge.note + font.pixelSize: 11 + color: Qt.alpha(Theme.textDim, 0.7) + } + + // The newest value, at the trace's end + Row { + id: readout + anchors { right: parent.right; top: parent.top } + spacing: 3 + opacity: gauge.stale ? 0.45 : 1.0 + Text { + id: valueLabel + objectName: "readout" + text: gauge.valueText + font.pixelSize: 22 + font.weight: Font.DemiBold + font.features: ({ "tnum": 1 }) + color: gauge.hasValue ? gauge.zoneColor(gauge.value, Theme.gaugeReadout) : Theme.textDim + } + DangerMark { + visible: !isNaN(gauge.dangerFrom) + opacity: gauge.inDanger ? 1 : 0 + size: 18 + anchors.verticalCenter: valueLabel.verticalCenter + } + Text { + objectName: "unit" + visible: gauge.hasValue + anchors.baseline: valueLabel.baseline + text: gauge.unit + font.pixelSize: 12 + color: Theme.textDim + } + } + + // The scale: the window's high at the top, its low at the bottom + Column { + id: scaleBox + objectName: "scaleBox" + anchors { left: parent.left; top: trace.top; bottom: trace.bottom } + // Sized from the scale's ends and a digit more, so the trace + // doesn't move when a label gains a digit + width: Math.max(highText.implicitWidth, lowText.implicitWidth, + sampleLow.implicitWidth, sampleHigh.implicitWidth) + Text { + id: highText + objectName: "scaleHigh" + text: gauge.history.length > 0 ? gauge.format(gauge.extent.hi) : "" + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + color: Qt.alpha(Theme.textDim, 0.8) + } + Item { width: 1; height: Math.max(0, scaleBox.height - highText.height - lowText.height) } + Text { + id: lowText + objectName: "scaleLow" + text: gauge.history.length > 0 ? gauge.format(gauge.extent.lo) : "" + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + color: Qt.alpha(Theme.textDim, 0.8) + } + } + + Text { + id: sampleLow + visible: false + text: gauge.format(gauge.from) + "0" + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + } + Text { + id: sampleHigh + visible: false + text: gauge.format(gauge.to) + "0" + font.pixelSize: 10 + font.features: ({ "tnum": 1 }) + } + + Shape { + id: trace + objectName: "trace" + anchors { left: scaleBox.right; leftMargin: 6; right: parent.right + top: readout.bottom; topMargin: 6; bottom: parent.bottom } + preferredRendererType: Shape.CurveRenderer + + readonly property var drawn: gauge.buildTrace(width, height) + + ShapePath { // baseline + strokeColor: Qt.alpha(Theme.gaugeTick, 0.06) + strokeWidth: 1 + fillColor: "transparent" + startX: 0; startY: trace.height - 0.5 + PathLine { x: trace.width; y: trace.height - 0.5 } + } + ShapePath { + strokeColor: "transparent" + fillGradient: LinearGradient { + x1: 0; y1: 0; x2: 0; y2: trace.height + GradientStop { position: 0.0; color: Qt.alpha(gauge.accent, 0.30) } + GradientStop { position: 1.0; color: Qt.alpha(gauge.accent, 0.0) } + } + PathPolyline { path: trace.drawn.area } + } + ShapePath { + strokeColor: gauge.stale ? Theme.textDim : gauge.accent + strokeWidth: 1.5 + fillColor: "transparent" + joinStyle: ShapePath.RoundJoin + capStyle: ShapePath.RoundCap + PathPolyline { path: trace.drawn.points } + } + } +} diff --git a/app/qml/StripChart.qml b/app/qml/StripChart.qml index bca8d8ee..6ed45d48 100644 --- a/app/qml/StripChart.qml +++ b/app/qml/StripChart.qml @@ -248,6 +248,12 @@ Canvas { ctx.setLineDash([]) } + // The traces and the chrome are read from Theme as they are painted: + // a new theme paints them again + Connections { + target: Theme + function onThemeChanged() { chart.requestPaint() } + } onWidthChanged: requestPaint() onHeightChanged: requestPaint() Component.onCompleted: requestPaint() diff --git a/app/qml/Theme.qml b/app/qml/Theme.qml index 0a523fda..d3c1d041 100644 --- a/app/qml/Theme.qml +++ b/app/qml/Theme.qml @@ -2,26 +2,132 @@ // Testing: QML: QmlTest.theme, QmlTest.liveview, QmlTest.log, QmlTest.phone // (test_qml); Manual smoke pragma Singleton +import QtCore import QtQuick -// Central palette - dark mode. main.cpp repeats three of these for the -// platform's own window: bg behind Android's, surface and text in -// Windows' title bar; change them there too +// Central palette: three themes, the one in `theme` read through the roles +// below. main.cpp colors the platform's own window (Android's background, +// Windows' title bar) from bg, surface and text when the theme changes. +// Dark is the default. Low glare (amber and orange on near black) and Night +// (red on near black) keep the light low for a car's cabin after dark; red +// is the danger color there too, so danger is told from the rest by more +// than hue (GaugeBase: a mark beside the readout and a heavier zone stroke). +// Text holds 4.5:1 or more against the surfaces it sits on in each theme, +// except text on the selected-row color (primary), held to Dark's own 4.2:1 +// (a lighter primary would be a bright row in a dark cabin); the readouts, +// the zone colors and the trace colors have their floors too +// (tests/qml/tst_theme.qml measures each). QtObject { - readonly property color bg: "#14141c" - readonly property color surface: "#1e1e2e" - readonly property color elevated: "#2a2a3e" - readonly property color elevatedLight: "#33334a" - readonly property color outline: "#64647e" // control borders; 3:1 on bg - readonly property color primary: "#6d4aff" - readonly property color text: "#e8e8f0" - readonly property color textDim: "#8888a0" - readonly property color success: "#4ade80" - readonly property color warning: "#ffd166" - readonly property color danger: "#f87171" - readonly property color info: "#60a5fa" + // The chosen theme, kept between runs under the `ui` settings. It is + // read here, when the singleton is made, so the first frame already has + // it. A name that is not a theme reads as dark (`active`) + property string theme: "dark" + readonly property string active: clampTheme(theme) + property Settings store: Settings { + category: "ui" + property string theme: "dark" + } + // qmllint disable missing-property + Component.onCompleted: theme = clampTheme(store.theme) + onThemeChanged: store.theme = theme + // qmllint enable missing-property + readonly property var themeNames: ["dark", "lowGlare", "night"] + function clampTheme(name) { return themeNames.indexOf(name) >= 0 ? name : "dark" } + function themeLabel(name) { + switch (name) { + case "lowGlare": return qsTr("Low glare") + case "night": return qsTr("Night") + default: return qsTr("Dark") + } + } + + // The analog dial's bezel, face, needle and hub shades from its face + // color, for a theme with no hand-picked ones + function shadesOf(face) { + return { bezelHi: Qt.lighter(face, 2.1), bezelLo: Qt.lighter(face, 1.6), + faceHi: Qt.lighter(face, 1.45), faceLo: Qt.darker(face, 1.9), + needleBase: Qt.lighter(face, 1.7), hubHi: Qt.lighter(face, 2.5) } + } + + readonly property var palettes: ({ + dark: { + bg: "#14141c", surface: "#1e1e2e", elevated: "#2a2a3e", elevatedLight: "#33334a", + outline: "#64647e", // control borders; 3:1 on bg + primary: "#6d4aff", text: "#e8e8f0", textDim: "#8888a0", + success: "#4ade80", warning: "#ffd166", danger: "#f87171", info: "#60a5fa", + gaugeFace: "#1b1b28", gaugeValue: Qt.lighter("#6d4aff", 1.3), + shades: { bezelHi: "#3a3a52", bezelLo: "#2c2c42", faceHi: "#25253a", faceLo: "#0e0e15", + needleBase: "#2a2a38", hubHi: "#4b4b63" }, + gaugeReadout: "#e8e8f0", gaugeNeedle: "#ff5a5f", gaugeTick: "#e8e8f0", + gaugeWarn: "#ffd166", gaugeDanger: "#f87171", + // One per hue family, so traces stay distinct on the dark surface + series: ["#4aa3ff", // blue + "#31d08c", // green + "#5dd9d0", // aqua + "#f0e442", // yellow + "#e39ac9", // reddish purple + "#ffa94d", // orange + "#f2f2f2", // near-white + "#b08cff", // violet + "#a3e635", // lime + "#e879f9"] // fuchsia + }, + lowGlare: { + bg: "#0d0a07", surface: "#18120c", elevated: "#261c12", elevatedLight: "#31241a", + outline: "#85694a", primary: "#7f440d", text: "#f3c895", textDim: "#b58f64", + success: "#f0a53a", warning: "#ff8a3a", danger: "#ff4a38", info: "#d2a86a", + gaugeFace: "#1a130c", gaugeValue: "#f0a53a", + shades: shadesOf("#1a130c"), + gaugeReadout: "#f7c98a", gaugeNeedle: "#ff7a2e", gaugeTick: "#e9bf8a", + gaugeWarn: "#ff8a3a", gaugeDanger: "#ff4a38", + // Warm, told apart by lightness and saturation as much as hue + series: ["#fff5bf", "#ff4000", "#ffd900", "#9e5d47", "#d17d00", + "#9e9147", "#ffb299", "#ffe373", "#ff794d", "#b89c00"] + }, + night: { + bg: "#080404", surface: "#130909", elevated: "#201010", elevatedLight: "#2b1616", + outline: "#934a44", primary: "#7a241c", text: "#ff9484", textDim: "#c46a5e", + success: "#e8584a", warning: "#ff8a4a", danger: "#ff3030", info: "#d98a78", + gaugeFace: "#150909", gaugeValue: "#ff5a4a", + shades: shadesOf("#150909"), + gaugeReadout: "#ff9686", gaugeNeedle: "#ff4a3a", gaugeTick: "#f08a7a", + gaugeWarn: "#ff8a4a", gaugeDanger: "#ff3030", + series: ["#ffdfbf", "#ff0000", "#9e5b18", "#ff7373", "#9e7777", + "#ff8000", "#ffab73", "#d1431f", "#b86253", "#ebb0b0"] + } + }) + readonly property var colors: palettes[active] + + readonly property color bg: colors.bg + readonly property color surface: colors.surface + readonly property color elevated: colors.elevated + readonly property color elevatedLight: colors.elevatedLight + readonly property color outline: colors.outline + readonly property color primary: colors.primary + readonly property color text: colors.text + readonly property color textDim: colors.textDim + readonly property color success: colors.success + readonly property color warning: colors.warning + readonly property color danger: colors.danger + readonly property color info: colors.info readonly property int radius: 8 + // The gauges' roles (ADR-0057 section 9): no gauge draws a literal color. + // The face under the dial and the cards; value: the lit segments, the + // progress arc and the trace; readout: the value's text; needle; the + // ticks and their numerals; warn and danger: the zones and a readout + // past them + readonly property color gaugeFace: colors.gaugeFace + readonly property color gaugeValue: colors.gaugeValue + readonly property color gaugeReadout: colors.gaugeReadout + readonly property color gaugeNeedle: colors.gaugeNeedle + readonly property color gaugeTick: colors.gaugeTick + readonly property color gaugeWarn: colors.gaugeWarn + readonly property color gaugeDanger: colors.gaugeDanger + // The analog dial's own shades (bezelHi, bezelLo, faceHi, faceLo, + // needleBase, hubHi): Dark's are fixed colors + readonly property var gaugeShade: colors.shades + // A phone's density: Main.qml sets dense when the layout (after the // zoom) is narrower than 720 px or shorter than 480 px, a phone // upright or on its side, or a window as small. Margins, spacing and @@ -31,12 +137,26 @@ QtObject { // Shorter than 480 px: a phone on its side, where Live's and the // viewer's charts start maximized (Main.qml sets it with dense) property bool shortLayout: false + // Narrower than 720 px: a phone upright, where the tab bar shows + // (Main.qml sets it) + property bool compact: false readonly property int spacing: dense ? 6 : 8 readonly property int pageMargin: dense ? 10 : 16 readonly property int controlHeight: dense ? 32 : 36 readonly property int rowHeight: dense ? 36 : 44 readonly property int toolBarHeight: dense ? 40 : 48 readonly property int sidebarWidth: dense ? 150 : 220 + // The least a tap target measures each way on a phone (Material's + // 48 dp), on the glass: in the layout's units, which the zoom scales, + // a zoom under 1 asks for more, so a target never shrinks below it; + // elsewhere a control's own height. A control may draw smaller + // inside it. + readonly property real touchTarget: mobile || compact ? 48 * Math.max(1, 1 / zoom) + : controlHeight + // Between a bar's targets and the window's edge, on the glass too, so + // a tap low on the tab bar never lands on the system's Back or Home + // beside it + readonly property real barGap: 8 * Math.max(1, 1 / zoom) // A phone or tablet: touch only, no keyboard shortcuts, no file // manager for the app's own folders @@ -86,21 +206,11 @@ QtObject { ? "Menlo" : "monospace" - // Chart trace colors, one per hue family so traces stay distinct on - // the dark surface. LiveView keys them by model row. No red: it is - // the danger color, so a trace drawn in it would read as an alarm. - readonly property var seriesColors: [ - "#4aa3ff", // blue - "#31d08c", // green - "#5dd9d0", // aqua - "#f0e442", // yellow - "#e39ac9", // reddish purple - "#ffa94d", // orange - "#f2f2f2", // near-white - "#b08cff", // violet - "#a3e635", // lime - "#e879f9", // fuchsia - ] + // Chart trace colors, per theme (each palette's `series`): one per hue + // family on Dark so traces stay distinct on the dark surface, warm in + // the night themes. LiveView keys them by model row. Dark has no red: + // it is the danger color, so a trace drawn in it would read as an alarm. + readonly property var seriesColors: colors.series // A trace's style by its row (Live's model row, a recording's signal // index): rows past the palette reuse its colors with a dashed trace, // so a chart still tells them apart (a list's swatch shows the color @@ -135,6 +245,18 @@ QtObject { // states fall to "Link degraded", mirroring linkColor. LiveView's // banner keeps its own longer messages, which carry the episode count // and error code. + // The same states in one short word, for a header with no room + function linkShortLabel(state: string): string { + switch (state) { + case "ok": return qsTr("Live") + case "fault": return qsTr("Fault") + case "requests": return qsTr("Failing") + case "quiet": return qsTr("Quiet") + case "stopped": return qsTr("Stopped") + case "disconnected": return qsTr("Offline") + default: return qsTr("Degraded") + } + } function linkLabel(state: string): string { switch (state) { case "ok": return qsTr("Session active") diff --git a/app/qml/ThemedButton.qml b/app/qml/ThemedButton.qml index 563434ea..6c745f42 100644 --- a/app/qml/ThemedButton.qml +++ b/app/qml/ThemedButton.qml @@ -1,3 +1,6 @@ +// File/layer: app/qml/ThemedButton.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings, QmlTest.phone (test_qml) + import QtQuick import QtQuick.Controls @@ -21,6 +24,20 @@ Button { : Math.max(implicitBackgroundWidth + leftInset + rightInset, implicitContentWidth + leftPadding + rightPadding) + // A page that needs its buttons a phone's touch size (Settings) has a + // touchMin property; the button takes the nearest one up its parents + // qmllint disable missing-property + readonly property real touchMin: { + for (let p = control.parent; p; p = p.parent) { + if (p.touchMin !== undefined) + return p.touchMin + } + return 0 + } + // qmllint enable missing-property + implicitHeight: Math.max(implicitBackgroundHeight + topInset + bottomInset, + implicitContentHeight + topPadding + bottomPadding, touchMin) + opacity: enabled ? 1.0 : 0.45 background: Rectangle { diff --git a/app/qml/ThemedCheckBox.qml b/app/qml/ThemedCheckBox.qml new file mode 100644 index 00000000..1b8563b2 --- /dev/null +++ b/app/qml/ThemedCheckBox.qml @@ -0,0 +1,24 @@ +// File/layer: app/qml/ThemedCheckBox.qml | Qt6 Quick, UI layer +// Testing: QML: QmlTest.settings (test_qml) +// A CheckBox that is a phone's touch size inside a page that asks for one + +import QtQuick +import QtQuick.Controls + +CheckBox { + id: control + + // The nearest ancestor's touchMin (SettingsSubpage sets one), as + // ThemedButton takes it + // qmllint disable missing-property + readonly property real touchMin: { + for (let p = control.parent; p; p = p.parent) { + if (p.touchMin !== undefined) + return p.touchMin + } + return 0 + } + // qmllint enable missing-property + implicitHeight: Math.max(implicitContentHeight + topPadding + bottomPadding, + implicitIndicatorHeight + topPadding + bottomPadding, touchMin) +} diff --git a/app/recordingframes.cpp b/app/recordingframes.cpp new file mode 100644 index 00000000..64df5152 --- /dev/null +++ b/app/recordingframes.cpp @@ -0,0 +1,197 @@ +// File/layer: app/recordingframes.cpp | Qt6 Core, app layer, C++17 +// Testing: BRIDGE: ViewerFramesTest (test_bridge) + +#include "recordingframes.h" + +#include +#include + +#include +#include +#include + +namespace { + +// Milliseconds since the recording started to its host_us; a negative +// time is the start +quint64 microseconds(double ms) +{ + return ms <= 0 ? 0 : static_cast(std::llround(ms * 1000.0)); +} + +} // namespace + +RecordingFrames::RecordingFrames(QObject* parent) + : QObject(parent), m_ids(&m_frames) +{ + // Oldest first: the part in view reads down the table in time + m_frames.setNewestFirst(false); + m_read = [](const char* folder, uint64_t from, uint64_t to, + ecuio_frame_row_callback_t cb, void* user, + ecuio_frames_read_t* summary) { + return ecuio_recording_read_frames(folder, from, to, cb, user, summary); + }; +} + +RecordingFrames::~RecordingFrames() +{ + stopAll(); + for (const std::shared_ptr& j : m_jobs) { + if (j->worker.joinable()) { + j->worker.join(); + } + } +} + +void RecordingFrames::stopAll() +{ + for (const std::shared_ptr& j : m_jobs) { + j->stop = true; + } +} + +void RecordingFrames::setLoading(bool loading) +{ + if (m_loading != loading) { + m_loading = loading; + emit loadingChanged(); + } +} + +void RecordingFrames::load(const QString& folder, double fromMs, double toMs) +{ + const quint64 toUs = microseconds(toMs); + if (toUs == 0) { + // A view that ends at the recording's start or before it has no + // rows (core reads a to of 0 as the end, which no view means) + clear(); + return; + } + stopAll(); + const double from = std::max(fromMs, 0.0); + auto job = std::make_shared(); + job->generation = ++m_generation; + job->folder = folder.toUtf8(); + job->fromUs = microseconds(from); + job->toUs = std::max(toUs, job->fromUs); + job->fromMs = from; + m_jobs.push_back(job); + setLoading(true); + const ReadFn read = m_read; + try { + job->worker = std::thread([job, read, this] { run(job, read, this); }); + } catch (...) { + // No thread to read on: nothing is running, and the page is told + m_jobs.pop_back(); + setLoading(false); + m_frames.clear(); + m_ids.refresh(); + m_rows = 0; + m_note.clear(); + m_error = tr("the frames could not be read: no thread to read on"); + emit loadedChanged(); + } +} + +void RecordingFrames::clear() +{ + stopAll(); + ++m_generation; // whatever is running posts to nobody + setLoading(false); + m_frames.clear(); + m_ids.refresh(); + m_rows = 0; + m_note.clear(); + m_error.clear(); + emit loadedChanged(); +} + +void RecordingFrames::run(const std::shared_ptr& job, const ReadFn& read, + RecordingFrames* self) +{ + struct State { + Job* job; + bool outOfMemory = false; + } state{job.get()}; + // Called from C: nothing may throw out of it + auto take = [](void* user, const ecuio_frame_t* f, uint64_t hostUs) -> int { + State* s = static_cast(user); + Job& j = *s->job; + try { + if (j.stop.load()) { + return 1; + } + if (j.rows.size() >= static_cast(MaxRows)) { + // One row past the cap: there is more to show than fits + j.capped = true; + return 1; + } + Row r; + r.id = f->arbitration_id; + r.flags = f->flags; + r.hostUs = hostUs; + r.data = QByteArray(reinterpret_cast(f->data), + f->data_length); + j.rows.push_back(std::move(r)); + return 0; + } catch (...) { + s->outOfMemory = true; + return 1; + } + }; + ecuio_frames_read_t summary{}; + job->rc = read(job->folder.constData(), job->fromUs, job->toUs, take, + &state, &summary); + if (state.outOfMemory) { + job->rc = ECUIO_ERR_OUT_OF_MEMORY; + job->detail = tr("out of memory"); + } else if (job->rc != ECUIO_OK && + !(job->rc == ECUIO_ERR_CANCELED && job->capped)) { + const char* detail = ecuio_last_error_detail(); + job->detail = detail != nullptr ? QString::fromUtf8(detail) : QString(); + } + QMetaObject::invokeMethod( + self, [self, job] { self->finished(job); }, Qt::QueuedConnection); +} + +void RecordingFrames::finished(const std::shared_ptr& job) +{ + ++m_finishedCount; + if (job->worker.joinable()) { + job->worker.join(); // it posted this as its last act + } + m_jobs.erase(std::remove(m_jobs.begin(), m_jobs.end(), job), m_jobs.end()); + if (job->generation != m_generation) { + return; // a newer read, or clear(), has the models + } + setLoading(false); + m_frames.clear(); + m_error.clear(); + m_note.clear(); + const bool failed = + job->rc != ECUIO_OK && !(job->rc == ECUIO_ERR_CANCELED && job->capped); + if (failed) { + m_error = job->detail.isEmpty() ? tr("the frames could not be read") + : job->detail; + } else { + ecuio_frame_t f; + for (const Row& r : job->rows) { + f = ecuio_frame_t{}; + f.timestamp_us = r.hostUs; + f.arbitration_id = r.id; + f.flags = r.flags; + f.data_length = static_cast(r.data.size()); + std::memcpy(f.data, r.data.constData(), + static_cast(r.data.size())); + m_frames.appendFrame(f, f.data_length); + } + if (job->capped) { + m_note = tr("the first %1 frames from %2 s: zoom in for the rest") + .arg(QLocale(QLocale::English).toString(MaxRows)) + .arg(job->fromMs / 1000.0, 0, 'f', 1); + } + } + m_rows = m_frames.heldCount(); + m_ids.refresh(); + emit loadedChanged(); +} diff --git a/app/recordingframes.h b/app/recordingframes.h new file mode 100644 index 00000000..c6b4e1f1 --- /dev/null +++ b/app/recordingframes.h @@ -0,0 +1,126 @@ +// File/layer: app/recordingframes.h | Qt6 Core, app layer, C++17 +// Testing: BRIDGE: ViewerFramesTest (test_bridge) + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +#include "ecuio/recording.h" +#include "sessionbridge.h" + +// The recording viewer's Frames table (ADR-0049's appendix "frames read +// back"): the frames.csv rows whose host_us lies in the part of the +// recording in view, read through ecuio_recording_read_frames on a thread +// of its own and handed to a FrameListModel and a FrameIdModel the page +// shows through the Log page's table components. Times are milliseconds +// since the recording started (host_us / 1000), as RecordingView's are; +// each row's time in the models is its host_us, never the frame's own +// session time, so the table's times and its filter's span read on the +// viewer's axis. +// +// A read gives at most MaxRows rows, the first from the part's left edge; +// note then says so. load() while a read runs stops that one (its rows +// never reach the models) and starts the next. +class RecordingFrames : public QObject +{ + Q_OBJECT + Q_PROPERTY(FrameListModel* frames READ frames CONSTANT) + Q_PROPERTY(FrameIdModel* ids READ ids CONSTANT) + // A read is running + Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged) + // The rows the models hold + Q_PROPERTY(int rows READ rows NOTIFY loadedChanged) + // "the first 10,000 frames from 12.3 s: zoom in for the rest" when the + // part had more rows than MaxRows; "" otherwise + Q_PROPERTY(QString note READ note NOTIFY loadedChanged) + // Core's words for a read that failed (a row it refuses, no + // frames.csv); "" otherwise. The models are empty then + Q_PROPERTY(QString error READ error NOTIFY loadedChanged) + +public: + // The models' ring size: the rows of one read + static constexpr int MaxRows = FrameListModel::MaxFrames; + + explicit RecordingFrames(QObject* parent = nullptr); + ~RecordingFrames() override; + + FrameListModel* frames() { return &m_frames; } + FrameIdModel* ids() { return &m_ids; } + bool loading() const { return m_loading; } + int rows() const { return m_rows; } + QString note() const { return m_note; } + QString error() const { return m_error; } + + // Reads the rows of the recording in folder from fromMs to toMs, both + // included; a view's edges, so a fromMs before the start is the start + // and a toMs at the start or before it is a view with no rows (the + // models empty, no read). Stops a read under way first. + // The models fill on the GUI thread when the read ends; loadedChanged + // follows, and a stopped read ends silently + Q_INVOKABLE void load(const QString& folder, double fromMs, double toMs); + // Stops a read under way and empties the models + Q_INVOKABLE void clear(); + + // The read, replaceable so a test can hold one in flight; the + // parameters are ecuio_recording_read_frames's + using ReadFn = std::function; + void setReadForTesting(ReadFn read) { m_read = std::move(read); } + // How many reads have ended and been taken on the GUI thread, those + // dropped for a newer one among them + int finishedForTesting() const { return m_finishedCount; } + +signals: + void loadingChanged(); + void loadedChanged(); + +private: + // One row as the worker keeps it: never an ecuio_frame_t, whose + // 4,120 bytes at MaxRows rows would be 41 MB + struct Row { + quint32 id = 0; + quint32 flags = 0; + quint64 hostUs = 0; + QByteArray data; + }; + struct Job { + quint64 generation = 0; + QByteArray folder; + quint64 fromUs = 0; + quint64 toUs = 0; + double fromMs = 0; + std::atomic stop{false}; + // The worker's alone until it posts its end + std::vector rows; + bool capped = false; + ecuio_status_t rc = ECUIO_OK; + QString detail; + std::thread worker; + }; + + static void run(const std::shared_ptr& job, const ReadFn& read, + RecordingFrames* self); + void finished(const std::shared_ptr& job); + void stopAll(); + void setLoading(bool loading); + + FrameListModel m_frames; + FrameIdModel m_ids; + ReadFn m_read; + // Every job whose thread hasn't been joined, the newest last + std::vector> m_jobs; + quint64 m_generation = 0; + bool m_loading = false; + int m_rows = 0; + int m_finishedCount = 0; + QString m_note; + QString m_error; +}; diff --git a/app/recordingimport.cpp b/app/recordingimport.cpp new file mode 100644 index 00000000..b8d53aa1 --- /dev/null +++ b/app/recordingimport.cpp @@ -0,0 +1,708 @@ +// File/layer: app/recordingimport.cpp | Qt6 Core, app layer, C++17 +// Testing: BRIDGE: BridgeTest.Import* (test_bridge); QML: QmlTest.recordings + +#include "recordingimport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ecuio/core.h" +#include "ecuio/recording.h" + +namespace { + +// A picked file opens through QFile as it is: a local one by its path, +// Android's content:// URI through its provider +QString openable(const QUrl& url) +{ + return url.isLocalFile() ? url.toLocalFile() : url.toString(); +} + +QVariantMap refused(const QString& words) +{ + return {{QStringLiteral("ok"), false}, {QStringLiteral("words"), words}}; +} + +// The file's bytes into path, a chunk at a time: a log can be larger than +// the memory a phone gives the app +bool copyTo(const QUrl& url, const QString& path, bool* readable) +{ + QFile in(openable(url)); + *readable = in.open(QIODevice::ReadOnly); + QFile out(path); + if (!*readable || !out.open(QIODevice::WriteOnly)) { + return false; + } + QByteArray chunk(1024 * 1024, Qt::Uninitialized); + for (;;) { + const qint64 n = in.read(chunk.data(), chunk.size()); + if (n < 0) { + *readable = false; + return false; + } + if (n == 0) { + return out.flush(); + } + if (out.write(chunk.constData(), n) != n) { + return false; + } + } +} + +struct Job { + QUrl file; + int kind = 0; + QUrl map; + QByteArray mapText; + bool hasMapText = false; + QString interfaceName; + QString root; + QString stamp; + bool copyLocal = false; +}; + +QVariantMap run(const Job& job) +{ + const bool csv = job.kind == RecordingImport::Csv; + QByteArray map; + if (csv && job.hasMapText) { + map = job.mapText; + if (map.size() > RecordingImport::MapMaxBytes) { + return refused( + QStringLiteral("the column map is larger than 1 MiB")); + } + } else if (csv) { + if (job.map.isEmpty()) { + return refused( + QStringLiteral("choose the logger's column map first")); + } + QFile f(openable(job.map)); + if (!f.open(QIODevice::ReadOnly)) { + return refused(QStringLiteral("the column map can't be read")); + } + map = f.read(RecordingImport::MapMaxBytes + 1); + if (map.size() > RecordingImport::MapMaxBytes) { + return refused( + QStringLiteral("the column map is larger than 1 MiB")); + } + } + if (job.root.isEmpty()) { + return refused(QStringLiteral( + "there's no Documents folder to keep recordings in")); + } + if (!QDir().mkpath(job.root)) { + return refused(QStringLiteral("the recordings folder can't be made")); + } + // Named and sorted as a recording is ("[-n]