Author SHA1 Message Date
seb 1b71f96cc0 Release v0.0.02-pre: car dashboard, nav bar rework, cached launcher
- Nav bar is icon-only and shorter, with a now-playing pill on non-home screens
- Clock opens a calendar and weather dashboard (adds READ_CALENDAR)
- Web page URL is now set from the car's Settings screen
- Launcher app scan and weather are cached
- Home player gains skip buttons and a larger cover
2026-09-20 03:00:25 -07:00
seb 24cfbee0c4 Gearslip: phone-side Android Auto client 2026-09-20 02:09:47 -07:00
196 changed files with 1546 additions and 23578 deletions

No files matched your search

-15
View File
@@ -1,15 +0,0 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: Seb3thehacker
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: seb3thehacker
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
-59
View File
@@ -1,59 +0,0 @@
name: Bug report
description: Something in Gearslip broke or behaves wrong.
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for reporting. Check the [open issues](https://github.com/twinksoftware/gearslip/issues) first, in case someone has already reported it.
- type: input
id: car
attributes:
label: Car
description: Make, model, and year.
placeholder: 2019 Honda Civic
validations:
required: true
- type: dropdown
id: head-unit
attributes:
label: Head unit
options:
- The one the car came with
- A factory unit from another car
- An aftermarket unit (Pioneer, Kenwood, Alpine, and so on)
- A homemade or open-source unit, such as LIVI
- I don't know
validations:
required: true
- type: dropdown
id: connection
attributes:
label: Connection
options:
- USB cable
- Wireless dongle
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened
description: What you did, what you expected, and what happened instead.
validations:
required: true
- type: textarea
id: log
attributes:
label: Log
description: |
On the phone, open Logs from Gearslip's home screen and tap Share log. Drag the file here.
The log records your phone, its Android version, the Gearslip version, and why the connection ended.
placeholder: Drop the log file here.
validations:
required: true
-65
View File
@@ -1,65 +0,0 @@
name: Car report
description: Tell us whether Gearslip works in your car, so others know before they install.
labels: ["car report"]
body:
- type: markdown
attributes:
value: |
Reports from working cars help as much as reports from broken ones.
- type: input
id: car
attributes:
label: Car
description: Make, model, and year.
placeholder: 2019 Honda Civic
validations:
required: true
- type: dropdown
id: head-unit
attributes:
label: Head unit
options:
- The one the car came with
- A factory unit from another car
- An aftermarket unit (Pioneer, Kenwood, Alpine, and so on)
- A homemade or open-source unit, such as LIVI
- I don't know
validations:
required: true
- type: dropdown
id: connection
attributes:
label: Connection
options:
- USB cable
- Wireless dongle
validations:
required: true
- type: dropdown
id: result
attributes:
label: Does it work?
options:
- Yes, everything I tried works
- Partly. It connects, but something is wrong
- No, it never connects
validations:
required: true
- type: textarea
id: notes
attributes:
label: Notes
description: What you tried, and anything that didn't work.
- type: textarea
id: log
attributes:
label: Log
description: |
Needed if the car doesn't work. On the phone, open Logs from Gearslip's home screen and tap Share log. Drag the file here.
placeholder: Drop the log file here.
-1
View File
@@ -1 +0,0 @@
blank_issues_enabled: false
@@ -1,23 +0,0 @@
name: Feature request
description: Suggest something Gearslip should do.
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: What do you want to do?
description: Describe the problem, not the solution. "I can't see my next turn while music plays" helps more than "add a turn widget."
validations:
required: true
- type: textarea
id: idea
attributes:
label: How should it work?
description: Your idea for a fix, if you have one.
- type: textarea
id: apps
attributes:
label: Apps involved
description: Any apps this touches, such as a map or music app.
-15
View File
@@ -1,15 +0,0 @@
# Weekly pull requests for newer Gradle libraries and GitHub Actions, aimed at experimental,
# where unreleased code lands. Security fixes come separately, as soon as an alert opens.
version: 2
updates:
- package-ecosystem: gradle
directory: /
target-branch: experimental
schedule:
interval: weekly
open-pull-requests-limit: 5
- package-ecosystem: github-actions
directory: /
target-branch: experimental
schedule:
interval: weekly
-15
View File
@@ -1,15 +0,0 @@
Gearslip 0.3.01 connects wirelessly on more phones and dongles.
## Fixed
- Wireless works with dongles that send their Wi-Fi details before their address.
- A VPN no longer stops a wireless drive without a word. Gearslip tries the phone's ordinary route around it, and if the VPN still blocks the car, Gearslip says so. To fix it for good, exclude Gearslip in your VPN app.
- When Android won't ask for the Nearby devices permission, a button opens Gearslip's settings, where you can turn it on.
## Changed
- An app that someone else has re-signed, such as a modified Waze, no longer shows the red X when it accepts Gearslip.
- Support Gearslip through Liberapay, Buy Me a Coffee, or Monero, in Settings.
- Gearslip now belongs to Twink Software LLC, and its code lives at github.com/twinksoftware/gearslip. Old links still work.
- The README lists Gearslip's signing certificate, so you can check your copy with AppVerifier.
## Known issues
- Phone calls are unstable right now and may drop or fail to connect.
-50
View File
@@ -1,50 +0,0 @@
name: CodeQL
# Kotlin can only be scanned while it compiles, so this builds the debug app, the same way
# release.yml does but without a signing key. Workflow files need no build.
on:
push:
branches: [main, experimental]
pull_request:
schedule:
- cron: "0 9 * * 1"
workflow_dispatch:
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
actions: read
strategy:
fail-fast: false
matrix:
include:
- language: actions
build-mode: none
- language: java-kotlin
build-mode: manual
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
- if: matrix.build-mode == 'manual'
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- if: matrix.build-mode == 'manual'
uses: gradle/actions/setup-gradle@v4
- if: matrix.build-mode == 'manual'
run: ./gradlew :gearslip:assembleDebug --no-daemon
- uses: github/codeql-action/analyze@v4
with:
category: "/language:${{ matrix.language }}"
-53
View File
@@ -1,53 +0,0 @@
name: Release
on:
push:
tags:
- "v*"
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- uses: gradle/actions/setup-gradle@v4
- name: Write signing key and properties
run: |
echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 -d > gearslip-release.jks
cat > keystore.properties <<EOF
storeFile=gearslip-release.jks
storePassword=${{ secrets.KEYSTORE_STORE_PASSWORD }}
keyAlias=${{ secrets.KEYSTORE_KEY_ALIAS }}
keyPassword=${{ secrets.KEYSTORE_KEY_PASSWORD }}
EOF
- name: Build release APK
run: ./gradlew :gearslip:assembleRelease
- name: Locate APK
id: apk
run: |
# The build moves its APKs to <root>/build/Gearslip-<variant>.apk (see renameApk).
apk=build/Gearslip-release.apk
test -f "$apk" || { echo "no APK at $apk"; ls -R build | head -50; exit 1; }
echo "path=$apk" >> "$GITHUB_OUTPUT"
- name: Create release
uses: softprops/action-gh-release@v2
with:
files: ${{ steps.apk.outputs.path }}
# The hand-written notes go first; GitHub adds the full changelog link under them.
body_path: .github/release-notes.md
generate_release_notes: true
# Every release starts as a pre-release: only phones on the Alpha update channel get it.
# Once it's tested, untick pre-release on GitHub and everyone gets it.
prerelease: true
-34
View File
@@ -1,34 +0,0 @@
name: Security scan
# Trivy looks through the repository for committed secrets and risky workflow or build
# settings. Findings show under the Security tab, next to CodeQL's and Dependabot's.
on:
push:
branches: [main, experimental]
pull_request:
schedule:
- cron: "0 9 * * 1"
workflow_dispatch:
jobs:
trivy:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v4
- uses: aquasecurity/trivy-action@v0.36.0
with:
scan-type: fs
scanners: vuln,secret,misconfig
format: sarif
output: trivy.sarif
severity: MEDIUM,HIGH,CRITICAL
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: trivy.sarif
category: trivy
+6 -28
View File
@@ -6,35 +6,13 @@
/build /build
local.properties local.properties
# Keys # Reference checkouts only - never referenced by the build; safe to delete entirely.
*.jks
*.keystore
keystore.properties
# Native build cache
.cxx/
# Testing
/cloned-repos /cloned-repos
docs-internal/
# Internal # The head unit certificate. Never committed or shared beyond who Seb sends it to directly.
*.pdf /cert
todo.md
logs/
# For AI code # Local investigation script; not meant for the public repo.
.claude/ /docs/cert-sweep.sh
CLAUDE.md
# Other
archive/ archive/
.wrangler/ CLAUDE.md
stats-worker/
# Certificates and keys never go in the repo; the app downloads or imports them on the phone.
*.p12
*.pfx
*.pem
*.crt
*.key
-49
View File
@@ -1,49 +0,0 @@
# Cars
Drivers who share usage notes tell us which cars Gearslip works in. This list comes from
those notes, and from our own testing. A car shows up here once Gearslip has reached its
screen at least once.
The year is the one the car reports. Some cars report the year of the head unit instead,
and some don't say.
## Works
| Car | Year | Head unit |
|---|---|---|
| Audi | | MIB2+ (Alpine) |
| Audi | | Harman |
| Chevrolet, with myChevrolet | 2019, 2020, 2021 | myChevrolet |
| Chevrolet, with MyLink | 2017 | MyLink |
| Dacia | | Media Nav (LG ULC 4.1) |
| Dacia | | LG ULC 4.5 |
| Ford | 2018 | SYNC 3.0 (Panasonic) |
| Ford Fiesta | 2019 | SYNC 3.2 (Panasonic) |
| Ford Fusion | 2018 | SYNC 3.1 (Panasonic) |
| Jeep Cherokee | 2019 | Uconnect 8.4 (Delphi) |
| MG | 2019 | Desay SV |
| Ram 1500 | 2018 | Uconnect 8.4 (Panasonic) |
| Škoda | 2018 | MIB Standard2 (TechniSat) |
| Subaru Outback | 2020 | Denso |
| Toyota RAV4 | 2020 | Pioneer T1 |
| Volkswagen | 2018 | MIB Standard2 (Delphi) |
| Volkswagen | 2024 | ICAS3 |
| Volvo XC90 | 2022 | SPA Plus (Mitsubishi Electric) |
| Wuling | 2021 | Desay SV |
| [LIVI](https://github.com/f-io/LIVI), the open-source head unit | | |
## Not working yet
| Car | Year | What happens |
|---|---|---|
| Honda | 2016 | The connection drops before Gearslip reaches the screen. |
| Honda | 2019 | The connection drops before Gearslip reaches the screen. |
| Mitsubishi Attrage | 2020 | The connection drops before Gearslip reaches the screen. |
Some cars reject Gearslip's certificate before they say what they are, so they can't appear
here by name. Most of these are from around 2020 or later.
## Add your car
Turn on usage notes in Gearslip's setup or Settings, and drive once. If your car is missing
or listed wrongly, open an issue.
-102
View File
@@ -1,102 +0,0 @@
# Gearslip Contributor License Agreement
Version 1.0, October 2026
Thank you for contributing to Gearslip. This agreement lets Twink Software LLC, the company
behind Gearslip, use your contribution. You keep the copyright in your work. You sign once,
and the agreement covers every contribution you make to Gearslip, past and future.
## Why we ask
Gearslip is free software under the GNU Affero General Public License, version 3 (the
"AGPL"). Twink Software LLC also sells commercial licenses to companies that cannot meet the
AGPL's terms, and that income helps pay for the project. Offering your code on those terms
needs your permission, and this agreement gives it.
## 1. Definitions
- **"We"** and **"us"** mean Twink Software LLC, a California limited liability company
(Secretary of State entity number B20260081700), under that name or any other, and its
successors and assigns.
- **"You"** means the person who signs this agreement.
- **"Contribution"** means any work of authorship, such as code, documentation, or images,
that you submit to Gearslip, whether before or after you sign. A submission includes a
pull request, patch, or issue attachment sent to a repository or channel we manage. It
excludes anything you mark in writing as "Not a Contribution".
## 2. Copyright license
You grant us, and anyone who receives software from us, a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable license to reproduce, prepare derivative
works of, publicly display, publicly perform, sublicense, and distribute your Contributions
and derivative works of them.
This license lets us offer your Contributions under licenses other than the AGPL, including
commercial licenses.
## 3. Patent license
You grant us, and anyone who receives software from us, a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer your Contributions. This license covers
only the patent claims you can license that your Contribution, alone or combined with
Gearslip, would infringe.
If anyone sues claiming that Gearslip or a Contribution infringes a patent, the patent
licenses granted to that party for Gearslip end on the date the suit is filed.
## 4. Our promise to you
As long as we distribute a Contribution, we will also offer it under the AGPL or another
license approved by the Open Source Initiative. Your work will always stay available as
free software.
## 5. Your promises
You promise that:
1. **The work is yours.** Each Contribution is your original creation, and you have the
right to grant these licenses.
2. **Your employer agrees.** If your employer has rights in what you create, you have its
permission to contribute on its behalf, or it has waived its rights in your
Contributions.
3. **You name other people's work.** If any part of a Contribution is not your own, you say
so when you submit it, and you name its source and its license.
4. **You'll tell us of changes.** If any of these promises stops being true, you will tell
us.
## 6. No warranty
You provide your Contributions "as is", without warranties or conditions of any kind. You do
not have to provide support for them.
## 7. No obligation
We are not required to use or include any Contribution.
## 8. General
- California law governs this agreement.
- This agreement does not change the rights you have under the AGPL in Gearslip as
released.
- We may publish a new version of this agreement. A new version applies only to
Contributions you make after you sign it; this version keeps covering the ones you made
under it.
## Signing
Most contributors sign on GitHub: the CLA Assistant bot comments on your first pull request,
and you sign there with one click. Your GitHub account then serves as your signature.
To sign by hand instead, fill in the following and send it to us on Matrix. The address is
on the [Seb3thehacker GitHub profile](https://github.com/Seb3thehacker).
Name: ______________________________
GitHub username: ______________________________
Email: ______________________________
Signature: ______________________________
Date: ______________________________
-55
View File
@@ -1,55 +0,0 @@
# Contributing to Gearslip
Thanks for helping. Bug reports from real cars are the most useful thing you can send, so
start there if you aren't sure where to begin.
## Reporting a bug
Open an issue on [GitHub](https://github.com/twinksoftware/gearslip/issues) and include:
- your car's make, model, and year, and whether the head unit is the original one; and
- the log from the drive. Open Logs on the phone app's home screen and tap Share log.
The log records your phone, its Android version, the Gearslip version, the head unit, and
why the connection ended. Most car bugs can't be fixed without it. Head units often report
only a part number, so the log can't name your car for you.
## Building
You need Android Studio, or the Android SDK with JDK 21. Gradle downloads the NDK, CMake,
and the speech library on the first build.
```
./gradlew :gearslip:assembleDebug
```
The APK lands at `build/Gearslip-debug.apk`. It installs as Gearslip Dev, next to the
regular app.
## Pull requests
Work happens on the `experimental` branch, which merges into `main` at each release. Base your
branch on `experimental`, and open your pull request against it.
- Keep each pull request to one change, and explain the problem it solves.
- Say how you tested it: which car or head unit, which phone, and which apps.
- Code written with AI tools is welcome. Read it, test it, and stand behind it as you would
your own.
- Gearslip asks for no adb, root, or Shizuku. A feature must work with ordinary Android
permissions and on-device consent dialogs.
## Writing
Text that users read, such as screens, release notes, and docs, follows Strunk's
[*The Elements of Style*](https://www.gutenberg.org/ebooks/37134). In short: use the active
voice, state things positively, cut needless words, and use the serial comma.
## License
Gearslip is licensed under AGPL-3.0, and your contributions are too. Twink Software LLC, which
owns Gearslip, also sells a commercial license, described in [NOTICE.md](NOTICE.md).
Before we can merge your first pull request, you sign the
[Contributor License Agreement](CLA.md). You keep the copyright in your work, and it stays
available as free software; the agreement lets us offer it under the commercial license too.
A bot comments on your pull request with a link, and signing takes one click.
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2026 Twink Software LLC and contributors Copyright (C) 2026 seb
GNU AFFERO GENERAL PUBLIC LICENSE GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007 Version 3, 19 November 2007
+10 -3
View File
@@ -1,9 +1,16 @@
# License # License
Gearslip is licensed under the GNU Affero General Public License v3.0. The full text is in `LICENSE`. Gearslip is licensed under the **GNU Affero General Public License v3.0** (see `LICENSE`).
You may use, run, and modify Gearslip freely. If you distribute a modified version, or let others use one over a network, you must publish your changes under the same license. The obligation follows the code even when you hand out no binary, which suits software that runs as a background service. In short: you're free to use, run, and modify it. If you modify it — or run a modified
version as a service others use over a network — the AGPL requires you to make your source
changes available on the same terms. That obligation follows the code even when you don't
redistribute a binary, which is what makes the AGPL fit for something that can run as a
background service.
## Commercial licensing ## Commercial licensing
If the AGPL's terms don't work for you, Twink Software LLC, which owns Gearslip, sells a separate commercial license. The usual case is a company that wants to use Gearslip privately without publishing its changes. Terms, including any limits on modification, are set case by case. Contact us on Matrix; the address is on the [Seb3thehacker GitHub profile](https://github.com/Seb3thehacker). If the AGPL's terms don't work for you — for example, you want to use Gearslip privately
without being required to publish your changes — a separate commercial license is available
directly from the author. Terms (including any restrictions on modification) are set on a
case-by-case basis. Contact me though Matrix (on my profile) to discuss one.
+32 -164
View File
@@ -2,149 +2,38 @@
# Gearslip # Gearslip
An Android Auto alternative built for everyone. Bring any app to your car screen.
## What this is
[![forthebadge](https://forthebadge.com/badges/compatibility-club-penguin.svg)](https://forthebadge.com) Gearslip is a phone-side Android Auto client. It speaks the Android Auto protocol directly
to a car head unit over USB and acts as a **Car App Library host**: apps that ship an
Android Auto car UI (navigation and media apps) hand Gearslip a template, and Gearslip
renders it natively on the car screen, full quality, no phone-screen mirroring. A separate
screen-sharing mode is included for apps that don't ship a car UI at all.
[<img src="https://raw.githubusercontent.com/ImranR98/Obtainium/main/assets/graphics/badge_obtainium.png" alt="Get it on Obtainium" height="80">](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/twinksoftware/gearslip) Built by reverse-engineering the protocol for interoperability - getting a non-Google client
talking to a car head unit that only expects Google's own app.
Questions, ideas?
[Join the discussion on Matrix](https://matrix.to/#/!mf0_mgBd5KqKpc9FfX_wHp1jFCcwAtPrndIn_oGIyMk?via=matrix.org).
## Which cars work
Most cars work. Starting around 2020, some cars added newer security standards that reject
Gearslip's certificate, and Gearslip can't run in those cars. [CARS.md](CARS.md) lists the
cars drivers have confirmed.
## What Gearslip is
Gearslip is an Android Auto client for the phone. It speaks the Android Auto protocol
directly to a car head unit, over USB or wirelessly, with no Google software in the path.
Gearslip acts as a Car App Library host: an app that ships a car interface hands Gearslip
a template, and Gearslip renders that template natively on the car screen. Nothing is
mirrored from the phone. For apps without a car interface, Gearslip offers a separate
screen-sharing mode.
| | |
|---|---|
| ![The launcher, with every car app on the phone and the route in the bar below](docs/screenshots/launcher.png) | ![Vela Maps showing the route, with the music player beside the map](docs/screenshots/navigation.png) |
| Your car apps in one place. A red X marks the ones that don't work yet. | Vela Maps navigating, with the player beside it. |
| ![ViVi Music's song, art, and controls in Gearslip's player](docs/screenshots/music.png) | ![A new message card over Organic Maps](docs/screenshots/message.png) |
| ViVi Music in Gearslip's player. | A new message, read aloud at a tap, over the map. |
| ![The dashboard, with the weather, the next calendar event, and recent notifications](docs/screenshots/dashboard.png) | ![DuckDuckGo open in Gearslip's web browser](docs/screenshots/web.png) |
| The weather, your next event, and what you missed. | Browse the web while parked. |
| ![The voice assistant listening over Organic Maps](docs/screenshots/assistant.png) | ![Coffee shops near you in Vela Maps, with the music player beside the map](docs/screenshots/places.png) |
| Ask for a place, a song, or an app. | Find coffee nearby without leaving the map. |
## Features
- **Phone calls.** Dial from a keypad, or search your contacts, then confirm before the
call goes out. When a call comes in, answer or decline it on the car screen.
- **Navigation.** Gearslip hosts real Car App Library map apps on the car screen.
Organic Maps, OsmAnd, and Flitsmeister work today. Vela runs, with rough
edges.
- **Music.** Browse, play, and queue tracks from a car-enabled media app, with a Now
Playing view, an Up Next queue, and lyrics. Type a search, and apps that accept one
play the best match.
- **The web.** A browser template with its own on-screen keyboard, for anything that
doesn't ship a car interface of its own.
- **Weather and the day ahead.** A dashboard screen shows the week's calendar next to
the current and coming weather.
- **Voice.** Tap the mic, or press the talk button on the wheel, and say "navigate to the
nearest gas station", "play Daft Punk", or "call Mom". Say "help" for the full list.
Speech turns into text on the phone, and nothing you say leaves it.
- **Messages.** New messages appear as a small card on the car screen. Gearslip reads
each one aloud, and you reply by voice or with a quick reply. Music pauses while
Gearslip speaks or listens. Speech runs on the phone, so it needs no Google account.
- **Notifications.** Only messages, missed calls, alarms, and reminders interrupt you.
The rest wait on the dashboard.
- **Your apps, your order.** The launcher groups apps by kind: phone, maps, music,
messaging, and the rest. Press and hold an app to move it.
- **Car controls.** Steering wheel buttons, control knobs, and D-pads all work.
- **Themes.** Choose flat buttons or skeuomorphic ones that look like real keys.
## Status ## Status
- **Wired or wireless.** Plug the phone into the car's USB port, or, in a car with wireless Real progress, with one hard limit that's worth knowing before you build on this:
Android Auto, tap Connect wirelessly and pick the car. Pair the phone with the car over
Bluetooth first.
- **Setup walks you through it.** First launch asks for the Android Auto certificate,
then one permission at a time, each with a plain reason and an Allow or Skip. A help
screen inside the car answers anything setup didn't cover.
- **Templated apps work.** Gearslip renders all 16 template types that the Car App
Library defines, and it draws its own keyboard for search, sign-in, and text fields.
It has been tested against several real navigation and media apps.
- **Gearslip works with [LIVI](https://github.com/f-io/LIVI),** the open-source head unit
used in homemade car dashboards.
- **Some apps refuse Gearslip.** Spotify, Waze, and Google Messages use a version of
Google's car library that accepts only Android Auto itself. Spotify still plays through
Gearslip's own player.
- **Calls use the car's Bluetooth,** as they do in Android Auto. Pair the phone with the
car to hear calls through its speakers.
- **Music reaches the car over Bluetooth or USB.** Setup asks which. Bluetooth is the
default: Android never asks for permission, and your map app's voice reaches the car
too. USB sounds a little clearer, with no delay, but Android shows a screen-share
consent dialog once per drive. Gearslip never reads the screen; capturing playback is
the only way an ordinary app can pass another app's audio along.
- **Gearslip needs no adb, root, or Shizuku.** Every feature relies on an ordinary
Android permission or an on-device consent dialog. For USB audio, setup offers two
optional adb commands: one removes the audio dialog for good, and the other keeps
notifications visible while audio plays.
- **Updates come from GitHub.** Once a day, Gearslip checks this repository's latest
release. When a new version is out, it downloads the APK, checks it against GitHub's
SHA-256, and installs it through Android's own installer. Turn off automatic checks in
Settings.
## Verify your download - **Templated app hosting works.** All 16 template types the Car App Library defines are
rendered, including a keyboard Gearslip draws itself for search and sign-in. Verified
Check that your copy of Gearslip is genuine with against several real navigation and media apps.
[AppVerifier](https://github.com/soupslurpr/AppVerifier): share this block to it, or compare it - **Media playback works.** Car-enabled media apps are browsable and controllable from the
with the output of `apksigner verify --print-certs`. car UI, with lyrics and playback state, over the same host connection.
- **The connection to a real head unit needs a certificate Google controls, and Gearslip
``` doesn't ship one.** A head unit only accepts a phone identity that chains to Google's
app.seb3thehacker.gearslip Automotive Link certificate authority - something only Google issues. Without one, Gearslip
4C:C5:6E:BD:D1:3A:54:D2:60:EC:A9:B7:E2:B2:AE:6B:30:E2:F2:25:BF:DA:8F:50:8F:07:09:ED:F0:84:94:8B still runs and renders everything correctly against a debug harness, but a real car will
``` reject the connection outright. See [SPIKE_FINDINGS.md](SPIKE_FINDINGS.md) for what was
tested, including one publicly-known leaked certificate that works on some older head
## Usage notes units and is rejected by newer firmware and by Google's own reference tooling.
- **No adb, root, or Shizuku is required to run it.** Every feature is gated on an ordinary
Gearslip can send short notes that show which cars it works in. They stay off unless you Android permission or an on-device consent dialog - nothing needs privileged access, on
turn them on, in setup or in Settings. the phone or in the car.
- **When they go out.** When you open Gearslip, at most once a day, and after each drive.
Nothing runs in the background.
- **What they carry.** The Gearslip version and which boxes you ticked, plus whatever
those boxes cover: the Android version and whether the phone runs GrapheneOS, the phone
model, whether a car connected that day, and each car's head unit, model, year, screen
size, and connection result, with whether that drive used the cable or wireless and
whether music went over USB or Bluetooth. If you tick it, how each drive went: how far
the connection got, how long it lasted, and how it ended. Settings shows the exact note. Untick a phone detail, and
the server drops the copy it kept.
- **What they leave out.** Your name, accounts, location, contacts, messages, and
anything you type or play.
- **How phones are counted.** A random number counts each phone once. The server keeps
only a salted hash of it.
- **Where they go.** To Gearslip's server. Like any website, it sees your IP address when a
note arrives, and it doesn't store it.
Turn the notes off, and they stop at once.
## How Gearslip is made
Gearslip is my beloved child. I decide what it does and how it looks, and Claude writes nearly
all of the code. I test every change myself before it ships: in a real car, with both a
GrapheneOS phone and a stock Android phone, and on [LIVI](https://github.com/f-io/LIVI), the
open-source head unit software. I watch the phone's temperature too, so a new feature doesn't
cook it. Then I beg my friends to try it in their cars, so it works in as many makes, models,
and years as possible. If something breaks, that's on me, so please open an issue.
## Contributing
Bug reports from real cars help most, and pull requests are welcome.
[CONTRIBUTING.md](CONTRIBUTING.md) explains what to put in a report, which branch to work
on, and the one-time agreement you sign before your first pull request merges.
## Building ## Building
@@ -154,35 +43,14 @@ on, and the one-time agreement you sign before your first pull request merges.
The APK lands at `build/Gearslip-debug.apk`. The APK lands at `build/Gearslip-debug.apk`.
A release build needs a signing key. Copy `keystore.properties.example` to ## Further reading
`keystore.properties`, fill in your own values, and run
`./gradlew :gearslip:assembleRelease`. Git ignores both the properties file and the
keystore. Without them, the debug build still works.
## Writing apps for Gearslip - [SPIKE_FINDINGS.md](SPIKE_FINDINGS.md) - the certificate investigation in full: what was
tried, what a real head unit does and doesn't accept, and why.
[docs/BUILDING_APPS.md](docs/BUILDING_APPS.md) specifies how to write apps that Gearslip - [CUSTOM_HEADUNIT_SCOPING.md](CUSTOM_HEADUNIT_SCOPING.md) - the original scoping of what a
can render: templated apps, media apps, and the Gearslip app protocol. custom head unit client would need.
## How Gearslip talks to cars
Gearslip is an independent program, written to work with car head units. What it knows of
the protocol comes from public open-source projects such as
[aasdk](https://github.com/opencardev/aasdk) and open-android-auto, and it contains none
of Google's Android Auto code.
Gearslip ships without a certificate. On first launch you choose where yours comes from:
download the one the aasdk project publishes, or import a file of your own. The
certificate stays on your phone. Gearslip never uploads, backs up, or logs it.
## Trademarks
Android, Android Auto, Google Messages, and Waze are trademarks of Google LLC. Spotify is
a trademark of Spotify AB. Gearslip is not affiliated with, endorsed by, or sponsored by
any of these companies. All other names belong to their owners.
## License ## License
Gearslip belongs to Twink Software LLC and is licensed under AGPL-3.0; see [LICENSE](LICENSE). AGPL-3.0 - see [LICENSE](LICENSE). A separate commercial license is available for private
The LLC also sells a separate commercial license for private use outside the AGPL's terms; see use outside the AGPL's terms; see [NOTICE.md](NOTICE.md).
[NOTICE.md](NOTICE.md).
-477
View File
@@ -1,477 +0,0 @@
# Building apps for Gearslip
Gearslip renders four kinds of app on a car screen. This page specifies all four.
| Kind | What it is | Status |
| --- | --- | --- |
| [Templated apps](#templated-apps) | An AndroidX Car App Library app. Gearslip hosts it. | Works today |
| [Media apps](#media-apps) | A `MediaBrowserService` that opted in to Android Auto. | Works today |
| [Messaging apps](#messaging-apps) | An app whose notifications opted in to Android Auto. | Works today |
| [Gearslip apps](#gearslip-apps) | A native Gearslip screen, described over binder. | Specified here; not yet implemented |
Write a templated app when your app fits the Car App Library's templates, because it runs today
and it also runs on Android Auto. Write a media app when you ship audio. Write a Gearslip app
when you want a screen the Car App Library cannot describe.
Gearslip's package name is `app.seb3thehacker.gearslip`. It declares
`android.car.permission.TEMPLATE_RENDERER`.
---
## Templated apps
A templated app exports a `CarAppService`, describes each screen as a `Template`, and lets the
host draw it. Gearslip implements the host half of that protocol, so an existing Android Auto app
needs no Gearslip-specific code. Build it against the AndroidX Car App Library as you would for
any other host.
### Letting Gearslip in
Your app decides which hosts may render it, through the `HostValidator` your `CarAppService`
returns.
Gearslip declares `android.car.permission.TEMPLATE_RENDERER`. Car App Library 1.8.0-beta01
and earlier, and 1.9.0-alpha01, accept any host holding it, so Gearslip passes the default
validator. From 1.8.0-rc01 and 1.9.0-alpha02 the library checks that permission only on
Android Automotive, so on a phone Gearslip passes only when your allowlist names it. Add this
entry:
```xml
<!-- res/values/arrays.xml -->
<array name="hosts_allowlist">
<item>4cc56ebdd13a54d260eca9b7e2b2ae6b30e2f225bfda8f508f0709edf084948b,app.seb3thehacker.gearslip</item>
</array>
```
```java
@Override
public HostValidator createHostValidator() {
return new HostValidator.Builder(getApplicationContext())
.addAllowedHosts(R.array.hosts_allowlist)
.build();
}
```
That digest belongs to Gearslip's release signing certificate. A Gearslip you built yourself
carries your own debug key and a different digest, so read the fingerprint off the APK you
actually installed when an allowlist entry fails to match.
Write each entry as the digest first, then a comma, then the package name. The digest is the
SHA-256 of the host's signing certificate as 64 lowercase hex characters, with no colons and no
`0x` prefix. The builder lowercases the entry and strips spaces, but it keeps colons, so convert
`keytool` output before pasting it:
```
keytool -list -v -keystore <keystore> -alias <alias> \
| grep 'SHA256:' | cut -d' ' -f3 | tr -d ':' | tr 'A-Z' 'a-z'
```
Reading the installed APK is more reliable, because it fingerprints the key that actually signed
the build, and `apksigner` already prints the required format:
```
apksigner verify --print-certs Gearslip.apk | grep 'SHA-256 digest'
```
During development, `HostValidator.ALLOW_ALL_HOSTS_VALIDATOR` accepts every host. Ship a real
validator instead.
An app that refuses a host returns no binder at all. Gearslip reports that as
`the app refused to bind - host not accepted`. Your own side logs the reason under the tag
`CarApp.Val`, including the exact `addAllowedHost` call to add, so read logcat there first.
### Discovery
Gearslip finds templated apps by querying `androidx.car.app.CarAppService`, then re-querying with
each known category to recover which ones your intent filter matched. Declare the categories you
belong to, or Gearslip files you under `app`:
```xml
<service android:name=".MyCarAppService" android:exported="true">
<intent-filter>
<action android:name="androidx.car.app.CarAppService" />
<category android:name="androidx.car.app.category.NAVIGATION" />
</intent-filter>
</service>
```
Gearslip recognises the `NAVIGATION`, `POI`, `PARKING`, `CHARGING`, `MESSAGING`, `CALLING`,
`SETTINGS`, `IOT` and `WEATHER` categories. Navigation apps start automatically on the home
screen when the driver used them last.
### The handshake
Gearslip offers car API level 8. It negotiates down to
`min(8, yourLatestCarAppApiLevel)` and refuses the app when that falls below your
`minCarAppApiLevel`, rather than drawing it wrongly. Keep your minimum at 8 or below.
### Templates Gearslip renders
Gearslip renders all sixteen templates. Ten describe their own content:
`ListTemplate`, `GridTemplate`, `PaneTemplate`, `MessageTemplate`, `LongMessageTemplate`,
`SearchTemplate`, `SignInTemplate`, `TabTemplate`, `SectionedItemTemplate`,
`MediaPlaybackTemplate`.
Six draw a map underneath and take chrome over the top:
`NavigationTemplate`, `MapWithContentTemplate`, `MapTemplate`, `PlaceListNavigationTemplate`,
`RoutePreviewNavigationTemplate`, `PlaceListMapTemplate`.
`SearchTemplate` and `SignInTemplate` need text. A phone keyboard cannot appear on the car's
virtual display, so Gearslip draws its own and feeds the result back through the template's
listener.
### Content limits
Gearslip reports these limits through the constraint service, and expects you to honour them:
| Limit | Value |
| --- | --- |
| Grid items | 12 |
| Pane rows | 4 |
| Route list rows | 3 |
| Anything else | 12 |
Gearslip enables app-driven refresh, so you may invalidate your own template without the driver
touching the screen.
### Drawing a map
A navigation app draws its own pixels. Gearslip lends it a real `Surface` taken from a
`SurfaceView` inside the car's virtual display, so your map reaches the head unit through the
existing video pipe. Gearslip never reads those pixels back.
Gearslip then reports which part of that surface the driver can see. Treat the visible area as
the region safe for your own controls, and the stable area as the region that never gets
covered. Gearslip reports the same area for both, and it depends on the template:
| Template | What Gearslip covers |
| --- | --- |
| `NavigationTemplate` | A strip along the bottom for the trip estimate |
| `MapWithContentTemplate`, `MapTemplate`, and the place list and route preview templates | A content pane on the left |
The turn card and map buttons float over the visible area, as they do in Android Auto.
Your app receives four gestures, never raw touches: `onClick`, `onScroll`, `onFling` and
`onScale`. Coordinates are surface pixels. Scroll distances follow `GestureDetector`'s
convention, which reports the previous position minus the current one.
### Car hardware
A phone knows nothing about a car's sensors, so Gearslip answers every car-hardware request with
"unsupported". It answers rather than ignores: an app whose sensor manager waits for a reply
hangs when the host stays silent. Design for a host that reports no vehicle data at all.
Gearslip accepts the suggestions an app pushes and discards them, because no screen shows them
yet. Your app will not fail for offering them.
### Day and night
Gearslip decides whether it is dark outside and pushes that to your app as a configuration
change, with `UI_MODE_NIGHT_YES` or `UI_MODE_NIGHT_NO`. Take your map style from the
configuration the host reports. The configuration also carries the car's density, screen size and
orientation, and always sets `UI_MODE_TYPE_CAR`.
---
## Media apps
Gearslip draws the media UI itself: browsing, artwork, lyrics, transport controls and a
now-playing pill in the nav bar. Your app supplies a browse tree and a media session.
Gearslip lists a media app when it exports a `MediaBrowserService` **and** declares the Android
Auto meta-data. Both halves are required, because the service alone also appears on phone-only
players that expose a browser to Bluetooth and Wear:
```xml
<application>
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
</application>
```
```xml
<!-- res/xml/automotive_app_desc.xml -->
<automotiveApp>
<uses name="media" />
</automotiveApp>
```
Publish playback state, metadata, duration and artwork through your `MediaSession`, and support
play, pause, next, previous and seek. Gearslip reconnects to the app the driver used last and
can start it playing on connection.
---
## Messaging apps
Gearslip shows conversations from the notifications your app already posts, as Android Auto
does. Your app needs no car screen of its own.
Gearslip lists a messaging app when its car descriptor declares notifications:
```xml
<!-- res/xml/automotive_app_desc.xml -->
<automotiveApp>
<uses name="notification" />
</automotiveApp>
```
Reference it from the same `com.google.android.gms.car.application` meta-data that a media app
uses. Opening your tile on the car screen shows your recent conversations.
### Posting messages
Post each conversation as a `MessagingStyle` notification. Gearslip reads the conversation
title, each message's sender and text, and whether the chat is a group, and shows the last eight
messages. Leave the sender empty on the phone owner's own messages; Gearslip treats a message
with no sender as one the driver sent.
Gearslip reads new messages aloud and lets the driver reply by voice or with a quick reply. For
that, attach two actions, either to the notification or to its `WearableExtender`:
- **Reply:** an action carrying a `RemoteInput` that allows free-form input. Gearslip fills it
with the driver's reply and fires the action's intent.
- **Mark as read:** an action with `SEMANTIC_ACTION_MARK_AS_READ`. Gearslip shows a Mark read
button when you provide it.
### Which notifications interrupt the driver
Gearslip pops up a card for a conversation, a notification with a reply action, or a
notification in the `msg`, `missed_call`, `alarm`, `reminder` or `event` category. A channel
below default importance never pops up. Every other notification waits quietly on the
dashboard.
Gearslip drops these altogether:
- ongoing notifications and group summaries;
- the `transport`, `progress`, `service`, `sys` and `navigation` categories; and
- media notifications, because the player already shows them.
---
## Gearslip apps
This section specifies protocol version 1. Gearslip does not yet implement it.
A Gearslip app describes a screen and lets Gearslip render it in Compose, using the car's theme,
the driver's chosen scale and the current day or night state. Your app draws nothing and receives
no surface. Everything the driver sees comes from the model below, which means your screen
matches the rest of the car UI and cannot be made unreadable.
Write a Gearslip app to reach the parts of the car UI the Car App Library does not cover. Write a
templated app if you need to draw a map, because version 1 lends no surface.
### Discovery
Export a service with the Gearslip action and declare the protocol version it speaks:
```xml
<service
android:name=".GearslipService"
android:exported="true">
<intent-filter>
<action android:name="app.seb3thehacker.gearslip.APP" />
</intent-filter>
<meta-data
android:name="app.seb3thehacker.gearslip.version"
android:value="1" />
</service>
```
Gearslip scans for these services once per car session and shows each one as a tile in the
launcher, under your application's own label and icon. To override either on the car screen, add
`app.seb3thehacker.gearslip.label` or `app.seb3thehacker.gearslip.icon`.
Gearslip binds to any app that declares this service. It asks the driver for nothing, exactly as
a head unit asks nothing before running an Android Auto app.
Gearslip binds your service when the driver opens your tile and unbinds it when they leave. Keep
no state that a rebind cannot rebuild.
### The interface
Copy these three files into `src/main/aidl/app/seb3thehacker/gearslip/api/`. A published artifact
will replace them.
```aidl
// IGearslipApp.aidl
package app.seb3thehacker.gearslip.api;
import app.seb3thehacker.gearslip.api.IGearslipHost;
import app.seb3thehacker.gearslip.api.IScreenCallback;
interface IGearslipApp {
/** Return the highest version both sides speak. Gearslip passes the version it offers. */
int negotiate(int hostVersion);
void onCreate(IGearslipHost host);
void onStart();
void onStop();
/** Describe the current screen. Answer through the callback, on any thread. */
void getScreen(IScreenCallback callback);
void onAction(String actionId);
void onTextInput(String fieldId, String text);
}
```
```aidl
// IGearslipHost.aidl
package app.seb3thehacker.gearslip.api;
interface IGearslipHost {
/** Tell Gearslip the screen changed. It calls getScreen again. */
void invalidate();
/** Open the car keyboard. The result arrives at onTextInput. */
void requestTextInput(String fieldId, String prompt, String initialText);
String getEnvironment();
String getNowPlaying();
/** One of play, pause, toggle, next, previous. */
void mediaCommand(String command);
/** Leave the app and return to the launcher. */
void finish();
}
```
```aidl
// IScreenCallback.aidl
package app.seb3thehacker.gearslip.api;
interface IScreenCallback {
void onScreen(String screenJson);
void onError(String message);
}
```
### Versioning
Gearslip calls `negotiate` first, passing the version it offers. Return the highest version you
also speak. Gearslip uses that version for the rest of the connection and drops the app when the
answer exceeds what it offered. This mirrors how Gearslip negotiates car API levels with
templated apps, and it lets either side move first.
Version 1 is the only version. Reject anything you do not recognise by returning 1.
### Lifecycle
1. Gearslip binds your service and calls `negotiate`.
2. Gearslip calls `onCreate`, handing you the host interface. Keep it.
3. Gearslip calls `onStart`, then `getScreen`.
4. You answer through `onScreen`. Gearslip renders it.
5. The driver taps something. Gearslip calls `onAction` with that element's id.
6. Your screen changes, so you call `invalidate`. Gearslip calls `getScreen` again.
7. The driver leaves. Gearslip calls `onStop` and unbinds.
Every call arrives on a binder thread. Answer `getScreen` promptly; Gearslip shows the previous
screen until you do. Gearslip coalesces repeated `invalidate` calls.
### The screen model
Answer `getScreen` with a JSON object.
```json
{
"protocol": 1,
"type": "list",
"title": "Stations",
"items": [
{ "id": "r6", "title": "BBC Radio 6", "subtitle": "Music", "icon": "play" },
{ "id": "r4", "title": "BBC Radio 4", "subtitle": "Speech", "icon": "play" }
],
"actions": [
{ "id": "refresh", "title": "Refresh", "icon": "refresh", "primary": true }
]
}
```
`type` takes one of four values:
| Type | Renders as | Uses |
| --- | --- | --- |
| `list` | A vertical list of rows | `items` |
| `grid` | A grid of tiles | `items` |
| `pane` | A short detail pane beside its actions | `items`, `actions` |
| `message` | A single message and its actions | `text`, `actions` |
An item takes `id`, `title`, and optionally `subtitle`, `icon` and `enabled`. Gearslip calls
`onAction` with the item's `id` when the driver taps it. An item with `"type": "input"` renders
as a text field carrying `value`; tapping it opens the car keyboard, and the result arrives at
`onTextInput` under the item's id.
An action takes `id`, `title`, and optionally `icon` and `primary`. Gearslip renders at most two
actions and emphasises the primary one.
`icon` names a built-in glyph: `play`, `pause`, `next`, `previous`, `search`, `settings`, `home`,
`apps`, `notifications`, `info`, `share`, `place`, `favorite`, `add`, `remove`, `refresh`,
`check`, `error`. Version 1 carries no images. Gearslip drops an unknown name and renders the
row without a glyph.
Gearslip truncates any list past the limits in [Content limits](#content-limits) and shortens
long strings. Send a screen that fits, rather than one Gearslip has to cut.
### Reading the car
`getEnvironment` returns the car's current state:
```json
{
"protocol": 1,
"darkOutside": true,
"moving": false,
"frameWidth": 800,
"frameHeight": 480,
"densityDpi": 160,
"batteryPercent": 82,
"charging": true,
"vehicle": "Honda"
}
```
`darkOutside` reports whether Gearslip believes it is dark, from the light sensor or the clock.
`moving` reports whether the phone's GPS shows the car moving. Both change during a session, so
read them each time you build a screen rather than caching them.
Treat `moving` as a comfort signal, not a safety guarantee. It reads false whenever the fix is
stale or missing, which includes tunnels and car parks.
### Controlling media
`getNowPlaying` returns what the car is playing, whichever app owns it:
```json
{ "title": "Sleepwalk", "artist": "Santo & Johnny", "playing": true, "durationMs": 142000 }
```
`mediaCommand` sends one of `play`, `pause`, `toggle`, `next` or `previous` to that app. Both
work regardless of which app is playing, so use them to put transport controls on your own
screen. Ship audio through a media app instead of driving these.
### Text input
A phone keyboard cannot appear on the car's virtual display, so Gearslip draws its own. Call
`requestTextInput` with a field id, a prompt and any existing text. Gearslip opens the keyboard
and calls `onTextInput` as the driver types, so treat each call as the current contents rather
than a final answer.
### What version 1 leaves out
Version 1 lends no surface, so no Gearslip app draws its own pixels. It carries no images beyond
the built-in glyphs. It places apps only in the launcher; contributing a dashboard card or a
home-screen pane comes later. Anything that needs its own rendering belongs in a templated app.
---
## Further reading
- [README.md](../README.md) - what Gearslip is.
- [CONTRIBUTING.md](../CONTRIBUTING.md) - how to build Gearslip and report bugs.
- [Android for Cars App Library](https://developer.android.com/training/cars/apps) - the
reference for templated apps.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" width="432" height="432" viewBox="0 0 108 108">
<defs>
<linearGradient id="trail" x1="73.4" y1="46.0" x2="95.8" y2="44.5" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#8C1F1F" stop-opacity="0"/>
<stop offset="100%" stop-color="#8C1F1F" stop-opacity="0.7"/>
</linearGradient>
</defs>
<rect width="108" height="108" fill="#0c0c0d"/>
<circle cx="54" cy="54" r="52" fill="#131415"/>
<path d="M 73.23,47.15 L 94.77,51.90 L 96.89,37.05 L 73.57,44.78 Z" fill="url(#trail)"/>
<path d="M 54.00,27.00 L 59.99,19.91 Q 61.02,18.69 62.50,19.30 L 72.52,23.45 Q 74.00,24.07 73.87,25.66 L 73.23,33.31 Q 73.09,34.91 73.70,36.39 L 80.39,52.52 Q 81.00,54.00 82.22,55.03 L 88.09,59.99 Q 89.31,61.02 88.70,62.50 L 84.55,72.52 Q 83.93,74.00 82.34,73.87 L 73.09,73.09 Q 73.09,73.09 73.09,73.09 L 73.09,73.09 Q 73.09,73.09 73.09,73.09 L 73.87,82.34 Q 74.00,83.93 72.52,84.55 L 62.50,88.70 Q 61.02,89.31 59.99,88.09 L 54.00,81.00 Q 54.00,81.00 54.00,81.00 L 54.00,81.00 Q 54.00,81.00 54.00,81.00 L 48.01,88.09 Q 46.98,89.31 45.50,88.70 L 35.48,84.55 Q 34.00,83.93 34.13,82.34 L 34.91,73.09 Q 34.91,73.09 34.91,73.09 L 34.91,73.09 Q 34.91,73.09 34.91,73.09 L 25.66,73.87 Q 24.07,74.00 23.45,72.52 L 19.30,62.50 Q 18.69,61.02 19.91,59.99 L 27.00,54.00 Q 27.00,54.00 27.00,54.00 L 27.00,54.00 Q 27.00,54.00 27.00,54.00 L 19.91,48.01 Q 18.69,46.98 19.30,45.50 L 23.45,35.48 Q 24.07,34.00 25.66,34.13 L 34.91,34.91 Q 34.91,34.91 34.91,34.91 L 34.91,34.91 Q 34.91,34.91 34.91,34.91 L 34.13,25.66 Q 34.00,24.07 35.48,23.45 L 45.50,19.30 Q 46.98,18.69 48.01,19.91 L 54.00,27.00 Q 54.00,27.00 54.00,27.00 L 54.00,27.00 Q 54.00,27.00 54.00,27.00 Z" fill="#8B9096"/>
<path d="M 92.78,34.42 L 99.94,37.20 Q 101.43,37.78 101.34,39.37 L 100.67,50.20 Q 100.58,51.80 99.03,52.19 L 91.58,54.08 Q 90.03,54.47 90.13,52.87 L 91.19,35.44 Q 91.29,33.84 92.78,34.42 Z" fill="#8C1F1F"/>
<circle cx="54" cy="54" r="12" fill="#0c0c0d"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 11 KiB

+1
View File
@@ -5,6 +5,7 @@
<stop offset="100%" stop-color="#8C1F1F" stop-opacity="0.7"/> <stop offset="100%" stop-color="#8C1F1F" stop-opacity="0.7"/>
</linearGradient> </linearGradient>
</defs> </defs>
<rect width="108" height="108" fill="#0c0c0d"/>
<circle cx="54" cy="54" r="52" fill="#131415"/> <circle cx="54" cy="54" r="52" fill="#131415"/>
<path d="M 73.23,47.15 L 94.77,51.90 L 96.89,37.05 L 73.57,44.78 Z" fill="url(#trail)"/> <path d="M 73.23,47.15 L 94.77,51.90 L 96.89,37.05 L 73.57,44.78 Z" fill="url(#trail)"/>
<path d="M 54.00,27.00 L 61.02,18.69 L 74.00,24.07 L 73.09,34.91 L 81.00,54.00 L 89.31,61.02 L 83.93,74.00 L 73.09,73.09 L 73.09,73.09 L 74.00,83.93 L 61.02,89.31 L 54.00,81.00 L 54.00,81.00 L 46.98,89.31 L 34.00,83.93 L 34.91,73.09 L 34.91,73.09 L 24.07,74.00 L 18.69,61.02 L 27.00,54.00 L 27.00,54.00 L 18.69,46.98 L 24.07,34.00 L 34.91,34.91 L 34.91,34.91 L 34.00,24.07 L 46.98,18.69 L 54.00,27.00 Z" fill="#8B9096"/> <path d="M 54.00,27.00 L 61.02,18.69 L 74.00,24.07 L 73.09,34.91 L 81.00,54.00 L 89.31,61.02 L 83.93,74.00 L 73.09,73.09 L 73.09,73.09 L 74.00,83.93 L 61.02,89.31 L 54.00,81.00 L 54.00,81.00 L 46.98,89.31 L 34.00,83.93 L 34.91,73.09 L 34.91,73.09 L 24.07,74.00 L 18.69,61.02 L 27.00,54.00 L 27.00,54.00 L 18.69,46.98 L 24.07,34.00 L 34.91,34.91 L 34.91,34.91 L 34.00,24.07 L 46.98,18.69 L 54.00,27.00 Z" fill="#8B9096"/>

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 421 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 538 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 569 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

+7 -72
View File
@@ -1,4 +1,3 @@
import java.util.Properties
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
@@ -14,90 +13,28 @@ plugins {
alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.compose)
} }
// The release signing key, read from an untracked keystore.properties beside this file or at the
// repository root. Third-party apps allowlist Gearslip by the SHA-256 of this certificate, so the
// key must stay the same for the life of the project - and must never be committed.
val keystoreProperties = Properties().apply {
listOf(
rootProject.file("keystore.properties"),
project.file("keystore.properties"),
).firstOrNull { it.exists() }?.inputStream()?.use { load(it) }
}
// Keeps build output out of the module folder: <root>/build/gearslip/... instead of
// <root>/gearslip/build/..., so everything this project produces lands under one
// root-level build/ directory. Set before android {}, which works out the path to R8's default
// rules from it.
layout.buildDirectory.set(rootProject.layout.buildDirectory.dir("gearslip"))
android { android {
namespace = "app.seb3thehacker.gearslip" namespace = "app.seb3thehacker.gearslip"
compileSdk = 37 compileSdk = 37
defaultConfig { defaultConfig {
applicationId = "app.seb3thehacker.gearslip" applicationId = "app.seb3thehacker.gearslip"
minSdk = 31 minSdk = 35
targetSdk = 37 targetSdk = 37
versionCode = 10 versionCode = 2
// -PgearslipVersionName=0.1.99-test makes a build that thinks it's older, to try the updater. versionName = "0.0.02-pre"
versionName = project.findProperty("gearslipVersionName")?.toString() ?: "0.3.01-alpha"
manifestPlaceholders["appLabel"] = "Gearslip"
// Where opted-in phones send their daily usage note: the stats-worker/ Worker's address,
// set as gearslipStatsUrl in gradle.properties. Left empty, nothing is ever sent.
buildConfigField("String", "STATS_URL", "\"${project.findProperty("gearslipStatsUrl") ?: ""}\"")
} }
signingConfigs { // Keeps build output out of the module folder: <root>/build/gearslip/... instead of
// Declared only when the properties file is present, so a clone without the key still // <root>/gearslip/build/..., so everything this project produces lands under one
// builds debug; assembleRelease then falls back to unsigned rather than failing here. // root-level build/ directory.
if (keystoreProperties.getProperty("storeFile") != null) { layout.buildDirectory.set(rootProject.layout.buildDirectory.dir("gearslip"))
create("release") {
storeFile = rootProject.file(keystoreProperties.getProperty("storeFile"))
storePassword = keystoreProperties.getProperty("storePassword")
keyAlias = keystoreProperties.getProperty("keyAlias")
keyPassword = keystoreProperties.getProperty("keyPassword")
}
}
}
buildTypes {
release {
signingConfig = signingConfigs.findByName("release")
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
// Its own package, so a debug build installs beside the release one instead of over it.
// Signed with the release key when it's here: both builds declare the car template
// permission, and Android refuses a second app declaring it under a different key.
debug {
applicationIdSuffix = ".dev"
signingConfigs.findByName("release")?.let { signingConfig = it }
manifestPlaceholders["appLabel"] = "Gearslip Debug"
// -Pr8 shrinks a debug build like a release one, to test R8 in the debug install.
if (project.hasProperty("r8")) {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
}
buildFeatures {
buildConfig = true
}
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_21 sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21 targetCompatibility = JavaVersion.VERSION_21
} }
defaultConfig {
// Speech-to-text (sherpa-onnx, in jniLibs) ships for 64-bit ARM only: every phone
// Gearslip runs on, and one copy of the native library instead of four.
ndk { abiFilters += "arm64-v8a" }
}
testOptions { testOptions {
// GearslipLog calls android.util.Log, which is a stub on the local JVM. // GearslipLog calls android.util.Log, which is a stub on the local JVM.
unitTests.isReturnDefaultValues = true unitTests.isReturnDefaultValues = true
@@ -137,7 +74,6 @@ dependencies {
// their Bundleables deserialize into. // their Bundleables deserialize into.
implementation(libs.androidx.car.app) implementation(libs.androidx.car.app)
implementation(libs.androidx.car.app.projected) implementation(libs.androidx.car.app.projected)
implementation(libs.androidx.media)
testImplementation(libs.junit) testImplementation(libs.junit)
} }
@@ -146,4 +82,3 @@ tasks.withType<KotlinJvmCompile>().configureEach {
jvmTarget.set(JvmTarget.JVM_21) jvmTarget.set(JvmTarget.JVM_21)
} }
} }
-13
View File
@@ -1,13 +0,0 @@
# R8 shrinks the release build; these keep what it can't see being used.
# Names stay readable, so stack traces in shared logs need no mapping file. Shrinking does
# the real work on size.
-dontobfuscate
# Gearslip hosts other apps' car screens: their templates arrive as Bundles, and the car
# library rebuilds them by class name and reflection. Any model class an app might send has to
# survive, used by Gearslip's code or not.
-keep class androidx.car.app.** { *; }
# Speech-to-text: the native library calls back into these classes by name.
-keep class com.k2fsa.sherpa.onnx.** { *; }
@@ -1,62 +0,0 @@
package app.seb3thehacker.gearslip
import app.seb3thehacker.gearslip.audio.CarAudio
import kotlin.math.abs
/**
* Debug-only stand-in for the head unit's media audio sink.
*
* The car end of the audio path can only be exercised in a car, but everything before it - the
* setting, the consent dialog, the capture service, and whether the media app allows itself to be
* heard at all - is phone-side and can be tested at a desk. This sink takes the place of
* [AudioLink] so that path runs to completion, and reports what arrived.
*
* adb shell am start -n app.seb3thehacker.gearslip/.CarPreviewActivity \
* --ei w 800 --ei h 480 --ez audio true --ei snaps 10
*
* A healthy run logs a rising byte count and a peak well above zero. A byte count that rises with
* a peak of zero means the app refused to be captured.
*/
class BenchAudioSink(override val sampleRate: Int = 48_000, override val channels: Int = 2) : CarAudio.Link {
private var chunks = 0
private var bytes = 0L
private var peak = 0
private var reportedAt = 0L
override fun start() {
chunks = 0
bytes = 0
peak = 0
reportedAt = System.currentTimeMillis()
GearslipLog.i("bench sink: started - pretending to be a ${sampleRate}Hz x$channels car sink")
}
override fun stop() {
GearslipLog.i("bench sink: stopped after $chunks chunks / $bytes bytes")
}
override fun write(pcm: ByteArray, size: Int) {
chunks++
bytes += size
for (i in 0 until size - 1 step 2) {
val sample = (pcm[i].toInt() and 0xFF) or (pcm[i + 1].toInt() shl 8)
peak = maxOf(peak, abs(sample.toShort().toInt()))
}
val now = System.currentTimeMillis()
if (now - reportedAt < REPORT_MS) return
reportedAt = now
val seconds = bytes / (sampleRate.toDouble() * channels * 2)
GearslipLog.i(
"bench sink: %d chunks / %d bytes (%.1fs of audio), peak %.3f%s".format(
chunks, bytes, seconds, peak / 32768f,
if (peak == 0) " - SILENT, the app is not letting itself be captured" else "",
),
)
peak = 0
}
companion object {
private const val REPORT_MS = 2_000L
}
}
@@ -9,9 +9,6 @@ import android.os.Handler
import android.os.Looper import android.os.Looper
import android.view.MotionEvent import android.view.MotionEvent
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import app.seb3thehacker.gearslip.audio.AudioCaptureService
import app.seb3thehacker.gearslip.audio.CarAudio
import app.seb3thehacker.gearslip.car.CarEnvironment import app.seb3thehacker.gearslip.car.CarEnvironment
import app.seb3thehacker.gearslip.car.CarSettings import app.seb3thehacker.gearslip.car.CarSettings
import app.seb3thehacker.gearslip.car.CarUi import app.seb3thehacker.gearslip.car.CarUi
@@ -34,28 +31,6 @@ class CarPreviewActivity : ComponentActivity() {
private var reader: ImageReader? = null private var reader: ImageReader? = null
@Volatile private var latest: Bitmap? = null @Volatile private var latest: Bitmap? = null
private val audioPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) askAudioCapture() else CarAudio.denied()
}
private val audioConsent = registerForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),
) { result ->
val data = result.data
if (result.resultCode == RESULT_OK && data != null) {
AudioCaptureService.start(this, result.resultCode, data)
} else {
GearslipLog.w("preview: audio capture consent declined")
CarAudio.denied()
}
}
private fun askAudioCapture() {
val manager = getSystemService(android.media.projection.MediaProjectionManager::class.java)
runCatching { audioConsent.launch(manager.createScreenCaptureIntent()) }
.onFailure { GearslipLog.e("preview: could not ask for audio capture", it); CarAudio.denied() }
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
GearslipLog.init(this) GearslipLog.init(this)
@@ -83,22 +58,6 @@ class CarPreviewActivity : ComponentActivity() {
val p = ScreenProjector(this).also { projector = it } val p = ScreenProjector(this).also { projector = it }
p.start(imageReader.surface, w, h, dpi) { CarUi() } p.start(imageReader.surface, w, h, dpi) { CarUi() }
// Stand in for the car's media sink, so the phone half of the audio path runs for real.
if (intent.getBooleanExtra("audio", false)) {
CarAudio.onConsentRequested = {
runOnUiThread {
if (checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
) {
askAudioCapture()
} else {
audioPermission.launch(android.Manifest.permission.RECORD_AUDIO)
}
}
}
CarAudio.attach(BenchAudioSink())
}
GearslipLog.i("preview: displayId=${p.displayId}") GearslipLog.i("preview: displayId=${p.displayId}")
if (intent.getBooleanExtra("hide", false)) p.setOverlayVisible(false) if (intent.getBooleanExtra("hide", false)) p.setOverlayVisible(false)
@@ -117,27 +76,6 @@ class CarPreviewActivity : ComponentActivity() {
GearslipLog.i("preview: wrote ${out.name}") GearslipLog.i("preview: wrote ${out.name}")
step++ step++
} }
// A two-finger pinch: "cx,cy,startGap,endGap" in projected pixels, after "pinchAfter" ms.
intent.getStringExtra("pinch")?.let { spec ->
val (cx, cy, gap0, gap1) = spec.split(",").map { it.toFloat() }
val pair = { gap: Float -> listOf(TouchPoint(3, cx - gap / 2, cy), TouchPoint(7, cx + gap / 2, cy)) }
val after = intent.getIntExtra("pinchAfter", 9000).toLong()
main.postDelayed({
snap()
p.dispatchTouch(MotionEvent.ACTION_DOWN, 0, listOf(pair(gap0)[0]))
p.dispatchTouch(MotionEvent.ACTION_POINTER_DOWN, 1, pair(gap0))
val steps = 14
for (i in 1..steps) main.postDelayed({
p.dispatchTouch(MotionEvent.ACTION_MOVE, 0, pair(gap0 + (gap1 - gap0) * i / steps))
}, 40L * i)
main.postDelayed({
p.dispatchTouch(MotionEvent.ACTION_POINTER_UP, 1, pair(gap1))
p.dispatchTouch(MotionEvent.ACTION_UP, 0, listOf(pair(gap1)[0]))
}, 40L * (steps + 1))
main.postDelayed({ snap() }, 40L * (steps + 1) + 2000)
}, after)
}
// Free-running mode: keep snapshotting on a timer so the display can be driven from // Free-running mode: keep snapshotting on a timer so the display can be driven from
// outside (adb `am start --display` / `input -d`) while the harness records it. // outside (adb `am start --display` / `input -d`) while the harness records it.
val snaps = intent.getIntExtra("snaps", 0) val snaps = intent.getIntExtra("snaps", 0)
@@ -151,9 +89,8 @@ class CarPreviewActivity : ComponentActivity() {
snap() snap()
taps.forEachIndexed { i, (x, y) -> taps.forEachIndexed { i, (x, y) ->
main.postDelayed({ main.postDelayed({
val point = listOf(TouchPoint(0, x, y)) p.dispatchTouch(MotionEvent.ACTION_DOWN, x, y)
p.dispatchTouch(MotionEvent.ACTION_DOWN, 0, point) main.postDelayed({ p.dispatchTouch(MotionEvent.ACTION_UP, x, y) }, 80)
main.postDelayed({ p.dispatchTouch(MotionEvent.ACTION_UP, 0, point) }, 80)
}, 2500L * (i + 1)) }, 2500L * (i + 1))
main.postDelayed({ snap() }, 2500L * (i + 1) + 1500) main.postDelayed({ snap() }, 2500L * (i + 1) + 1500)
} }
@@ -164,8 +101,6 @@ class CarPreviewActivity : ComponentActivity() {
super.onDestroy() super.onDestroy()
projector?.stop() projector?.stop()
reader?.close() reader?.close()
CarAudio.onConsentRequested = null
CarAudio.release()
CarEnvironment.stop() CarEnvironment.stop()
} }
} }
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Debug-only override of the main icon background (src/debug/res wins over src/main/res),
so a debug install is never mistaken for a release one on the home screen. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:pathData="M0,0h108v108h-108z"
android:fillColor="#f5c518"/>
<path
android:pathData="M54,2 A52,52 0 1,1 53.99,2 Z"
android:fillColor="#e6b400"/>
</vector>
@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Debug-only override of the main icon foreground, to go with the yellow debug background:
a charcoal gear rather than light grey, and a yellow centre hole to match the background
instead of the release icon's near-black. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M 66.69,49.48 L 80.91,52.61 L 82.31,42.81 L 66.92,47.91 Z">
<aapt:attr name="android:fillColor">
<gradient
android:type="linear"
android:startX="66.80"
android:startY="48.70"
android:endX="81.61"
android:endY="47.71">
<item android:offset="0" android:color="#00E5484D"/>
<item android:offset="1" android:color="#E5484D"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M 54.00,36.18 L 58.64,30.70 L 67.20,34.24 L 66.60,41.40 L 71.82,54.00 L 77.30,58.64 L 73.76,67.20 L 66.60,66.60 L 66.60,66.60 L 67.20,73.76 L 58.64,77.30 L 54.00,71.82 L 54.00,71.82 L 49.36,77.30 L 40.80,73.76 L 41.40,66.60 L 41.40,66.60 L 34.24,67.20 L 30.70,58.64 L 36.18,54.00 L 36.18,54.00 L 30.70,49.36 L 34.24,40.80 L 41.40,41.40 L 41.40,41.40 L 40.80,34.24 L 49.36,30.70 L 54.00,36.18 Z"
android:fillColor="#2E3033"/>
<path
android:pathData="M 78.61,40.70 L 85.31,43.29 L 84.74,52.55 L 77.78,54.31 Z"
android:fillColor="#E5484D"/>
<path
android:pathData="M54,46.08 A7.92,7.92 0 1,1 53.99,46.08 Z"
android:fillColor="#e6b400"/>
</vector>
+5 -118
View File
@@ -1,10 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:tools="http://schemas.android.com/tools">
<!-- The projected WebView loads real pages; without this every load fails silently. --> <!-- The projected WebView loads real pages; without this every load fails silently. -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- <!--
Phone mirroring. Android refuses to hand over a MediaProjection unless a foreground Phone mirroring. Android refuses to hand over a MediaProjection unless a foreground
@@ -13,65 +11,18 @@
--> -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<!--
Wireless Android Auto: Bluetooth reaches the paired car's Android Auto service, which
hands over its Wi-Fi details; Gearslip then joins that network to reach the car.
-->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.NEARBY_WIFI_DEVICES"
android:usesPermissionFlags="neverForLocation" />
<!-- Android 17 drops an app's traffic to the car's Wi-Fi without this. -->
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- The dashboard opened from the car clock: today's agenda and current weather. --> <!-- The dashboard opened from the car clock: today's agenda and current weather. -->
<uses-permission android:name="android.permission.READ_CALENDAR" /> <uses-permission android:name="android.permission.READ_CALENDAR" />
<!-- Capturing a media app's playback (to send to the car) is gated on this by the platform. --> <!-- Capturing a media app's playback (to send to the car) is gated on this by the platform. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.RECORD_AUDIO" />
<!--
Playback capture copies a stream rather than moving it, so the phone keeps playing the
music it is sending to the car. Silencing the phone's own speaker for the drive needs this.
-->
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<!--
Audio capture counts as a screen share, and Android hides notifications during one. The
protection can be switched off for the drive, but only with this, granted once over adb
(pm grant). Without it Gearslip works the same and notifications stay hidden.
-->
<uses-permission
android:name="android.permission.WRITE_SECURE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<!--
Phone calls on the car screen. READ_PHONE_STATE and READ_CALL_LOG together are what a
call's own state (ringing, in progress) and the incoming number need; READ_CONTACTS
turns that number into a name; ANSWER_PHONE_CALLS lets the driver pick up from here.
Declining a call, and the caller ID itself, need Gearslip set as the phone's caller ID
and spam app too - an on-device consent, not a permission declared here.
-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<!-- Placing a call from the car screen's dial pad or contacts list needs this. -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!-- <!--
Declared, not just requested. Templated apps decide whether to talk to a host by asking Declared, not just requested. Templated apps decide whether to talk to a host by asking
whether it holds this permission (HostValidator.isValidHost checks it before falling back whether it holds this permission (HostValidator.isValidHost checks it before falling back
@@ -87,14 +38,6 @@
<uses-feature android:name="android.hardware.usb.accessory" android:required="true" /> <uses-feature android:name="android.hardware.usb.accessory" android:required="true" />
<queries> <queries>
<!-- Named directly: current builds have no launcher-category entry point for the MAIN/
LAUNCHER query below to find, so the setup guide's Android Auto check needs this to see
whether the package is installed at all. -->
<package android:name="com.google.android.projection.gearhead" />
<!-- The opt-in usage note names the OS: GrapheneOS's setup app and /e/OS's app store give
them away (UsageStats.osName). -->
<package android:name="app.grapheneos.setupwizard" />
<package android:name="foundation.e.apps" />
<intent> <intent>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
@@ -107,35 +50,16 @@
<intent> <intent>
<action android:name="android.media.browse.MediaBrowserService" /> <action android:name="android.media.browse.MediaBrowserService" />
</intent> </intent>
<!-- Speech: without these, Android hides the recognizer and the voice from us and
SpeechRecognizer reports none installed even when one is. -->
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries> </queries>
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher"
android:label="${appLabel}" android:label="Gearslip"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.Gearslip"> android:theme="@style/Theme.Gearslip">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.logshare"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/share_paths" />
</provider>
<!-- <!--
singleTop: the head unit can re-attach while we are already foregrounded, which singleTop: the head unit can re-attach while we are already foregrounded, which
arrives via onNewIntent rather than a fresh instance. arrives via onNewIntent rather than a fresh instance.
@@ -144,7 +68,6 @@
android:name=".GearslipActivity" android:name=".GearslipActivity"
android:exported="true" android:exported="true"
android:launchMode="singleTop" android:launchMode="singleTop"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|uiMode|density|locale|layoutDirection|fontScale"> android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|uiMode|density|locale|layoutDirection|fontScale">
<intent-filter> <intent-filter>
@@ -152,18 +75,6 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity>
<!--
Answers the car's USB connection on GearslipActivity's behalf. Kept apart from the
activity so Settings can switch off just this (AppSettings.setGearslipEnabled) and leave
the head unit to Android Auto, without disabling the screen the switch is on.
-->
<activity-alias
android:name=".GearslipUsbAccessory"
android:targetActivity=".GearslipActivity"
android:exported="true">
<intent-filter> <intent-filter>
<action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" /> <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
</intent-filter> </intent-filter>
@@ -171,12 +82,7 @@
<meta-data <meta-data
android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
android:resource="@xml/accessory_filter" /> android:resource="@xml/accessory_filter" />
</activity-alias> </activity>
<!-- Dev builds' test message: its Reply and Mark as read actions land here. -->
<receiver
android:name=".notify.TestMessageReceiver"
android:exported="false" />
<service <service
android:name=".mirror.MirrorService" android:name=".mirror.MirrorService"
@@ -188,14 +94,11 @@
android:exported="false" android:exported="false"
android:foregroundServiceType="location" /> android:foregroundServiceType="location" />
<!-- <!-- Holds the capture session that carries a media app's audio to the car. -->
Holds the capture session that carries a media app's audio to the car. It also claims
the microphone, so voice replies can hear the driver with the phone locked.
-->
<service <service
android:name=".audio.AudioCaptureService" android:name=".audio.AudioCaptureService"
android:exported="false" android:exported="false"
android:foregroundServiceType="mediaProjection|microphone" /> android:foregroundServiceType="mediaProjection" />
<!-- <!--
Touch on the car screen is replayed onto the phone through this service. Touch on the car screen is replayed onto the phone through this service.
@@ -228,21 +131,5 @@
<action android:name="android.service.notification.NotificationListenerService" /> <action android:name="android.service.notification.NotificationListenerService" />
</intent-filter> </intent-filter>
</service> </service>
<!--
Sees incoming calls before they ring, so the car screen can show the caller and
decline it. Inert until the driver sets Gearslip as the phone's caller ID and spam
app, under Settings > Apps > Default apps - the same consent a call-blocking app asks
for, not a privileged one.
-->
<service
android:name=".call.GearslipCallScreening"
android:exported="true"
android:label="Gearslip calls"
android:permission="android.permission.BIND_SCREENING_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallScreeningService" />
</intent-filter>
</service>
</application> </application>
</manifest> </manifest>
@@ -1,17 +1,13 @@
package app.seb3thehacker.gearslip package app.seb3thehacker.gearslip
import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
/** User-facing preferences. Read fresh on every session, so changes apply on the next connect. */ /** User-facing preferences. Read fresh on every session, so changes apply on the next connect. */
object AppSettings { object AppSettings {
private const val PREFS = "gearslip_settings" private const val PREFS = "gearslip_settings"
private const val KEY_STARTUP_URL = "startup_url" private const val KEY_STARTUP_URL = "startup_url"
private const val KEY_SKIPPED_CERT_SETUP = "skipped_cert_setup" private const val KEY_SEEN_COMPAT_WARNING = "seen_compat_warning"
private const val KEY_SEEN_PERMISSIONS_SETUP = "seen_permissions_setup"
private const val KEY_GEARSLIP_ENABLED = "gearslip_enabled"
private fun prefs(context: Context) = private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
@@ -31,58 +27,11 @@ object AppSettings {
prefs(context).edit().putString(KEY_STARTUP_URL, value.trim()).apply() prefs(context).edit().putString(KEY_STARTUP_URL, value.trim()).apply()
} }
/** Whether the certificate setup screen has been deliberately skipped. */ /** Whether the newer-car compatibility warning has already been shown and dismissed once. */
fun hasSkippedCertSetup(context: Context): Boolean = fun hasSeenCompatWarning(context: Context): Boolean =
prefs(context).getBoolean(KEY_SKIPPED_CERT_SETUP, false) prefs(context).getBoolean(KEY_SEEN_COMPAT_WARNING, false)
fun setSkippedCertSetup(context: Context) { fun setSeenCompatWarning(context: Context) {
prefs(context).edit().putBoolean(KEY_SKIPPED_CERT_SETUP, true).apply() prefs(context).edit().putBoolean(KEY_SEEN_COMPAT_WARNING, true).apply()
}
/** Whether the one-by-one permissions wizard has already run once. */
fun hasSeenPermissionsSetup(context: Context): Boolean =
prefs(context).getBoolean(KEY_SEEN_PERMISSIONS_SETUP, false)
fun setSeenPermissionsSetup(context: Context) {
prefs(context).edit().putBoolean(KEY_SEEN_PERMISSIONS_SETUP, true).apply()
}
/**
* Whether Gearslip is allowed to claim the USB accessory connection. Off leaves the app
* installed but disables the GearslipUsbAccessory alias that answers
* USB_ACCESSORY_ATTACHED, so a real Android Auto head unit (or Google's own app) gets the
* connection instead - the two fight over it otherwise, since only one app can win the
* accessory handoff. The alias is separate from GearslipActivity itself - the activity that
* shows this very switch - so turning it off can't disable the screen you're looking at.
* On by default.
*/
fun gearslipEnabled(context: Context): Boolean =
prefs(context).getBoolean(KEY_GEARSLIP_ENABLED, true)
fun setGearslipEnabled(context: Context, value: Boolean) {
prefs(context).edit().putBoolean(KEY_GEARSLIP_ENABLED, value).apply()
applyGearslipEnabled(context)
}
/**
* Makes the USB alias match the saved switch. Called at every launch as well, so a switch
* saved without the alias following it (an older build crashed right there) heals itself.
* Only the alias changes: the driver's "always open with Gearslip" choice for the car is kept.
*/
fun applyGearslipEnabled(context: Context) {
val value = gearslipEnabled(context)
val appContext = context.applicationContext
// The class name comes from the code's namespace, not the package: a debug build installs
// as ".dev", but the alias is still app.seb3thehacker.gearslip.GearslipUsbAccessory.
val component = ComponentName(appContext.packageName, "${GearslipActivity::class.java.`package`!!.name}.GearslipUsbAccessory")
val state = if (value) {
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
}
val pm = appContext.packageManager
if (pm.getComponentEnabledSetting(component) == state) return
runCatching { pm.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP) }
.onFailure { GearslipLog.e("could not switch the USB connection ${if (value) "on" else "off"}", it) }
} }
} }
@@ -1,28 +0,0 @@
package app.seb3thehacker.gearslip
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* Who has the car's screen: Gearslip, or the car's own interface. Android Auto's "Exit" hands the
* screen back to the car with the session still running, so music keeps playing; the car's own
* Android Auto button brings Gearslip back. [GearslipRunner] fills in [request] while connected.
*/
object CarFocus {
private val projectedFlow = MutableStateFlow(true)
/** False while the car shows its own interface. */
val projected: StateFlow<Boolean> = projectedFlow
@Volatile internal var request: (() -> Unit)? = null
/** Asks the car to show its own interface. Does nothing when no car is connected. */
fun exitToCar() {
request?.invoke()
}
internal fun set(projected: Boolean) {
projectedFlow.value = projected
}
}
@@ -1,52 +0,0 @@
package app.seb3thehacker.gearslip
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
/**
* Fetches the publicly available head unit certificate and key from the opencardev/aasdk
* repository on GitHub. The app ships no certificates; it downloads them only when the
* user chooses to, the same way a browser would.
*/
object CertDownloader {
private val log = GearslipLog.tagged("DOWNL")
private const val BASE = "https://raw.githubusercontent.com/opencardev/aasdk/main/cert"
private const val CRT = "$BASE/headunit.crt"
private const val KEY = "$BASE/headunit.key"
private const val CONNECT_TIMEOUT_MS = 10_000
private const val READ_TIMEOUT_MS = 15_000
class Downloaded(val certificatePem: String, val privateKeyPem: String)
/** Fetches both files; throws with a readable message on any failure. */
fun fetch(): Downloaded {
log.i("fetching certificate from $BASE")
val crt = fetch(CRT, "certificate")
val key = fetch(KEY, "private key")
log.i("downloaded certificate (${crt.length} bytes) and key (${key.length} bytes)")
return Downloaded(crt, key)
}
private fun fetch(url: String, label: String): String {
val body = try {
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = CONNECT_TIMEOUT_MS
readTimeout = READ_TIMEOUT_MS
}
conn.inputStream.use { input ->
val out = ByteArrayOutputStream()
val buf = ByteArray(4096)
var n: Int
while (input.read(buf).also { n = it } != -1) out.write(buf, 0, n)
out.toString(Charsets.UTF_8)
}
} catch (e: Exception) {
throw RuntimeException("could not download the $label: ${e.message}", e)
}
if (body.isBlank()) throw RuntimeException("the $label file is empty")
return body
}
}
@@ -2,7 +2,6 @@ package app.seb3thehacker.gearslip
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import java.io.ByteArrayOutputStream
import java.io.File import java.io.File
import java.security.KeyStore import java.security.KeyStore
import java.security.cert.X509Certificate import java.security.cert.X509Certificate
@@ -15,9 +14,7 @@ import java.security.cert.X509Certificate
* *
* 1. **Imported** in the app (Settings > Certificate): a PKCS#12 file plus its password, * 1. **Imported** in the app (Settings > Certificate): a PKCS#12 file plus its password,
* copied into the app's private storage. * copied into the app's private storage.
* 2. **Downloaded** from the public opencardev/aasdk repository. Fetched only when the * 2. **Staged over adb** into the app's external files directory, the way the spike has
* user asks; the app never ships or hosts the certificate.
* 3. **Staged over adb** into the app's external files directory, the way the spike has
* always done it. Still honoured, so existing setups keep working untouched: * always done it. Still honoured, so existing setups keep working untouched:
* *
* openssl pkcs12 -export -in headunit.crt -inkey headunit.key \ * openssl pkcs12 -export -in headunit.crt -inkey headunit.key \
@@ -26,18 +23,17 @@ import java.security.cert.X509Certificate
* *
* Default password is "aaspike" (kept as-is so an already-staged phone.p12 doesn't need * Default password is "aaspike" (kept as-is so an already-staged phone.p12 doesn't need
* regenerating); a `phone.pass` file next to it overrides it. * regenerating); a `phone.pass` file next to it overrides it.
* 4. A freshly generated self-signed cert, which a real head unit rejects (see * 3. A freshly generated self-signed cert, which a real head unit rejects (see
* SPIKE_FINDINGS.md). * SPIKE_FINDINGS.md).
*/ */
object CertProvider { object CertProvider {
private val log = GearslipLog.tagged("CERT")
private const val P12_NAME = "phone.p12" private const val P12_NAME = "phone.p12"
private const val PASS_NAME = "phone.pass" private const val PASS_NAME = "phone.pass"
private const val DEFAULT_PASSWORD = "aaspike" private const val DEFAULT_PASSWORD = "aaspike"
private const val IMPORT_DIR = "identity" private const val IMPORT_DIR = "identity"
enum class Kind { IMPORTED, DOWNLOADED, ADB_STAGED, SELF_SIGNED } enum class Kind { IMPORTED, ADB_STAGED, SELF_SIGNED }
class Identity( class Identity(
val keyStore: KeyStore, val keyStore: KeyStore,
@@ -47,10 +43,7 @@ object CertProvider {
val kind: Kind = Kind.SELF_SIGNED, val kind: Kind = Kind.SELF_SIGNED,
) )
/** /** Loaded fresh each call, so a newly imported or pushed cert takes effect on the next connect. */
* The identity for the next connection. A newly imported or pushed cert takes effect on the
* next connect: see [loadFromFiles] for how the cache notices.
*/
fun load(context: Context): Identity = loadFromFiles(context) ?: run { fun load(context: Context): Identity = loadFromFiles(context) ?: run {
val generated = SelfSignedCert.generate() val generated = SelfSignedCert.generate()
Identity( Identity(
@@ -68,50 +61,12 @@ object CertProvider {
*/ */
fun loadSupplied(context: Context): Identity? = loadFromFiles(context) fun loadSupplied(context: Context): Identity? = loadFromFiles(context)
/**
* Unlocking a PKCS#12 file takes about a second on a Pixel 6, which a head unit waiting for
* its first reply may not wait out. So the unlocked identity is kept, keyed on the files it
* could come from: importing, downloading, removing or pushing a cert changes the key.
*/
@Volatile private var cached: Pair<String, Identity>? = null
private fun sourcesKey(context: Context): String {
val dir = context.getExternalFilesDir(null)
val files = listOf(
importedFile(context, P12_NAME),
downloadedFile(context, P12_NAME),
dir?.let { File(it, P12_NAME) },
dir?.let { File(it, PASS_NAME) },
)
return files.joinToString("|") { f -> f?.let { "${it.path}:${it.lastModified()}:${it.length()}" } ?: "-" }
}
/** Unlocks the certificate ahead of time, so the first connection doesn't wait on it. */
fun warm(context: Context) {
runCatching { loadFromFiles(context) }
}
private fun loadFromFiles(context: Context): Identity? { private fun loadFromFiles(context: Context): Identity? {
val key = sourcesKey(context)
cached?.let { (k, identity) -> if (k == key) return identity }
val identity = unlockFromFiles(context) ?: return null
cached = key to identity
return identity
}
private fun unlockFromFiles(context: Context): Identity? {
val imported = importedFile(context, P12_NAME) val imported = importedFile(context, P12_NAME)
if (imported.isFile) { if (imported.isFile) {
runCatching { runCatching {
return loadP12(imported, importedPassword(context), "imported certificate", Kind.IMPORTED) return loadP12(imported, importedPassword(context), "imported certificate", Kind.IMPORTED)
}.onFailure { log.e("could not load the imported certificate - trying the next source", it) } }.onFailure { GearslipLog.e("could not load the imported certificate - trying the next source", it) }
}
val downloaded = downloadedFile(context, P12_NAME)
if (downloaded.isFile) {
runCatching {
return loadP12(downloaded, DEFAULT_PASSWORD, "downloaded certificate", Kind.DOWNLOADED)
}.onFailure { log.e("could not load the downloaded certificate - trying the next source", it) }
} }
val dir = context.getExternalFilesDir(null) val dir = context.getExternalFilesDir(null)
@@ -125,7 +80,7 @@ object CertProvider {
DEFAULT_PASSWORD DEFAULT_PASSWORD
} }
return loadP12(staged, password, "$P12_NAME staged over adb", Kind.ADB_STAGED) return loadP12(staged, password, "$P12_NAME staged over adb", Kind.ADB_STAGED)
}.onFailure { log.e("could not load $P12_NAME - falling back to self-signed", it) } }.onFailure { GearslipLog.e("could not load $P12_NAME - falling back to self-signed", it) }
} }
return null return null
} }
@@ -148,7 +103,7 @@ object CertProvider {
target.parentFile?.mkdirs() target.parentFile?.mkdirs()
staging.copyTo(target, overwrite = true) staging.copyTo(target, overwrite = true)
importedFile(context, PASS_NAME).writeText(password) importedFile(context, PASS_NAME).writeText(password)
log.i("imported a certificate: ${identity.certificate.subjectX500Principal}") GearslipLog.i("imported a certificate: ${identity.certificate.subjectX500Principal}")
return identity return identity
} finally { } finally {
staging.delete() staging.delete()
@@ -157,84 +112,17 @@ object CertProvider {
fun hasImported(context: Context): Boolean = importedFile(context, P12_NAME).isFile fun hasImported(context: Context): Boolean = importedFile(context, P12_NAME).isFile
/** Whether a downloaded certificate is stored (may or may not also be imported). */ /** Drops the imported identity; the next source in line (adb-staged, then self-signed) takes over. */
fun hasDownloaded(context: Context): Boolean = downloadedFile(context, P12_NAME).isFile
/** Drops the imported identity; the next source in line (downloaded, adb-staged, then self-signed) takes over. */
fun removeImported(context: Context) { fun removeImported(context: Context) {
importedFile(context, P12_NAME).delete() importedFile(context, P12_NAME).delete()
importedFile(context, PASS_NAME).delete() importedFile(context, PASS_NAME).delete()
log.i("removed the imported certificate") GearslipLog.i("removed the imported certificate")
}
/** Drops the downloaded identity. */
fun removeDownloaded(context: Context) {
downloadedFile(context, P12_NAME).delete()
downloadedFile(context, PASS_NAME).delete()
log.i("removed the downloaded certificate")
}
/** Whether any certificate is available (imported, downloaded, or adb-staged). */
fun hasAnyCert(context: Context): Boolean =
hasImported(context) || hasDownloaded(context) || hasAdbStaged(context)
private fun hasAdbStaged(context: Context): Boolean =
context.getExternalFilesDir(null)?.let { File(it, P12_NAME).isFile } == true
/**
* Validates raw PKCS#12 bytes with [password] and, if good, writes them as the imported
* identity. Used when the app assembles a certificate in memory (e.g. from a download)
* rather than importing from a file picker.
*/
fun importFromBytes(context: Context, p12Bytes: ByteArray, password: String): Identity {
val staging = File(context.cacheDir, "import-$P12_NAME")
try {
staging.writeBytes(p12Bytes)
val identity = loadP12(staging, password, "imported certificate", Kind.IMPORTED)
val target = importedFile(context, P12_NAME)
target.parentFile?.mkdirs()
staging.copyTo(target, overwrite = true)
importedFile(context, PASS_NAME).writeText(password)
log.i("imported a certificate from bytes: ${identity.certificate.subjectX500Principal}")
return identity
} finally {
staging.delete()
}
}
/**
* Downloads the publicly available head unit certificate from the opencardev/aasdk
* repository, converts it from PEM to PKCS#12, and stores it ready for use.
* Runs synchronously (caller is responsible for threading). Throws on any failure.
*/
fun downloadAndImport(context: Context): Identity {
val download = CertDownloader.fetch()
val result = PemKeyParser.build(download.certificatePem, download.privateKeyPem)
val target = downloadedFile(context, P12_NAME)
target.parentFile?.mkdirs()
val p12Password = DEFAULT_PASSWORD
val keyStore = result.keyStore
val p12Bytes = ByteArrayOutputStream().use { stream ->
keyStore.store(stream, p12Password.toCharArray())
stream.toByteArray()
}
target.writeBytes(p12Bytes)
downloadedFile(context, PASS_NAME).writeText(p12Password)
log.i("downloaded and stored certificate: ${result.certificate.subjectX500Principal}")
return Identity(keyStore, result.certificate, p12Password.toCharArray(),
"downloaded certificate (opencardev/aasdk)", Kind.DOWNLOADED)
} }
// The imported files live in the app's private internal storage (not the external files // The imported files live in the app's private internal storage (not the external files
// dir), so other apps cannot read the key, and `adb uninstall` clearing it is expected. // dir), so other apps cannot read the key, and `adb uninstall` clearing it is expected.
private fun importedFile(context: Context, name: String) = File(File(context.filesDir, IMPORT_DIR), name) private fun importedFile(context: Context, name: String) = File(File(context.filesDir, IMPORT_DIR), name)
private fun downloadedFile(context: Context, name: String) =
File(File(context.filesDir, "$IMPORT_DIR-downloaded"), name)
private fun importedPassword(context: Context): String = private fun importedPassword(context: Context): String =
importedFile(context, PASS_NAME).takeIf { it.isFile }?.readText().orEmpty() importedFile(context, PASS_NAME).takeIf { it.isFile }?.readText().orEmpty()
@@ -1,96 +0,0 @@
package app.seb3thehacker.gearslip
/**
* What changed in each release, newest first, shown on the car screen after an update (and on
* the phone). Only the changes a driver would notice. Plain words, short lines: this is read in
* a parked car.
*/
object Changelog {
class Release(val versionCode: Int, val versionName: String, val changes: List<String>)
val releases = listOf(
Release(
9, "0.3.00-alpha",
listOf(
"Wireless Android Auto: pair the phone with the car once, and leave the cable at home.",
"Voice control is built in. Say \"navigate to a gas station\", \"play\" a song or artist, or open an app by name.",
"\"Navigate to\" picks the nearest place and stops at the map app's start screen, so you only tap Start.",
"Gearslip turns speech into text on the phone, with no Google account. Download the voice models once in setup.",
"The car's rotary knob moves between buttons, so cars without a touchscreen work too.",
"Choose how music reaches the car: Bluetooth, or USB with no delay. Gearslip offers to pair with the car the first time.",
"The car speaks each turn from your map app, and shows the directions on its own display where it can.",
"The car shows what's playing, and music apps get their own like, shuffle and repeat buttons.",
"Pick how the car's buttons look. Change it any time in the car's settings.",
"A new destination mid-route replaces the old route, and switching map apps ends the old app's route.",
"The car warns you when the phone's location is off.",
"Gearslip finds new versions and installs them for you.",
"More cars play music over USB, show a sharper picture, and put taps where you press.",
"On GrapheneOS, Gearslip no longer needs exploit protection compatibility mode.",
"The app is half the size it was.",
),
),
Release(
8, "0.2.00-alpha",
listOf(
"Exit takes you to the car's own screen. Tap Android Auto on the car to come back.",
"Gearslip listens through the car's microphone when the car has one, so voice works with the phone in a pocket.",
"A voice reply sends when its bar runs out, even over road noise or the radio. Say \"cancel\" or \"change it\" before then.",
"Maps turn dark when the car switches to night mode.",
"A moving map no longer makes the car screen fall behind your taps.",
"Gearslip asks to send sound to the car as soon as you connect, so videos in the web browser play in the car too.",
"Cars that offer more than one kind of music audio, such as the 2022 Dacia Jogger, play sound again.",
"When the car shows a keyboard, you can type on the phone instead. The car's keyboard is taller too.",
"Every car screen has a back button.",
"App icons show whether an app works in Gearslip. Metrolist works and shows the green check.",
"LIVI connects again, and touch works on cars with a second screen.",
"The phone's Settings screen has a new layout, with What's new and the setup guide at the top.",
"You can choose to send short usage notes that help the project. They hold no name, account, or location, and they're off unless you turn them on.",
"Searching inside a media app moved to Settings > Experimental features.",
"Under Settings > Media audio, the choices are now Phone audio and Car audio.",
"Logs leave out your location and the car's serial number.",
),
),
Release(
7, "0.1.10-alpha",
listOf(
"The launcher groups your apps: Phone, Maps, Music, Messaging, Web, Screen sharing, and Settings.",
"To move an app, press and hold it on the launcher, then tap Move left or Move right.",
"MapQuest and Flitsmeister work in Gearslip and show the green check.",
"Spotify has one tile. If Spotify isn't open on the phone, tap Open Spotify to start it.",
"Flick a map and it glides on, as it does in Android Auto.",
"The map picks up where it left off when you come back from another screen.",
"Search boxes in map apps are larger and easier to read.",
"Map apps keep the right icons on their buttons after they update.",
"When Gearslip asks \"Do you want to reply?\", a bar shows how long it will listen. The bar stops while you speak.",
"Gearslip fits its picture to wide car screens and keeps it clear of the edges the car crops.",
"Gearslip answers the car's connection checks correctly. Some cars, Audis among them, hung up after a second without this.",
"Google Maps no longer shows up as a messaging app.",
),
),
Release(
6, "0.1.0-alpha",
listOf(
"Messaging apps such as Signal and Molly open to your recent chats.",
"Gearslip reads a message aloud, and you reply by voice. Say \"cancel\" or \"change it\" before it sends, or tap a quick reply such as your arrival time.",
"Voice works on any phone, GrapheneOS included. Gearslip turns speech into text itself, so it needs no Google account.",
"New messages show as a small card at the top right, even while you drive. A bar shows how long until the card closes or the reply sends.",
"Only messages, missed calls, alarms, and reminders pop up. Everything else waits on the dashboard.",
"The map stays loaded when you switch screens, so it no longer flashes black.",
"Map apps draw more reliably and keep their connection when the phone is locked.",
"The Home button shows your map app, so it no longer appears twice.",
"The next turn shows in the nav bar when you leave the map.",
"Steering wheel buttons, control knobs, and D-pads now work. If yours don't, open an issue on GitHub.",
"To see the whole song title and artist in the nav bar, choose Settings > Player in the nav bar > Song title.",
"Choose miles or kilometres under Settings > Units.",
"Try the voice assistant and the vehicle data screen under Settings > Experimental features.",
"Logs now say why a car ended the connection.",
"Spotify, Waze, and Google Messages updated to a version of Google's car library that only accepts Android Auto itself. Their own car screens won't open in Gearslip. Spotify still plays through the Gearslip player, which has the green check.",
"Calls go through the car's Bluetooth, as they do in Android Auto. Pair your phone with the car to hear calls on its speakers.",
),
),
)
/** The release that matches this build, if it has notes. */
val current: Release? get() = releases.firstOrNull { it.versionCode == BuildConfig.VERSION_CODE }
}
@@ -12,10 +12,9 @@ import java.util.concurrent.TimeUnit
* the TLS self-test: make our own failures loud on the bench. * the TLS self-test: make our own failures loud on the bench.
*/ */
object EncoderSelfTest { object EncoderSelfTest {
private val log = GearslipLog.tagged("VIDEO")
fun run(width: Int = 800, height: Int = 480, frameRate: Int = 30): Boolean { fun run(width: Int = 800, height: Int = 480, frameRate: Int = 30): Boolean {
log.i("=== encoder self-test starting (${width}x$height @ ${frameRate}fps) ===") GearslipLog.i("=== encoder self-test starting (${width}x$height @ ${frameRate}fps) ===")
var codecConfig: ByteArray? = null var codecConfig: ByteArray? = null
var frames = 0 var frames = 0
@@ -60,37 +59,37 @@ object EncoderSelfTest {
val csd = codecConfig val csd = codecConfig
when { when {
csd == null -> { csd == null -> {
log.e("encoder self-test FAILED: no CODEC_CONFIG (SPS/PPS) produced") GearslipLog.e("encoder self-test FAILED: no CODEC_CONFIG (SPS/PPS) produced")
false false
} }
frames == 0 -> { frames == 0 -> {
log.e("encoder self-test FAILED: no frames produced") GearslipLog.e("encoder self-test FAILED: no frames produced")
false false
} }
!sawKeyFrame -> { !sawKeyFrame -> {
log.e("encoder self-test FAILED: no keyframe - the car needs one first") GearslipLog.e("encoder self-test FAILED: no keyframe - the car needs one first")
false false
} }
!sawResyncKeyFrame -> { !sawResyncKeyFrame -> {
log.e( GearslipLog.e(
"encoder self-test FAILED: requestSyncFrame() produced no keyframe - " + "encoder self-test FAILED: requestSyncFrame() produced no keyframe - " +
"the resync-after-drop fix would silently do nothing on this device", "the resync-after-drop fix would silently do nothing on this device",
) )
false false
} }
else -> { else -> {
log.i( GearslipLog.i(
"SPS/PPS = ${csd.size} bytes, $frames frames, keyframe present, " + "SPS/PPS = ${csd.size} bytes, $frames frames, keyframe present, " +
"requestSyncFrame() confirmed working", "requestSyncFrame() confirmed working",
) )
log.hex(" csd", csd, limit = 48) GearslipLog.hex(" csd", csd, limit = 48)
log.i("=== encoder self-test PASSED ===") GearslipLog.i("=== encoder self-test PASSED ===")
true true
} }
} }
} catch (t: Throwable) { } catch (t: Throwable) {
runCatching { source.stop() } runCatching { source.stop() }
log.e("encoder self-test FAILED with an exception", t) GearslipLog.e("encoder self-test FAILED with an exception", t)
false false
} }
} }
@@ -8,17 +8,13 @@ import android.hardware.usb.UsbAccessory
import android.hardware.usb.UsbManager import android.hardware.usb.UsbManager
import android.media.projection.MediaProjection import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import android.os.ParcelFileDescriptor import android.os.ParcelFileDescriptor
import android.provider.Settings
import android.view.MotionEvent import android.view.MotionEvent
import android.view.Surface import android.view.Surface
import android.view.WindowManager import android.view.WindowManager
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import android.content.res.Configuration import android.content.res.Configuration
@@ -30,8 +26,6 @@ import app.seb3thehacker.gearslip.mirror.TouchRelayService
import app.seb3thehacker.gearslip.car.CarEnvironment import app.seb3thehacker.gearslip.car.CarEnvironment
import app.seb3thehacker.gearslip.car.CarSettings import app.seb3thehacker.gearslip.car.CarSettings
import app.seb3thehacker.gearslip.car.CarUi import app.seb3thehacker.gearslip.car.CarUi
import app.seb3thehacker.gearslip.car.Prefetch
import app.seb3thehacker.gearslip.stats.UsageStats
import app.seb3thehacker.gearslip.ui.GearslipApp import app.seb3thehacker.gearslip.ui.GearslipApp
import app.seb3thehacker.gearslip.ui.GearslipTheme import app.seb3thehacker.gearslip.ui.GearslipTheme
import java.io.FileInputStream import java.io.FileInputStream
@@ -45,12 +39,8 @@ import java.io.FileOutputStream
* rotation or theme change from recreating it and dropping the connection. * rotation or theme change from recreating it and dropping the connection.
*/ */
class GearslipActivity : ComponentActivity(), Projection { class GearslipActivity : ComponentActivity(), Projection {
private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
private var descriptor: ParcelFileDescriptor? = null private var descriptor: ParcelFileDescriptor? = null
/** The wireless session's socket, when the car came over Wi-Fi instead of USB. */
private var wirelessSocket: java.net.Socket? = null
private var runner: GearslipRunner? = null private var runner: GearslipRunner? = null
private var screenProjector: ScreenProjector? = null private var screenProjector: ScreenProjector? = null
private var worker: Thread? = null private var worker: Thread? = null
@@ -78,13 +68,7 @@ class GearslipActivity : ComponentActivity(), Projection {
private val audioPermission = registerForActivityResult( private val audioPermission = registerForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.RequestPermission(), androidx.activity.result.contract.ActivityResultContracts.RequestPermission(),
) { granted -> ) { granted ->
if (granted) askAudioCapture() if (granted) askAudioCapture() else {
else if (!shouldShowRequestPermissionRationale(android.Manifest.permission.RECORD_AUDIO)) {
// Refused twice: Android now says no without showing anything, so the phone must.
GearslipLog.w("audio: record permission blocked - Android no longer asks")
CarAudio.micBlocked()
micBlockedNotice.value = true
} else {
GearslipLog.w("audio: record permission declined") GearslipLog.w("audio: record permission declined")
CarAudio.denied() CarAudio.denied()
} }
@@ -97,86 +81,47 @@ class GearslipActivity : ComponentActivity(), Projection {
} else { } else {
GearslipLog.w("audio: capture consent declined") GearslipLog.w("audio: capture consent declined")
CarAudio.denied() CarAudio.denied()
if (!CarSettings.audioChoiceAsked) offerBluetooth.value = true
} }
} }
/** Raised when the microphone permission is blocked; see [MicBlockedDialog]. */
private val micBlockedNotice = kotlinx.coroutines.flow.MutableStateFlow(false)
/** Raised once, after the first "no" to the capture dialog; see [AudioChoiceDialog]. */
private val offerBluetooth = kotlinx.coroutines.flow.MutableStateFlow(false)
private val detachReceiver = object : BroadcastReceiver() { private val detachReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == UsbManager.ACTION_USB_ACCESSORY_DETACHED) { if (intent?.action == UsbManager.ACTION_USB_ACCESSORY_DETACHED) {
GearslipLog.w("accessory detached") GearslipLog.w("accessory detached")
// A wireless session has no accessory to lose; leave it running. closeAccessory()
if (wirelessSocket == null) closeAccessory()
} }
} }
} }
/** Setting Gearslip as the phone's caller ID and spam app - what lets it decline a ringing call. */ /** Hosted map apps need Gearslip to hold location so they can keep it in the background. */
private val callScreeningRole = registerForActivityResult(StartActivityForResult()) { result -> private val locationPermission = registerForActivityResult(
if (result.resultCode != RESULT_OK) GearslipLog.w("calls: call screening role declined") androidx.activity.result.contract.ActivityResultContracts.RequestPermission(),
} ) { }
/** The car dashboard's agenda card; declined just leaves it empty rather than asking again. */
private val calendarPermission = registerForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.RequestPermission(),
) { }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
// Location, calendar, the phone/contacts group, and the microphone are asked for one at if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) !=
// a time by PermissionsSetupScreen instead of here, each only after the driver taps android.content.pm.PackageManager.PERMISSION_GRANTED
// Allow on a screen explaining what it is for. Firing them all from onCreate, unprompted, ) locationPermission.launch(android.Manifest.permission.ACCESS_FINE_LOCATION)
// is both a bad first impression and unreliable: Android does not consistently show more if (checkSelfPermission(android.Manifest.permission.READ_CALENDAR) !=
// than one system permission dialog fired back-to-back, which was silently dropping some. android.content.pm.PackageManager.PERMISSION_GRANTED
) calendarPermission.launch(android.Manifest.permission.READ_CALENDAR)
enableEdgeToEdge() enableEdgeToEdge()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
GearslipLog.init(this) GearslipLog.init(this)
GearslipLog.installCrashHandler()
GearslipLog.i("Gearslip ready") GearslipLog.i("Gearslip ready")
app.seb3thehacker.gearslip.wireless.WirelessLink.onConnected = { socket ->
runOnUiThread { startWireless(socket) }
}
CarSettings.init(this) CarSettings.init(this)
AppSettings.applyGearslipEnabled(this)
// A capture that died without tidying up would leave notifications exposed to every
// later screen share. Nothing is capturing if the service is not running, so undo it.
if (!app.seb3thehacker.gearslip.audio.AudioCaptureService.running) {
app.seb3thehacker.gearslip.audio.ScreenShareGuard.restore(this)
}
Prefetch.warm(this)
CarEnvironment.setPhoneTheme(resources.configuration) CarEnvironment.setPhoneTheme(resources.configuration)
setContent { setContent {
GearslipTheme { GearslipTheme {
GearslipApp(onDisconnect = { closeAccessory() }, onRequestCallScreening = ::requestCallScreeningRole) GearslipApp(onDisconnect = ::closeAccessory)
val offer by offerBluetooth.collectAsState()
if (offer) {
fun close() {
CarSettings.markAudioChoiceAsked()
offerBluetooth.value = false
}
app.seb3thehacker.gearslip.ui.AudioChoiceDialog(
onUseBluetooth = {
CarSettings.setPipeAudio(false)
close()
},
onKeepAsking = ::close,
)
}
val micNotice by micBlockedNotice.collectAsState()
if (micNotice) {
app.seb3thehacker.gearslip.ui.MicBlockedDialog(
onOpenSettings = {
micBlockedNotice.value = false
startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)),
)
},
onDismiss = { micBlockedNotice.value = false },
)
}
} }
} }
@@ -196,18 +141,6 @@ class GearslipActivity : ComponentActivity(), Projection {
CarEnvironment.setPhoneTheme(newConfig) CarEnvironment.setPhoneTheme(newConfig)
} }
// Throttled inside Prefetch, so this only does work if the last run was a while ago.
override fun onStart() {
super.onStart()
Prefetch.warm(this)
UsageStats.onAppOpened(this)
app.seb3thehacker.gearslip.update.UpdateChecker.onAppOpened(this)
// Back from the app's settings with the microphone turned on: try car audio again.
if (checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED) {
CarAudio.micAllowed()
}
}
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
handleIntent(intent) handleIntent(intent)
@@ -215,7 +148,6 @@ class GearslipActivity : ComponentActivity(), Projection {
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
app.seb3thehacker.gearslip.wireless.WirelessLink.onConnected = null
runCatching { unregisterReceiver(detachReceiver) } runCatching { unregisterReceiver(detachReceiver) }
PhoneMirror.onStartRequested = null PhoneMirror.onStartRequested = null
PhoneMirror.onTokenReady = null PhoneMirror.onTokenReady = null
@@ -227,19 +159,6 @@ class GearslipActivity : ComponentActivity(), Projection {
GearslipLog.flush() GearslipLog.flush()
} }
/** Launches the system dialog that offers Gearslip the call-screening role, if it isn't held already. */
private fun requestCallScreeningRole() {
val roleManager = getSystemService(android.app.role.RoleManager::class.java)
if (roleManager == null || !roleManager.isRoleAvailable(android.app.role.RoleManager.ROLE_CALL_SCREENING)) {
GearslipLog.w("calls: call screening role unavailable on this phone")
return
}
if (roleManager.isRoleHeld(android.app.role.RoleManager.ROLE_CALL_SCREENING)) return
runCatching {
callScreeningRole.launch(roleManager.createRequestRoleIntent(android.app.role.RoleManager.ROLE_CALL_SCREENING))
}.onFailure { GearslipLog.e("could not ask for the call screening role", it) }
}
// --- Media audio -------------------------------------------------------------------- // --- Media audio --------------------------------------------------------------------
private fun requestAudioCapture() { private fun requestAudioCapture() {
@@ -305,12 +224,6 @@ class GearslipActivity : ComponentActivity(), Projection {
private fun handleIntent(intent: Intent?) { private fun handleIntent(intent: Intent?) {
if (intent?.action != UsbManager.ACTION_USB_ACCESSORY_ATTACHED) return if (intent?.action != UsbManager.ACTION_USB_ACCESSORY_ATTACHED) return
// Switched off in Settings: the system shouldn't route the car here at all, but if it
// does, leave the accessory alone.
if (!AppSettings.gearslipEnabled(this)) {
GearslipLog.i("accessory attached, but Gearslip is switched off - not connecting")
return
}
val accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY, UsbAccessory::class.java) val accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY, UsbAccessory::class.java)
if (accessory == null) { if (accessory == null) {
GearslipLog.e("attach intent carried no accessory") GearslipLog.e("attach intent carried no accessory")
@@ -322,13 +235,10 @@ class GearslipActivity : ComponentActivity(), Projection {
} }
private fun start(accessory: UsbAccessory) { private fun start(accessory: UsbAccessory) {
// A fresh ATTACHED intent means the system wants a new session, whatever state the old if (worker?.isAlive == true) {
// one is in - closing first guarantees openAccessory() below never fights a descriptor GearslipLog.w("a run is already in progress")
// this same process forgot to release. The old worker thread often isn't alive by this return
// point anyway (its read loop already died when the head unit dropped the transport), }
// but the accessory it opened was never explicitly closed, which is what actually blocks
// a re-open - a dead thread does not release the file descriptor on its own.
closeAccessory()
describe(accessory) describe(accessory)
val manager = getSystemService(UsbManager::class.java) val manager = getSystemService(UsbManager::class.java)
@@ -351,44 +261,15 @@ class GearslipActivity : ComponentActivity(), Projection {
worker = Thread { runner.run() }.apply { name = "gearslip"; start() } worker = Thread { runner.run() }.apply { name = "gearslip"; start() }
} }
/** A wireless session: the same runner, on the socket [WirelessLink] opened to the car. */
private fun startWireless(socket: java.net.Socket) {
closeAccessory(stopWireless = false)
if (!AppSettings.gearslipEnabled(this)) {
GearslipLog.i("wireless: Gearslip is switched off - not connecting")
runCatching { socket.close() }
return
}
GearslipLog.i("wireless: starting a session over Wi-Fi to ${socket.inetAddress?.hostAddress}:${socket.port}")
wirelessSocket = socket
val runner = GearslipRunner(
input = socket.getInputStream(),
output = socket.getOutputStream(),
identityProvider = { CertProvider.load(this) },
projection = this,
vehicleProfileFor = { info -> VehicleProfiles.find(VehicleProfiles.load(this), info) },
wireless = true,
)
this.runner = runner
worker = Thread { runner.run() }.apply { name = "gearslip"; start() }
}
private fun describe(accessory: UsbAccessory) { private fun describe(accessory: UsbAccessory) {
GearslipLog.i("accessory: manufacturer=${accessory.manufacturer} model=${accessory.model}") GearslipLog.i("accessory: manufacturer=${accessory.manufacturer} model=${accessory.model}")
GearslipLog.i(" version=${accessory.version} description=${accessory.description}") GearslipLog.i(" version=${accessory.version} description=${accessory.description}")
} }
private fun closeAccessory() = closeAccessory(stopWireless = true) private fun closeAccessory() {
/** Ends the session, wired or wireless. [stopWireless] also drops the car's Bluetooth and Wi-Fi. */
private fun closeAccessory(stopWireless: Boolean) {
runner?.stop() runner?.stop()
SessionReport.print()
runCatching { descriptor?.close() } runCatching { descriptor?.close() }
descriptor = null descriptor = null
runCatching { wirelessSocket?.close() }
wirelessSocket = null
if (stopWireless) app.seb3thehacker.gearslip.wireless.WirelessLink.stop(this)
runner = null runner = null
} }
@@ -403,28 +284,19 @@ class GearslipActivity : ComponentActivity(), Projection {
CarEnvironment.setDisplay(width, height, densityDpi) CarEnvironment.setDisplay(width, height, densityDpi)
CarEnvironment.start(this) CarEnvironment.start(this)
showCarUi() showCarUi()
app.seb3thehacker.gearslip.car.CarKeys.focusSink = { code, down ->
runOnUiThread { screenProjector?.dispatchKey(code, down) }
}
} }
} }
override fun onTouch(action: Int, actionIndex: Int, points: List<TouchPoint>) { override fun onTouch(action: Int, x: Float, y: Float) {
// To the front of the main thread's queue: a touch waiting behind other work is lag the runOnUiThread {
// driver feels, while the work it jumps ahead of can wait a frame. if (PhoneMirror.active.value) relayTouch(action, x, y)
mainHandler.postAtFrontOfQueue { else screenProjector?.dispatchTouch(action, x, y)
// Mirroring drives one phone touch at a time, so it follows the first finger only.
if (PhoneMirror.active.value) points.firstOrNull()?.let { relayTouch(action, it.x, it.y) }
else screenProjector?.dispatchTouch(action, actionIndex, points)
} }
} }
override fun onProjectionStopped() { override fun onProjectionStopped() {
// Before the car UI goes, while the media connection is still up.
app.seb3thehacker.gearslip.car.CarServices.pausePhoneMedia()
runOnUiThread { runOnUiThread {
PhoneMirror.requestStop() PhoneMirror.requestStop()
app.seb3thehacker.gearslip.car.CarKeys.focusSink = null
screenProjector?.stop() screenProjector?.stop()
screenProjector = null screenProjector = null
surface = null surface = null
@@ -31,13 +31,6 @@ object GearslipLog {
private var file: File? = null private var file: File? = null
/**
* Off drops the noisy trace output (hex dumps, and logcat copies of info lines); warnings,
* errors and the file copy are always kept, so a crash report is never empty. Always on for
* now, while the project is pre-release.
*/
@Volatile var debug = true
// What the live log screen shows. Bounded, and separate from the file, which always keeps // What the live log screen shows. Bounded, and separate from the file, which always keeps
// everything. The flow carries only a version number so a burst of lines costs the UI one // everything. The flow carries only a version number so a burst of lines costs the UI one
// snapshot per frame rather than one list copy per line. // snapshot per frame rather than one list copy per line.
@@ -51,7 +44,6 @@ object GearslipLog {
val name = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) val name = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
file = File(dir, "gearslip-$name.log") file = File(dir, "gearslip-$name.log")
i("log file: ${file?.absolutePath}") i("log file: ${file?.absolutePath}")
SessionReport.init(context)
} }
fun snapshot(): List<String> = synchronized(live) { live.toList() } fun snapshot(): List<String> = synchronized(live) { live.toList() }
@@ -69,81 +61,13 @@ object GearslipLog {
return if (f != null && f.isFile) f.readText() else snapshot().joinToString("\n") return if (f != null && f.isFile) f.readText() else snapshot().joinToString("\n")
} }
/** fun i(message: String) = write("I", message)
* The current session's log, with the session report on top, copied to the cache dir for
* sharing as an attachment (a whole log can exceed what an Intent may carry as text).
*/
fun shareableFile(context: Context): android.net.Uri {
val dir = File(context.cacheDir, "shared").apply { mkdirs() }
dir.listFiles()?.forEach { it.delete() }
val out = File(dir, "gearslip-log.txt")
out.writeText(SessionReport.render() + "\n\n" + fullText())
return androidx.core.content.FileProvider.getUriForFile(
context, "${context.packageName}.logshare", out,
)
}
fun i(message: String, tag: String = "APP") = write("I", message, tag) fun w(message: String) = write("W", message)
fun w(message: String, tag: String = "APP") = write("W", message, tag) fun e(message: String, t: Throwable? = null) {
write("E", if (t == null) message else "$message: ${t.javaClass.simpleName}: ${t.message}")
/** Logs the message, then the exception with its cause chain and top stack frames. */ if (t != null) Log.e(TAG, message, t)
fun e(message: String, t: Throwable? = null, tag: String = "APP") {
write("E", if (t == null) message else "$message: ${rootCause(t)}", tag)
if (t != null) {
Log.e(TAG, message, t)
stackTrace(t).lines().forEach { write("E", " $it", tag) }
}
}
/** A logger that stamps every line with [tag], so the log can be scanned by subsystem. */
fun tagged(tag: String) = Tagged(tag)
class Tagged(private val tag: String) {
fun i(message: String) = GearslipLog.i(message, tag)
fun w(message: String) = GearslipLog.w(message, tag)
fun e(message: String, t: Throwable? = null) = GearslipLog.e(message, t, tag)
fun hex(label: String, data: ByteArray, limit: Int = 256) = GearslipLog.hex(label, data, limit, tag)
fun verdict(headline: String, detail: String) = GearslipLog.verdict(headline, detail)
fun flush() = GearslipLog.flush()
}
/** "SSLHandshakeException: Received fatal alert: bad_certificate" - the deepest cause wins. */
fun rootCause(t: Throwable): String {
var cause: Throwable = t
while (cause.cause != null && cause.cause !== cause) cause = cause.cause!!
val top = "${t.javaClass.simpleName}: ${t.message}"
return if (cause === t) top else "$top <- ${cause.javaClass.simpleName}: ${cause.message}"
}
private fun stackTrace(t: Throwable, frames: Int = 12): String {
val out = StringBuilder()
var cause: Throwable? = t
var depth = 0
while (cause != null && depth < 4) {
if (depth > 0) out.append("caused by ${cause.javaClass.name}: ${cause.message}\n")
cause.stackTrace.take(frames).forEach { out.append("at $it\n") }
cause = cause.cause?.takeIf { it !== cause }
depth++
}
return out.toString().trimEnd()
}
/**
* Records an uncaught exception in the log file before the process dies, then lets the
* system's own handler run. Without it the file ends mid-sentence and the reason is lost.
*/
fun installCrashHandler() {
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
runCatching {
SessionReport.fail(SessionReport.Category.CRASH, "uncaught in thread ${thread.name}", throwable)
e("FATAL uncaught exception in thread ${thread.name}", throwable)
SessionReport.print()
flush()
}
previous?.uncaughtException(thread, throwable)
}
} }
/** Unmissable in a scrolling logcat - this is what the whole spike exists to print. */ /** Unmissable in a scrolling logcat - this is what the whole spike exists to print. */
@@ -165,8 +89,7 @@ object GearslipLog {
runCatching { latch.await(timeoutMs, TimeUnit.MILLISECONDS) } runCatching { latch.await(timeoutMs, TimeUnit.MILLISECONDS) }
} }
fun hex(label: String, data: ByteArray, limit: Int = 256, tag: String = "APP") { fun hex(label: String, data: ByteArray, limit: Int = 256) {
if (!debug) return
val shown = minOf(data.size, limit) val shown = minOf(data.size, limit)
val sb = StringBuilder() val sb = StringBuilder()
for (idx in 0 until shown) { for (idx in 0 until shown) {
@@ -174,16 +97,16 @@ object GearslipLog {
if (idx % 16 == 15) sb.append('\n') else sb.append(' ') if (idx % 16 == 15) sb.append('\n') else sb.append(' ')
} }
val suffix = if (data.size > limit) "\n... (${data.size - limit} more bytes)" else "" val suffix = if (data.size > limit) "\n... (${data.size - limit} more bytes)" else ""
i("$label (${data.size} bytes)\n$sb$suffix", tag) i("$label (${data.size} bytes)\n$sb$suffix")
} }
private fun write(level: String, message: String, tag: String = "APP") { private fun write(level: String, message: String) {
when (level) { when (level) {
"W" -> Log.w(TAG, message) "W" -> Log.w(TAG, message)
"E" -> Log.e(TAG, message) "E" -> Log.e(TAG, message)
else -> if (debug) Log.i(TAG, message) else -> Log.i(TAG, message)
} }
val line = "${stamp.format(Date())} $level ${tag.padEnd(5)} $message" val line = "${stamp.format(Date())} $level $message"
synchronized(live) { synchronized(live) {
live.addLast(line) live.addLast(line)
while (live.size > MAX_LIVE_LINES) live.removeFirst() while (live.size > MAX_LIVE_LINES) live.removeFirst()
File diff suppressed because it is too large. Load diff
@@ -1,125 +0,0 @@
package app.seb3thehacker.gearslip
import java.io.ByteArrayInputStream
import java.math.BigInteger
import java.security.KeyFactory
import java.security.KeyStore
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.security.spec.RSAPrivateCrtKeySpec
import java.security.spec.RSAPublicKeySpec
/**
* Converts a PEM-encoded X.509 certificate and PEM-encoded RSA PKCS#1 private key into a
* PKCS#12 [KeyStore], using only standard JCA APIs — no BouncyCastle.
*
* The DER parsing of the PKCS#1 key is done by hand (matching the same approach used in
* [SelfSignedCert] for writing). Android's Conscrypt [KeyFactory] only accepts PKCS#8,
* so we translate PKCS#1 → [RSAPrivateCrtKeySpec] ourselves.
*/
object PemKeyParser {
private const val CERT_HEADER = "-----BEGIN CERTIFICATE-----"
private const val CERT_FOOTER = "-----END CERTIFICATE-----"
private const val KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----"
private const val KEY_FOOTER = "-----END RSA PRIVATE KEY-----"
class Result(val keyStore: KeyStore, val certificate: X509Certificate)
/**
* Parses PEM strings for the certificate and private key, verifies they match, and
* returns a PKCS#12 [KeyStore] ready for [CertProvider] to consume.
*/
fun build(certificatePem: String, privateKeyPem: String, alias: String = "phone"): Result {
val cert = parseCertificate(certificatePem)
val keySpec = parsePrivateKey(privateKeyPem)
val kf = KeyFactory.getInstance("RSA")
val pubSpec = RSAPublicKeySpec(keySpec.spec.modulus, keySpec.spec.publicExponent)
require(kf.generatePublic(pubSpec) == cert.publicKey) {
"the certificate's public key does not match the private key"
}
val keyStore = KeyStore.getInstance("PKCS12").apply {
load(null, null)
setKeyEntry(alias, keySpec.getPrivate(), CharArray(0), arrayOf(cert))
}
return Result(keyStore, cert)
}
/** Strips PEM headers/footers and decodes the base64 body. */
fun parseCertificate(pem: String): X509Certificate {
val der = pemToDer(pem, CERT_HEADER, CERT_FOOTER)
return CertificateFactory.getInstance("X.509")
.generateCertificate(ByteArrayInputStream(der)) as X509Certificate
}
/** Parses an RSA PKCS#1 private key (ASN.1 DER) into a key spec. */
fun parsePrivateKey(pem: String): KeySpec {
val der = pemToDer(pem, KEY_HEADER, KEY_FOOTER)
val integers = readPkcs1Sequence(der)
require(integers.size == 9) { "PKCS#1 RSA key needs 9 integers, got ${integers.size}" }
val spec = RSAPrivateCrtKeySpec(integers[1], integers[2], integers[3], integers[4], integers[5], integers[6], integers[7], integers[8])
val privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec)
return KeySpec(spec, privateKey)
}
/** Holds both the spec and the constructed key for matching against a certificate's public key. */
class KeySpec(val spec: RSAPrivateCrtKeySpec, private val privateKey: java.security.PrivateKey) {
fun getPrivate() = privateKey
}
/** Strips headers and decodes base64. */
private fun pemToDer(pem: String, header: String, footer: String): ByteArray {
val start = pem.indexOf(header)
val end = pem.indexOf(footer)
if (start == -1 || end == -1 || end <= start) {
throw IllegalArgumentException("not a valid PEM $header block")
}
val b64 = pem.substring(start + header.length, end)
.replace(Regex("\\s+"), "")
return java.util.Base64.getDecoder().decode(b64)
}
/**
* Parses the inner SEQUENCE of an RSA PKCS#1 DER blob into a list of [BigInteger]s.
* Throws if the ASN.1 structure is wrong, so caller gets a clear error rather than a
* silent wrong key.
*/
private fun readPkcs1Sequence(der: ByteArray): List<BigInteger> {
var pos = 0
fun readTag(): Int {
require(pos < der.size) { "unexpected end of DER at tag" }
return der[pos++].toInt() and 0xFF
}
fun readLength(): Int {
require(pos < der.size) { "unexpected end of DER at length" }
val b0 = der[pos++].toInt() and 0xFF
if (b0 < 0x80) return b0
val numBytes = b0 and 0x7F
require(pos + numBytes <= der.size) { "truncated long-form length" }
var result = 0
repeat(numBytes) {
result = (result shl 8) or (der[pos++].toInt() and 0xFF)
}
return result
}
val outerTag = readTag()
require(outerTag == 0x30) { "expected SEQUENCE (0x30), got 0x${outerTag.toString(16)}" }
val outerLen = readLength()
require(pos + outerLen <= der.size) { "SEQUENCE length $outerLen exceeds remaining data" }
val integers = mutableListOf<BigInteger>()
while (pos < der.size) {
val tag = readTag()
require(tag == 0x02) { "expected INTEGER (0x02), got 0x${tag.toString(16)} at offset ${pos - 1}" }
val len = readLength()
require(pos + len <= der.size) { "INTEGER length $len exceeds remaining data" }
integers.add(BigInteger(der.copyOfRange(pos, pos + len)))
pos += len
}
require(integers.size == 9) { "PKCS#1 RSA key needs 9 integers, got ${integers.size}" }
return integers
}
}
@@ -29,7 +29,6 @@ import javax.net.ssl.X509ExtendedTrustManager
* the right tool. * the right tool.
*/ */
class PhoneTls(keyStore: KeyStore, password: CharArray) { class PhoneTls(keyStore: KeyStore, password: CharArray) {
private val log = GearslipLog.tagged("TLS")
private val engine: SSLEngine private val engine: SSLEngine
private var netIn = ByteArray(0) private var netIn = ByteArray(0)
@@ -157,7 +156,7 @@ class PhoneTls(keyStore: KeyStore, password: CharArray) {
continue continue
} }
SSLEngineResult.Status.BUFFER_UNDERFLOW -> { SSLEngineResult.Status.BUFFER_UNDERFLOW -> {
log.w("decrypt: record split across frames (${source.remaining()} bytes left over)") GearslipLog.w("decrypt: record split across frames (${source.remaining()} bytes left over)")
break break
} }
SSLEngineResult.Status.CLOSED -> break SSLEngineResult.Status.CLOSED -> break
@@ -174,29 +173,26 @@ class PhoneTls(keyStore: KeyStore, password: CharArray) {
private fun describeSession() { private fun describeSession() {
val session = engine.session val session = engine.session
log.i("TLS handshake COMPLETE - protocol=${session.protocol} cipher=${session.cipherSuite}") GearslipLog.i("TLS handshake COMPLETE - protocol=${session.protocol} cipher=${session.cipherSuite}")
SessionReport.tls(session.protocol, session.cipherSuite)
try { try {
val peers = session.peerCertificates val peers = session.peerCertificates
log.i("head unit presented ${peers.size} certificate(s):") GearslipLog.i("head unit presented ${peers.size} certificate(s):")
peers.forEachIndexed { index, certificate -> peers.forEachIndexed { index, certificate ->
if (certificate is X509Certificate) { if (certificate is X509Certificate) {
log.i(" [$index] subject=${certificate.subjectX500Principal}") GearslipLog.i(" [$index] subject=${certificate.subjectX500Principal}")
log.i(" issuer =${certificate.issuerX500Principal}") GearslipLog.i(" issuer =${certificate.issuerX500Principal}")
log.i(" serial =${certificate.serialNumber} valid=${certificate.notBefore}..${certificate.notAfter}") GearslipLog.i(" serial =${certificate.serialNumber} valid=${certificate.notBefore}..${certificate.notAfter}")
} }
} }
} catch (_: SSLPeerUnverifiedException) { } catch (_: SSLPeerUnverifiedException) {
log.i("head unit presented NO certificate (we asked but did not require one)") GearslipLog.i("head unit presented NO certificate (we asked but did not require one)")
} }
} }
/** Accepts everything and reports what it saw. We want the data, not a verdict. */ /** Accepts everything and reports what it saw. We want the data, not a verdict. */
private class LoggingTrustManager : X509ExtendedTrustManager() { private class LoggingTrustManager : X509ExtendedTrustManager() {
private val log = GearslipLog.tagged("TLS")
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
log.i("peer certificate offered (authType=$authType, chain=${chain?.size ?: 0}) - accepting") GearslipLog.i("peer certificate offered (authType=$authType, chain=${chain?.size ?: 0}) - accepting")
} }
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?, socket: Socket?) = override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?, socket: Socket?) =
@@ -8,7 +8,8 @@ object ProjectedContent {
/** /**
* Precedence: the URL saved in Settings, then a `url.txt` in the external files dir (the * Precedence: the URL saved in Settings, then a `url.txt` in the external files dir (the
* pre-Settings way, still honoured so existing setups keep working), then [DEFAULT_URL]. * pre-Settings way, still honoured so existing setups keep working), then the built-in
* test page.
*/ */
fun resolve(context: Context): String { fun resolve(context: Context): String {
val saved = AppSettings.startupUrl(context) val saved = AppSettings.startupUrl(context)
@@ -25,12 +26,9 @@ object ProjectedContent {
return url return url
} }
} }
return DEFAULT_URL return TEST_PAGE
} }
/** What the Web app opens until a page is chosen in Settings. */
const val DEFAULT_URL = "https://duckduckgo.com"
/** A bare "example.com" is a URL the user meant; raw HTML is passed through untouched. */ /** A bare "example.com" is a URL the user meant; raw HTML is passed through untouched. */
private fun normalize(value: String): String = private fun normalize(value: String): String =
if (value.startsWith("<") || "://" in value) value else "https://$value" if (value.startsWith("<") || "://" in value) value else "https://$value"
@@ -17,14 +17,9 @@ interface Projection {
/** /**
* A touch from the head unit, already scaled into projected-video coordinates. * A touch from the head unit, already scaled into projected-video coordinates.
* [action] is an Android MotionEvent action - Android Auto's PointerAction enum uses * [action] is an Android MotionEvent action - Android Auto's PointerAction enum uses
* identical values (DOWN=0, UP=1, MOVED=2, POINTER_DOWN=5, POINTER_UP=6). [points] is every * identical values (DOWN=0, UP=1, MOVED=2, POINTER_DOWN=5, POINTER_UP=6).
* finger currently down, and [actionIndex] says which of them [action] is about, so a pinch
* arrives as it would on the phone's own screen.
*/ */
fun onTouch(action: Int, actionIndex: Int, points: List<TouchPoint>) fun onTouch(action: Int, x: Float, y: Float)
fun onProjectionStopped() fun onProjectionStopped()
} }
/** One finger on the car's screen: a stable [id] for as long as it stays down, and where it is. */
class TouchPoint(val id: Int, val x: Float, val y: Float)
@@ -31,17 +31,11 @@ object Protobuf {
return varint(((field shl 3) or 2).toLong()) + varint(bytes.size.toLong()) + bytes return varint(((field shl 3) or 2).toLong()) + varint(bytes.size.toLong()) + bytes
} }
fun bytesField(field: Int, bytes: ByteArray): ByteArray =
varint(((field shl 3) or 2).toLong()) + varint(bytes.size.toLong()) + bytes
fun varintField(field: Int, value: Long): ByteArray = fun varintField(field: Int, value: Long): ByteArray =
varint((field shl 3).toLong()) + varint(value) varint((field shl 3).toLong()) + varint(value)
/** Reads the single int32 in AuthResponse. Negative values are 10-byte varints. */ /** Reads the single int32 in AuthResponse. Negative values are 10-byte varints. */
fun readInt32Field(data: ByteArray, field: Int): Int? = readInt64Field(data, field)?.toInt() fun readInt32Field(data: ByteArray, field: Int): Int? {
/** Reads a varint field whole, for int64s such as a ping's timestamp. */
fun readInt64Field(data: ByteArray, field: Int): Long? {
var pos = 0 var pos = 0
while (pos < data.size) { while (pos < data.size) {
val (tag, afterTag) = readVarint(data, pos) ?: return null val (tag, afterTag) = readVarint(data, pos) ?: return null
@@ -51,7 +45,7 @@ object Protobuf {
0 -> { 0 -> {
val (value, afterValue) = readVarint(data, pos) ?: return null val (value, afterValue) = readVarint(data, pos) ?: return null
pos = afterValue pos = afterValue
if (number == field) return value if (number == field) return value.toInt()
} }
2 -> { 2 -> {
val (len, afterLen) = readVarint(data, pos) ?: return null val (len, afterLen) = readVarint(data, pos) ?: return null
@@ -45,19 +45,7 @@ class ScreenProjector(private val context: Context) {
/** Tracks the synthetic gesture so injected MotionEvents have a coherent downTime. */ /** Tracks the synthetic gesture so injected MotionEvents have a coherent downTime. */
private var downTime = 0L private var downTime = 0L
/** fun start(surface: Surface, width: Int, height: Int, densityDpi: Int, content: @Composable () -> Unit) {
* [name] names the virtual display so the two callers are told apart from outside the app
* (`dumpsys display`): the real car session keeps "gearslip-projection", the on-phone bench
* preview passes "gearslip-preview".
*/
fun start(
surface: Surface,
width: Int,
height: Int,
densityDpi: Int,
name: String = "gearslip-projection",
content: @Composable () -> Unit,
) {
stop() stop()
val displayManager = context.getSystemService(DisplayManager::class.java) val displayManager = context.getSystemService(DisplayManager::class.java)
@@ -69,7 +57,7 @@ class ScreenProjector(private val context: Context) {
// driver on every connect. // driver on every connect.
val display = try { val display = try {
displayManager.createVirtualDisplay( displayManager.createVirtualDisplay(
name, width, height, densityDpi, surface, "gearslip-projection", width, height, densityDpi, surface,
DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION or DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION or
DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
) )
@@ -148,41 +136,13 @@ class ScreenProjector(private val context: Context) {
} }
} }
/** /** [action] is already an Android MotionEvent action; x/y are in projected coordinates. */
* [action] is already an Android MotionEvent action; [points] are in projected coordinates and fun dispatchTouch(action: Int, x: Float, y: Float) {
* hold every finger down, with [actionIndex] naming the one the action is about. Two fingers
* arrive as one gesture, so pinch and two-finger drags work as they do on the phone itself.
*/
fun dispatchTouch(action: Int, actionIndex: Int, points: List<TouchPoint>) {
val target = root ?: return val target = root ?: return
if (points.isEmpty()) return
val now = SystemClock.uptimeMillis() val now = SystemClock.uptimeMillis()
if (action == MotionEvent.ACTION_DOWN || downTime == 0L) downTime = now if (action == MotionEvent.ACTION_DOWN || downTime == 0L) downTime = now
val properties = Array(points.size) { i -> val event = MotionEvent.obtain(downTime, now, action, x, y, 0)
MotionEvent.PointerProperties().apply {
id = points[i].id
toolType = MotionEvent.TOOL_TYPE_FINGER
}
}
val coords = Array(points.size) { i ->
MotionEvent.PointerCoords().apply {
x = points[i].x
y = points[i].y
pressure = 1f
size = 1f
}
}
// A second finger going down or up carries which finger it was in the action itself.
val encoded = when (action) {
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP ->
action or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
else -> action
}
val event = MotionEvent.obtain(
downTime, now, encoded, points.size, properties, coords,
0, 0, 1f, 1f, 0, 0, android.view.InputDevice.SOURCE_TOUCHSCREEN, 0,
)
try { try {
target.dispatchTouchEvent(event) target.dispatchTouchEvent(event)
} finally { } finally {
@@ -191,34 +151,6 @@ class ScreenProjector(private val context: Context) {
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) downTime = 0L if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) downTime = 0L
} }
/**
* A key from the car's D-pad or knob, as a hardware key event on the car display. Compose
* moves focus between buttons on arrows and Tab, and clicks the focused one on OK/Enter.
* [keyCode] of [CarKeys.KEYCODE_SHIFT_TAB] is Tab with Shift held.
*/
fun dispatchKey(keyCode: Int, down: Boolean) {
val target = root ?: return
// Keys handed straight to the view skip the step where Android leaves touch mode, and in
// touch mode Compose's buttons refuse focus, so the knob had nothing to move between.
if (target.isInTouchMode) {
target.requestFocusFromTouch()
GearslipLog.i("keys: left touch mode for the knob/D-pad (now in touch mode: ${target.isInTouchMode})")
}
// Nothing on the display takes keys until something in it holds focus.
if (target.findFocus() == null) target.requestFocus()
val shift = keyCode == app.seb3thehacker.gearslip.car.CarKeys.KEYCODE_SHIFT_TAB
val code = if (shift) android.view.KeyEvent.KEYCODE_TAB else keyCode
val now = SystemClock.uptimeMillis()
val event = android.view.KeyEvent(
now, now,
if (down) android.view.KeyEvent.ACTION_DOWN else android.view.KeyEvent.ACTION_UP,
code, 0,
if (shift) android.view.KeyEvent.META_SHIFT_ON or android.view.KeyEvent.META_SHIFT_LEFT_ON else 0,
android.view.KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, android.view.InputDevice.SOURCE_DPAD,
)
target.dispatchKeyEvent(event)
}
fun stop() { fun stop() {
runCatching { presentation?.dismiss() } runCatching { presentation?.dismiss() }
runCatching { owner?.destroy() } runCatching { owner?.destroy() }
@@ -20,8 +20,8 @@ object ServiceDiscovery {
/** /**
* [widthMargin]/[heightMargin] are the head unit's own numbers (VideoConfiguration fields 3 * [widthMargin]/[heightMargin] are the head unit's own numbers (VideoConfiguration fields 3
* and 4): pixels of the frame it crops away, split evenly between the two edges, to fit the * and 4): pixels of the frame it does not treat as usable UI. Logged, and available to a
* frame to a screen of a different shape. A matched vehicle profile's insets override them. * vehicle profile, but not applied automatically - what they mean varies by unit.
*/ */
class VideoConfig( class VideoConfig(
val resolution: Int, val resolution: Int,
@@ -38,21 +38,11 @@ object ServiceDiscovery {
fun pixelCount(): Int = pixelSize()?.let { it.first * it.second } ?: Int.MAX_VALUE fun pixelCount(): Int = pixelSize()?.let { it.first * it.second } ?: Int.MAX_VALUE
/** What's left on the car's screen once the margins are cropped off. */
fun visibleSize(): Pair<Int, Int>? = pixelSize()?.let { (w, h) -> (w - widthMargin) to (h - heightMargin) }
/** The margins as the strips of the frame the car UI keeps clear. */
fun marginInsets(): Insets = Insets(
top = heightMargin / 2, bottom = heightMargin - heightMargin / 2,
left = widthMargin / 2, right = widthMargin - widthMargin / 2,
)
override fun toString() = override fun toString() =
"$resolutionName @ $frameRateName, density=$density, margin=${widthMargin}x$heightMargin" "$resolutionName @ $frameRateName, density=$density, margin=${widthMargin}x$heightMargin"
} }
/** [displayId] is MediaSinkService field 6: 0, the default, is the main screen. */ class VideoService(val serviceId: Int, val codecType: Int, val configs: List<VideoConfig>) {
class VideoService(val serviceId: Int, val codecType: Int, val configs: List<VideoConfig>, val displayId: Int = 0) {
val codecName: String get() = CODECS[codecType] ?: "unknown($codecType)" val codecName: String get() = CODECS[codecType] ?: "unknown($codecType)"
} }
@@ -99,100 +89,6 @@ object ServiceDiscovery {
} }
} }
/**
* The media sink to stream to. Gearslip sends raw PCM, so a PCM sink wins: the 2022 Dacia
* Jogger (LGE ULC 4.5) lists an AAC media sink on channel 3 before a PCM one on channel 5,
* and PCM pushed into the AAC sink was acked but played as silence. With no PCM sink, the
* first media sink is the best there is.
*/
fun pickMediaSink(sinks: List<AudioService>): AudioService? {
val media = sinks.filter { it.streamType == STREAM_MEDIA }
return media.firstOrNull { it.codecType == CODEC_PCM } ?: media.firstOrNull()
}
/**
* The channel the car takes "now playing" on (MediaPlaybackStatusService, Service field 9),
* which feeds its cluster and media screens. It carries no settings. Null when the car has none.
*/
fun findMediaStatusChannel(response: ByteArray): Int? = findChannelWith(response, 9)
/** The instrument cluster's turn-by-turn channel (NavigationStatusService, Service field 8). */
fun findNavStatusChannel(response: ByteArray): Int? = findChannelWith(response, 8)
private fun findChannelWith(response: ByteArray, serviceField: Int): Int? =
Wire.allBytes(Wire.fields(response), 1).firstNotNullOfOrNull { channel ->
val service = Wire.fields(channel)
if (service.any { it.number == serviceField }) Wire.varint(service, 1)?.toInt() else null
}
/**
* The car's microphone, from MediaSourceService (Service field 5):
* MediaSourceService { MediaCodecType available_type = 1; AudioConfiguration audio_config = 2;
* bool available_while_in_call = 3; }
* Null when the head unit has none.
*/
fun findMicService(response: ByteArray): AudioService? {
for (channel in Wire.allBytes(Wire.fields(response), 1)) {
val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: continue
val source = Wire.fields(Wire.bytes(service, 5) ?: continue)
val f = Wire.fields(Wire.bytes(source, 2) ?: continue)
return AudioService(
serviceId = id,
streamType = 0,
codecType = Wire.varint(source, 1)?.toInt() ?: CODEC_PCM,
configs = listOf(
AudioConfig(
sampleRate = Wire.varint(f, 1)?.toInt() ?: 16_000,
bits = Wire.varint(f, 2)?.toInt() ?: 16,
channels = Wire.varint(f, 3)?.toInt() ?: 1,
),
),
)
}
return null
}
/**
* The car's Bluetooth, from BluetoothService (Service field 6):
* BluetoothService { string car_address = 1; repeated BluetoothPairingMethod methods = 2 [packed]; }
* Null when the car offers no pairing over the link.
*/
class BluetoothService(val serviceId: Int, val carAddress: String, val pairingMethods: List<Int>)
/** A carmaker's own channel (service field 12), for its apps on the phone: GM's is "com.gm.vip". */
class VendorService(val serviceId: Int, val name: String)
fun findVendorServices(response: ByteArray): List<VendorService> =
Wire.allBytes(Wire.fields(response), 1).mapNotNull { channel ->
val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: return@mapNotNull null
val fields = Wire.fields(Wire.bytes(service, 12) ?: return@mapNotNull null)
val name = Wire.bytes(fields, 1)?.let { String(it, Charsets.UTF_8) } ?: return@mapNotNull null
VendorService(id, name)
}
fun findBluetoothService(response: ByteArray): BluetoothService? {
for (channel in Wire.allBytes(Wire.fields(response), 1)) {
val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: continue
val fields = Wire.fields(Wire.bytes(service, 6) ?: continue)
val address = Wire.bytes(fields, 1)?.let { String(it, Charsets.UTF_8) } ?: continue
// Packed as declared, though a car may send each method as its own varint.
val methods = fields.filter { it.number == 2 }.flatMap { f ->
f.bytes?.let(::packedVarints) ?: listOf(f.varint.toInt())
}
return BluetoothService(id, address, methods)
}
return null
}
const val STREAM_GUIDANCE = 1
const val STREAM_MEDIA = 3
const val CODEC_PCM = 1
const val CODEC_AAC_LC = 2
const val CODEC_AAC_LC_ADTS = 4
private val STREAMS = mapOf(0 to "NONE", 1 to "GUIDANCE", 2 to "SYSTEM_AUDIO", 3 to "MEDIA", 4 to "TELEPHONY") private val STREAMS = mapOf(0 to "NONE", 1 to "GUIDANCE", 2 to "SYSTEM_AUDIO", 3 to "MEDIA", 4 to "TELEPHONY")
private val RESOLUTIONS = mapOf( private val RESOLUTIONS = mapOf(
@@ -210,83 +106,30 @@ object ServiceDiscovery {
) )
/** /**
* The head unit's touchscreen and button set, from InputSourceService (Service field 4): * The head unit's touchscreen, from InputSourceService (Service field 4):
* InputSourceService { repeated int32 keycodes_supported = 1 [packed=true]; * InputSourceService { keycodes = 1; repeated TouchScreen touchscreen = 2; ... }
* repeated TouchScreen touchscreen = 2; ... }
* TouchScreen { required int32 width = 1; required int32 height = 2; type = 3; } * TouchScreen { required int32 width = 1; required int32 height = 2; type = 3; }
* *
* Touch coordinates arrive in this space (1258x708 on the 2018 Uconnect) and must be * Touch coordinates arrive in this space (1258x708 on the 2018 Uconnect) and must be
* scaled to the projected video size before injection. [keycodesSupported] is what the * scaled to the projected video size before injection.
* head unit says it will actually send over the Input channel as key events (steering-wheel
* buttons, etc.) - not every unit reports the same set, so it's kept for diagnostics and to
* know ahead of time whether a button like voice/PTT is even wired up on this hardware.
*/ */
class InputService( class InputService(val serviceId: Int, val touchWidth: Int, val touchHeight: Int)
val serviceId: Int,
val touchWidth: Int,
val touchHeight: Int,
val keycodesSupported: List<Int> = emptyList(),
/** InputSourceService field 5: which screen this input belongs to, 0 for the main one. */
val displayId: Int = 0,
)
/** fun findInputService(response: ByteArray): InputService? {
* The input for the screen Gearslip projects to ([displayId]). A head unit with two screens
* offers an input service for each: LIVI lists an empty one for its second screen first,
* and taking that one left every touch on the real touchscreen ignored.
*/
fun findInputService(response: ByteArray, displayId: Int = 0): InputService? {
val inputs = inputServices(response)
return inputs.firstOrNull { it.displayId == displayId }
?: inputs.firstOrNull { it.touchWidth > 0 && it.touchHeight > 0 }
?: inputs.firstOrNull()
}
private fun inputServices(response: ByteArray): List<InputService> = buildList {
for (channel in Wire.allBytes(Wire.fields(response), 1)) { for (channel in Wire.allBytes(Wire.fields(response), 1)) {
val service = Wire.fields(channel) val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: continue val id = Wire.varint(service, 1)?.toInt() ?: continue
val input = Wire.bytes(service, 4) ?: continue val input = Wire.bytes(service, 4) ?: continue
val inputFields = Wire.fields(input) val touch = Wire.bytes(Wire.fields(input), 2) ?: continue
// A unit with only a knob and buttons has no touchscreen entry; it still has keys. val touchFields = Wire.fields(touch)
val touchFields = Wire.bytes(inputFields, 2)?.let { Wire.fields(it) }.orEmpty() val width = Wire.varint(touchFields, 1)?.toInt() ?: continue
val width = Wire.varint(touchFields, 1)?.toInt() ?: 0 val height = Wire.varint(touchFields, 2)?.toInt() ?: continue
val height = Wire.varint(touchFields, 2)?.toInt() ?: 0 return InputService(id, width, height)
// Declared packed, but some units send each keycode as its own field.
val keycodes = inputFields.filter { it.number == 1 }.flatMap { f ->
f.bytes?.let(::packedVarints) ?: listOf(f.varint.toInt())
}
add(InputService(id, width, height, keycodes, Wire.varint(inputFields, 5)?.toInt() ?: 0))
} }
return null
} }
/** Decodes a `[packed=true]` repeated varint field's raw bytes into individual values. */
private fun packedVarints(data: ByteArray): List<Int> = buildList {
var pos = 0
while (pos < data.size) {
var result = 0L
var shift = 0
while (pos < data.size) {
val b = data[pos].toInt() and 0xFF
result = result or ((b and 0x7F).toLong() shl shift)
pos++
if (b and 0x80 == 0) break
shift += 7
}
add(result.toInt())
}
}
/**
* The main screen's video sink. A head unit with a second screen, such as LIVI with a
* cluster display, offers a sink for each; the one without a display id (0) is the main one.
*/
fun findVideoService(response: ByteArray): VideoService? { fun findVideoService(response: ByteArray): VideoService? {
val sinks = videoServices(response)
return sinks.firstOrNull { it.displayId == 0 } ?: sinks.firstOrNull()
}
private fun videoServices(response: ByteArray): List<VideoService> = buildList {
for (channel in Wire.allBytes(Wire.fields(response), 1)) { for (channel in Wire.allBytes(Wire.fields(response), 1)) {
val service = Wire.fields(channel) val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: continue val id = Wire.varint(service, 1)?.toInt() ?: continue
@@ -307,31 +150,7 @@ object ServiceDiscovery {
heightMargin = Wire.varint(f, 4)?.toInt() ?: 0, heightMargin = Wire.varint(f, 4)?.toInt() ?: 0,
) )
} }
add(VideoService(id, codecType, configs, Wire.varint(sinkFields, 6)?.toInt() ?: 0)) return VideoService(id, codecType, configs)
}
}
/**
* The head unit's sensor feed, from SensorSourceService (Service field 2; field 5 is the car's mic):
* SensorSourceService { repeated Sensor sensors = 1; }
* Sensor { required SensorType sensor_type = 1; }
*
* Field numbers for what actually rides inside each SensorEvent once subscribed are not
* pinned down here - unlike video/audio/input, there's no independent source to check them
* against, so [CarSensors] shows the raw decode instead of trusting a guessed field map.
*/
class SensorService(val serviceId: Int, val types: List<Int>)
fun findSensorService(response: ByteArray): SensorService? {
for (channel in Wire.allBytes(Wire.fields(response), 1)) {
val service = Wire.fields(channel)
val id = Wire.varint(service, 1)?.toInt() ?: continue
val sensorSource = Wire.bytes(service, 2) ?: continue
val types = Wire.allBytes(Wire.fields(sensorSource), 1).mapNotNull {
Wire.varint(Wire.fields(it), 1)?.toInt()
}
if (types.isEmpty()) continue
return SensorService(id, types)
} }
return null return null
} }
@@ -1,244 +0,0 @@
package app.seb3thehacker.gearslip
import android.content.Context
import app.seb3thehacker.gearslip.stats.UsageStats
import android.os.Build
/**
* The facts a bug report needs, gathered as a session runs and printed as one readable block
* when it ends. The log holds the full trace; this holds the answer to "what went wrong,
* on what car, on what phone" so nobody has to read the trace to find out.
*
* Nothing here identifies a person: no serial numbers, accounts, locations or accessory
* serials. The head unit and vehicle strings are what the head unit itself announces.
*/
object SessionReport {
/** Where a session failed, coarse enough to count and group reports by. */
enum class Category(val label: String) {
NONE("none"),
USB("USB transport"),
NO_HANDSHAKE("head unit never started talking"),
TLS("TLS handshake failed"),
CERTIFICATE("certificate rejected by the head unit"),
AUTH("authentication failed"),
SERVICE_DISCOVERY("service discovery failed"),
VIDEO("video stream failed"),
BYEBYE("head unit ended the session"),
CRASH("app crash"),
UNKNOWN("unclassified"),
}
/**
* How far a session got, in the order a connection is built. The usage note's "Where
* connections fail" share sends the furthest one reached, so a failure says where it broke.
*/
enum class Stage(val key: String) {
USB("usb"), // the link opened; the car may have said nothing
VERSIONS("versions"), // the car said which protocol it speaks
TLS("tls"), // the secure link is up
ACCEPTED("accepted"), // the car accepted the certificate
CHANNELS("channels"), // the car listed its channels and said who it is
VIDEO("video"), // the car's screen is set up for Gearslip
STREAMING("streaming"), // video frames are reaching the car
}
private var appVersion = "?"
private var appCode = 0L
@Volatile private var startedAt = 0L
@Volatile var category = Category.NONE; private set
@Volatile private var failure = ""
@Volatile var stage = Stage.USB; private set
/** What the car or the phone said when it broke: a TLS alert, an auth status, a ByeBye reason, an errno. */
@Volatile private var failCode = ""
@Volatile private var failedAfter = 0L
@Volatile private var protocolVersion = ""
@Volatile private var certSource = ""
@Volatile private var certIssuer = ""
@Volatile private var tlsProtocol = ""
@Volatile private var tlsCipher = ""
@Volatile private var authStatus: Int? = null
@Volatile private var headUnit = ""
@Volatile private var profile = ""
@Volatile private var video = ""
@Volatile private var audio = ""
@Volatile private var lastStream = ""
@Volatile private var lastState = ""
private var printed = false
private var appContext: Context? = null
fun init(context: Context) {
appContext = context.applicationContext
val info = runCatching { context.packageManager.getPackageInfo(context.packageName, 0) }.getOrNull()
appVersion = info?.versionName ?: "?"
appCode = info?.longVersionCode ?: 0
}
/** How this drive reached the car, and how its music did: "usb" or "wireless", "usb" or "bluetooth". */
@Volatile var link = ""; private set
@Volatile var audioMode = ""; private set
fun begin(wireless: Boolean) {
startedAt = System.currentTimeMillis()
link = if (wireless) "wireless" else "usb"
audioMode = if (app.seb3thehacker.gearslip.car.CarSettings.pipeAudio.value) "usb" else "bluetooth"
category = Category.NONE
failure = ""; protocolVersion = ""; certSource = ""; certIssuer = ""
stage = Stage.USB; failCode = ""; failedAfter = 0
tlsProtocol = ""; tlsCipher = ""; authStatus = null
headUnitInfo = null
carScreen = ""; carDpi = 0
headUnit = ""; profile = ""; video = ""; lastStream = ""; lastState = ""
printed = false
}
/** Moves the session's furthest stage on; never back. */
private fun reached(next: Stage) { if (next > stage) stage = next }
fun protocolVersion(major: Int, minor: Int) { protocolVersion = "$major.$minor"; reached(Stage.VERSIONS) }
fun certificate(source: String, issuer: String) { certSource = source; certIssuer = issuer }
fun tls(protocol: String, cipher: String) { tlsProtocol = protocol; tlsCipher = cipher; reached(Stage.TLS) }
fun auth(status: Int) { authStatus = status; if (status == 0) reached(Stage.ACCEPTED) }
fun headUnit(info: String) { headUnit = info }
/** Who the car said it is, for the opt-in usage note; null until service discovery. */
@Volatile var headUnitInfo: ServiceDiscovery.HeadUnitInfo? = null
set(value) { field = value; if (value != null) reached(Stage.CHANNELS) }
/** The car screen's usable size once its margins are cropped, and its density; blank before video starts. */
@Volatile var carScreen = ""; private set
@Volatile var carDpi = 0; private set
fun carScreen(size: String, dpi: Int) { carScreen = size; carDpi = dpi; reached(Stage.VIDEO) }
fun profile(name: String?) { profile = name ?: "none matched" }
fun video(summary: String) { video = summary }
fun audio(summary: String) { audio = summary }
fun stream(summary: String) { lastStream = summary; reached(Stage.STREAMING) }
/**
* Records the first failure only: later ones are usually fallout from it. [code] is the short
* thing the car or the phone said, like "auth -3" or "bye 1", for the usage note.
*/
fun fail(category: Category, detail: String, state: String = "", code: String = "") {
if (this.category != Category.NONE) return
this.category = category
failure = detail
lastState = state
failCode = code
failedAfter = if (startedAt == 0L) 0 else (System.currentTimeMillis() - startedAt) / 1000
}
fun fail(category: Category, detail: String, t: Throwable, state: String = "") =
fail(category, "$detail (${GearslipLog.rootCause(t)})", state, codeOf(t))
/**
* A short code from an exception, never its whole message: the TLS alert's name, the errno
* of a USB failure, or else the exception's class.
*/
private fun codeOf(t: Throwable): String {
var root = t
while (root.cause != null && root.cause !== root) root = root.cause!!
val text = "${t.message} ${root.message}"
Regex("(?i)alert[ _:]*\\(?([a-z_ ]{3,40}?)\\)?(?:\\s|$|[,;.])").find(text)?.let {
return "alert ${it.groupValues[1].trim().lowercase().replace(' ', '_')}"
}
Regex("\\b(E[A-Z]{2,12})\\b").find(text)?.let { return it.groupValues[1] }
return root.javaClass.simpleName.take(40)
}
/**
* One session for the usage note's "Where connections fail" share: how far it got, how and
* when it ended, and with which kind of certificate. Counts and codes only, nothing personal.
*/
fun sessionNote(): org.json.JSONObject {
val seconds = if (startedAt == 0L) 0 else (System.currentTimeMillis() - startedAt) / 1000
val source = certSource.lowercase()
return org.json.JSONObject()
.put("stage", stage.key)
.put("ended", category.name.lowercase())
.put("code", failCode)
.put("failed_at", if (category == Category.NONE) 0 else rounded(failedAfter))
.put("seconds", rounded(seconds))
.put("cert", when {
"imported" in source -> "imported"
"downloaded" in source -> "downloaded"
"self" in source -> "self-signed"
source.isEmpty() -> ""
else -> "other"
})
}
/** Seconds rounded so a drive's length can't be matched to anything: 5 s, then minutes, then 5 minutes. */
private fun rounded(s: Long): Long = when {
s < 60 -> (s + 2) / 5 * 5
s < 3600 -> (s + 30) / 60 * 60
else -> (s + 150) / 300 * 300
}
/** The report as plain text, for the log file and for anything that gets sent. */
fun render(): String {
val seconds = if (startedAt == 0L) 0 else (System.currentTimeMillis() - startedAt) / 1000
fun row(name: String, value: String) = if (value.isEmpty()) "" else " ${name.padEnd(16)}$value\n"
return buildString {
append("=".repeat(60)).append('\n')
append("SESSION REPORT\n")
append(row("result", if (category == Category.NONE) "ok / no failure recorded" else "FAILED - ${category.label}"))
append(row("detail", failure))
append(row("failed in state", lastState))
append(row("duration", "${seconds}s"))
append("\n")
append(row("gearslip", "$appVersion (code $appCode)"))
append(row("phone", "${Build.MANUFACTURER} ${Build.MODEL}"))
append(row("android", "${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}, patch ${Build.VERSION.SECURITY_PATCH})"))
append("\n")
append(row("head unit", headUnit))
append(row("AA protocol", protocolVersion))
append(row("profile", profile))
append("\n")
append(row("phone cert", certSource))
append(row("cert issuer", certIssuer))
append(row("TLS", listOf(tlsProtocol, tlsCipher).filter { it.isNotEmpty() }.joinToString(" / ")))
append(row("auth status", authStatus?.let { "$it (${authName(it)})" } ?: ""))
append("\n")
append(row("video", video))
append(row("audio", audio))
append(row("last stream stat", lastStream))
append("=".repeat(60))
}
}
/** Prints the report into the log, once per session. */
fun print() {
if (printed || startedAt == 0L) return
printed = true
render().lines().forEach { GearslipLog.i(it) }
appContext?.let { context ->
// Video started means the car showed Gearslip: that's a working car, and unplugging or
// switching the car off at the end shows up as a USB or ByeBye "failure" that isn't one.
val reached = carScreen.isNotEmpty()
val outcome = when {
reached && category in setOf(Category.NONE, Category.USB, Category.BYEBYE) -> "connected"
reached -> "connected, then ${category.label}"
category == Category.NONE -> "ended before video"
else -> category.label
}
runCatching {
UsageStats.recordSession(context, headUnitInfo, protocolVersion, outcome, carScreen, carDpi, sessionNote(), link, audioMode)
}
if (outcome == "connected") runCatching {
app.seb3thehacker.gearslip.stats.WorkedPrompt.onDriveWorked(context, headUnitInfo, protocolVersion, carScreen, carDpi)
app.seb3thehacker.gearslip.ui.DonatePrompt.onDriveWorked(context)
}
runCatching { app.seb3thehacker.gearslip.update.UpdateChecker.onDriveEnded(context) }
}
GearslipLog.flush()
}
private fun authName(status: Int) = when (status) {
0 -> "success"
-2 -> "certificate error"
-3 -> "authentication failure"
else -> "unknown"
}
}
@@ -20,7 +20,7 @@ object SessionStatus {
Snapshot( Snapshot(
Phase.IDLE, Phase.IDLE,
"Not connected", "Not connected",
"Plug into the car's USB port, or connect wirelessly. Gearslip opens by itself when the car answers.", "Plug the phone into the car's USB port. Gearslip opens by itself when the head unit connects.",
), ),
) )
@@ -21,13 +21,12 @@ import javax.net.ssl.X509ExtendedTrustManager
* unit, not about this code. * unit, not about this code.
*/ */
object TlsSelfTest { object TlsSelfTest {
private val log = GearslipLog.tagged("TLS")
fun run(identity: CertProvider.Identity): Boolean { fun run(identity: CertProvider.Identity): Boolean {
log.i("=== TLS self-test starting ===") GearslipLog.i("=== TLS self-test starting ===")
log.i("cert source: ${identity.source}") GearslipLog.i("cert source: ${identity.source}")
log.i(" subject = ${identity.certificate.subjectX500Principal}") GearslipLog.i(" subject = ${identity.certificate.subjectX500Principal}")
log.i(" issuer = ${identity.certificate.issuerX500Principal}") GearslipLog.i(" issuer = ${identity.certificate.issuerX500Principal}")
return try { return try {
val server = PhoneTls(identity.keyStore, identity.password) val server = PhoneTls(identity.keyStore, identity.password)
val client = Driver(clientEngine()) val client = Driver(clientEngine())
@@ -45,7 +44,7 @@ object TlsSelfTest {
} }
if (!server.handshakeComplete) { if (!server.handshakeComplete) {
log.e("self-test FAILED: handshake did not complete after $rounds rounds") GearslipLog.e("self-test FAILED: handshake did not complete after $rounds rounds")
return false return false
} }
@@ -54,14 +53,14 @@ object TlsSelfTest {
val plaintext = "gearslip round trip".toByteArray() val plaintext = "gearslip round trip".toByteArray()
val decrypted = client.decrypt(server.encrypt(plaintext)) val decrypted = client.decrypt(server.encrypt(plaintext))
if (!decrypted.contentEquals(plaintext)) { if (!decrypted.contentEquals(plaintext)) {
log.e("self-test FAILED: round trip mismatch (${decrypted.size} bytes back)") GearslipLog.e("self-test FAILED: round trip mismatch (${decrypted.size} bytes back)")
return false return false
} }
log.i("=== TLS self-test PASSED - certificate, key manager and engine are sound ===") GearslipLog.i("=== TLS self-test PASSED - certificate, key manager and engine are sound ===")
true true
} catch (t: Throwable) { } catch (t: Throwable) {
log.e("self-test FAILED with an exception", t) GearslipLog.e("self-test FAILED with an exception", t)
false false
} }
} }
@@ -23,12 +23,9 @@ class VideoSource(
private val height: Int, private val height: Int,
private val frameRate: Int, private val frameRate: Int,
private val mode: Mode = Mode.TEST_CARD, private val mode: Mode = Mode.TEST_CARD,
/** Over Wi-Fi: a fraction of the cable bitrate, so the link keeps up and sound isn't starved. */
private val wireless: Boolean = false,
private val onCodecConfig: (ByteArray) -> Unit, private val onCodecConfig: (ByteArray) -> Unit,
private val onFrame: (data: ByteArray, presentationTimeUs: Long, keyFrame: Boolean) -> Unit, private val onFrame: (data: ByteArray, presentationTimeUs: Long, keyFrame: Boolean) -> Unit,
) { ) {
private val log = GearslipLog.tagged("VIDEO")
/** /**
* TEST_CARD feeds generated YUV buffers; SURFACE exposes a MediaCodec input Surface for * TEST_CARD feeds generated YUV buffers; SURFACE exposes a MediaCodec input Surface for
@@ -47,11 +44,7 @@ class VideoSource(
private var frameIndex = 0L private var frameIndex = 0L
fun start() { fun start() {
val level = levelFor(width, height, frameRate) val format = MediaFormat.createVideoFormat(MIME, width, height).apply {
val bitRate = defaultBitRate(width, height, frameRate, level).let {
if (wireless) (it * WIRELESS_SHARE).toInt().coerceAtMost(WIRELESS_MAX_BIT_RATE) else it
}
fun format(tuned: Boolean) = MediaFormat.createVideoFormat(MIME, width, height).apply {
setInteger( setInteger(
MediaFormat.KEY_COLOR_FORMAT, MediaFormat.KEY_COLOR_FORMAT,
if (mode == Mode.SURFACE) { if (mode == Mode.SURFACE) {
@@ -60,54 +53,25 @@ class VideoSource(
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible
}, },
) )
setInteger(MediaFormat.KEY_BIT_RATE, bitRate) setInteger(MediaFormat.KEY_BIT_RATE, 2_000_000)
setInteger(MediaFormat.KEY_FRAME_RATE, frameRate) setInteger(MediaFormat.KEY_FRAME_RATE, frameRate)
// Drops already ask for a fresh keyframe, so a long interval costs nothing in recovery setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)
// and spares the link a big frame every second.
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, I_FRAME_INTERVAL_S)
if (mode == Mode.SURFACE) {
// A surface encoder only makes a frame when the screen changes, and many decoders
// show a frame only once the next one arrives. So the last change before the
// screen goes still (a menu closing) sat in the car's decoder until something
// else moved. Repeating the last frame after a short pause pushes it through;
// a repeat of an unchanged screen costs a few bytes. scrcpy does the same.
setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_AFTER_US)
// An app that draws nonstop (a moving map) renders at the phone's refresh rate,
// faster than the car acks. Every extra frame queued inside the encoder, and the
// car's screen fell 25 seconds behind. Capping the input drops the extras before
// they're encoded, so the car always gets the newest frame.
setFloat(MediaFormat.KEY_MAX_FPS_TO_ENCODER, frameRate.toFloat())
}
setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline) setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
setInteger(MediaFormat.KEY_LEVEL, level.codecLevel) setInteger(MediaFormat.KEY_LEVEL, MediaCodecInfo.CodecProfileLevel.AVCLevel31)
if (tuned) {
// Hints only: a car screen wants each frame now, not the best frame a moment later.
setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR)
setInteger(MediaFormat.KEY_PRIORITY, 0)
setInteger(MediaFormat.KEY_LATENCY, 1)
}
} }
var encoder = MediaCodec.createEncoderByType(MIME) val encoder = MediaCodec.createEncoderByType(MIME)
try { encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
encoder.configure(format(tuned = true), null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
} catch (e: Exception) {
// Some encoders refuse a hint they don't know. The plain format is what always worked.
log.w("encoder refused the tuned format (${e.message}) - using the plain one")
encoder.release()
encoder = MediaCodec.createEncoderByType(MIME)
encoder.configure(format(tuned = false), null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
}
if (mode == Mode.SURFACE) inputSurface = encoder.createInputSurface() if (mode == Mode.SURFACE) inputSurface = encoder.createInputSurface()
encoder.start() encoder.start()
codec = encoder codec = encoder
running = true running = true
log.i("encoder started: ${width}x$height @ ${frameRate}fps, ${bitRate / 1000} kbps${if (wireless) " (wireless)" else ""}, H.264 Baseline level ${level.label}, mode=$mode") GearslipLog.i("encoder started: ${width}x$height @ ${frameRate}fps, H.264 Baseline, mode=$mode")
worker = Thread { worker = Thread {
runCatching { pump(encoder) } runCatching { pump(encoder) }
.onFailure { if (running) log.e("encoder loop failed", it) } .onFailure { if (running) GearslipLog.e("encoder loop failed", it) }
}.apply { name = "gearslip-encoder"; start() } }.apply { name = "gearslip-encoder"; start() }
} }
@@ -125,7 +89,7 @@ class VideoSource(
codec?.setParameters(Bundle().apply { codec?.setParameters(Bundle().apply {
putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)
}) })
}.onFailure { log.w("requestSyncFrame failed: ${it.message}") } }.onFailure { GearslipLog.w("requestSyncFrame failed: ${it.message}") }
} }
fun stop() { fun stop() {
@@ -158,10 +122,7 @@ class VideoSource(
frameIndex++ frameIndex++
} }
// A surface-fed encoder has nothing to do between frames, so block until one is ready var outIndex = encoder.dequeueOutputBuffer(info, TIMEOUT_US)
// instead of sleeping a fixed time: less delay on screen, fewer wakeups for the CPU.
val wait = if (mode == Mode.SURFACE) SURFACE_TIMEOUT_US else TIMEOUT_US
var outIndex = encoder.dequeueOutputBuffer(info, wait)
while (outIndex >= 0) { while (outIndex >= 0) {
val buffer = encoder.getOutputBuffer(outIndex) val buffer = encoder.getOutputBuffer(outIndex)
if (buffer != null && info.size > 0) { if (buffer != null && info.size > 0) {
@@ -182,7 +143,7 @@ class VideoSource(
outIndex = encoder.dequeueOutputBuffer(info, 0) outIndex = encoder.dequeueOutputBuffer(info, 0)
} }
if (mode != Mode.SURFACE) Thread.sleep(maxOf(1L, frameIntervalUs / 2000)) Thread.sleep(maxOf(1L, frameIntervalUs / 2000))
} }
} }
@@ -226,52 +187,6 @@ class VideoSource(
private companion object { private companion object {
const val MIME = MediaFormat.MIMETYPE_VIDEO_AVC const val MIME = MediaFormat.MIMETYPE_VIDEO_AVC
const val TIMEOUT_US = 10_000L const val TIMEOUT_US = 10_000L
const val SURFACE_TIMEOUT_US = 100_000L
/**
* 800x480 at 30fps gets 8 Mbps: about the most that size can show, enough that a moving
* video in the browser stays sharp. Bigger screens get more, but less than in proportion,
* since large frames compress better: bitrate grows with pixels^0.75. 60fps gets 1.5x,
* because frames that close together are mostly alike.
*/
const val BASE_BIT_RATE = 8_000_000.0
const val BASE_PIXELS = 800.0 * 480
/** No car's decoder is asked for more than this, whatever its level allows. */
const val MAX_BIT_RATE = 25_000_000
/**
* The H.264 levels a car screen can need, smallest first: macroblocks a second each
* decodes, and the Baseline bitrate it must handle. The encoder declares the smallest
* that fits, and the bitrate stays within it, so a car decoder isn't asked for more than
* the level it was told about.
*/
enum class Level(val label: String, val codecLevel: Int, val macroblocksPerSecond: Int, val maxBitRate: Int) {
L31("3.1", MediaCodecInfo.CodecProfileLevel.AVCLevel31, 108_000, 14_000_000),
L32("3.2", MediaCodecInfo.CodecProfileLevel.AVCLevel32, 216_000, 20_000_000),
L4("4", MediaCodecInfo.CodecProfileLevel.AVCLevel4, 245_760, 20_000_000),
L42("4.2", MediaCodecInfo.CodecProfileLevel.AVCLevel42, 522_240, 50_000_000),
}
fun levelFor(width: Int, height: Int, frameRate: Int): Level {
val perSecond = ((width + 15) / 16) * ((height + 15) / 16) * frameRate
return Level.entries.firstOrNull { perSecond <= it.macroblocksPerSecond } ?: Level.L42
}
fun defaultBitRate(width: Int, height: Int, frameRate: Int, level: Level): Int {
val size = Math.pow(width.toDouble() * height / BASE_PIXELS, 0.75)
val rate = if (frameRate > 30) 1.5 else 1.0
return (BASE_BIT_RATE * size * rate).toInt().coerceAtMost(minOf(level.maxBitRate, MAX_BIT_RATE))
}
/**
* A car's Wi-Fi is shared, noisy and far slower than its nominal rate, and the sound rides
* the same link behind the video. Real Android Auto sends a few Mbps wirelessly; at the
* cable rate (15-20 Mbps for 720p) a laptop hotspot fell seconds behind and the music
* cut in and out. 720p30 comes out near 5.4 Mbps.
*/
const val WIRELESS_SHARE = 0.35
const val WIRELESS_MAX_BIT_RATE = 8_000_000
const val I_FRAME_INTERVAL_S = 5
private const val REPEAT_AFTER_US = 100_000L
/** (Y, Cb, Cr) - white, yellow, cyan, green, magenta, red, blue. */ /** (Y, Cb, Cr) - white, yellow, cyan, green, magenta, red, blue. */
val BAR_COLOURS = listOf( val BAR_COLOURS = listOf(
@@ -1,94 +0,0 @@
package app.seb3thehacker.gearslip.audio
import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
/**
* Turns captured PCM into AAC-LC for a car whose music channel takes nothing else. Cars that
* offer PCM never get here: AAC costs a little delay and quality, and every car that works today
* is a PCM car.
*
* Android's encoder hands back raw access units, which is what AUDIO_AAC_LC expects. For
* AUDIO_AAC_LC_ADTS each unit gets the 7-byte ADTS header in front, so the car can find the
* frame edges itself. The encoder's first output is its configuration, not audio, and is skipped.
*/
internal class AacEncoder(private val sampleRate: Int, private val channels: Int, private val adts: Boolean) {
private val codec: MediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {
val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, sampleRate, channels).apply {
setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)
setInteger(MediaFormat.KEY_BIT_RATE, if (channels == 1) 96_000 else 192_000)
setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16 * 1024)
}
configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
start()
}
private val info = MediaCodec.BufferInfo()
private var samplesIn = 0L
/** Encodes [size] bytes of 16-bit PCM and returns the AAC frames that came out, oldest first. */
fun encode(pcm: ByteArray, size: Int): List<ByteArray> {
var offset = 0
val out = ArrayList<ByteArray>()
while (offset < size) {
val index = codec.dequeueInputBuffer(INPUT_WAIT_US)
if (index < 0) {
drain(out)
continue
}
val buffer = codec.getInputBuffer(index) ?: continue
val n = minOf(buffer.remaining(), size - offset)
buffer.put(pcm, offset, n)
val presentationUs = samplesIn * 1_000_000L / sampleRate
codec.queueInputBuffer(index, 0, n, presentationUs, 0)
samplesIn += n / (2 * channels)
offset += n
drain(out)
}
return out
}
private fun drain(out: MutableList<ByteArray>) {
while (true) {
val index = codec.dequeueOutputBuffer(info, 0)
if (index < 0) return
if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0 && info.size > 0) {
val buffer = codec.getOutputBuffer(index)
if (buffer != null) {
val frame = ByteArray(info.size)
buffer.position(info.offset)
buffer.get(frame)
out.add(if (adts) adtsHeader(frame.size) + frame else frame)
}
}
codec.releaseOutputBuffer(index, false)
}
}
/** ADTS for one AAC-LC frame: sync word, no CRC, and the frame's length including this header. */
private fun adtsHeader(payload: Int): ByteArray {
val length = payload + 7
val freq = FREQUENCIES.indexOf(sampleRate).let { if (it < 0) 3 else it }
val profile = 1 // AAC-LC is object type 2, written as type minus one
return byteArrayOf(
0xFF.toByte(),
0xF1.toByte(),
((profile shl 6) or (freq shl 2) or (channels shr 2)).toByte(),
(((channels and 3) shl 6) or (length shr 11)).toByte(),
((length shr 3) and 0xFF).toByte(),
(((length and 7) shl 5) or 0x1F).toByte(),
0xFC.toByte(),
)
}
fun release() {
runCatching { codec.stop() }
runCatching { codec.release() }
}
private companion object {
const val INPUT_WAIT_US = 10_000L
val FREQUENCIES = listOf(96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350)
}
}
@@ -7,7 +7,6 @@ import android.app.PendingIntent
import android.app.Service import android.app.Service
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo import android.content.pm.ServiceInfo
import android.media.AudioAttributes import android.media.AudioAttributes
import android.media.AudioFormat import android.media.AudioFormat
@@ -16,7 +15,6 @@ import android.media.AudioRecord
import android.media.projection.MediaProjection import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager import android.media.projection.MediaProjectionManager
import android.os.IBinder import android.os.IBinder
import android.os.Process
import app.seb3thehacker.gearslip.GearslipLog import app.seb3thehacker.gearslip.GearslipLog
import kotlin.math.abs import kotlin.math.abs
@@ -26,51 +24,16 @@ import kotlin.math.abs
* Playback capture is the one public route to another app's sound, and it hangs off a * Playback capture is the one public route to another app's sound, and it hangs off a
* MediaProjection - so, as with [app.seb3thehacker.gearslip.mirror.MirrorService], the consent * MediaProjection - so, as with [app.seb3thehacker.gearslip.mirror.MirrorService], the consent
* result is carried into a foreground service of type mediaProjection before it can be redeemed. * result is carried into a foreground service of type mediaProjection before it can be redeemed.
* Capture is scoped to media playback: notification pings, calls and alarms stay on the phone. * Capture is scoped to the media app's uid: notification pings and other apps stay on the phone.
* The grant lasts as long as this service does, which is as long as the car is connected, so the
* driver answers the consent dialog once per drive rather than once per app.
*/ */
class AudioCaptureService : Service() { class AudioCaptureService : Service() {
@Volatile private var reading = false @Volatile private var reading = false
private var projection: MediaProjection? = null private var projection: MediaProjection? = null
private var thread: Thread? = null private var thread: Thread? = null
private var mutedPhone = false
/**
* Silence the phone's own speaker while the car is being fed.
*
* Playback capture copies the stream instead of moving it, so without this the music plays in
* two places at once. Muting the stream does not affect what is captured - the tap sits before
* the volume the speaker gets - so the car still receives full-level audio.
*/
private fun mutePhone() {
if (mutedPhone) return
runCatching {
getSystemService(android.media.AudioManager::class.java)
.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, android.media.AudioManager.ADJUST_MUTE, 0)
mutedPhone = true
GearslipLog.i("audio: muted the phone's speaker for the drive")
}.onFailure { GearslipLog.w("audio: could not mute the phone: ${it.message}") }
}
private fun unmutePhone() {
if (!mutedPhone) return
mutedPhone = false
runCatching {
getSystemService(android.media.AudioManager::class.java)
.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, android.media.AudioManager.ADJUST_UNMUTE, 0)
GearslipLog.i("audio: gave the phone's speaker back")
}.onFailure { GearslipLog.w("audio: could not unmute the phone: ${it.message}") }
}
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
running = true
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) { if (intent?.action == ACTION_STOP) {
stopSelf() stopSelf()
@@ -85,14 +48,7 @@ class AudioCaptureService : Service() {
return START_NOT_STICKY return START_NOT_STICKY
} }
// Android silences the microphone for apps in the background unless a running service startForeground(NOTIFICATION_ID, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
// claims it. Claiming it here lets voice replies hear the driver with the phone locked.
// Without the permission, claiming it would crash, so it's left off.
val micGranted = checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
val type = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION or
(if (micGranted) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0)
startForeground(NOTIFICATION_ID, notification(), type)
ScreenShareGuard.lift(this)
projection = try { projection = try {
getSystemService(MediaProjectionManager::class.java).getMediaProjection(resultCode, data) getSystemService(MediaProjectionManager::class.java).getMediaProjection(resultCode, data)
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -118,14 +74,13 @@ class AudioCaptureService : Service() {
private fun beginCapture(token: MediaProjection) { private fun beginCapture(token: MediaProjection) {
val rate = CarAudio.sampleRate val rate = CarAudio.sampleRate
val channels = CarAudio.channels val channels = CarAudio.channels
val uid = CarAudio.uid
val record = try { val record = try {
// Matched by usage, not by app. A uid filter would have to be rebuilt every time the
// driver changed media app, and rebuilding means a fresh consent dialog - so the
// filter is what the sound is for, and any app playing media reaches the car.
val config = AudioPlaybackCaptureConfiguration.Builder(token) val config = AudioPlaybackCaptureConfiguration.Builder(token)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA) .addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.addMatchingUsage(AudioAttributes.USAGE_GAME) .addMatchingUsage(AudioAttributes.USAGE_GAME)
.addMatchingUsage(AudioAttributes.USAGE_UNKNOWN) .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
.apply { if (uid >= 0) addMatchingUid(uid) }
.build() .build()
val mask = if (channels == 1) AudioFormat.CHANNEL_IN_MONO else AudioFormat.CHANNEL_IN_STEREO val mask = if (channels == 1) AudioFormat.CHANNEL_IN_MONO else AudioFormat.CHANNEL_IN_STEREO
val format = AudioFormat.Builder() val format = AudioFormat.Builder()
@@ -137,7 +92,7 @@ class AudioCaptureService : Service() {
AudioRecord.Builder() AudioRecord.Builder()
.setAudioPlaybackCaptureConfig(config) .setAudioPlaybackCaptureConfig(config)
.setAudioFormat(format) .setAudioFormat(format)
.setBufferSizeInBytes(maxOf(minimum, CHUNK_BYTES * BUFFER_CHUNKS)) .setBufferSizeInBytes(maxOf(minimum, CHUNK_BYTES * 4))
.build() .build()
} catch (t: Throwable) { } catch (t: Throwable) {
GearslipLog.e("audio: could not set up playback capture", t) GearslipLog.e("audio: could not set up playback capture", t)
@@ -148,31 +103,20 @@ class AudioCaptureService : Service() {
reading = true reading = true
thread = Thread({ thread = Thread({
// A busy phone (a map app drawing, the video encoder) would otherwise starve this
// loop, and the car hears every late read as a skip.
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO)
val buffer = ByteArray(CHUNK_BYTES) val buffer = ByteArray(CHUNK_BYTES)
var peak = 0 var peak = 0
var heardAt = System.currentTimeMillis() var heardAt = System.currentTimeMillis()
val startedAt = heardAt
var everHeard = false
var warnedSilent = false
try { try {
record.startRecording() record.startRecording()
GearslipLog.i("audio: capturing media playback at ${rate}Hz x$channels") GearslipLog.i("audio: capturing uid=$uid at ${rate}Hz x$channels")
mutePhone()
CarAudio.captureStarted() CarAudio.captureStarted()
while (reading) { while (reading) {
val n = record.read(buffer, 0, buffer.size) val n = record.read(buffer, 0, buffer.size)
if (n <= 0) { if (n <= 0) break
GearslipLog.e("audio: AudioRecord.read returned $n - capture has stopped")
break
}
for (i in 0 until n - 1 step 2) { for (i in 0 until n - 1 step 2) {
val sample = (buffer[i].toInt() and 0xFF) or (buffer[i + 1].toInt() shl 8) val sample = (buffer[i].toInt() and 0xFF) or (buffer[i + 1].toInt() shl 8)
peak = maxOf(peak, abs(sample.toShort().toInt())) peak = maxOf(peak, abs(sample.toShort().toInt()))
} }
if (peak > 0) everHeard = true
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val level = peak / 32768f val level = peak / 32768f
if (now - heardAt >= LEVEL_LOG_MS) { if (now - heardAt >= LEVEL_LOG_MS) {
@@ -180,16 +124,6 @@ class AudioCaptureService : Service() {
heardAt = now heardAt = now
peak = 0 peak = 0
} }
// Capture never fails for an app that opts out; it just hands back digital
// silence. Say so, because the symptom is identical to a broken car link.
if (!everHeard && !warnedSilent && now - startedAt >= SILENCE_MS) {
warnedSilent = true
GearslipLog.w(
"audio: ${SILENCE_MS / 1000}s of capture and every sample is zero. " +
"Either nothing is playing, or the app does not allow its audio " +
"to be captured.",
)
}
CarAudio.deliver(buffer, n, level) CarAudio.deliver(buffer, n, level)
} }
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -197,7 +131,6 @@ class AudioCaptureService : Service() {
} finally { } finally {
runCatching { record.stop() } runCatching { record.stop() }
record.release() record.release()
unmutePhone()
CarAudio.captureStopped() CarAudio.captureStopped()
} }
}, "gearslip-audio").apply { isDaemon = true; start() } }, "gearslip-audio").apply { isDaemon = true; start() }
@@ -207,13 +140,8 @@ class AudioCaptureService : Service() {
super.onDestroy() super.onDestroy()
reading = false reading = false
runCatching { thread?.join(500) } runCatching { thread?.join(500) }
// Belt and braces: a phone left muted after the drive is a bug the driver blames on their
// phone, not on Gearslip, so unmute on every way out of here.
unmutePhone()
runCatching { projection?.stop() } runCatching { projection?.stop() }
projection = null projection = null
ScreenShareGuard.restore(this)
running = false
} }
private fun notification(): Notification { private fun notification(): Notification {
@@ -244,17 +172,10 @@ class AudioCaptureService : Service() {
/** About 21 ms of 48 kHz stereo: small enough for lip-sync, big enough not to flood the link. */ /** About 21 ms of 48 kHz stereo: small enough for lip-sync, big enough not to flood the link. */
private const val CHUNK_BYTES = 4096 private const val CHUNK_BYTES = 4096
/** About half a second: room to wait out a slow ack from the car without losing sound. */
private const val BUFFER_CHUNKS = 24
private const val LEVEL_LOG_MS = 3_000L private const val LEVEL_LOG_MS = 3_000L
private const val SILENCE_MS = 5_000L
private var appContext: Context? = null private var appContext: Context? = null
/** True between onCreate and onDestroy; lets the activity tell a live capture from a crashed one. */
@Volatile var running = false
private set
fun start(context: Context, resultCode: Int, data: Intent) { fun start(context: Context, resultCode: Int, data: Intent) {
appContext = context.applicationContext appContext = context.applicationContext
context.startForegroundService( context.startForegroundService(
@@ -22,35 +22,15 @@ class AudioLink(
private val service: ServiceDiscovery.AudioService, private val service: ServiceDiscovery.AudioService,
private val sendOnChannel: (messageId: Int, body: ByteArray) -> Unit, private val sendOnChannel: (messageId: Int, body: ByteArray) -> Unit,
private val sendControl: (messageId: Int, body: ByteArray) -> Unit, private val sendControl: (messageId: Int, body: ByteArray) -> Unit,
/** Log name: "audio" for the media sink, "guidance" for the directions sink. */
private val tag: String = "audio",
private val sessionId: Int = SESSION_ID,
/** Media asks the car for focus; directions just start, and the car ducks music under them. */
private val asksFocus: Boolean = true,
private val onReady: (AudioLink) -> Unit = { CarAudio.attach(it) },
private val onClose: (AudioLink) -> Unit = { CarAudio.detach(it) },
/** The car took the sound back after giving it, as when the driver switches to the radio. */
private val onTakenBack: () -> Unit = {},
) : CarAudio.Link { ) : CarAudio.Link {
private var configIndex = 0 private var configIndex = 0
@Volatile private var ready = false @Volatile private var ready = false
@Volatile private var started = false @Volatile private var started = false
@Volatile private var focusGranted = false
@Volatile private var focusRequested = false
@Volatile private var inFlight = 0 @Volatile private var inFlight = 0
// The Uconnect asks for 4 on its video channel; assume the same until its Config says otherwise. @Volatile private var maxUnacked = 8
@Volatile private var maxUnacked = 4
@Volatile private var lastAckAt = 0L @Volatile private var lastAckAt = 0L
private var stalls = 0
private var chunks = 0 private var chunks = 0
private var bytes = 0L
private var dropped = 0
@Volatile private var configTimer: Thread? = null
private val ackLock = Object()
/** Only for a sink that takes AAC and nothing else; PCM sinks get the capture as it is. */
@Volatile private var aac: AacEncoder? = null
private val aacSink get() = service.codecType == ServiceDiscovery.CODEC_AAC_LC || service.codecType == ServiceDiscovery.CODEC_AAC_LC_ADTS
private val config get() = service.configs.getOrNull(configIndex) ?: service.configs.firstOrNull() private val config get() = service.configs.getOrNull(configIndex) ?: service.configs.firstOrNull()
override val sampleRate get() = config?.sampleRate ?: 48_000 override val sampleRate get() = config?.sampleRate ?: 48_000
@@ -59,54 +39,12 @@ class AudioLink(
val channelId get() = service.serviceId val channelId get() = service.serviceId
fun opened(status: Int) { fun opened(status: Int) {
GearslipLog.i("$tag: <- ChannelOpenResponse: status=$status")
if (status != 0) { if (status != 0) {
GearslipLog.w("$tag: the head unit refused the $tag channel (status $status)") GearslipLog.w("audio: the head unit refused the media audio channel (status $status)")
return return
} }
// Setup { required MediaCodecType type = 1 }: the codec the car advertised for this sink
// (aasdk's current protos, and LIVI reads it as the codec). Gearslip used to send 0 here,
// read from an older proto as a config index; 0 is no codec at all, and the 2024 VW
// answered UNEXPECTED_MESSAGE (id 255), never acked a chunk and played nothing.
sendOnChannel(MSG_SETUP, Protobuf.varintField(1, service.codecType.toLong())) sendOnChannel(MSG_SETUP, Protobuf.varintField(1, service.codecType.toLong()))
GearslipLog.i("$tag: -> Setup(codec=${service.codecName}) on channel ${service.serviceId}") GearslipLog.i("audio: -> Setup(codec=${service.codecName})")
armConfigFallback()
}
/**
* The 2018 Uconnect, a Dacia ULC 4.5 and the 2024 VW answered the old Setup (codec 0) with
* UNEXPECTED_MESSAGE (id 255, no body) rather than a Config, so the sink never reached READY.
* [MSG_SETUP_ANSWER] still takes that as the go-ahead, in case a car rejects the real codec too.
*
* Service discovery already told us everything a Config would have: the sink's rate, channels
* and its one configuration. So for a car that answers nothing at all, wait a moment and then
* assume the advertised configuration. If that guess is wrong the head unit simply will not
* ack, which the write path already reports.
*/
private fun armConfigFallback() {
val timer = Thread({
try {
Thread.sleep(CONFIG_WAIT_MS)
} catch (e: InterruptedException) {
return@Thread
}
useAdvertisedSink("no usable Config after ${CONFIG_WAIT_MS}ms")
}, "gearslip-audio-config").apply { isDaemon = true }
configTimer = timer
timer.start()
}
@Synchronized
private fun useAdvertisedSink(why: String) {
if (ready) return
configTimer?.interrupt()
GearslipLog.i(
"$tag: $why - using the sink the head unit advertised " +
"(${sampleRate}Hz x$channels, config_index=0, max_unacked=$maxUnacked)",
)
configIndex = 0
ready = true
onReady(this)
} }
fun onMessage(messageId: Int, body: ByteArray) { fun onMessage(messageId: Int, body: ByteArray) {
@@ -118,176 +56,77 @@ class AudioLink(
val status = Wire.varint(fields, 1)?.toInt() val status = Wire.varint(fields, 1)?.toInt()
val window = Wire.varint(fields, 2)?.toInt() val window = Wire.varint(fields, 2)?.toInt()
val indices = fields.filter { it.number == 3 && it.wireType == 0 }.map { it.varint.toInt() } val indices = fields.filter { it.number == 3 && it.wireType == 0 }.map { it.varint.toInt() }
GearslipLog.i("$tag: <- Config status=$status max_unacked=$window indices=$indices") GearslipLog.i("audio: <- Config status=$status max_unacked=$window indices=$indices")
if (window != null) maxUnacked = maxOf(1, window) if (window != null) maxUnacked = maxOf(1, window)
configIndex = indices.firstOrNull() ?: 0 configIndex = indices.firstOrNull() ?: 0
if (status == STATUS_READY) { if (status == STATUS_READY) {
configTimer?.interrupt()
ready = true ready = true
GearslipLog.i("$tag: sink ready - ${sampleRate}Hz x$channels ${config?.bits}bit") GearslipLog.i("audio: ready - ${sampleRate}Hz x$channels ${config?.bits}bit")
onReady(this) CarAudio.attach(this)
} else {
GearslipLog.w(
"$tag: the sink is not ready (status=$status, 1=WAIT 2=READY) - " +
"nothing will be sent until it is",
)
} }
} }
MSG_ACK -> { MSG_ACK -> {
val acked = Wire.varint(Wire.fields(body), 2)?.toInt() ?: 1 val acked = Wire.varint(Wire.fields(body), 2)?.toInt() ?: 1
synchronized(ackLock) {
inFlight = maxOf(0, inFlight - maxOf(1, acked)) inFlight = maxOf(0, inFlight - maxOf(1, acked))
lastAckAt = System.currentTimeMillis() lastAckAt = System.currentTimeMillis()
ackLock.notifyAll() }
else -> GearslipLog.i("audio: <- unhandled message id=$messageId (${body.size} bytes)")
} }
} }
// Whatever else the head unit answers Setup with, we need its bytes to identify it.
else -> if (messageId == MSG_SETUP_ANSWER && body.isEmpty()) {
useAdvertisedSink("<- empty Setup answer (id $messageId)")
} else {
GearslipLog.i("$tag: <- unhandled message id=$messageId (${body.size} bytes)")
GearslipLog.hex(" audio msg", body, limit = 64)
}
}
}
/**
* The head unit's answer to our AudioFocusRequest. Until it grants focus the sink is wired to
* whatever else the car is playing - the radio, usually - and anything we send is discarded,
* so [start] waits here rather than streaming into nothing.
*/
fun onFocus(state: Int) { fun onFocus(state: Int) {
val name = FOCUS_STATES[state] ?: "unknown($state)" GearslipLog.i("audio: <- AudioFocus state=$state (1=GAIN, 2=GAIN_TRANSIENT, 3=LOSS, 4=LOSS_TRANSIENT)")
GearslipLog.i("$tag: <- AudioFocusResponse state=$name")
val had = focusGranted
focusGranted = state == FOCUS_STATE_GAIN || state == FOCUS_STATE_GAIN_TRANSIENT ||
state == FOCUS_STATE_GAIN_MEDIA_ONLY
if (focusGranted) startStream() else stop()
// A ducking request leaves the music playing; a loss means another source has the speakers.
if (had && (state == FOCUS_STATE_LOSS || state == FOCUS_STATE_LOSS_TRANSIENT)) onTakenBack()
} }
override fun start() { override fun start() {
if (!ready || started) return if (!ready || started) return
if (asksFocus && !focusRequested) {
focusRequested = true
sendControl(MSG_FOCUS_REQUEST, Protobuf.varintField(1, FOCUS_GAIN.toLong())) sendControl(MSG_FOCUS_REQUEST, Protobuf.varintField(1, FOCUS_GAIN.toLong()))
GearslipLog.i("$tag: -> AudioFocusRequest(GAIN); waiting for the head unit to hand the sink over")
}
// Some head units grant the sink silently and never answer. Do not let that be the end of
// it: start anyway, and let the acks say whether anything is being taken.
startStream()
}
private fun startStream() {
if (!ready || started) return
sendOnChannel( sendOnChannel(
MSG_START, MSG_START,
Protobuf.varintField(1, sessionId.toLong()) + Protobuf.varintField(2, configIndex.toLong()), Protobuf.varintField(1, SESSION_ID.toLong()) + Protobuf.varintField(2, configIndex.toLong()),
) )
inFlight = 0 inFlight = 0
lastAckAt = System.currentTimeMillis() lastAckAt = System.currentTimeMillis()
if (aacSink && aac == null) {
aac = runCatching { AacEncoder(sampleRate, channels, adts = service.codecType == ServiceDiscovery.CODEC_AAC_LC_ADTS) }
.onSuccess { GearslipLog.i("$tag: the car takes ${service.codecName} only - encoding to AAC") }
.onFailure { GearslipLog.e("$tag: couldn't start the AAC encoder", it) }
.getOrNull()
}
started = true started = true
GearslipLog.i("$tag: -> Start(session=$sessionId, config=$configIndex) - streaming ${sampleRate}Hz x$channels") GearslipLog.i("audio: -> AudioFocusRequest(GAIN), Start(config=$configIndex)")
} }
override fun stop() { override fun stop() {
if (!started) return if (!started) return
started = false started = false
synchronized(ackLock) { ackLock.notifyAll() }
runCatching { runCatching {
sendOnChannel(MSG_STOP, Protobuf.varintField(1, sessionId.toLong())) sendOnChannel(MSG_STOP, Protobuf.varintField(1, SESSION_ID.toLong()))
if (focusRequested) sendControl(MSG_FOCUS_REQUEST, Protobuf.varintField(1, FOCUS_RELEASE.toLong())) sendControl(MSG_FOCUS_REQUEST, Protobuf.varintField(1, FOCUS_RELEASE.toLong()))
} }
focusRequested = false GearslipLog.i("audio: -> Stop, AudioFocusRequest(RELEASE) after $chunks chunks")
focusGranted = false
aac?.release()
aac = null
GearslipLog.i("$tag: -> Stop, AudioFocusRequest(RELEASE) after $chunks chunks / $bytes bytes")
chunks = 0 chunks = 0
bytes = 0
} }
override fun write(pcm: ByteArray, size: Int) { override fun write(pcm: ByteArray, size: Int) {
if (!started) return if (!started) return
val encoder = aac if (inFlight >= maxUnacked) {
if (encoder == null) {
send(pcm.copyOf(size))
return
}
val frames = try {
encoder.encode(pcm, size)
} catch (e: Exception) {
// A codec that dies mid-drive leaves the car silent, as it was before AAC; log it once.
GearslipLog.e("$tag: AAC encoding failed - no more audio this drive", e)
aac = null
started = false
return
}
frames.forEach(::send)
}
/** One Data message, once the car has room for it. */
private fun send(payload: ByteArray) {
// Wait for the car to catch up rather than throw the chunk away: a dropped chunk is a gap
// the driver hears, while a short wait is soaked up by the capture buffer behind us.
synchronized(ackLock) {
while (started && inFlight >= maxUnacked) {
val waited = System.currentTimeMillis() - lastAckAt
if (waited > STALL_MS) {
// A lost ack must not silence the stream for good; after a stall assume the window cleared. // A lost ack must not silence the stream for good; after a stall assume the window cleared.
// A car that never acks (the 2024 VW, the Bolt) hits this every chunk: say so if (System.currentTimeMillis() - lastAckAt > STALL_MS) inFlight = 0 else return
// once, then now and then, so the rest of the log stays readable.
if (stalls++ % 500 == 0) {
GearslipLog.w("$tag: no ack for ${STALL_MS}ms with $inFlight in flight - reopening the window ($stalls times)")
}
inFlight = 0
break
}
ackLock.wait(STALL_MS - waited + 1)
}
}
if (!started) {
dropped++
return
} }
val timestamp = ByteArray(8) val timestamp = ByteArray(8)
val micros = System.nanoTime() / 1_000 val micros = System.nanoTime() / 1_000
for (i in 0 until 8) timestamp[i] = ((micros shr ((7 - i) * 8)) and 0xFF).toByte() for (i in 0 until 8) timestamp[i] = ((micros shr ((7 - i) * 8)) and 0xFF).toByte()
try { try {
sendOnChannel(MSG_DATA, timestamp + payload) sendOnChannel(MSG_DATA, timestamp + pcm.copyOf(size))
} catch (e: java.io.IOException) { } catch (e: java.io.IOException) {
GearslipLog.e("$tag: the link died mid-stream", e)
started = false started = false
return return
} }
synchronized(ackLock) { inFlight++ } inFlight++
chunks++ chunks++
bytes += payload.size
// The first chunk proves the whole path; after that, an occasional line is enough to show
// the car is still taking audio and to catch a window that has quietly closed.
if (chunks == 1 || chunks % CHUNK_LOG_EVERY == 0) {
GearslipLog.i(
"$tag: -> $chunks chunks / $bytes bytes, inFlight=$inFlight/$maxUnacked, " +
"dropped=$dropped, focus=${if (focusGranted) "granted" else "not granted"}",
)
}
} }
fun close() { fun close() {
configTimer?.interrupt()
configTimer = null
stop() stop()
ready = false ready = false
onClose(this) CarAudio.detach(this)
} }
companion object { companion object {
@@ -300,24 +139,10 @@ class AudioLink(
private const val MSG_STOP = 32770 private const val MSG_STOP = 32770
private const val MSG_CONFIG = 32771 private const val MSG_CONFIG = 32771
private const val MSG_ACK = 32772 private const val MSG_ACK = 32772
private const val MSG_SETUP_ANSWER = 255
private const val STATUS_READY = 2 private const val STATUS_READY = 2
private const val FOCUS_GAIN = 1 private const val FOCUS_GAIN = 1
private const val FOCUS_RELEASE = 4 private const val FOCUS_RELEASE = 4
private const val FOCUS_STATE_GAIN = 1
private const val FOCUS_STATE_GAIN_TRANSIENT = 2
private const val FOCUS_STATE_GAIN_MEDIA_ONLY = 6
private const val FOCUS_STATE_LOSS = 3
private const val FOCUS_STATE_LOSS_TRANSIENT = 5
private const val SESSION_ID = 2 private const val SESSION_ID = 2
private const val STALL_MS = 2_000L private const val STALL_MS = 2_000L
private const val CHUNK_LOG_EVERY = 200 // about every four seconds
private const val CONFIG_WAIT_MS = 1_000L
// AudioFocusStateNotification.AudioFocusState in aasdk.
private val FOCUS_STATES = mapOf(
1 to "GAIN", 2 to "GAIN_TRANSIENT", 3 to "LOSS", 4 to "LOSS_TRANSIENT_CAN_DUCK",
5 to "LOSS_TRANSIENT", 6 to "GAIN_MEDIA_ONLY", 7 to "GAIN_TRANSIENT_GUIDANCE_ONLY",
)
} }
} }
@@ -6,15 +6,12 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
/** /**
* Joins the two ends of the audio path: [AudioCaptureService] on the phone, which hears what the * Joins the two ends of the audio path: [AudioCaptureService] on the phone, which hears what a
* phone is playing, and the car's audio channel, which is where it has to end up. * media app plays, and the car's audio channel, which is where it has to end up.
* *
* Capture belongs to the car session, not to any one app. Android grants it through a consent * They come and go independently. The phone side needs on-device consent and can be running on
* dialog that cannot be answered in advance or remembered, so Gearslip asks once, when a head unit * the bench with no car attached; the car side exists only while a head unit is connected and
* first offers a sink to play through, and then holds that grant for as long as the car is * offers a media audio sink. Whichever pair is present, samples flow.
* connected. Switching between media apps, or starting playback from the phone, costs nothing
* further: the capture is by audio usage rather than by app, so whatever the phone plays as media
* goes to the car.
*/ */
object CarAudio { object CarAudio {
@@ -39,8 +36,9 @@ object CarAudio {
/** Set by the activity: shows the permission and consent dialogs, which only it can. */ /** Set by the activity: shows the permission and consent dialogs, which only it can. */
var onConsentRequested: (() -> Unit)? = null var onConsentRequested: (() -> Unit)? = null
/** Whether the driver has asked for the car to be fed at all; see CarSettings.pipeAudio. */ /** The uid being captured (or waited on). */
@Volatile private var wanted = false @Volatile var uid: Int = -1
private set
@Volatile private var link: Link? = null @Volatile private var link: Link? = null
@@ -50,48 +48,30 @@ object CarAudio {
fun attach(link: Link) { fun attach(link: Link) {
this.link = link this.link = link
GearslipLog.i("audio: the car offered a sink at ${link.sampleRate}Hz x${link.channels}") if (_capture.value == Capture.ON) link.start()
when {
_capture.value == Capture.ON -> link.start()
wanted -> ask()
}
} }
fun detach(link: Link) { fun detach(link: Link) {
if (this.link === link) this.link = null if (this.link === link) this.link = null
} }
/** /** A media app was opened: start hearing it. */
* The car wants sound. Safe to call as often as the session likes: the consent dialog appears fun request(uid: Int) {
* at most once, and only once there is a sink to play through - asking on the bench, where the if (this.uid == uid && _capture.value != Capture.OFF && _capture.value != Capture.DENIED) return
* sound has nowhere to go, would put a system dialog in front of the driver for nothing. if (this.uid != uid) AudioCaptureService.stop()
*/ this.uid = uid
fun request() { _capture.value = Capture.ASKING
wanted = true val ask = onConsentRequested
when (_capture.value) { if (ask == null) {
Capture.ON, Capture.ASKING, Capture.DENIED -> return GearslipLog.w("audio: nothing on the phone can ask for capture consent")
Capture.OFF -> if (link == null) { _capture.value = Capture.DENIED
GearslipLog.i("audio: waiting for the car to offer an audio sink")
} else { } else {
ask() ask()
} }
} }
}
private fun ask() {
_capture.value = Capture.ASKING
val request = onConsentRequested
if (request == null) {
GearslipLog.w("audio: nothing on the phone can ask for capture consent")
_capture.value = Capture.DENIED
} else {
request()
}
}
/** The car went away. Everything is torn down; the next connection asks again. */
fun release() { fun release() {
wanted = false uid = -1
AudioCaptureService.stop() AudioCaptureService.stop()
_capture.value = Capture.OFF _capture.value = Capture.OFF
} }
@@ -100,26 +80,6 @@ object CarAudio {
_capture.value = Capture.DENIED _capture.value = Capture.DENIED
} }
private val _micBlocked = MutableStateFlow(false)
/** The microphone permission is off for good: Android refuses without asking, so say why. */
val micBlocked: StateFlow<Boolean> = _micBlocked.asStateFlow()
fun micBlocked() {
_micBlocked.value = true
denied()
}
/** The driver turned the permission back on mid-drive: ask for capture again. */
fun micAllowed() {
if (!_micBlocked.value) return
_micBlocked.value = false
if (_capture.value == Capture.DENIED) {
_capture.value = Capture.OFF
if (wanted) request()
}
}
internal fun captureStarted() { internal fun captureStarted() {
_capture.value = Capture.ON _capture.value = Capture.ON
link?.start() link?.start()
@@ -1,136 +0,0 @@
package app.seb3thehacker.gearslip.audio
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.Protobuf
import app.seb3thehacker.gearslip.ServiceDiscovery
import app.seb3thehacker.gearslip.Wire
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* The car's own microphone, which most head units offer over the same link as the screen:
*
* -> CHANNEL_OPEN_REQUEST <- CHANNEL_OPEN_RESPONSE
* -> Setup { config_index } <- Config
* -> VoiceSessionNotification { START } (control channel)
* -> MicrophoneRequest { open } <- MicrophoneResponse { status, session_id }
* <- Data { 8-byte timestamp, PCM }... -> Ack { session_id, ack }
* -> MicrophoneRequest { open = false }
* -> VoiceSessionNotification { END }
*
* The channel opens with the session, but the car only records between [start] and [stop], and
* only inside a voice session: the 2024 VW answered a bare MicrophoneRequest with status -7.
* Speech wants 16 kHz mono; a car that records at a multiple of that is averaged down to it, and
* one that doesn't isn't used, so voice falls back to the phone's microphone.
*/
class CarMic(
private val service: ServiceDiscovery.AudioService,
private val sendOnChannel: (messageId: Int, body: ByteArray) -> Unit,
private val voiceSession: (start: Boolean) -> Unit,
) {
val channelId get() = service.serviceId
private val config = service.configs.first()
private val step = config.sampleRate / RATE
private val usable = service.codecType == ServiceDiscovery.CODEC_PCM && config.bits == 16 &&
config.sampleRate % RATE == 0 && step >= 1 && config.channels in 1..2
@Volatile private var ready = false
@Volatile private var listening = false
@Volatile private var session = 0
private var packets = 0
private val chunks = LinkedBlockingQueue<ShortArray>()
fun onMessage(messageId: Int, body: ByteArray) {
when (messageId) {
MSG_CHANNEL_OPEN_RESPONSE -> {
val status = Protobuf.readInt32Field(body, 1) ?: 0
GearslipLog.i("mic: <- ChannelOpenResponse: status=$status")
if (status != 0) return
// Setup { type = the codec }, as for audio: 0 got UNEXPECTED_MESSAGE from the VW.
sendOnChannel(MSG_SETUP, Protobuf.varintField(1, service.codecType.toLong()))
ready = usable
if (!usable) {
GearslipLog.w(
"mic: the car records ${service.codecName} ${config.sampleRate}Hz/${config.bits}bit/x${config.channels}, " +
"which speech can't use - voice stays on the phone's microphone",
)
}
}
MSG_CONFIG -> GearslipLog.i("mic: <- Config status=${Wire.varint(Wire.fields(body), 1)}")
MSG_MIC_RESPONSE -> {
val fields = Wire.fields(body)
session = Wire.varint(fields, 2)?.toInt() ?: 0
GearslipLog.i("mic: <- MicrophoneResponse status=${Wire.varint(fields, 1)} session=$session")
}
MSG_DATA -> {
sendOnChannel(MSG_ACK, Protobuf.varintField(1, session.toLong()) + Protobuf.varintField(2, 1L))
if (!listening || body.size <= TIMESTAMP_BYTES) return
if (packets++ == 0) GearslipLog.i("mic: first audio from the car (${body.size - TIMESTAMP_BYTES} bytes)")
chunks.offer(toSpeechRate(body))
}
else -> GearslipLog.i("mic: <- unhandled message id=$messageId (${body.size} bytes)")
}
}
/** Little-endian PCM after the timestamp, mixed to mono and averaged down to [RATE]. */
private fun toSpeechRate(body: ByteArray): ShortArray {
val frameBytes = 2 * config.channels
val frames = (body.size - TIMESTAMP_BYTES) / frameBytes
val out = ShortArray(frames / step)
for (i in out.indices) {
var sum = 0
for (s in 0 until step) {
val at = TIMESTAMP_BYTES + (i * step + s) * frameBytes
for (c in 0 until config.channels) {
val o = at + 2 * c
sum += (body[o].toInt() and 0xFF) or (body[o + 1].toInt() shl 8)
}
}
out[i] = (sum / (step * config.channels)).toShort()
}
return out
}
/** Asks the car to start recording. False when it can't, so the phone's microphone is used. */
fun start(): Boolean {
if (!ready) return false
chunks.clear()
packets = 0
listening = true
voiceSession(true)
sendOnChannel(MSG_MIC_REQUEST, Protobuf.varintField(1, 1L) + Protobuf.varintField(4, 1L))
GearslipLog.i("mic: -> MicrophoneRequest(open)")
return true
}
/** The next piece of audio, or null if the car sent nothing for [timeoutMs]. */
fun read(timeoutMs: Long): ShortArray? = chunks.poll(timeoutMs, TimeUnit.MILLISECONDS)
fun stop() {
if (!listening) return
listening = false
sendOnChannel(MSG_MIC_REQUEST, Protobuf.varintField(1, 0L))
voiceSession(false)
GearslipLog.i("mic: -> MicrophoneRequest(close) after $packets packets, voice session ended")
}
companion object {
/** The connected car's microphone, or null with no car or one that has none. */
@Volatile var current: CarMic? = null
const val RATE = 16_000
private const val TIMESTAMP_BYTES = 8
private const val MSG_CHANNEL_OPEN_RESPONSE = 8
private const val MSG_DATA = 0
private const val MSG_SETUP = 32768
private const val MSG_CONFIG = 32771
private const val MSG_ACK = 32772
private const val MSG_MIC_REQUEST = 32773
private const val MSG_MIC_RESPONSE = 32774
}
}
@@ -1,64 +0,0 @@
package app.seb3thehacker.gearslip.audio
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.Settings
import app.seb3thehacker.gearslip.GearslipLog
/**
* Keeps the phone's notifications readable while audio is being sent to the car.
*
* Playback capture hangs off a MediaProjection, and since Android 15 any full-screen projection
* makes SystemUI hide notification contents, on the assumption that someone is watching the
* screen. Nobody is: the audio projection never makes a display. The one exemption an ordinary app
* can reach is the developer setting that switches the protection off, so Gearslip turns it off for
* the length of the capture and back on afterwards.
*
* Writing it needs WRITE_SECURE_SETTINGS, granted once over adb. Without the grant this does
* nothing and notifications stay hidden while music plays, which is the platform's default.
*
* Phone mirroring deliberately does not use this: there the screen really is being shown.
*/
internal object ScreenShareGuard {
/** Settings.Global.DISABLE_SCREEN_SHARE_PROTECTIONS_FOR_APPS_AND_NOTIFICATIONS, hidden API. */
private const val SETTING = "disable_screen_share_protections_for_apps_and_notifications"
private const val PREFS = "gearslip_screen_share_guard"
/** Set while Gearslip has the protection switched off, so a crash can be undone at next launch. */
private const val KEY_LIFTED = "lifted"
fun canLift(context: Context): Boolean =
context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) ==
PackageManager.PERMISSION_GRANTED
/** Call before the projection starts: the system decides what to hide at that moment. */
fun lift(context: Context) {
if (!canLift(context)) {
GearslipLog.i("audio: notifications will be hidden while capturing (no WRITE_SECURE_SETTINGS)")
return
}
val resolver = context.contentResolver
// Already off, whether by the driver in Developer options or by us: leave it as found.
if (Settings.Global.getInt(resolver, SETTING, 0) != 0) return
runCatching {
prefs(context).edit().putBoolean(KEY_LIFTED, true).commit()
Settings.Global.putInt(resolver, SETTING, 1)
GearslipLog.i("audio: screen share protection off for the drive, notifications stay visible")
}.onFailure { GearslipLog.w("audio: could not lift screen share protection: ${it.message}") }
}
/** Put the protection back, if Gearslip is the one that took it away. */
fun restore(context: Context) {
if (!prefs(context).getBoolean(KEY_LIFTED, false)) return
runCatching {
Settings.Global.putInt(context.contentResolver, SETTING, 0)
prefs(context).edit().remove(KEY_LIFTED).commit()
GearslipLog.i("audio: screen share protection back on")
}.onFailure { GearslipLog.w("audio: could not restore screen share protection: ${it.message}") }
}
private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
@@ -1,135 +0,0 @@
package app.seb3thehacker.gearslip.call
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.ContactsContract
import android.telecom.TelecomManager
import android.telephony.TelephonyCallback
import android.telephony.TelephonyManager
import app.seb3thehacker.gearslip.GearslipLog
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/** A caller as the car shows it: whatever the contacts app knows, or just the number. */
data class Caller(val number: String, val name: String?) {
val label: String get() = name ?: number.ifBlank { "Unknown number" }
}
sealed interface CallUiState {
data object None : CallUiState
data class Ringing(val caller: Caller, val canDecline: Boolean) : CallUiState
data class Active(val caller: Caller?) : CallUiState
}
/**
* Tracks the phone's call state for the car screen, and answers or declines through the two
* doors a sideloaded app can use: [android.telecom.TelecomManager.acceptRingingCall] to answer,
* and [GearslipCallScreening]'s response to decline one that is still ringing.
*
* Ending a call already answered needs MODIFY_PHONE_STATE, a privileged permission Gearslip
* cannot hold, so a call taken here is finished the way it would be without Gearslip at all -
* from the phone itself, a paired headset, or the car's own Bluetooth if it has any. Call audio
* stays on the phone's normal voice path too; nothing here sends it over the USB link, which
* only ever carries media playback.
*/
object CarCalls {
private val _state = MutableStateFlow<CallUiState>(CallUiState.None)
val state: StateFlow<CallUiState> = _state.asStateFlow()
private var telephony: TelephonyManager? = null
private var watcher: TelephonyCallback? = null
private var pendingRespond: ((allow: Boolean) -> Unit)? = null
private var ringingCaller: Caller? = null
fun start(context: Context) {
if (watcher != null) return
if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) return
val manager = context.getSystemService(TelephonyManager::class.java) ?: return
val callback = object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) = onPhoneState(state)
}
runCatching { manager.registerTelephonyCallback(context.mainExecutor, callback) }
.onSuccess { telephony = manager; watcher = callback }
.onFailure { GearslipLog.w("calls: could not watch call state: ${it.message}") }
}
fun stop() {
val callback = watcher ?: return
runCatching { telephony?.unregisterTelephonyCallback(callback) }
telephony = null
watcher = null
pendingRespond = null
ringingCaller = null
_state.value = CallUiState.None
}
private fun onPhoneState(state: Int) {
when (state) {
TelephonyManager.CALL_STATE_IDLE -> {
pendingRespond = null
ringingCaller = null
_state.value = CallUiState.None
}
TelephonyManager.CALL_STATE_OFFHOOK -> {
pendingRespond = null
_state.value = CallUiState.Active(ringingCaller)
}
TelephonyManager.CALL_STATE_RINGING -> {
// The number itself only ever arrives through the screening service; if this
// fires first, the ringing card appears once incomingCall() catches up.
ringingCaller?.let { _state.value = CallUiState.Ringing(it, pendingRespond != null) }
}
}
}
/** Called by [GearslipCallScreening] the moment a call comes in - the only place with a number. */
fun incomingCall(context: Context, number: String?, respond: (allow: Boolean) -> Unit) {
val caller = Caller(number.orEmpty(), number?.let { lookUpName(context, it) })
ringingCaller = caller
pendingRespond = respond
_state.value = CallUiState.Ringing(caller, canDecline = true)
}
/** The screening window closed by itself - the call rings normally now, and can't be declined from here. */
fun screeningExpired() {
pendingRespond = null
val caller = ringingCaller ?: return
if (_state.value is CallUiState.Ringing) _state.value = CallUiState.Ringing(caller, canDecline = false)
}
fun decline() {
val respond = pendingRespond ?: return
pendingRespond = null
runCatching { respond(false) }.onFailure { GearslipLog.w("calls: decline failed: ${it.message}") }
}
fun answer(context: Context) {
if (context.checkSelfPermission(Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
GearslipLog.w("calls: answer needs ANSWER_PHONE_CALLS, which was never granted")
return
}
val telecom = context.getSystemService(TelecomManager::class.java) ?: return
runCatching { telecom.acceptRingingCall() }
.onFailure { GearslipLog.w("calls: answer failed: ${it.message}") }
}
private fun lookUpName(context: Context, number: String): String? {
if (context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) return null
return runCatching {
val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
context.contentResolver.query(uri, arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull()
}
}
/** Posts to the main thread after a delay - used to give up on a screening response Gearslip never sent. */
internal fun mainThreadDelay(ms: Long, action: () -> Unit) {
Handler(Looper.getMainLooper()).postDelayed(action, ms)
}
@@ -1,53 +0,0 @@
package app.seb3thehacker.gearslip.call
import android.telecom.Call
import android.telecom.CallScreeningService
import app.seb3thehacker.gearslip.GearslipLog
/**
* Sees every incoming call before it rings, so the car screen can show who is calling and
* decline it in the same window a spam-blocker would use. Inert until the driver sets Gearslip
* as the phone's caller ID and spam app - the same on-device consent Truecaller-style apps ask
* for, not a privileged permission.
*
* The system gives an app a few seconds to answer before it lets the call ring on its own, so a
* response is sent either when the driver taps a button or when that window is about to close,
* whichever comes first. Answering a call that has already passed this point still works, since
* [CarCalls.answer] goes through the ordinary ringing-call API rather than through screening.
*/
class GearslipCallScreening : CallScreeningService() {
override fun onScreenCall(callDetails: Call.Details) {
val number = callDetails.handle?.schemeSpecificPart
var responded = false
val respond: (Boolean) -> Unit = { allow ->
if (!responded) {
responded = true
runCatching {
respondToCall(
callDetails,
CallResponse.Builder()
.setDisallowCall(!allow)
.setRejectCall(!allow)
.setSkipNotification(false)
.build(),
)
}.onFailure { GearslipLog.w("calls: screening response failed: ${it.message}") }
}
}
CarCalls.incomingCall(applicationContext, number, respond)
// Answer for the system if nobody has by the time its own patience runs out, so a call
// Gearslip is slow to show never gets silently blocked.
mainThreadDelay(SCREENING_WINDOW_MS) {
respond(true)
CarCalls.screeningExpired()
}
}
private companion object {
const val SCREENING_WINDOW_MS = 3_500L
}
}
@@ -1,385 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.content.Context
import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.speech.VoiceFocus
import java.text.DateFormat
import java.util.Date
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/**
* Turns what [CarAssistant] heard into an action plus something to say back.
*
* Deliberately small and keyword-matched rather than run through any NLU or bundled model: a
* fixed set of things a driver actually wants hands-free (media, calling, opening an app,
* getting back Home), covering the same ground the rest of the car UI already does rather than
* trying to be a general assistant.
*/
object AssistantCommands {
suspend fun handle(context: Context, navigator: CarNavigator, frame: CarEnvironment.Frame, heardRaw: String): String {
val heard = natural(heardRaw)
VoiceHelp.hide()
if (heard in HELP_WORDS || heard.startsWith("what can i say") || heard.startsWith("what can you do")) {
VoiceHelp.show()
return "Here's what you can say."
}
if (heard.matches(Regex("(fuck|f\\*+) (you|off)( too)?"))) return "Fuck you too."
navigateCommand(context, navigator, frame, heard)?.let { return it }
playSearchCommand(context, navigator, heard)?.let { return it }
mediaCommand(heard)?.let { return it }
navCommand(navigator, heard)?.let { return it }
infoCommand(heard)?.let { return it }
callCommand(context, heard)?.let { return it }
openAppCommand(context, navigator, frame, heard)?.let { return it }
return "I don't know how to do that yet."
}
/**
* What was said, minus the padding people wrap a command in: "hey", "can you", "I want to",
* "please", "thanks". Each command below then only has to know its own words.
*/
private fun natural(raw: String): String {
var t = raw.lowercase().replace(Regex("[.,!?]"), " ").replace(Regex("\\s+"), " ").trim()
var changed = true
while (changed) {
changed = false
for (lead in LEAD_FILLERS) if (t.startsWith("$lead ")) { t = t.removePrefix("$lead ").trim(); changed = true }
for (tail in TAIL_FILLERS) if (t.endsWith(" $tail")) { t = t.removeSuffix(" $tail").trim(); changed = true }
}
return t
}
/** The part after the first of [triggers] that [text] starts with, or null. */
private fun after(text: String, triggers: List<String>): String? =
triggers.firstOrNull { text.startsWith(it) }?.let { text.removePrefix(it).trim() }
private suspend fun allEntries(context: Context): List<Entry> {
val vehicleData = CarSettings.experimentalFeaturesEnabled.value && CarSettings.carSensorsEnabled.value
val builtIn = BuiltInApps.entries.filter { it.builtIn !== BuiltInApps.VehicleData || vehicleData }
return builtIn + (LauncherCache.entries ?: withContext(Dispatchers.IO) { LauncherCache.load(context) })
}
/**
* Best label match: exact, then a label starting with [name], then one containing it. Spaces
* and punctuation don't count, since the recognizer may hear "MapQuest" as "map quest".
*/
private fun <T> bestMatch(items: List<T>, name: String, label: (T) -> String): T? {
val n = squash(name.removePrefix("the ").removePrefix("my ").removeSuffix(" app"))
if (n.isEmpty()) return null
items.firstOrNull { squash(label(it)) == n }?.let { return it }
// Loose matches need a real word: "pizza in a" mustn't pick "Organic Maps" for its "a".
if (n.length < 3) return null
return items.firstOrNull { squash(label(it)).startsWith(n) }
?: items.firstOrNull { squash(label(it)).contains(n) }
}
private fun squash(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
/**
* "navigate to X [with|using|on|via Y]" - Y picks the nav app by (partial) label; without it,
* whichever nav app was used last, or the only one installed, or the first one found. Starts
* it straight into navigating there via [CarAppConnection]'s `ACTION_NAVIGATE` deep link -
* the same one Android Auto's own Assistant integration uses - rather than opening the app
* and leaving the driver to type the address in on the car keyboard.
*/
private suspend fun navigateCommand(
context: Context,
navigator: CarNavigator,
frame: CarEnvironment.Frame,
heard: String,
): String? {
// "use Organic Maps to get to X", "open OsmAnd and navigate to X": the app comes first.
var text = heard
var leadingApp: String? = null
Regex("^(?:use|using|with|open|in|on) (.+?) (?:to |and )(.+)$").find(text)?.let { m ->
if (after(m.groupValues[2], NAVIGATE_TRIGGERS) != null) {
leadingApp = m.groupValues[1]
text = m.groupValues[2]
}
}
var destination = after(text, NAVIGATE_TRIGGERS) ?: return null
if (destination.isBlank()) return "Where to?"
val entries = allEntries(context)
// "go to Spotify" means the app, and "go to settings" the screen; "go to Target" is a place.
val asApp = destination.removePrefix("the ").removeSuffix(" app")
if (text.startsWith("go to ") &&
(asApp in SCREEN_WORDS || asApp in APP_NICKNAMES || entries.any { it.label.lowercase() == asApp })
) {
return null
}
val navApps = entries.filter { it.template?.isNavigation == true }
if (navApps.isEmpty()) return "You don't have any navigation apps installed."
// "X with Organic Maps", "X on OsmAnd": split only when the end names a nav app, so a
// place like "Starbucks on Main Street" stays whole.
var chosenApp = leadingApp?.let { name -> bestMatch(navApps, name) { it.label } ?: return "I couldn't find a navigation app called $name." }
if (chosenApp == null) {
for (sep in listOf(" with ", " using ", " on ", " via ", " in ", " through ")) {
val at = destination.lastIndexOf(sep)
if (at <= 0) continue
val app = bestMatch(navApps, destination.substring(at + sep.length)) { it.label } ?: continue
chosenApp = app
destination = destination.substring(0, at).trim()
break
}
}
// "the nearest gas station" -> "gas station": the map app already searches around the car
// and AutoRoute picks the nearest result, and Organic Maps took "nearest" as part of the name.
val (place, nearby) = plainPlace(destination)
destination = place
if (destination.isBlank()) return "Where to?"
val chosen = chosenApp ?: when {
navApps.size == 1 -> navApps.first()
else -> navApps.firstOrNull { it.componentId == CarSettings.lastNav.value } ?: navApps.first()
}
val template = chosen.template ?: return "That's not a navigation app."
CarServices.connectNav(template, frame, destination)
navigator.home()
return if (nearby) "Finding the nearest $destination with ${chosen.label}." else "Navigating to $destination with ${chosen.label}."
}
/** [destination] without "a", "the nearest", "near me" and the like, and whether any of that said "close by". */
private fun plainPlace(destination: String): Pair<String, Boolean> {
var t = destination
var nearby = false
var changed = true
while (changed) {
changed = false
for (lead in PLACE_LEADS) if (t.startsWith(lead)) {
t = t.removePrefix(lead).trim(); changed = true
if (lead.trim() !in ARTICLES) nearby = true
}
for (tail in PLACE_TAILS) if (t.endsWith(tail)) { t = t.removeSuffix(tail).trim(); changed = true; nearby = true }
}
return t to nearby
}
/**
* "play X" with something after it: a song, artist, album or playlist, asked of the music app
* that's open through its own search ([CarMedia.search]). A bare "play", or "play music",
* falls through to resume.
*/
private suspend fun playSearchCommand(context: Context, navigator: CarNavigator, heard: String): String? {
var query = after(heard, PLAY_TRIGGERS) ?: return null
query = query.removePrefix("some ").trim()
if (query.isEmpty() || query in RESUME_WORDS) return null
val media = CarServices.media
// "play Daft Punk on Metrolist": switch to that app first, if it's one we know.
for (sep in listOf(" on ", " in ", " from ", " with ", " using ")) {
val at = query.lastIndexOf(sep)
if (at <= 0) continue
val apps = withContext(Dispatchers.IO) { app.seb3thehacker.gearslip.media.MediaCatalog.installed(context) }
val wanted = bestMatch(apps, query.substring(at + sep.length)) { it.label } ?: continue
query = query.substring(0, at).trim()
if (query.isEmpty() || query in RESUME_WORDS) {
CarServices.openMedia(wanted, autoplay = true)
navigator.media()
return "Opening ${wanted.label}."
}
if (CarServices.mediaApp.value?.component != wanted.component) {
CarServices.openMedia(wanted)
navigator.media()
// Give it a moment to connect before asking it to search.
withTimeoutOrNull(APP_CONNECT_MS) {
while (media.appLabel == null || (!media.canSearchLibrary && !media.now.value.canSearch)) delay(200)
}
}
break
}
// No music app open, or its connection is gone (the app was closed): use the one played
// last, the way "play X" works on Android Auto.
val phase = media.phase.value
if (media.appLabel == null || phase == CarMedia.Phase.IDLE || phase == CarMedia.Phase.REJECTED) {
if (!CarServices.reopenLastMedia()) return "Open a music app first, then ask again."
navigator.media()
}
withTimeoutOrNull(APP_CONNECT_MS) {
while (media.phase.value != CarMedia.Phase.READY || media.appLabel == null ||
(!media.canSearchLibrary && !media.now.value.canSearch)
) delay(200)
}
val app = media.appLabel ?: return "Your music app didn't open in time. Try again."
if (!media.canSearchLibrary && !media.now.value.canSearch) {
return "$app ignores voice searches. Pick something on its screen instead."
}
media.playBestMatch(query)
return "Looking for $query on $app."
}
private fun mediaCommand(heard: String): String? {
val media = CarServices.media
return when {
"pause" in heard || heard.startsWith("stop") || heard == "quiet" || heard == "shut up" -> {
media.pause()
VoiceFocus.afterRelease { media.pause() }
"Paused."
}
"resume" in heard || "unpause" in heard || heard in RESUME_PHRASES ||
(heard.startsWith("play") && "playing" !in heard) -> {
if (!media.now.value.playing) media.togglePlay()
"Playing."
}
"next" in heard || "skip" in heard || heard.startsWith("change the song") -> {
media.next()
"Skipping."
}
"previous" in heard || "last song" in heard || "back song" in heard || "go back a song" in heard ||
"play that again" in heard || "replay" in heard -> {
media.previous()
"Playing the previous track."
}
("what" in heard && "playing" in heard) || "what song" in heard || "who sings" in heard ||
"who's singing" in heard || "who is singing" in heard || "what's this song" in heard ||
"name of this song" in heard -> {
val now = media.now.value
if (now.isActive) listOf(now.title, now.artist).filter { it.isNotBlank() }.joinToString(" by ")
else "Nothing's playing."
}
else -> null
}
}
private fun navCommand(navigator: CarNavigator, heard: String): String? = when {
heard == "go back" || heard == "back" -> {
navigator.back()
"Going back."
}
heard in EXIT_WORDS -> {
BuiltInApps.Exit.open(navigator)
"Back to the car's screen."
}
"go home" in heard || heard == "home" || heard == "home screen" || "go to the home screen" in heard -> {
navigator.home()
"Heading home."
}
"open apps" in heard || heard == "apps" || "app list" in heard || "all apps" in heard || "my apps" in heard || heard == "go to apps" -> {
navigator.apps()
"Here are your apps."
}
"settings" in heard -> {
navigator.settings()
"Opening settings."
}
"vehicle data" in heard || "car data" in heard -> {
if (CarSettings.experimentalFeaturesEnabled.value && CarSettings.carSensorsEnabled.value) {
navigator.vehicleData()
"Opening vehicle data."
} else {
"Vehicle data is off. Turn it on under experimental features in settings."
}
}
else -> null
}
private fun infoCommand(heard: String): String? = when {
"what time" in heard || "what's the time" in heard || heard == "time" || "the time" in heard ->
"It's ${DateFormat.getTimeInstance(DateFormat.SHORT).format(Date())}."
"weather" in heard || "going to rain" in heard || "gonna rain" in heard || "how hot" in heard ||
"how cold" in heard || "temperature outside" in heard -> {
val data = (Weather.state.value as? WeatherState.Ready)?.data
if (data != null) "${data.temp}${data.tempUnit} and ${Weather.describe(data.code)} in ${data.place}."
else "I don't have the weather yet."
}
else -> null
}
private suspend fun callCommand(context: Context, heard: String): String? {
val name = (
after(heard, CALL_TRIGGERS)
?: Regex("^give (.+) a (?:call|ring)$").find(heard)?.groupValues?.get(1)
?: return null
).replace(Regex(" (?:on|at) (?:their |his |her )?(?:mobile|cell|phone|home|work)$"), "").trim()
if (name.isBlank()) return "Who should I call?"
if (!hasCallPermissions(context)) return "Gearslip needs the phone and contacts permissions first, from the phone screen."
val match = withContext(Dispatchers.IO) {
loadContacts(context).firstOrNull { it.name.lowercase().contains(name) }
} ?: return "I couldn't find $name in your contacts."
placeCall(context, match.number)
return "Calling ${match.name}."
}
private suspend fun openAppCommand(
context: Context,
navigator: CarNavigator,
frame: CarEnvironment.Frame,
heard: String,
): String? {
val name = (after(heard, OPEN_TRIGGERS) ?: return null)
.removePrefix("the ").removePrefix("my ").removeSuffix(" app").trim()
if (name.isBlank()) return null
val wanted = APP_NICKNAMES[name] ?: name
// Gearslip's own apps come first in the list, so "phone" opens its dialer, not the phone's.
val match = bestMatch(allEntries(context), wanted) { it.label }
?: return "I couldn't find an app called $name."
launchEntry(match, navigator, frame)
return "Opening ${match.label}."
}
private val EXIT_WORDS = setOf("exit", "exit gearslip", "close gearslip", "quit", "quit gearslip", "open exit")
/** Other names people use for Gearslip's own apps. */
private val APP_NICKNAMES = mapOf(
"web" to "browser", "internet" to "browser", "the web" to "browser", "web browser" to "browser",
"dialer" to "phone", "the dialer" to "phone", "keypad" to "phone",
"screen share" to "screen sharing", "screen mirroring" to "screen sharing", "mirroring" to "screen sharing",
)
private val NAVIGATE_TRIGGERS = listOf(
"navigate to ", "navigate me to ", "directions to ", "get directions to ", "give me directions to ",
"take me to ", "drive to ", "drive me to ", "get me to ", "go to ", "head to ", "route to ",
"how do i get to ", "show me the way to ", "find a route to ", "navigation to ", "get to ",
// Last, so "navigate to" wins: the recognizer sometimes drops the "to".
"navigate me ", "navigate ", "find me the nearest ", "find the nearest ", "find the closest ",
)
private val ARTICLES = setOf("a", "an", "the", "some")
// Longest first, so "the nearest " goes before "the ".
private val PLACE_LEADS = listOf(
"the nearest ", "the closest ", "a nearby ", "the nearby ", "nearest ", "closest ", "nearby ",
"a ", "an ", "some ",
)
private val PLACE_TAILS = listOf(" near me", " nearby", " near here", " around here", " close by", " closest to me")
private val PLAY_TRIGGERS = listOf("play me ", "play ", "put on ", "listen to ", "i want to hear ", "shuffle ")
private val CALL_TRIGGERS = listOf("call ", "phone ", "dial ", "ring ", "make a call to ", "place a call to ", "start a call with ")
private val OPEN_TRIGGERS = listOf("open ", "launch ", "start ", "go to ", "switch to ", "show me ", "bring up ", "pull up ")
/** Screens "go to X" means rather than a place. */
private val SCREEN_WORDS = setOf("settings", "home", "the home screen", "home screen", "apps", "my apps", "all apps")
/** Padding stripped from the front of a command, longest first where they overlap. */
private val LEAD_FILLERS = listOf(
"hey gearslip", "ok gearslip", "okay gearslip", "gearslip", "hey", "ok", "okay", "um", "uh", "so",
"please", "can you please", "can you", "could you", "would you", "will you", "can i", "could i",
"i want you to", "i want to", "i'd like to", "i would like to", "i wanna", "i need to", "i need you to",
"let's", "lets", "go ahead and", "just", "now", "quickly",
)
/** Longest first, so "right now" goes whole rather than leaving "right". */
private val TAIL_FILLERS = listOf("thank you very much", "thank you", "right now", "for me", "please", "thanks", "now")
private const val APP_CONNECT_MS = 5_000L
private val HELP_WORDS = setOf("help", "commands", "voice commands", "list commands", "show commands")
private val RESUME_WORDS = setOf("music", "the music", "some music", "something", "it", "again", "that", "my music")
private val RESUME_PHRASES = setOf("keep playing", "continue", "keep going", "start the music", "music on", "turn the music back on")
}
@@ -1,140 +0,0 @@
package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import app.seb3thehacker.gearslip.R
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
/**
* What the assistant hears and says, laid over the bottom of whatever screen is up: a dark shade
* so white words read over a bright map, and a glow along the bottom edge in the phone's own
* colours that breathes while listening. The shade passes touches through; only the buttons take them.
*/
@Composable
fun AssistantOverlay(modifier: Modifier = Modifier) {
val state by CarAssistant.state.collectAsState()
if (state.phase == CarAssistant.Phase.IDLE) return
val context = LocalContext.current
val listening = state.phase == CarAssistant.Phase.LISTENING && state.ready
val glow = MaterialTheme.colorScheme.primary
val glow2 = MaterialTheme.colorScheme.tertiary
val breathe by rememberInfiniteTransition(label = "glow").animateFloat(
0.55f, 1f, infiniteRepeatable(tween(900, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "glow",
)
val strength = when (state.phase) {
CarAssistant.Phase.LISTENING -> if (state.ready) breathe else 0.3f
CarAssistant.Phase.ERROR -> 0.3f
else -> 0.6f
}
Box(
modifier
.fillMaxWidth()
.drawBehind {
drawRect(Brush.verticalGradient(0f to Color.Transparent, 0.45f to Color.Black.copy(alpha = 0.6f), 1f to Color.Black.copy(alpha = 0.85f)))
// A wide, flat oval of light rising from the bottom edge.
scale(1f, 0.22f, Offset(size.width / 2, size.height)) {
drawCircle(
Brush.radialGradient(
0f to glow.copy(alpha = 0.9f * strength), 0.5f to glow2.copy(alpha = 0.35f * strength), 1f to Color.Transparent,
center = Offset(size.width / 2, size.height), radius = size.width * 0.55f,
),
radius = size.width * 0.55f, center = Offset(size.width / 2, size.height),
)
}
}
.padding(start = 16.dp, end = 16.dp, top = 56.dp, bottom = 20.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
PulsingMic(listening)
Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) {
val (small, big) = when (state.phase) {
CarAssistant.Phase.LISTENING -> "" to state.heard.ifBlank { if (state.ready) "Listening…" else "One moment…" }
CarAssistant.Phase.THINKING -> "" to state.heard.ifBlank { "…" }
else -> state.heard to state.reply
}
if (small.isNotBlank()) {
Text(small, color = Color.White.copy(alpha = 0.7f), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(
big,
color = if (big == "Listening…" || big == "One moment…" || big == "…") Color.White.copy(alpha = 0.7f) else Color.White,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
if (state.missingPermission) {
GsButton(tone = GsTone.Tonal, onClick = {
context.startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null)),
)
}) { Text("Grant") }
}
GsIconButton(Icons.Filled.Close, "Dismiss", CarAssistant::cancel)
}
}
}
/** A filled circle with a mic glyph, pulsing gently while actually listening. */
@Composable
private fun PulsingMic(listening: Boolean, modifier: Modifier = Modifier) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary,
modifier = modifier.size(36.dp),
) {
Row(horizontalArrangement = Arrangement.Center) {
MicGlyph(Modifier.padding(8.dp).size(20.dp))
}
}
// `listening` only changes what's drawn elsewhere in the row (the "Listening…" label);
// the glyph itself doesn't need to animate for this to read clearly on a glance.
}
/** The assistant's mic, from `R.drawable.mic_24`, tinted with the current content colour. */
@Composable
fun MicGlyph(modifier: Modifier = Modifier) {
Icon(ImageVector.vectorResource(R.drawable.mic_24), contentDescription = "Assistant", modifier = modifier)
}
@@ -1,146 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothA2dp
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Looper
import app.seb3thehacker.gearslip.GearslipLog
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* With Bluetooth audio chosen, music only reaches the car if the phone is connected to it over
* Bluetooth. Twenty seconds after the car shows Gearslip, long enough for a car to connect on its
* own, this checks. If the phone isn't connected, the car and the phone's Home screen both say so,
* until it connects or the drive ends.
*
* When the car named its Bluetooth address, only that device counts. Otherwise any audio
* connection does, since there's no telling which device is the car.
*/
object BluetoothAudioCheck {
private val _missing = MutableStateFlow(false)
/** True while Bluetooth audio is chosen and the phone isn't connected to the car for it. */
val missing: StateFlow<Boolean> = _missing
private val _carDismissed = MutableStateFlow(false)
/** The driver tapped OK on the car's card; it stays away for the rest of this drive. */
val carDismissed: StateFlow<Boolean> = _carDismissed
private val log = GearslipLog.tagged("bluetooth")
private val main = Handler(Looper.getMainLooper())
private var appContext: Context? = null
private var armed = false
private var receiver: BroadcastReceiver? = null
fun init(context: Context) {
appContext = context.applicationContext
}
/** The car shows Gearslip. Called again whenever the video restarts, so it arms once per drive. */
fun onProjecting() = main.post {
if (armed) return@post
armed = true
main.postDelayed(::start, WAIT_MS)
}
fun onCarDisconnected() = main.post {
armed = false
main.removeCallbacksAndMessages(null)
stopWatching()
_missing.value = false
_carDismissed.value = false
}
fun dismissOnCar() {
_carDismissed.value = true
}
/** "Don't show again" on the car: turns the warning off in Settings, for every car. */
fun neverAgain() {
CarSettings.setBluetoothWarning(false)
log.i("Bluetooth audio warning turned off")
_carDismissed.value = true
_missing.value = false
}
private fun start() {
if (!armed) return
check()
// Connecting later clears the warning, and losing the connection brings it back.
val context = appContext ?: return
val r = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
main.postDelayed(::check, SETTLE_MS)
}
}
context.registerReceiver(
r,
IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED).apply {
addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
},
Context.RECEIVER_EXPORTED,
)
receiver = r
}
@SuppressLint("MissingPermission")
private fun check() {
if (!armed) return
val context = appContext ?: return
if (CarSettings.pipeAudio.value) {
set(false, "USB audio is on")
return
}
if (!CarSettings.bluetoothWarning.value) {
set(false, "the warning is turned off")
return
}
if (context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
log.i("can't check the audio connection: the Bluetooth permission isn't granted")
return
}
val adapter = context.getSystemService(BluetoothManager::class.java)?.adapter ?: return
if (!adapter.isEnabled) {
set(true, "Bluetooth is off")
return
}
val car = CarBluetooth.carAddress?.uppercase()
adapter.getProfileProxy(context, object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
val connected = runCatching { proxy.connectedDevices }.getOrDefault(emptyList())
adapter.closeProfileProxy(profile, proxy)
val ok = if (car != null) connected.any { it.address.uppercase() == car } else connected.isNotEmpty()
main.post {
set(!ok, if (ok) "connected to the car" else "not connected to the car")
}
}
override fun onServiceDisconnected(profile: Int) {}
}, BluetoothProfile.A2DP)
}
private fun set(missing: Boolean, why: String) {
if (!armed || _missing.value == missing) return
_missing.value = missing
log.i("Bluetooth audio: $why")
}
private fun stopWatching() {
val r = receiver ?: return
receiver = null
runCatching { appContext?.unregisterReceiver(r) }
}
private const val WAIT_MS = 20_000L
private const val SETTLE_MS = 1_000L
}
@@ -1,118 +0,0 @@
package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
/**
* Asks once per car whether to pair it over Bluetooth, then waits while the phone shows its
* pairing dialog. See [CarBluetooth]. With no pairing to do, says when Bluetooth audio isn't
* connected (see [BluetoothAudioCheck]), or else when the phone's location is off (see
* [LocationCheck]). Unlike the call prompt, a tap outside the card does nothing:
* the driver picks Pair or Not now.
*/
@Composable
internal fun BluetoothPairOverlay() {
val prompt by CarBluetooth.prompt.collectAsState()
val bluetoothAudio = !CarSettings.pipeAudio.collectAsState().value
when (prompt) {
CarBluetooth.Prompt.NONE -> {
val missing by BluetoothAudioCheck.missing.collectAsState()
val dismissed by BluetoothAudioCheck.carDismissed.collectAsState()
val warn by CarSettings.bluetoothWarning.collectAsState()
val locationOff by LocationCheck.off.collectAsState()
val locationDismissed by LocationCheck.carDismissed.collectAsState()
if (missing && bluetoothAudio && warn && !dismissed) PairCard(
title = "Bluetooth isn't connected",
body = "Music plays over Bluetooth, but your phone isn't connected to the car. " +
"Connect it from the car's Bluetooth menu or your phone's.",
secondary = "Don't show again" to BluetoothAudioCheck::neverAgain,
primary = "OK" to BluetoothAudioCheck::dismissOnCar,
) else if (locationOff && !locationDismissed) PairCard(
title = "Location is off",
body = "Map apps can't show where you are or give directions. Turn on location " +
"in your phone's quick settings when you're parked.",
secondary = "Don't show again" to LocationCheck::neverAgain,
primary = "OK" to LocationCheck::dismissOnCar,
)
}
CarBluetooth.Prompt.ASK -> PairCard(
title = "Pair with this car?",
body = (if (bluetoothAudio) "Calls and music play" else "Calls play") +
" through the car's speakers once your phone and the car are paired. Your phone " +
"then asks you to confirm a code.",
secondary = "Not now" to CarBluetooth::notNow,
primary = "Pair" to CarBluetooth::pair,
)
CarBluetooth.Prompt.PAIRING -> PairCard(
title = "Confirm on your phone",
body = "Check the code on your phone and tap Pair. The car may ask too.",
secondary = null,
primary = "Hide" to CarBluetooth::hide,
)
}
}
@Composable
private fun PairCard(title: String, body: String, secondary: Pair<String, () -> Unit>?, primary: Pair<String, () -> Unit>) {
Box(
Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f)).clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() },
onClick = {},
),
contentAlignment = Alignment.Center,
) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth(0.85f).padding(16.dp),
) {
Column(
Modifier.padding(32.dp),
verticalArrangement = Arrangement.spacedBy(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
Text(
body,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
secondary?.let { (label, onClick) ->
GsButton(onClick = onClick, tone = GsTone.Outline, modifier = Modifier.weight(1f).height(56.dp)) {
Text(label, style = MaterialTheme.typography.titleMedium)
}
}
GsButton(onClick = primary.second, modifier = Modifier.weight(1f).height(56.dp)) {
Text(primary.first, style = MaterialTheme.typography.titleMedium)
}
}
}
}
}
}
@@ -0,0 +1,89 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp
/**
* Draws the raw video frame with pixel rulers, for measuring what the head unit actually shows.
*
* Numbers are frame pixels. Read the last number visible on each edge to see how much the head
* unit crops there (the frame is 800 wide by 480 tall when the ruler runs to those values), and
* tap anywhere: the crosshair is drawn where the phone believes the touch landed, so a mismatch
* with your finger is the touch offset. Ignores vehicle insets on purpose.
*/
@Composable
fun CalibrationApp() {
val navigator = LocalCarNavigator.current
val measurer = rememberTextMeasurer()
var touch by remember { mutableStateOf<Offset?>(null) }
Box(
Modifier
.fillMaxSize()
.background(Color.Black)
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown()
touch = down.position
}
},
) {
Canvas(Modifier.fillMaxSize()) {
val label = TextStyle(color = Color.White, fontSize = 11.sp)
val faint = Color(0x55FFFFFF)
val w = size.width
val h = size.height
var y = 0
while (y <= h) {
drawLine(if (y % 100 == 0) Color.White else faint, Offset(0f, y.toFloat()), Offset(w, y.toFloat()), strokeWidth = 1f)
if (y % 20 == 0) {
drawText(measurer, "$y", Offset(2f, y.toFloat()), style = label)
drawText(measurer, "$y", Offset(w - 30f, y.toFloat()), style = label)
}
y += 20
}
var x = 0
while (x <= w) {
drawLine(if (x % 100 == 0) Color.White else faint, Offset(x.toFloat(), 0f), Offset(x.toFloat(), h), strokeWidth = 1f)
if (x % 50 == 0 && x > 0) {
drawText(measurer, "$x", Offset(x.toFloat() + 2f, 2f), style = label)
drawText(measurer, "$x", Offset(x.toFloat() + 2f, h - 46f), style = label)
}
x += 20
}
// Frame border, drawn last and inset by 1px so it is the outermost thing that can show.
drawRect(Color.Red, topLeft = Offset(1f, 1f), size = androidx.compose.ui.geometry.Size(w - 2f, h - 2f), style = androidx.compose.ui.graphics.drawscope.Stroke(2f))
drawText(measurer, "frame ${w.toInt()}x${h.toInt()}", Offset(w / 2 - 50f, h / 2 - 60f), style = TextStyle(color = Color.Yellow, fontSize = 14.sp))
touch?.let { t ->
drawLine(Color.Green, Offset(t.x, 0f), Offset(t.x, h), strokeWidth = 2f)
drawLine(Color.Green, Offset(0f, t.y), Offset(w, t.y), strokeWidth = 2f)
drawText(measurer, "touch ${t.x.toInt()},${t.y.toInt()}", Offset(w / 2 - 50f, h / 2 + 40f), style = TextStyle(color = Color.Green, fontSize = 14.sp))
}
}
Button(onClick = { navigator.home() }, modifier = Modifier.align(Alignment.Center)) {
Text("Exit calibration")
}
}
}
@@ -1,134 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.shape.CircleShape
import app.seb3thehacker.gearslip.car.theme.*
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.call.CallUiState
import app.seb3thehacker.gearslip.call.CarCalls
/**
* Sits above whatever the car is showing while a call is ringing or under way. Ringing takes the
* whole screen, because nothing else matters more right now; an active call is a thin band along
* the top, since from here the driver can only see who it is, not end it - see [CarCalls].
*/
@Composable
fun CallOverlay(modifier: Modifier = Modifier) {
val state by CarCalls.state.collectAsState()
val context = LocalContext.current.applicationContext
when (val s = state) {
// Covers the box regardless of where the caller aligned it, so the alignment below is
// only ever felt by the active-call banner, which is the one that isn't full-screen.
is CallUiState.Ringing -> IncomingCall(s, onAnswer = { CarCalls.answer(context) }, onDecline = CarCalls::decline)
is CallUiState.Active -> ActiveCallBanner(s, modifier)
CallUiState.None -> {}
}
}
@Composable
private fun IncomingCall(s: CallUiState.Ringing, onAnswer: () -> Unit, onDecline: () -> Unit) {
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainerLowest) {
Column(
Modifier.fillMaxSize().padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Icon(
Icons.Filled.Call,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.height(16.dp))
Text(
"Incoming call",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(8.dp))
Text(
s.caller.label,
style = MaterialTheme.typography.displaySmall,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(56.dp))
Row(horizontalArrangement = Arrangement.spacedBy(48.dp)) {
CallButton(Icons.Filled.Close, "Decline", MaterialTheme.colorScheme.error, enabled = s.canDecline, onClick = onDecline)
CallButton(Icons.Filled.Call, "Answer", MaterialTheme.colorScheme.primary, enabled = true, onClick = onAnswer)
}
if (!s.canDecline) {
Spacer(Modifier.height(20.dp))
Text(
"Already ringing out loud - answer here, or let it ring.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@Composable
private fun CallButton(icon: ImageVector, label: String, color: Color, enabled: Boolean, onClick: () -> Unit) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
GsIconButton(
icon, label, onClick,
colors = GsColors(color, Color.White),
enabled = enabled,
size = 72.dp,
iconSize = 30.dp,
shape = CircleShape,
)
Spacer(Modifier.height(8.dp))
Text(label, style = MaterialTheme.typography.labelLarge)
}
}
@Composable
private fun ActiveCallBanner(s: CallUiState.Active, modifier: Modifier = Modifier) {
Surface(
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = modifier.fillMaxWidth(),
) {
Row(
Modifier.padding(horizontal = 20.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.Center,
) {
Icon(Icons.Filled.Call, contentDescription = null, modifier = Modifier.size(20.dp))
Spacer(Modifier.height(0.dp))
Text(
" On a call" + (s.caller?.let { " with ${it.label}" } ?: ""),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
)
}
}
}
@@ -1,15 +1,9 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import android.view.SurfaceHolder import android.view.SurfaceHolder
import android.view.SurfaceView import android.view.SurfaceView
import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.util.VelocityTracker
import kotlin.math.hypot
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -19,11 +13,11 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -66,6 +60,7 @@ fun CarAppStage(
AppSurface(connection, frame, template, Modifier.fillMaxSize()) AppSurface(connection, frame, template, Modifier.fillMaxSize())
} }
TemplateChrome(template, Modifier.fillMaxSize().padding(top = if (embedded) 0.dp else CHROME_BAR)) TemplateChrome(template, Modifier.fillMaxSize().padding(top = if (embedded) 0.dp else CHROME_BAR))
if (embedded) CornerMask(EMBEDDED_RADIUS, MaterialTheme.colorScheme.background)
if (!embedded) ChromeBar(status, onDisconnect, Modifier.align(Alignment.TopCenter)) if (!embedded) ChromeBar(status, onDisconnect, Modifier.align(Alignment.TopCenter))
} }
} }
@@ -95,29 +90,6 @@ private fun AppSurface(
} }
} }
// A fresh SurfaceView - and so a fresh Surface - for every size, the way Android Auto hands an
// app a new surface rather than resizing the old one. A resized SurfaceView keeps the same
// BufferQueue, and apps that draw through their own VirtualDisplay build the
// new one on it before releasing the old: the old display's disconnect then takes the new one's
// connection with it and the map freezes for good. The nav bar hiding for the search keyboard
// and the lyrics pane opening both resize this area.
androidx.compose.foundation.layout.BoxWithConstraints(modifier) {
val epoch by connection.surfaceEpoch.collectAsState()
androidx.compose.runtime.key(constraints.maxWidth, constraints.maxHeight, epoch) {
SurfaceHost(connection, frame, onSize = { size = it }, Modifier.fillMaxSize())
}
}
DisposableEffect(connection) { onDispose { connection.detachSurface() } }
}
@Composable
private fun SurfaceHost(
connection: CarAppConnection,
frame: CarEnvironment.Frame,
onSize: (Pair<Int, Int>) -> Unit,
modifier: Modifier,
) {
AndroidView( AndroidView(
modifier = modifier modifier = modifier
.pointerInput(connection) { .pointerInput(connection) {
@@ -130,30 +102,6 @@ private fun SurfaceHost(
if (pan != Offset.Zero) connection.surfaceScroll(-pan.x, -pan.y) if (pan != Offset.Zero) connection.surfaceScroll(-pan.x, -pan.y)
if (zoom != 1f) connection.surfaceScale(centroid.x, centroid.y, zoom) if (zoom != 1f) connection.surfaceScale(centroid.x, centroid.y, zoom)
} }
}
.pointerInput(connection) {
// detectTransformGestures has no velocity, so a fling is measured here alongside
// it: one finger lifting while still moving lets the map glide on, as on a car.
// Velocity is the finger's own, which is GestureDetector's onFling convention.
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
val tracker = VelocityTracker()
tracker.addPosition(down.uptimeMillis, down.position)
var pinched = false
while (true) {
val event = awaitPointerEvent(PointerEventPass.Final)
if (event.changes.size > 1) pinched = true
val change = event.changes.firstOrNull { it.id == down.id } ?: break
tracker.addPosition(change.uptimeMillis, change.position)
if (!change.pressed) {
val v = tracker.calculateVelocity()
if (!pinched && hypot(v.x, v.y) >= FLING_MIN_PX_S) {
connection.surfaceFling(v.x, v.y)
}
break
}
}
}
}, },
factory = { context -> factory = { context ->
SurfaceView(context).apply { SurfaceView(context).apply {
@@ -167,20 +115,20 @@ private fun SurfaceHost(
height: Int, height: Int,
) { ) {
GearslipLog.i("stage: surface ready at ${width}x$height") GearslipLog.i("stage: surface ready at ${width}x$height")
onSize(width to height) size = width to height
connection.attachSurface(holder.surface, width, height, frame.densityDpi) connection.attachSurface(holder.surface, width, height, frame.densityDpi)
} }
override fun surfaceDestroyed(holder: SurfaceHolder) { override fun surfaceDestroyed(holder: SurfaceHolder) {
GearslipLog.i("stage: surface destroyed") GearslipLog.i("stage: surface destroyed")
// Only this view's own surface: a replaced view's teardown can land after connection.detachSurface()
// its successor has already lent the app a new one.
connection.detachSurface(holder.surface)
} }
}) })
} }
}, },
) )
DisposableEffect(connection) { onDispose { connection.detachSurface() } }
} }
@Composable @Composable
@@ -210,13 +158,34 @@ private fun ChromeBar(
}.joinToString(" - ") }.joinToString(" - ")
Text(detail, style = MaterialTheme.typography.bodySmall) Text(detail, style = MaterialTheme.typography.bodySmall)
} }
GsButton(onClick = onDisconnect, tone = GsTone.Tonal) { Text("Stop") } TextButton(onClick = onDisconnect) { Text("Stop", color = Color.White) }
} }
} }
} }
/** Corner radius of the home screen's map pane and player. */
val EMBEDDED_RADIUS = 18.dp
/**
* Rounds the corners of a SurfaceView, which Compose cannot clip: the app draws into its own
* layer, so the corners are covered from above with the surrounding colour instead.
*/
@Composable
private fun CornerMask(radius: androidx.compose.ui.unit.Dp, color: Color) {
androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {
val bounds = androidx.compose.ui.geometry.Rect(0f, 0f, size.width, size.height)
val cut = androidx.compose.ui.graphics.Path().apply {
addRect(bounds)
addRoundRect(
androidx.compose.ui.geometry.RoundRect(
bounds, androidx.compose.ui.geometry.CornerRadius(radius.toPx()),
),
)
fillType = androidx.compose.ui.graphics.PathFillType.EvenOdd
}
drawPath(cut, color)
}
}
/** Height of [ChromeBar]; the template's own chrome starts below it. */ /** Height of [ChromeBar]; the template's own chrome starts below it. */
private val CHROME_BAR = 44.dp private val CHROME_BAR = 44.dp
/** Slower than this when the finger lifts and it was a drag that stopped, not a fling. */
private const val FLING_MIN_PX_S = 400f
@@ -1,7 +1,7 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
@@ -22,14 +22,14 @@ class CarApp(
object CarApps { object CarApps {
val all: List<CarApp> = listOf( val all: List<CarApp> = listOf(
CarApp("web", "Browser", Icons.Filled.Search) { CarApp("web", "Web", Icons.Filled.Search) {
WebApp(content = ProjectedContent.resolve(LocalContext.current)) WebApp(content = ProjectedContent.resolve(LocalContext.current))
}, },
CarApp("phone", "Screen sharing", Icons.Filled.Share) { CarApp("phone", "Screen sharing", Icons.Filled.Share) {
PhoneAppsScreen() PhoneAppsScreen()
}, },
CarApp("dialer", "Phone", Icons.Filled.Call) { CarApp("calibrate", "Display test", Icons.Filled.Info) {
PhoneDialerScreen() CalibrationApp()
}, },
CarApp("settings", "Settings", Icons.Filled.Settings) { CarApp("settings", "Settings", Icons.Filled.Settings) {
CarSettingsScreen() CarSettingsScreen()
@@ -1,276 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import androidx.core.content.ContextCompat
import app.seb3thehacker.gearslip.call.CallUiState
import app.seb3thehacker.gearslip.call.CarCalls
import app.seb3thehacker.gearslip.speech.SpeechEngine
import app.seb3thehacker.gearslip.speech.VoiceFocus
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* A voice assistant: Gearslip's own [SpeechEngine] (whisper.cpp) to listen, the system's
* [TextToSpeech] to answer. Listening used to go through the system's [SpeechRecognizer] alone,
* but many phones have no recognizer at all (GrapheneOS ships only text-to-speech), so the
* system one is now just the fallback for when the bundled engine can't run.
*
* Listening and speaking live here; deciding what a command *means* is [AssistantCommands], kept
* separate because it needs a [CarNavigator] and a frame to act on, neither of which this object
* has - see [pendingCommand].
*/
object CarAssistant {
enum class Phase { IDLE, LISTENING, THINKING, SPEAKING, ERROR }
data class State(
val phase: Phase = Phase.IDLE,
val heard: String = "",
val reply: String = "",
val missingPermission: Boolean = false,
/** False from the press until the microphone is actually open, so the overlay doesn't claim to listen early. */
val ready: Boolean = false,
)
private val _state = MutableStateFlow(State())
val state: StateFlow<State> = _state
/** Set once a recognition result comes in; [reply] clears it once handled. */
private val _pendingCommand = MutableStateFlow<String?>(null)
val pendingCommand: StateFlow<String?> = _pendingCommand
private var appContext: Context? = null
private var recognizer: SpeechRecognizer? = null
private var tts: TextToSpeech? = null
private var ttsReady = false
fun init(context: Context) {
appContext = context.applicationContext
if (tts != null) return
tts = TextToSpeech(appContext) { status -> ttsReady = status == TextToSpeech.SUCCESS }
}
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Starts listening, or does nothing if the assistant is already busy with the last request.
* [SpeechRecognizer] must be driven from a thread with a Looper, but this is also called from
* the raw wire-protocol worker thread ([GearslipRunner]'s key-event handling for the head
* unit's own PTT button) which has none - so this always hops to the main thread itself
* rather than asking every caller to remember to.
*/
fun start() {
if (Looper.myLooper() == Looper.getMainLooper()) startOnMainThread() else mainHandler.post(::startOnMainThread)
}
private fun startOnMainThread() {
val context = appContext ?: return
if (_state.value.phase == Phase.LISTENING || _state.value.phase == Phase.THINKING) return
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) !=
PackageManager.PERMISSION_GRANTED
) {
_state.value = State(Phase.ERROR, reply = "Needs the microphone permission.", missingPermission = true)
return
}
// Android hands every app but the dialer a silent microphone during a call.
if (CarCalls.state.value is CallUiState.Active) {
_state.value = State(Phase.ERROR, reply = "Voice commands work once the call ends.")
return
}
tts?.stop()
_state.value = State(Phase.LISTENING)
listenOnce(
onListening = { _state.value = _state.value.copy(ready = true) },
onPartial = { text -> _state.value = _state.value.copy(heard = text) },
onHeard = { _state.value = _state.value.copy(phase = Phase.THINKING) },
onResult = { text ->
_state.value = _state.value.copy(phase = Phase.THINKING, heard = text)
_pendingCommand.value = text
},
onError = { message -> _state.value = State(Phase.ERROR, reply = message) },
)
}
/** Closes the overlay from wherever it's showing: mid-listen, mid-think, or after speaking. */
fun cancel() {
releaseRecognizer()
tts?.stop()
_pendingCommand.value = null
_state.value = State(Phase.IDLE)
}
/**
* Called once [pendingCommand] has been turned into an answer - from [CarUi], the one place
* that actually has a [CarNavigator] to have acted on it with.
*/
fun reply(text: String) {
_pendingCommand.value = null
_state.value = _state.value.copy(phase = Phase.SPEAKING, reply = text)
val engine = tts
if (engine == null || !ttsReady || text.isBlank()) {
_state.value = _state.value.copy(phase = Phase.IDLE)
return
}
appContext?.let(VoiceFocus::acquire)
engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) {
VoiceFocus.release()
_state.value = _state.value.copy(phase = Phase.IDLE)
}
@Deprecated("Deprecated in Java, no replacement on this API level")
override fun onError(utteranceId: String?) {
VoiceFocus.release()
_state.value = _state.value.copy(phase = Phase.IDLE)
}
override fun onStop(utteranceId: String?, interrupted: Boolean) { VoiceFocus.release() }
})
engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, "gearslip-assistant")
}
/**
* Speaks [text] for someone other than the assistant (a message read aloud), then runs
* [onDone] on the main thread - straight away if speech isn't available.
*/
fun say(text: String, onDone: () -> Unit) {
val engine = tts
val context = appContext
if (engine == null || context == null || !ttsReady || text.isBlank()) {
mainHandler.post(onDone)
return
}
VoiceFocus.acquire(context)
engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) { VoiceFocus.release(); mainHandler.post(onDone) }
@Deprecated("Deprecated in Java, no replacement on this API level")
override fun onError(utteranceId: String?) { VoiceFocus.release(); mainHandler.post(onDone) }
// Stopped part way: whoever stopped it has already moved on.
override fun onStop(utteranceId: String?, interrupted: Boolean) { VoiceFocus.release() }
})
engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, "gearslip-say")
}
fun stopSpeaking() { tts?.stop() }
/**
* Listens once, the same way the assistant does, and hands back what was said without acting
* on it. Callbacks arrive on the main thread; [onError] gets a sentence fit to show.
*/
fun dictate(
onPartial: (String) -> Unit,
onResult: (String) -> Unit,
onError: (String) -> Unit,
cue: Boolean = true,
onSpeaking: () -> Unit = {},
) {
cancel()
listenOnce(onPartial, onHeard = {}, onResult = onResult, onError = onError, cue = cue, onSpeaking = onSpeaking)
}
/**
* One phrase, through Gearslip's own [SpeechEngine], or the phone's recognizer when the driver
* chose it in settings. Never the phone's on its own: on most phones that's Google's.
*/
private fun listenOnce(
onPartial: (String) -> Unit,
onListening: () -> Unit = {},
onHeard: () -> Unit,
onResult: (String) -> Unit,
onError: (String) -> Unit,
cue: Boolean = true,
onSpeaking: () -> Unit = {},
) {
val context = appContext ?: return onError("Speech isn't ready yet.")
if (CarSettings.systemSpeech.value && SpeechRecognizer.isRecognitionAvailable(context)) {
return systemListen(context, onListening, onPartial, onHeard, onResult, onError)
}
SpeechEngine.listen(
context,
cue = cue,
onSpeaking = onSpeaking,
onPartial = onPartial,
onListening = onListening,
onHeard = onHeard,
onResult = onResult,
onError = onError,
)
}
private fun systemListen(
context: Context,
onListening: () -> Unit,
onPartial: (String) -> Unit,
onHeard: () -> Unit,
onResult: (String) -> Unit,
onError: (String) -> Unit,
) {
val r = SpeechRecognizer.createSpeechRecognizer(context)
recognizer = r
r.setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) = onListening()
override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() = onHeard()
override fun onEvent(eventType: Int, params: Bundle?) {}
override fun onError(error: Int) {
releaseRecognizer()
onError(errorMessage(error))
}
override fun onResults(results: Bundle?) {
releaseRecognizer()
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
if (text.isBlank()) onError("Didn't catch that.") else onResult(text)
}
override fun onPartialResults(partialResults: Bundle?) {
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.let(onPartial)
}
})
r.startListening(
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
},
)
}
fun stopListening() = releaseRecognizer()
private fun releaseRecognizer() {
SpeechEngine.cancel()
recognizer?.let { runCatching { it.cancel() }; it.destroy() }
recognizer = null
}
private fun errorMessage(code: Int): String = when (code) {
SpeechRecognizer.ERROR_NO_MATCH, SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "Didn't catch that."
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Needs the microphone permission."
SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "The speech recognizer is busy."
SpeechRecognizer.ERROR_NETWORK, SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "The speech recognizer needs a network it doesn't have."
else -> "Speech recognition failed."
}
fun shutdown() {
releaseRecognizer()
tts?.shutdown()
tts = null
ttsReady = false
}
}
@@ -1,255 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Looper
import androidx.car.app.CarToast
import app.seb3thehacker.gearslip.AppSettings
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.Protobuf
import app.seb3thehacker.gearslip.ServiceDiscovery
import app.seb3thehacker.gearslip.Wire
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.security.MessageDigest
/**
* Pairs the phone with the car over Bluetooth the first time they meet, so calls (and music, when
* the driver chose Bluetooth audio) reach the car's speakers. Android Auto does this on its own;
* Gearslip asks first, on the car screen.
*
* The car names its Bluetooth address in its service list. When the driver taps Pair, Gearslip
* opens the car's Bluetooth channel and sends what Android Auto sends:
*
* -> CHANNEL_OPEN_REQUEST <- CHANNEL_OPEN_RESPONSE
* -> PairingRequest { phone_address, method }
* <- PairingResponse { status, already_paired }
*
* then starts pairing from the phone. Two things Android Auto has that Gearslip can't: the
* phone's own Bluetooth address (apps get a placeholder), and confirming the pairing code without
* asking. So a car may turn the request down, and the phone always shows its pairing dialog. The
* channel stays closed unless the driver taps Pair: every new channel is a risk to cars that work.
*/
object CarBluetooth {
enum class Prompt { NONE, ASK, PAIRING }
private val _prompt = MutableStateFlow(Prompt.NONE)
val prompt: StateFlow<Prompt> = _prompt
private val log = GearslipLog.tagged("bluetooth")
private val main = Handler(Looper.getMainLooper())
private var appContext: Context? = null
/** This session's car: its channel, and how to open and write to it. */
private class Car(
val service: ServiceDiscovery.BluetoothService,
val open: () -> Unit,
val send: (messageId: Int, body: ByteArray) -> Unit,
)
@Volatile private var car: Car? = null
@Volatile private var bondStarted = false
/** From the Pair tap until it succeeds or fails, whether or not the card still shows. */
@Volatile private var pairing = false
private var receiver: BroadcastReceiver? = null
/** The car's Bluetooth address, when it named one in its service list. */
val carAddress: String? get() = car?.service?.carAddress
/** The car's Bluetooth channel once the driver has asked to pair, -1 otherwise. */
val channelId: Int get() = car?.takeIf { pairing }?.service?.serviceId ?: -1
fun init(context: Context) {
appContext = context.applicationContext
}
/** Called once the car lists its services. Asks on the car screen only if there's pairing to do. */
fun onCarConnected(
service: ServiceDiscovery.BluetoothService,
open: () -> Unit,
send: (messageId: Int, body: ByteArray) -> Unit,
) {
car = Car(service, open, send)
bondStarted = false
log.i("the car offers Bluetooth pairing, methods=${service.pairingMethods}")
val device = device() ?: return
when {
device.bondState == BluetoothDevice.BOND_BONDED -> log.i("already paired with this car")
declined(service.carAddress) -> log.i("not paired, and the driver said not now for this car")
else -> _prompt.value = Prompt.ASK
}
}
fun onCarDisconnected() {
car = null
pairing = false
main.post {
stopWatching()
_prompt.value = Prompt.NONE
}
}
/** The driver tapped Pair. */
fun pair() {
val c = car ?: return
val device = device() ?: return
pairing = true
_prompt.value = Prompt.PAIRING
watchBonding(device)
c.open()
log.i("-> ChannelOpenRequest on channel ${c.service.serviceId}")
// If the car never answers on its channel, pair from the phone anyway.
main.postDelayed({ startBond("the car didn't answer the pairing request") }, CAR_REPLY_WAIT_MS)
main.postDelayed({
if (pairing) finish("Pairing didn't finish. Pair from the car's Bluetooth menu instead.")
}, GIVE_UP_MS)
}
/** The driver tapped Not now: this car isn't asked about again. */
fun notNow() {
car?.service?.carAddress?.let { address ->
val context = appContext ?: return@let
val list = AppSettings.getString(context, KEY_DECLINED, "").split(",").filter { it.isNotEmpty() }
AppSettings.putString(context, KEY_DECLINED, (list + hash(address)).distinct().joinToString(","))
}
_prompt.value = Prompt.NONE
}
/** Hides the pairing card. The phone's own dialog carries on. */
fun hide() {
_prompt.value = Prompt.NONE
}
fun onMessage(messageId: Int, body: ByteArray) {
val c = car ?: return
when (messageId) {
MSG_CHANNEL_OPEN_RESPONSE -> {
val status = Protobuf.readInt32Field(body, 1) ?: 0
log.i("<- ChannelOpenResponse: status=$status")
if (status != 0) {
main.post { startBond("the car wouldn't open its Bluetooth channel") }
return
}
val method = c.service.pairingMethods.firstOrNull { it == METHOD_NUMERIC_COMPARISON }
?: c.service.pairingMethods.firstOrNull() ?: METHOD_NUMERIC_COMPARISON
c.send(
MSG_PAIRING_REQUEST,
Protobuf.stringField(1, phoneAddress()) + Protobuf.varintField(2, method.toLong()),
)
log.i("-> PairingRequest(method=$method)")
}
MSG_PAIRING_RESPONSE -> {
val fields = Wire.fields(body)
log.i("<- PairingResponse status=${Wire.varint(fields, 1)} already_paired=${Wire.varint(fields, 2) == 1L}")
// Some cars start pairing themselves once they answer; give them a moment first.
main.postDelayed({ startBond("the car answered") }, CAR_BOND_WAIT_MS)
}
// Carries the pairing code. Android shows it to the driver, so it stays out of the log.
MSG_AUTHENTICATION_DATA -> log.i("<- AuthenticationData (${body.size} bytes)")
else -> log.i("<- unhandled message id=$messageId (${body.size} bytes)")
}
}
@SuppressLint("MissingPermission")
private fun startBond(why: String) {
if (bondStarted || !pairing) return
val device = device() ?: return
if (device.bondState != BluetoothDevice.BOND_NONE) return
bondStarted = true
val started = runCatching { device.createBond() }.getOrDefault(false)
log.i("pairing from the phone ($why): ${if (started) "started" else "refused"}")
if (!started) finish("Pairing didn't start. Pair from the car's Bluetooth menu instead.")
}
private fun watchBonding(device: BluetoothDevice) {
val context = appContext ?: return
stopWatching()
val r = object : BroadcastReceiver() {
@Suppress("DEPRECATION")
override fun onReceive(context: Context, intent: Intent) {
val changed = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
if (changed.address != device.address) return
val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE)
val previous = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE)
log.i("bond state $previous -> $state")
when {
state == BluetoothDevice.BOND_BONDING -> bondStarted = true
state == BluetoothDevice.BOND_BONDED -> finish("Paired. Calls now play through the car.")
previous == BluetoothDevice.BOND_BONDING -> finish("Pairing didn't finish. Pair from the car's Bluetooth menu instead.")
}
}
}
context.registerReceiver(r, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), Context.RECEIVER_EXPORTED)
receiver = r
}
private fun finish(message: String) {
pairing = false
stopWatching()
main.removeCallbacksAndMessages(null)
_prompt.value = Prompt.NONE
CarToasts.show(this, message, CarToast.LENGTH_LONG)
}
private fun stopWatching() {
val r = receiver ?: return
receiver = null
runCatching { appContext?.unregisterReceiver(r) }
}
/** The car as a Bluetooth device, or null (and logged) when Gearslip can't reach Bluetooth. */
private fun device(): BluetoothDevice? {
val context = appContext ?: return null
val address = car?.service?.carAddress ?: return null
if (context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
log.i("can't check pairing: the Bluetooth permission isn't granted")
return null
}
val adapter = context.getSystemService(BluetoothManager::class.java)?.adapter
if (adapter == null || !adapter.isEnabled) {
log.i("can't check pairing: Bluetooth is off")
return null
}
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
log.w("the car sent an address that isn't one")
return null
}
return adapter.getRemoteDevice(address)
}
/** Apps get 02:00:00:00:00:00 here, not the real address. Sent anyway, as the field is required. */
@SuppressLint("MissingPermission", "HardwareIds")
private fun phoneAddress(): String =
runCatching { appContext?.getSystemService(BluetoothManager::class.java)?.adapter?.address }.getOrNull()
?: "02:00:00:00:00:00"
private fun declined(address: String): Boolean {
val context = appContext ?: return false
return hash(address) in AppSettings.getString(context, KEY_DECLINED, "").split(",")
}
/** Settings keep a short hash, not the car's address. */
private fun hash(address: String): String =
MessageDigest.getInstance("SHA-256").digest(address.uppercase().toByteArray())
.take(8).joinToString("") { "%02x".format(it) }
private const val KEY_DECLINED = "bluetooth_pair_declined"
private const val CAR_REPLY_WAIT_MS = 5_000L
private const val CAR_BOND_WAIT_MS = 3_000L
private const val GIVE_UP_MS = 90_000L
private const val METHOD_NUMERIC_COMPARISON = 2
private const val MSG_CHANNEL_OPEN_RESPONSE = 8
private const val MSG_PAIRING_REQUEST = 32769
private const val MSG_PAIRING_RESPONSE = 32770
private const val MSG_AUTHENTICATION_DATA = 32771
}
@@ -19,11 +19,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
import app.seb3thehacker.gearslip.car.theme.GsColors
import app.seb3thehacker.gearslip.car.theme.GsIconBox
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
@@ -44,8 +40,7 @@ import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
/** /**
* Opened from the nav bar clock: the current weather, the week's calendar and the phone's * Opened from the nav bar clock: the week's calendar and the current weather, at a glance. Both
* notifications, at a glance. The first two
* need permissions granted on the phone (READ_CALENDAR, location) - if either was declined * need permissions granted on the phone (READ_CALENDAR, location) - if either was declined
* this just shows an empty state instead of asking again from inside the car UI. * this just shows an empty state instead of asking again from inside the car UI.
*/ */
@@ -60,46 +55,33 @@ fun CarDashboardScreen() {
.padding(horizontal = 24.dp, vertical = 16.dp), .padding(horizontal = 24.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp), verticalArrangement = Arrangement.spacedBy(24.dp),
) { ) {
ScreenHeader("Today") Text("Today", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
WeatherCard(context) WeatherCard(context)
AgendaCard(context) AgendaCard(context)
NotificationsSection()
} }
} }
@Composable @Composable
private fun WeatherCard(context: Context) { private fun WeatherCard(context: Context) {
val state by Weather.state.collectAsState() val weather by produceState<Weather?>(Weather.LOADING) {
val navigator = LocalCarNavigator.current value = withContext(Dispatchers.IO) { fetchWeather(context) }
LaunchedEffect(Unit) { Weather.refresh(context) } }
GsIconBox( Surface(color = MaterialTheme.colorScheme.surfaceContainerHigh, shape = MaterialTheme.shapes.extraLarge) {
onClick = { navigator.weather() }, Row(Modifier.fillMaxWidth().padding(20.dp), verticalAlignment = Alignment.CenterVertically) {
colors = GsColors(MaterialTheme.colorScheme.surfaceContainerHigh, MaterialTheme.colorScheme.onSurface), val w = weather
shape = MaterialTheme.shapes.extraLarge, when {
) { w === Weather.LOADING -> Text("Getting weather…", style = MaterialTheme.typography.bodyLarge)
Row( w == null -> Text(
Modifier.fillMaxWidth().padding(20.dp), "Weather unavailable - no location fix yet.",
verticalAlignment = Alignment.CenterVertically, style = MaterialTheme.typography.bodyLarge,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
when (val s = state) {
WeatherState.Loading -> Text("Getting weather…", style = MaterialTheme.typography.bodyLarge)
is WeatherState.Unavailable -> Text(
s.reason, style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
is WeatherState.Ready -> { else -> Text(
val w = s.data "${w.tempC.toInt()}°C · ${w.description}",
WeatherIcon(w.code, w.isDay, size = 44.dp) style = MaterialTheme.typography.titleLarge,
Column { fontWeight = FontWeight.SemiBold,
Text(
"${w.temp}${w.tempUnit} · ${Weather.describe(w.code)}",
style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold,
) )
Text(w.place, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
} }
} }
} }
@@ -107,8 +89,8 @@ private fun WeatherCard(context: Context) {
@Composable @Composable
private fun AgendaCard(context: Context) { private fun AgendaCard(context: Context) {
val events by produceState<List<AgendaEvent>?>(cachedAgenda) { val events by produceState<List<AgendaEvent>?>(null) {
value = withContext(Dispatchers.IO) { fetchAgenda(context) }.also { cachedAgenda = it } value = withContext(Dispatchers.IO) { fetchAgenda(context) }
} }
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
@@ -161,14 +143,63 @@ private fun eventWhen(event: AgendaEvent): String {
return SimpleDateFormat("EEE", Locale.getDefault()).apply { timeZone = zone }.format(Date(event.startMillis)) + " " + time return SimpleDateFormat("EEE", Locale.getDefault()).apply { timeZone = zone }.format(Date(event.startMillis)) + " " + time
} }
private data class Weather(val tempC: Double, val description: String) {
companion object { val LOADING = Weather(Double.NaN, "") }
}
private data class AgendaEvent(val title: String, val startMillis: Long, val allDay: Boolean) private data class AgendaEvent(val title: String, val startMillis: Long, val allDay: Boolean)
@Volatile private var cachedAgenda: List<AgendaEvent>? = null private const val WEATHER_TTL_MS = 60 * 60 * 1000L
private var cachedWeather: Weather? = null
private var cachedWeatherAt = 0L
/** Loads the weather and the agenda ahead of time, so the dashboard opens with both in place. */ /** Served from memory for up to an hour: weather barely changes, and each call is a network request. */
fun warmDashboard(context: Context) { private fun fetchWeather(context: Context): Weather? {
Weather.refresh(context, force = true) val now = System.currentTimeMillis()
cachedAgenda = fetchAgenda(context) cachedWeather?.let { if (now - cachedWeatherAt < WEATHER_TTL_MS) return it }
return loadWeather(context)?.also { cachedWeather = it; cachedWeatherAt = now }
}
/** Null means no fix or no permission; the card shows a plain empty state either way. */
private fun loadWeather(context: Context): Weather? {
if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null
}
val manager = context.getSystemService(LocationManager::class.java) ?: return null
val location = manager.allProviders
.mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }
.maxByOrNull { it.time }
?: return null
return runCatching {
// Open-Meteo: no API key, no account - the simplest thing that gives a real reading.
val url = URL(
"https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}" +
"&longitude=${location.longitude}&current_weather=true",
)
val body = (url.openConnection() as HttpURLConnection).run {
connectTimeout = 5_000
readTimeout = 5_000
inputStream.bufferedReader().use { it.readText() }
}
val current = JSONObject(body).getJSONObject("current_weather")
Weather(current.getDouble("temperature"), weatherDescription(current.getInt("weathercode")))
}.onFailure { GearslipLog.w("weather fetch failed: ${it.message}") }.getOrNull()
}
/** Open-Meteo's WMO weather codes, collapsed to what's worth a glance from the driver's seat. */
private fun weatherDescription(code: Int): String = when (code) {
0 -> "Clear"
1, 2 -> "Partly cloudy"
3 -> "Overcast"
45, 48 -> "Fog"
in 51..57 -> "Drizzle"
in 61..67 -> "Rain"
in 71..77 -> "Snow"
in 80..82 -> "Rain showers"
in 85..86 -> "Snow showers"
in 95..99 -> "Thunderstorm"
else -> "-"
} }
/** /**
@@ -1,6 +1,6 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.* import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -13,62 +13,43 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.FilledIconButton
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import android.support.v4.media.session.PlaybackStateCompat
import app.seb3thehacker.gearslip.R
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import android.media.session.PlaybackState
import app.seb3thehacker.gearslip.media.MediaArt
import kotlinx.coroutines.delay
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.animation.animateColorAsState import androidx.compose.material3.IconButton
import androidx.compose.animation.core.tween
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import app.seb3thehacker.gearslip.media.ArtColor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.clip
import android.media.session.PlaybackState
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.seb3thehacker.gearslip.host.CarAppConnection import app.seb3thehacker.gearslip.host.CarAppConnection
import app.seb3thehacker.gearslip.media.CarMedia import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.media.NowPlaying import app.seb3thehacker.gearslip.media.MediaArt
import kotlinx.coroutines.launch import kotlinx.coroutines.delay
/** /**
* The home screen: the map on the left, the docked player on the right when asked for. * The home screen: the map on the left, what is playing on the right.
* *
* The map is whatever navigation app was used last, brought back on its own. The player sits in * The map is whatever navigation app was used last, brought back on its own. The player only
* the nav bar's pill until its dock button moves it here; the column closes itself back to a * takes its share of the screen while something is loaded; otherwise the map has all of it.
* full-width map once nothing is playing.
*/ */
@Composable @Composable
fun CarHome() { fun CarHome() {
@@ -80,36 +61,19 @@ fun CarHome() {
LaunchedEffect(Unit) { CarServices.autostart(frame) } LaunchedEffect(Unit) { CarServices.autostart(frame) }
LaunchedEffect(phase) { if (phase == CarMedia.Phase.READY) CarServices.autoplayIfDue() } LaunchedEffect(phase) { if (phase == CarMedia.Phase.READY) CarServices.autoplayIfDue() }
val navigator = LocalCarNavigator.current val showPlayer = phase == CarMedia.Phase.READY && now.hasTrack
val panel = navigator.sidePanel
// Coming back to the map from another screen: the map stayed loaded underneath, so its surface Row(Modifier.fillMaxSize().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// is only replaced if it died meanwhile. The first composition is skipped, since the surface
// is only just being lent.
val onHome = navigator.current == CarScreen.Home
val seenHome = remember { booleanArrayOf(false) }
LaunchedEffect(onHome) {
if (onHome && seenHome[0]) CarServices.nav.replaceDeadSurface()
if (onHome) seenHome[0] = true
}
val splitScreen = phase == CarMedia.Phase.READY && now.isActive && panel != SidePanel.NONE
// No outer padding on any side, split screen or not - only the gap between the two panes
// when the player is sharing the screen with the map.
Row(
Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Box( Box(
Modifier Modifier
.weight(if (splitScreen) 2.1f else 1f) .weight(if (showPlayer) 2.1f else 1f)
.fillMaxHeight(), .fillMaxHeight()
.clip(RoundedCornerShape(EMBEDDED_RADIUS)),
) { ) {
MapPane(navStatus, frame) MapPane(navStatus, frame)
} }
if (splitScreen) { if (showPlayer) {
val side = Modifier.weight(1f).fillMaxHeight() MiniPlayer(Modifier.weight(1f).fillMaxHeight())
if (panel == SidePanel.LYRICS) SideLyrics(now, side) else DockedPlayer(now, side)
} }
} }
} }
@@ -128,131 +92,104 @@ private fun MapPane(status: CarAppConnection.Status, frame: CarEnvironment.Frame
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
val hasLast = CarSettings.lastNav.value != null val hasLast = CarSettings.lastNav.value != null
val hasNavApps by CarServices.hasNavApps.collectAsStateWithLifecycle()
val scope = androidx.compose.runtime.rememberCoroutineScope()
when (status.phase) { when (status.phase) {
CarAppConnection.Phase.BINDING, CarAppConnection.Phase.HANDSHAKE -> CarAppConnection.Phase.BINDING, CarAppConnection.Phase.HANDSHAKE ->
Text("Starting ${status.app ?: "the map"}…", style = MaterialTheme.typography.titleMedium) Text("Starting ${status.app ?: "the map"}…", style = MaterialTheme.typography.titleMedium)
CarAppConnection.Phase.REJECTED, CarAppConnection.Phase.FAILED -> { CarAppConnection.Phase.REJECTED, CarAppConnection.Phase.FAILED -> {
Text("${status.app ?: "The map app"} would not start.", style = MaterialTheme.typography.titleMedium) Text("${status.app ?: "The map app"} would not start.", style = MaterialTheme.typography.titleMedium)
status.detail?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } status.detail?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) }
GsButton(onClick = navigator::apps, tone = GsTone.Tonal) { Text("Choose another app") } TextButton(onClick = navigator::apps) { Text("Choose another app") }
} }
else -> if (!hasNavApps) { else -> {
// Nothing to auto-select and nothing to pick from Car apps either - this is the
// only case worth a distinct screen, since every other IDLE case resolves itself.
Text("No mapping apps found.", style = MaterialTheme.typography.titleMedium)
Text( Text(
"Install a navigation app that supports Android Auto and it will start here on its own.", if (hasLast) "Starting the map…" else "No map app chosen yet.",
style = MaterialTheme.typography.titleMedium,
)
if (!hasLast) {
Text(
"Open Car apps and connect a navigation app; it will start here next time.",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} else if (hasLast) { TextButton(onClick = { navigator.apps() }) { Text("Car apps") }
// IDLE with a last app on record means the driver stopped it themselves - it will }
// not come back on its own, so the screen must offer a way to bring it back rather
// than sit on a "starting" message that never resolves.
Text("Map stopped.", style = MaterialTheme.typography.titleMedium)
GsButton(onClick = { scope.launch { CarServices.reconnectNav(frame) } }, tone = GsTone.Tonal) { Text("Reopen") }
GsButton(onClick = { navigator.apps() }, tone = GsTone.Tonal) { Text("Car apps") }
} else {
// Autostart is still picking one - a navigation app is installed, so this resolves
// to a "Starting..." state itself, in the next frame or two.
} }
} }
} }
} }
/** /** Previous, play/pause, next and a seek bar, and nothing else: the full controls are in the media screen. */
* The player, docked beside the map: art, title, progress, transport, then like, shuffle, repeat
* and lyrics. While it's here the nav bar's pill steps aside on Home, so the controls never show
* twice. The X sends it back to the nav bar.
*/
@Composable @Composable
private fun DockedPlayer(now: NowPlaying, modifier: Modifier) { private fun MiniPlayer(modifier: Modifier) {
val navigator = LocalCarNavigator.current
val media = CarServices.media val media = CarServices.media
val now by media.now.collectAsStateWithLifecycle()
val context = LocalContext.current val context = LocalContext.current
val scheme = MaterialTheme.colorScheme
val art by produceState(now.art, now.art, now.artUri) { value = now.art ?: MediaArt.load(context, now.artUri) } val art by produceState(now.art, now.art, now.artUri) { value = now.art ?: MediaArt.load(context, now.artUri) }
Surface(modifier = modifier, color = rememberArtColor(art, MaterialTheme.colorScheme.surfaceVariant)) { var position by remember { mutableStateOf(0L) }
BoxWithConstraints(Modifier.fillMaxSize().padding(12.dp)) { LaunchedEffect(now) {
// Whatever height the controls below leave over, so the art grows on a taller while (true) {
// screen and shrinks rather than pushing the buttons off a short one. position = now.currentPosition()
val artSize = minOf(maxWidth - 44.dp, maxHeight - 250.dp).coerceIn(56.dp, 200.dp) delay(500)
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) { }
Box(Modifier.fillMaxWidth()) { }
// Art opens the full media screen, same as on the pill.
Box( val navigator = LocalCarNavigator.current
Modifier Surface(
.align(Alignment.TopCenter) onClick = navigator::media,
.size(artSize) modifier = modifier,
.clip(RoundedCornerShape(12.dp)) shape = RoundedCornerShape(EMBEDDED_RADIUS),
.background(scheme.surface) color = MaterialTheme.colorScheme.surfaceVariant,
.clickable { navigator.media() },
) { ) {
Column(
Modifier.fillMaxSize().padding(18.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Box(Modifier.size(140.dp).clip(RoundedCornerShape(EMBEDDED_RADIUS))) {
art?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } art?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) }
} }
GsIconButton(
Icons.Filled.Close, "Back to the nav bar", navigator::closeSidePanel,
Modifier.align(Alignment.TopEnd), size = 36.dp, iconSize = 20.dp,
)
}
Spacer(Modifier.height(10.dp)) Spacer(Modifier.height(10.dp))
Text( Text(
now.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, now.title.ifEmpty { "Nothing playing" },
style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
maxLines = 1, overflow = TextOverflow.Ellipsis, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
Text( Text(
now.artist, style = MaterialTheme.typography.bodyMedium, color = scheme.onSurfaceVariant, now.artist,
style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
if (now.durationMs > 0) {
PlayerProgress(now, media, Modifier.fillMaxWidth().padding(vertical = 2.dp), showTimes = false)
} else {
Spacer(Modifier.height(10.dp))
}
TransportRow(now, media, skip = 48.dp, modifier = Modifier.fillMaxWidth())
Spacer(Modifier.height(10.dp))
PlayModeRow(now, media, size = 42.dp, modifier = Modifier.fillMaxWidth()) {
GsIconButton(
ImageVector.vectorResource(R.drawable.lyrics_24), "Lyrics", navigator::showSideLyrics,
size = 42.dp, iconSize = 22.dp,
)
}
}
}
}
}
/** if (now.durationMs > 0) {
* Lyrics alone beside the map, big enough to read at a glance. No art: that space goes to a WavyProgress(
* larger title and artist instead. The player goes back to the nav bar meanwhile, whose dock fraction = position.toFloat() / now.durationMs,
* button swaps these back out for the controls. playing = now.state == PlaybackState.STATE_PLAYING,
*/ onSeek = { media.seek((it * now.durationMs).toLong()) },
@Composable modifier = Modifier.padding(vertical = 4.dp),
private fun SideLyrics(now: NowPlaying, modifier: Modifier) {
val navigator = LocalCarNavigator.current
val context = LocalContext.current
val art by produceState(now.art, now.art, now.artUri) { value = now.art ?: MediaArt.load(context, now.artUri) }
Surface(modifier = modifier, color = rememberArtColor(art, MaterialTheme.colorScheme.surfaceVariant)) {
Column(Modifier.fillMaxSize().padding(16.dp)) {
Row(verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1f)) {
Text(
now.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
maxLines = 2, overflow = TextOverflow.Ellipsis,
) )
Text( } else {
now.artist, style = MaterialTheme.typography.titleMedium, Spacer(Modifier.height(16.dp))
color = MaterialTheme.colorScheme.onSurfaceVariant, }
maxLines = 1, overflow = TextOverflow.Ellipsis,
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = { media.previous() }, modifier = Modifier.size(48.dp)) {
Icon(MediaIcons.Previous, "Previous", Modifier.size(30.dp))
}
FilledIconButton(onClick = media::togglePlay, modifier = Modifier.size(60.dp)) {
Icon(
if (now.playing) MediaIcons.Pause else Icons.Filled.PlayArrow,
if (now.playing) "Pause" else "Play",
Modifier.size(36.dp),
) )
} }
GsIconButton(Icons.Filled.Close, "Hide lyrics", navigator::closeSidePanel, size = 36.dp, iconSize = 20.dp) IconButton(onClick = { media.next() }, modifier = Modifier.size(48.dp)) {
Icon(MediaIcons.Next, "Next", Modifier.size(30.dp))
}
} }
Spacer(Modifier.height(12.dp))
LyricsPanel(now, Modifier.weight(1f).fillMaxWidth(), lineStyle = MaterialTheme.typography.headlineSmall)
} }
} }
} }
@@ -1,6 +1,5 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -9,14 +8,12 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
@@ -26,23 +23,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.foundation.clickable
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.coerceIn
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.LaunchedEffect
/**
* Whether a [CarKeyboard] is on screen right now, so [CarUi] can give it the row of height the
* bottom nav bar normally holds instead of squeezing it in above - a driver typing has no use
* for Home/Apps/Settings shortcuts anyway, and the screen is small enough that the space matters.
*/
object CarKeyboardVisibility {
val state = mutableStateOf(false)
}
/** /**
* A keyboard the host draws itself. * A keyboard the host draws itself.
@@ -53,13 +35,7 @@ object CarKeyboardVisibility {
* the same reasons, so this does too - large keys, no long-press, no prediction. * the same reasons, so this does too - large keys, no long-press, no prediction.
* *
* It is a pure function of [text]: every key reports the new string and holds no state beyond * It is a pure function of [text]: every key reports the new string and holds no state beyond
* which layer is showing. Laid out like a PC's QWERTY keyboard rather than a phone's: shift and * which layer is showing.
* backspace flank the letter block (top-right and bottom-left of it, same as a physical board),
* not the space bar, so a fumbled reach for space never lands on delete instead.
*
* [onDismiss] is null wherever there's no keyboard-shown state independent of the screen itself
* (a search template, sign-in) - there, the header's own back action is the only way out and no
* dismiss button is drawn.
*/ */
@Composable @Composable
fun CarKeyboard( fun CarKeyboard(
@@ -69,30 +45,12 @@ fun CarKeyboard(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
submitIcon: Boolean = true, submitIcon: Boolean = true,
submitImage: ImageVector? = null, submitImage: ImageVector? = null,
onDismiss: (() -> Unit)? = null,
) { ) {
var symbols by remember { mutableStateOf(false) } var symbols by remember { mutableStateOf(false) }
var shifted by remember { mutableStateOf(false) } var shifted by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
CarKeyboardVisibility.state.value = true
onDispose { CarKeyboardVisibility.state.value = false }
}
// The same field on the phone, for typing on its own keyboard: see [PhoneTyping].
val latestChange by rememberUpdatedState(onTextChange)
val latestSubmit by rememberUpdatedState(onSubmit)
val latestDismiss by rememberUpdatedState(onDismiss)
val phoneField = remember {
PhoneTyping.open(text, { latestChange(it) }, { latestSubmit() }, onDismiss?.let { { latestDismiss?.invoke() } })
}
DisposableEffect(phoneField) { onDispose { PhoneTyping.close(phoneField) } }
LaunchedEffect(text) { PhoneTyping.carText(phoneField, text) }
val rows = if (symbols) SYMBOL_ROWS else LETTER_ROWS val rows = if (symbols) SYMBOL_ROWS else LETTER_ROWS
val keyHeight = keyHeight(LocalConfiguration.current.screenHeightDp)
CompositionLocalProvider(LocalKeyHeight provides keyHeight) {
Surface( Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh, color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = modifier.fillMaxWidth(), modifier = modifier.fillMaxWidth(),
@@ -101,7 +59,7 @@ fun CarKeyboard(
Modifier.padding(horizontal = 6.dp, vertical = 4.dp), Modifier.padding(horizontal = 6.dp, vertical = 4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp),
) { ) {
rows.dropLast(1).forEach { row -> rows.forEach { row ->
Row( Row(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
@@ -116,53 +74,31 @@ fun CarKeyboard(
} }
} }
// The bottom letter row: shift and backspace bookend it, exactly where a physical
// keyboard puts them relative to the letter block, not down beside the space bar.
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
if (!symbols) {
Key(if (shifted) "SHIFT" else "shift", Modifier.weight(1.6f)) { shifted = !shifted }
}
rows.last().forEach { key ->
val label = if (shifted && !symbols) key.uppercase() else key
Key(label, Modifier.weight(1f)) {
onTextChange(text + label)
shifted = false
}
}
Key("⌫", Modifier.weight(1.6f)) {
if (text.isNotEmpty()) onTextChange(text.dropLast(1))
}
}
// Control row: no backspace here - it stays with the letters above, not next to the
// key most likely to be hit right after it by mistake. Search/enter takes the
// bottom-right corner, where a thumb expects it; dismiss (when offered) sits left of it.
Row( Row(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
) { ) {
Key(if (symbols) "abc" else "?123", Modifier.weight(1.4f)) { symbols = !symbols } Key(if (symbols) "abc" else "?123", Modifier.weight(1.4f)) { symbols = !symbols }
Key("space", Modifier.weight(if (onDismiss != null) 3.2f else 4f)) { onTextChange("$text ") } if (!symbols) {
if (onDismiss != null) { Key(if (shifted) "SHIFT" else "shift", Modifier.weight(1.4f)) { shifted = !shifted }
DismissKey(onDismiss, Modifier.weight(1.4f)) }
Key("space", Modifier.weight(3f)) { onTextChange("$text ") }
Key("⌫", Modifier.weight(1.4f)) {
if (text.isNotEmpty()) onTextChange(text.dropLast(1))
} }
SubmitKey(Modifier.weight(1.6f), submitIcon, submitImage, onSubmit) SubmitKey(Modifier.weight(1.6f), submitIcon, submitImage, onSubmit)
} }
} }
} }
}
} }
@Composable @Composable
private fun Key(label: String, modifier: Modifier = Modifier, onClick: () -> Unit) { private fun Key(label: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
GsIconBox( Surface(
onClick = onClick, color = MaterialTheme.colorScheme.surfaceContainerHighest,
modifier = modifier.height(LocalKeyHeight.current), contentColor = MaterialTheme.colorScheme.onSurface,
colors = GsColors(MaterialTheme.colorScheme.surfaceContainerHighest, MaterialTheme.colorScheme.onSurface),
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
modifier = modifier.height(KEY_HEIGHT).clickable(onClick = onClick),
) { ) {
Row( Row(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
@@ -179,31 +115,13 @@ private fun Key(label: String, modifier: Modifier = Modifier, onClick: () -> Uni
} }
} }
@Composable
private fun DismissKey(onClick: () -> Unit, modifier: Modifier = Modifier) {
GsIconBox(
onClick = onClick,
modifier = modifier.height(LocalKeyHeight.current),
colors = GsColors(MaterialTheme.colorScheme.surfaceContainerHighest, MaterialTheme.colorScheme.onSurfaceVariant),
shape = RoundedCornerShape(8.dp),
) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Close, contentDescription = "Hide keyboard")
}
}
}
@Composable @Composable
private fun SubmitKey(modifier: Modifier, search: Boolean, image: ImageVector?, onClick: () -> Unit) { private fun SubmitKey(modifier: Modifier, search: Boolean, image: ImageVector?, onClick: () -> Unit) {
GsIconBox( Surface(
onClick = onClick, color = MaterialTheme.colorScheme.primary,
modifier = modifier.height(LocalKeyHeight.current), contentColor = MaterialTheme.colorScheme.onPrimary,
colors = GsColors(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary),
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
modifier = modifier.height(KEY_HEIGHT).clickable(onClick = onClick),
) { ) {
Row( Row(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
@@ -219,12 +137,10 @@ private fun SubmitKey(modifier: Modifier, search: Boolean, image: ImageVector?,
} }
/** /**
* Big enough to hit on a bumpy road, small enough that four rows plus a field plus a few results * Big enough to hit on a bumpy road, small enough that four rows plus a field plus a few
* still fit. A 480-tall screen sets the floor; a taller one (LIVI's 1280x720) gets bigger keys. * results all fit a 480px-tall screen - which is the real constraint here, not the key size.
*/ */
private fun keyHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.09f).dp.coerceIn(44.dp, 64.dp) private val KEY_HEIGHT = 34.dp
private val LocalKeyHeight = compositionLocalOf { 44.dp }
private val LETTER_ROWS = listOf( private val LETTER_ROWS = listOf(
"qwertyuiop".map { it.toString() }, "qwertyuiop".map { it.toString() },
@@ -1,139 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.call.CallUiState
import app.seb3thehacker.gearslip.call.CarCalls
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
/**
* The car's own buttons: steering wheel, rotary knob, D-pad and the hard keys around the screen.
*
* The head unit sends Android keycodes as they are, so the numbers here are android.view.KeyEvent's.
* Media, voice and call keys act straight away. Keys that move around the car UI (back, home, the
* knob) need a [CarNavigator], which only [CarUi] has, so they go out on [screenKeys]. Focus keys
* (D-pad, knob turns, OK) become real key events on the car's display through [focusSink], where
* Compose moves focus between buttons the same way it would with a keyboard.
*/
object CarKeys {
/** A key that changes which screen is showing. */
enum class ScreenKey { BACK, HOME, MAP, MEDIA, PHONE }
private val _screenKeys = MutableSharedFlow<ScreenKey>(extraBufferCapacity = 8)
val screenKeys: SharedFlow<ScreenKey> = _screenKeys
private val _focusMoves = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
/** A knob turn or D-pad press, so controls that hide when left alone can come back. */
val focusMoves: SharedFlow<Unit> = _focusMoves
/** Delivers an Android key event to the car display; set while the car UI is showing. */
@Volatile var focusSink: ((keyCode: Int, down: Boolean) -> Unit)? = null
private var appContext: Context? = null
private val main = Handler(Looper.getMainLooper())
fun init(context: Context) { appContext = context.applicationContext }
/**
* Every key worth asking the head unit for. The binding request lists what the head unit
* offered; when it offers nothing (some units leave the list empty and send keys anyway),
* this is what's asked for instead.
*/
val WANTED = listOf(
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE,
KeyEvent.KEYCODE_MEDIA_NEXT, KeyEvent.KEYCODE_MEDIA_PREVIOUS, KeyEvent.KEYCODE_MEDIA_STOP,
KeyEvent.KEYCODE_SEARCH, KeyEvent.KEYCODE_VOICE_ASSIST,
KeyEvent.KEYCODE_CALL, KeyEvent.KEYCODE_ENDCALL,
KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_HOME,
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
KEYCODE_ROTARY_CONTROLLER, KEYCODE_MEDIA, KEYCODE_NAVIGATION, KEYCODE_TEL,
)
/**
* One key edge from the head unit. Most keys act on the press; focus keys pass both edges on,
* so a held D-pad key repeats the way it would anywhere else. Returns false for a key nothing
* here knows, for the caller to log.
*/
fun onKey(keyCode: Int, down: Boolean, longPress: Boolean): Boolean {
if (keyCode in FOCUS_KEYS) {
_focusMoves.tryEmit(Unit)
focusSink?.invoke(keyCode, down)
return true
}
if (!down) return keyCode in WANTED
val media = CarServices.media
when (keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> media.togglePlay()
KeyEvent.KEYCODE_MEDIA_PLAY -> if (!media.now.value.playing) media.togglePlay()
KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_MEDIA_STOP -> if (media.now.value.playing) media.togglePlay()
KeyEvent.KEYCODE_MEDIA_NEXT -> media.next()
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> media.previous()
KeyEvent.KEYCODE_SEARCH, KeyEvent.KEYCODE_VOICE_ASSIST -> voice()
KeyEvent.KEYCODE_CALL -> call()
KeyEvent.KEYCODE_ENDCALL -> endCall()
KeyEvent.KEYCODE_BACK -> screen(ScreenKey.BACK)
KeyEvent.KEYCODE_HOME -> screen(ScreenKey.HOME)
KEYCODE_NAVIGATION -> screen(ScreenKey.MAP)
KEYCODE_MEDIA -> screen(ScreenKey.MEDIA)
KEYCODE_TEL -> screen(ScreenKey.PHONE)
else -> return false
}
if (longPress) GearslipLog.i("keys: long press on $keyCode")
return true
}
/** A turn of the rotary knob: each click moves focus one step, like Tab or Shift+Tab. */
fun onRotate(delta: Int) {
val sink = focusSink ?: return
_focusMoves.tryEmit(Unit)
val code = if (delta > 0) KeyEvent.KEYCODE_TAB else KEYCODE_SHIFT_TAB
repeat(kotlin.math.abs(delta).coerceAtMost(MAX_ROTARY_STEPS)) {
sink(code, true)
sink(code, false)
}
}
/**
* The voice key: answers the message on screen if there is one, otherwise starts the
* assistant.
*/
private fun voice() = main.post {
if (!VoiceReply.onVoiceKey()) CarAssistant.start()
}
/** Answers a ringing call; with nothing ringing, opens the phone screen. */
private fun call() = main.post {
val context = appContext ?: return@post
if (CarCalls.state.value is CallUiState.Ringing) CarCalls.answer(context) else screen(ScreenKey.PHONE)
}
private fun endCall() = main.post {
if (CarCalls.state.value is CallUiState.Ringing) CarCalls.decline()
else GearslipLog.i("keys: end call pressed with no ringing call; hanging up needs the dialer")
}
private fun screen(key: ScreenKey) { _screenKeys.tryEmit(key) }
// aap_protobuf's KeyCode.proto: car-only keys past the end of Android's own range.
const val KEYCODE_ROTARY_CONTROLLER = 65536
const val KEYCODE_MEDIA = 65537
const val KEYCODE_NAVIGATION = 65538
const val KEYCODE_TEL = 65540
/** Stands in for Shift+Tab: the sink sends Tab with the shift meta state. */
const val KEYCODE_SHIFT_TAB = -KeyEvent.KEYCODE_TAB
private const val MAX_ROTARY_STEPS = 5
private val FOCUS_KEYS = setOf(
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
)
}
@@ -1,8 +1,6 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
@@ -15,21 +13,17 @@ import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmap
@@ -42,26 +36,10 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap import androidx.core.graphics.drawable.toBitmap
import android.content.Context import android.content.Context
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.graphics.Color
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.border
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Warning
import app.seb3thehacker.gearslip.host.KnownApps
import app.seb3thehacker.gearslip.host.CarAppCatalog import app.seb3thehacker.gearslip.host.CarAppCatalog
import app.seb3thehacker.gearslip.host.TemplateApp import app.seb3thehacker.gearslip.host.TemplateApp
import app.seb3thehacker.gearslip.media.MediaApp import app.seb3thehacker.gearslip.media.MediaApp
import app.seb3thehacker.gearslip.media.MediaCatalog import app.seb3thehacker.gearslip.media.MediaCatalog
import app.seb3thehacker.gearslip.notify.MessagingApp
import app.seb3thehacker.gearslip.notify.MessagingCatalog
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -70,198 +48,64 @@ private class Tile(
val label: String, val label: String,
val icon: ImageBitmap? = null, val icon: ImageBitmap? = null,
val glyph: ImageVector? = null, val glyph: ImageVector? = null,
/** Known not to work; drawn with a red X instead of being left off the launcher. */
val broken: Boolean = false,
val onLongClick: (() -> Unit)? = null,
val onClick: () -> Unit, val onClick: () -> Unit,
) )
/** A launcher app's data, kept apart from [Tile] so it can be cached without capturing click state. */ /** A launcher app's data, kept apart from [Tile] so it can be cached without capturing click state. */
internal class Entry( private class Entry(
val label: String, val label: String,
val icon: ImageBitmap?, val icon: ImageBitmap?,
val template: TemplateApp? = null, val template: TemplateApp? = null,
val media: MediaApp? = null, val media: MediaApp? = null,
val builtIn: BuiltInApp? = null, )
val messaging: MessagingApp? = null,
) {
/** What a pin or a nav-bar shortcut remembers this entry as; null for nothing pinnable. */
val componentId: String?
get() = builtIn?.let { BUILT_IN_PREFIX + it.id }
?: messaging?.let { MESSAGING_PREFIX + it.packageName }
?: (template?.component ?: media?.component)?.flattenToString()
val packageName: String?
get() = template?.component?.packageName ?: media?.component?.packageName ?: messaging?.packageName
}
/** A messaging app has no component of its own to open, so its pin carries the package instead. */
internal const val MESSAGING_PREFIX = "messages:"
/** /**
* The installed car and media apps with their icons. Scanning the package manager and decoding * The installed car and media apps with their icons. Scanning the package manager and decoding
* icons is slow, so [Prefetch] does it ahead of time and again at the start of each car session, * icons is slow, so it happens once per car session; [invalidate] is called when one starts, which
* which is when new installs are picked up. * is the only time new installs are picked up.
*/ */
internal object LauncherCache { private object LauncherCache {
/** Observed, not read once: the nav bar is drawn before the car session's rescan finishes, @Volatile var entries: List<Entry>? = null
* and an app installed since the last scan has to show up there when it does. */
private val flow = MutableStateFlow<List<Entry>?>(null)
val state: StateFlow<List<Entry>?> = flow.asStateFlow()
val entries: List<Entry>? get() = flow.value fun invalidate() { entries = null }
/** Returns the scan if there is one; [force] rescans. Synchronized so two callers share one scan. */ fun load(context: Context): List<Entry> {
@Synchronized
fun load(context: Context, force: Boolean = false): List<Entry> {
if (!force) entries?.let { return it }
fun iconOf(pkg: String) = runCatching { fun iconOf(pkg: String) = runCatching {
context.packageManager.getApplicationIcon(pkg).toBitmap(128, 128).asImageBitmap() context.packageManager.getApplicationIcon(pkg).toBitmap(128, 128).asImageBitmap()
}.getOrNull() }.getOrNull()
val navApps = CarAppCatalog.installed(context) val nav = CarAppCatalog.installed(context).map { Entry(it.label, iconOf(it.component.packageName), template = it) }
val mediaApps = MediaCatalog.installed(context) val media = MediaCatalog.installed(context).map { Entry(it.label, iconOf(it.component.packageName), media = it) }
// Some apps (Spotify among them) ship both a Car App Library template and a legacy return (nav + media).sortedBy { it.label.lowercase() }.also { entries = it }
// MediaBrowserService, which otherwise land as two identically-labeled tiles with no
// way to tell them apart. They're genuinely different screens - browsing versus Now
// Playing - so only the label needs disambiguating, not the tile itself.
val mediaPackages = mediaApps.map { it.component.packageName }.toSet()
val messagingApps = MessagingCatalog.installed(context)
// Google Messages ships its own car app, which won't start under Gearslip. Gearslip's
// own Messages screen does the same job, so a messenger gets only that tile.
val messagingPackages = messagingApps.map { it.packageName }.toSet()
val nav = navApps
.filter { it.component.packageName !in messagingPackages }
// An app whose template screen is rejected but whose player works through Gearslip
// (Spotify) shows only its player tile - a "· Browse" tile beside it would just report
// that the car screen isn't supported.
.filter { !(KnownApps.screenBroken(it.component.packageName) && KnownApps.playerWorks(it.component.packageName)) }
.map {
val label = if (it.component.packageName in mediaPackages) "${it.label} · Browse" else it.label
Entry(label, iconOf(it.component.packageName), template = it)
}
val media = mediaApps.map { Entry(it.label, iconOf(it.component.packageName), media = it) }
// A messenger that is also a car media app keeps only its player tile.
val messaging = messagingApps
.filter { it.packageName !in mediaPackages }
.map { Entry(it.label, iconOf(it.packageName), messaging = it) }
return (nav + media + messaging).sortedBy { it.label.lowercase() }.also { flow.value = it }
} }
} }
/** Every app the launcher knows: Gearslip's own and the installed ones, rescans included. */ /** Forgets the scanned apps so the next launcher open rescans; call at the start of a car session. */
@Composable fun invalidateLauncherApps() = LauncherCache.invalidate()
internal fun rememberAllEntries(): List<Entry> {
val context = LocalContext.current
val installed by LauncherCache.state.collectAsState()
LaunchedEffect(context) {
if (LauncherCache.entries == null) withContext(Dispatchers.IO) { LauncherCache.load(context) }
}
return remember(installed) { BuiltInApps.entries + installed.orEmpty() }
}
/** The launcher's groups, in the order they're laid out. */ /** The app launcher: Web and Screen sharing, every car app the phone has, then Settings, as an icon grid. */
private enum class AppGroup { PHONE, MAPS, MUSIC, MESSAGING, WEB, SCREEN_SHARING, OTHER, SETTINGS, EXIT }
private fun groupOf(entry: Entry, mediaPackages: Set<String>): AppGroup {
entry.builtIn?.let {
return when (it) {
BuiltInApps.Phone -> AppGroup.PHONE
BuiltInApps.Web -> AppGroup.WEB
BuiltInApps.ScreenSharing -> AppGroup.SCREEN_SHARING
BuiltInApps.Exit -> AppGroup.EXIT
else -> AppGroup.SETTINGS
}
}
if (entry.media != null) return AppGroup.MUSIC
if (entry.messaging != null) return AppGroup.MESSAGING
val app = entry.template ?: return AppGroup.OTHER
// A media app's "· Browse" tile sits next to its player.
if (app.component.packageName in mediaPackages) return AppGroup.MUSIC
return when (app.kind) {
"calling" -> AppGroup.PHONE
"navigation", "poi", "parking", "charging" -> AppGroup.MAPS
// Template-only media apps may have no legacy browser/player tile to identify them.
"media" -> AppGroup.MUSIC
"messaging" -> AppGroup.MESSAGING
"settings" -> AppGroup.SETTINGS
else -> AppGroup.OTHER
}
}
/**
* The launcher's tiles in the order they're drawn: grouped by [AppGroup], alphabetical inside a
* group with Settings last of all, then with the driver's own moves from [custom] laid over it.
* Moved apps only trade places among themselves, so an app installed later still lands in its group.
*/
internal fun launcherOrder(all: List<Entry>, showVehicleData: Boolean, custom: List<String>): List<Entry> {
val shown = all.filter { it.builtIn !== BuiltInApps.VehicleData || showVehicleData }
val mediaPackages = shown.mapNotNull { it.media?.component?.packageName }.toSet()
val grouped = shown.sortedWith(
compareBy<Entry>({ groupOf(it, mediaPackages) }, { it.builtIn === BuiltInApps.Settings }, { it.label.lowercase() }),
)
if (custom.isEmpty()) return grouped
val rank = custom.withIndex().associate { (i, id) -> id to i }
fun Entry.rank() = componentId?.let { rank[it] }
val moved = grouped.filter { it.rank() != null }.sortedBy { it.rank() }.iterator()
return grouped.map { if (it.rank() != null) moved.next() else it }
}
/** An app by the id a pin or the running list knows it by, built-in or installed. */
internal fun findEntry(id: String): Entry? =
BuiltInApps.entries.find { it.componentId == id } ?: LauncherCache.entries?.find { it.componentId == id }
/** Rescans the car and media apps now, replacing the cached list; the launcher keeps showing the old one meanwhile. */
fun warmLauncherApps(context: Context) { LauncherCache.load(context, force = true) }
/**
* Connects or opens [entry] - what tapping its tile does, shared with the nav bar's pinned
* shortcuts and its open-app icon so there is exactly one place that knows how to launch either
* kind of app.
*/
internal fun launchEntry(entry: Entry, navigator: CarNavigator, frame: CarEnvironment.Frame) {
entry.builtIn?.let { it.open(navigator); return }
entry.template?.let {
if (it.isNavigation) {
CarServices.connectNav(it, frame)
navigator.home()
} else {
CarServices.connectBrowse(it, frame)
navigator.browse(entry.label)
}
}
entry.media?.let { CarServices.openMedia(it); navigator.media() }
entry.messaging?.let { navigator.messages(it.packageName, it.label) }
}
/** The app launcher: every app as an icon grid, grouped Phone, Maps, Music, Messaging, Web, Screen sharing, Settings. */
@Composable @Composable
fun CarLauncher() { fun CarLauncher() {
val context = LocalContext.current val context = LocalContext.current
val navigator = LocalCarNavigator.current val navigator = LocalCarNavigator.current
val frame by CarEnvironment.frame.collectAsState() val frame by CarEnvironment.frame.collectAsState()
// Painted from the cache at once; scanned only if [Prefetch] has not got there first. // Scanned once per car session (see LauncherCache), not every time the launcher opens.
val all = rememberAllEntries() val installed by produceState(initialValue = LauncherCache.entries ?: emptyList(), context) {
val running = rememberRunningApps() value = LauncherCache.entries ?: withContext(Dispatchers.IO) { LauncherCache.load(context) }
val showVehicleData = rememberVehicleDataShown()
fun tileOf(entry: Entry): Tile {
// Only apps that don't work get a mark. The X rates an app's own car screens; a messenger
// shown on Gearslip's own Messages screen has none, so it never gets one.
val pkg = entry.packageName?.takeIf { entry.messaging == null }
val id = entry.componentId
return Tile(
entry.label, entry.icon, entry.builtIn?.glyph,
broken = pkg != null && (KnownApps.isBroken(context, pkg) || (entry.template != null && KnownApps.screenBroken(pkg))),
onLongClick = id?.let { { navigator.showAppMenu(it) } },
) { openApp(entry, id?.let { running[it] }, navigator, frame) }
} }
val appOrder by CarSettings.appOrder.collectAsState() val tiles = listOf(
val tiles = launcherOrder(all, showVehicleData, appOrder).map(::tileOf) Tile("Web", glyph = Icons.Filled.Search) { navigator.open("web") },
Tile("Screen sharing", glyph = Icons.Filled.Share) { navigator.open("phone") },
) + installed.map { entry ->
Tile(entry.label, entry.icon) {
entry.template?.let { CarServices.connectNav(it, frame); navigator.home() }
entry.media?.let { CarServices.openMedia(it); navigator.media() }
}
} + listOf(
Tile("Settings", glyph = Icons.Filled.Settings) { navigator.settings() },
)
LazyVerticalGrid( LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 108.dp), columns = GridCells.Adaptive(minSize = 108.dp),
@@ -274,72 +118,33 @@ fun CarLauncher() {
} }
} }
/** A red disc with a white X: marks a tile known not to work with Gearslip yet. */
@Composable
private fun BrokenBadge(size: androidx.compose.ui.unit.Dp, modifier: Modifier = Modifier) {
Box(
modifier.size(size).background(Color(0xFFD32F2F), CircleShape),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Close, contentDescription = "Doesn't work with Gearslip", tint = Color.White, modifier = Modifier.size(size * 0.66f))
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
private fun AppTile(tile: Tile) { private fun AppTile(tile: Tile) {
val shape = MaterialTheme.shapes.extraLarge Surface(
// A long press opens the app's menu (pin, close) - the same gesture everywhere apps are
// shown, here and on the nav bar. GsIconBox marks it in the theme's style.
GsIconBox(
onClick = tile.onClick, onClick = tile.onClick,
onLongClick = tile.onLongClick,
modifier = Modifier.height(120.dp), modifier = Modifier.height(120.dp),
colors = GsColors(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.colorScheme.onSurfaceVariant), shape = MaterialTheme.shapes.extraLarge,
shape = shape, color = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
) { ) {
Box(Modifier.fillMaxSize()) {
Column( Column(
Modifier.fillMaxSize().padding(8.dp), Modifier.fillMaxSize().padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
) { ) {
Box {
TileIcon(tile)
if (tile.broken) {
// Pinned to the icon's lower corner, ringed in the tile's colour so it
// reads as sitting on top of the icon.
BrokenBadge(
22.dp,
Modifier.align(Alignment.BottomEnd).offset(x = 6.dp, y = 4.dp)
.border(2.dp, MaterialTheme.colorScheme.surfaceVariant, CircleShape),
)
}
}
Spacer(Modifier.height(8.dp))
TileLabel(tile)
}
}
}
}
@Composable
private fun TileIcon(tile: Tile) {
when { when {
tile.icon != null -> Image(tile.icon, contentDescription = null, modifier = Modifier.size(52.dp)) tile.icon != null -> Image(tile.icon, contentDescription = null, modifier = Modifier.size(52.dp))
tile.glyph != null -> Icon(tile.glyph, contentDescription = null, modifier = Modifier.size(52.dp)) tile.glyph != null -> Icon(tile.glyph, contentDescription = null, modifier = Modifier.size(52.dp))
} }
} Spacer(Modifier.height(8.dp))
@Composable
private fun TileLabel(tile: Tile, maxLines: Int = 2, modifier: Modifier = Modifier) {
Text( Text(
tile.label, tile.label,
modifier = modifier,
style = MaterialTheme.typography.labelLarge, style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
maxLines = maxLines, maxLines = 2,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
}
}
} }
@@ -1,7 +1,6 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.staticCompositionLocalOf
@@ -14,139 +13,45 @@ sealed interface CarScreen {
/** Opened from the clock: the day's calendar and the weather, nothing that needs a keyboard. */ /** Opened from the clock: the day's calendar and the weather, nothing that needs a keyboard. */
data object Dashboard : CarScreen data object Dashboard : CarScreen
/** Opened from the weather chip or the dashboard: now, the next hours and the week. */
data object Weather : CarScreen
/** Everything the head unit's sensor channel has advertised and sent, raw. */
data object VehicleData : CarScreen
/** The current media app, full size: browse, lyrics and controls. */ /** The current media app, full size: browse, lyrics and controls. */
data object Media : CarScreen data object Media : CarScreen
/**
* A templated app that isn't a navigation app - Spotify's own Car App Library service, among
* others - opened on its own screen rather than the Home map slot, which only a genuine
* navigation app can claim.
*/
data object Browse : CarScreen
/** A messaging app's recent conversations, read from the notifications it posts. */
data class Messages(val packageName: String) : CarScreen
/** [replyTo] is a notification key to open straight into its reply pane. */ /** [replyTo] is a notification key to open straight into its reply pane. */
data class Notifications(val replyTo: String? = null) : CarScreen data class Notifications(val replyTo: String? = null) : CarScreen
data class App(val id: String) : CarScreen data class App(val id: String) : CarScreen
} }
enum class SidePanel { NONE, CONTROLS, LYRICS }
/** One step on the breadcrumb trail: the screen it shows and the word for it in the trail. */
data class Crumb(val screen: CarScreen, val label: String)
/** /**
* Where the car UI is, and how it got there. A car touchscreen has no hardware back button, so * Where the car UI is. A car touchscreen has no hardware back button, so [back] is driven by
* every screen that isn't reached from [home] is pushed onto a trail (like a browser's history, * the on-screen one; an open app can claim it first (a browser going back a page) through
* or a file manager's breadcrumb bar) rather than replacing the last one outright - that's what * [backInterceptor].
* lets the breadcrumb bar show "Home > Apps > Settings" and jump straight back to any of them,
* and lets [back] undo exactly one step instead of always dumping you back at Home. An open app
* can claim a back step first (a browser going back a page) through [backInterceptor].
*/ */
class CarNavigator(startId: String) { class CarNavigator(startId: String) {
private val stack = mutableStateListOf( var current: CarScreen by mutableStateOf(
Crumb(
if (CarApps.find(startId) != null) CarScreen.App(startId) else CarScreen.Home, if (CarApps.find(startId) != null) CarScreen.App(startId) else CarScreen.Home,
"Home",
),
) )
private set
/** The whole trail, root first. Size 1 means "at Home" - the breadcrumb bar hides then. */
val trail: List<Crumb> get() = stack
val current: CarScreen get() = stack.last().screen
var backInterceptor: (() -> Boolean)? = null var backInterceptor: (() -> Boolean)? = null
/** Pushes a new step, unless it's the same screen already on top - tapping the button for fun home() { current = CarScreen.Home }
* where you already are shouldn't grow the trail. */
private fun push(screen: CarScreen, label: String) {
if (stack.last().screen == screen) return
stack.add(Crumb(screen, label))
}
/** The one way back to a clean slate: resets the whole trail to just Home. */ fun media() { current = CarScreen.Media }
fun home() {
stack.clear()
stack.add(Crumb(CarScreen.Home, "Home"))
}
/** fun apps() { current = CarScreen.Apps }
* What the column beside the map on Home is showing, if anything. The player lives in one
* place at a time: with [SidePanel.CONTROLS] it moves into the column and the nav bar's pill
* steps aside; with [SidePanel.LYRICS] the column is all lyrics and the pill comes back.
* Every other screen has no room for the column, so there the pill stays in the nav bar.
*/
var sidePanel by mutableStateOf(SidePanel.NONE)
private set
/** fun settings() { current = CarScreen.Settings }
* The pill's dock button: moves the player beside the map, going Home first if need be. With
* lyrics already there it swaps them for the controls; with the controls there it closes.
*/
fun togglePlayerDock() {
if (current != CarScreen.Home) {
sidePanel = SidePanel.CONTROLS
home()
return
}
sidePanel = if (sidePanel == SidePanel.CONTROLS) SidePanel.NONE else SidePanel.CONTROLS
}
fun showSideLyrics() { sidePanel = SidePanel.LYRICS } fun dashboard() { current = CarScreen.Dashboard }
fun closeSidePanel() { sidePanel = SidePanel.NONE } fun notifications(replyTo: String? = null) { current = CarScreen.Notifications(replyTo) }
/** Component id of the app whose long-press menu (pin, close) is open, or null. */ fun open(id: String) { current = CarScreen.App(id) }
var appMenu by mutableStateOf<String?>(null)
private set
fun showAppMenu(componentId: String) { appMenu = componentId }
fun dismissAppMenu() { appMenu = null }
fun media() { push(CarScreen.Media, "Media") }
fun browse(label: String) { push(CarScreen.Browse, label) }
fun apps() { push(CarScreen.Apps, "Apps") }
fun settings() { push(CarScreen.Settings, "Settings") }
fun dashboard() { push(CarScreen.Dashboard, "Dashboard") }
fun weather() { push(CarScreen.Weather, "Weather") }
fun vehicleData() { push(CarScreen.VehicleData, "Vehicle data") }
fun messages(packageName: String, label: String) { push(CarScreen.Messages(packageName), label) }
/** The list lives on the dashboard; only a reply gets a screen of its own. */
fun notifications(replyTo: String? = null) {
if (replyTo == null) dashboard() else push(CarScreen.Notifications(replyTo), "Reply")
}
fun open(id: String) { push(CarScreen.App(id), CarApps.find(id)?.label ?: id) }
/** Jumps straight to a step already on the trail, dropping everything after it - what
* tapping a breadcrumb does. Index 0 (Home) is always on the trail, so this always succeeds. */
fun jumpTo(index: Int) {
while (stack.size > index + 1) stack.removeAt(stack.lastIndex)
}
/** One step back, same as tapping the crumb before the current one. */
fun back() { fun back() {
if (backInterceptor?.invoke() == true) return if (backInterceptor?.invoke() == true) return
if (stack.size > 1) stack.removeAt(stack.lastIndex) current = CarScreen.Home
} }
} }
@@ -1,95 +0,0 @@
package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.Protobuf
import app.seb3thehacker.gearslip.Wire
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* Everything the head unit's sensor channel has offered and sent, for the "Vehicle data" screen.
*
* [ServiceDiscovery.findSensorService] tells us which numeric sensor types this head unit is
* willing to stream; [SensorType] names the ones publicly documented by other AA reverse-engineering
* projects (aasdk, openauto). That mapping is carried over from other projects, not verified
* against this exact unit, so it's a label, not a guarantee - the raw field dump next to it is
* the ground truth. Once [onEvent] starts decoding real traffic from the 2018 Uconnect, correct
* any type that turns out to be mislabeled.
*/
object CarSensors {
data class Reading(val typeId: Int, val typeName: String, val raw: String, val updatedAtMs: Long)
private val readingsFlow = MutableStateFlow<List<Reading>>(emptyList())
val readings: StateFlow<List<Reading>> = readingsFlow
/** Seeds one row per sensor type the head unit advertised, so the screen shows what's on
* offer even before the first event for it arrives. */
fun onDiscovered(types: List<Int>) {
readingsFlow.value = types.map { id ->
Reading(id, SensorType.name(id), "(waiting for data)", 0L)
}
}
/**
* One SensorEventIndication. Every reverse-engineered version of this message multiplexes
* every sensor type into one shared set of message-level field numbers (field N = "the data
* for sensor type N", roughly) rather than tagging events with the type id from
* SensorType.type - so field number is read here as a best-effort type id, same as the
* other services in this file.
*/
fun onEvent(body: ByteArray) {
val now = System.currentTimeMillis()
val fields = Wire.fields(body)
val byType = fields.groupBy { it.number }
val updated = byType.mapValues { (number, group) ->
Reading(
number,
SensorType.name(number),
group.joinToString("; ") { field ->
field.bytes?.let { Protobuf.describe(it, indent = "").trim().replace("\n", ", ") }
?: "varint=${field.varint}"
},
now,
)
}
val existing = readingsFlow.value.associateBy { it.typeId }
readingsFlow.value = (existing + updated).values.sortedBy { it.typeId }
}
fun clear() {
readingsFlow.value = emptyList()
}
}
/**
* Sensor type ids as named across public Android Auto reverse-engineering references. Treated as
* a label, not a fact - see [CarSensors] doc.
*/
object SensorType {
private val NAMES = mapOf(
1 to "Location (GPS)",
2 to "Compass",
3 to "Speed",
4 to "RPM",
5 to "Odometer",
6 to "Fuel",
7 to "Parking brake",
8 to "Gear",
9 to "Diagnostics",
10 to "Night mode",
11 to "Environment",
12 to "HVAC",
13 to "Driving status",
14 to "Dead reckoned location",
15 to "Passenger",
16 to "Door",
17 to "Light",
18 to "Tire pressure",
19 to "Accelerometer",
20 to "Gyroscope",
21 to "GPS satellites",
22 to "Toll card",
)
fun name(id: Int): String = NAMES[id]?.let { "$it (#$id)" } ?: "Sensor #$id"
}
@@ -2,17 +2,13 @@ package app.seb3thehacker.gearslip.car
import android.content.ComponentName import android.content.ComponentName
import android.content.Context import android.content.Context
import android.media.session.MediaSessionManager
import android.media.session.PlaybackState
import app.seb3thehacker.gearslip.audio.CarAudio import app.seb3thehacker.gearslip.audio.CarAudio
import app.seb3thehacker.gearslip.host.CarAppCatalog import app.seb3thehacker.gearslip.host.CarAppCatalog
import app.seb3thehacker.gearslip.host.CarAppConnection import app.seb3thehacker.gearslip.host.CarAppConnection
import app.seb3thehacker.gearslip.host.KnownApps
import app.seb3thehacker.gearslip.host.TemplateApp import app.seb3thehacker.gearslip.host.TemplateApp
import app.seb3thehacker.gearslip.media.CarMedia import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.media.MediaApp import app.seb3thehacker.gearslip.media.MediaApp
import app.seb3thehacker.gearslip.media.MediaCatalog import app.seb3thehacker.gearslip.media.MediaCatalog
import app.seb3thehacker.gearslip.notify.GearslipNotificationListener
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
@@ -33,29 +29,9 @@ object CarServices {
val nav: CarAppConnection by lazy { CarAppConnection(requireNotNull(context)) } val nav: CarAppConnection by lazy { CarAppConnection(requireNotNull(context)) }
val media: CarMedia by lazy { CarMedia(requireNotNull(context)) } val media: CarMedia by lazy { CarMedia(requireNotNull(context)) }
/** [nav], or null before the car screen has set things up. */
fun navOrNull(): CarAppConnection? = if (context != null) nav else null
/** [media], or null before the car screen has set things up: for code outside the car UI. */
fun mediaOrNull(): CarMedia? = if (context != null) media else null
/**
* A second, independent connection for templated apps that aren't navigation apps - Spotify's
* own Car App Library service is the first of these. Kept apart from [nav] so opening one
* can never bump the map off Home: this one gets its own screen ([CarScreen.Browse]) instead.
*/
val browse: CarAppConnection by lazy { CarAppConnection(requireNotNull(context)) }
private val _mediaApp = MutableStateFlow<MediaApp?>(null) private val _mediaApp = MutableStateFlow<MediaApp?>(null)
val mediaApp: StateFlow<MediaApp?> = _mediaApp.asStateFlow() val mediaApp: StateFlow<MediaApp?> = _mediaApp.asStateFlow()
/**
* Whether the phone has any navigation app installed at all. True until [autostart] has
* actually checked, so the home screen never flashes "none found" before it knows.
*/
private val _hasNavApps = MutableStateFlow(true)
val hasNavApps: StateFlow<Boolean> = _hasNavApps.asStateFlow()
/** Set when the driver stops the map by hand, so going Home doesn't immediately restart it. */ /** Set when the driver stops the map by hand, so going Home doesn't immediately restart it. */
private var navStopped = false private var navStopped = false
private var autoplayPending = false private var autoplayPending = false
@@ -63,65 +39,21 @@ object CarServices {
fun init(appContext: Context) { fun init(appContext: Context) {
context = appContext.applicationContext context = appContext.applicationContext
app.seb3thehacker.gearslip.notify.CarMotion.start(appContext) app.seb3thehacker.gearslip.notify.CarMotion.start(appContext)
app.seb3thehacker.gearslip.call.CarCalls.start(appContext)
CarAssistant.init(appContext)
DirectionsVoice.init(appContext)
CarBluetooth.init(appContext)
BluetoothAudioCheck.init(appContext)
LocationCheck.init(appContext)
CarKeys.init(appContext)
VoiceReply.init(appContext)
// Loaded now, while nothing's waiting on it, so the first reply isn't slower than the rest.
app.seb3thehacker.gearslip.speech.SpeechEngine.warm(appContext)
} }
// --- map ----------------------------------------------------------------------------- // --- map -----------------------------------------------------------------------------
/** fun connectNav(app: TemplateApp, frame: CarEnvironment.Frame) {
* [destination] is a search query to start navigating to right away - "navigate to X with Y"
* from the voice assistant - left null for a plain app launch. An app that's already the one
* running gets the destination sent to its live session instead of being torn down and
* rebuilt, same as [CarAppConnection.navigateTo] documents.
*/
fun connectNav(app: TemplateApp, frame: CarEnvironment.Frame, destination: String? = null) {
navStopped = false navStopped = false
CarSettings.setLastNav(app.component.flattenToString()) CarSettings.setLastNav(app.component.flattenToString())
if (destination != null && nav.connectedComponent == app.component) { nav.connect(app, frame.width, frame.height, frame.densityDpi)
nav.navigateTo(destination)
} else {
// Another map app taking over ends the old one's route, or it keeps guiding unseen.
if (nav.connectedComponent != app.component) endRoute()
nav.connect(app, frame.width, frame.height, frame.densityDpi, destination)
}
} }
fun stopNav() { fun stopNav() {
navStopped = true navStopped = true
endRoute()
nav.disconnect() nav.disconnect()
} }
private fun endRoute() {
if (nav.navigating) nav.stopNavigating()
}
/** Undoes [stopNav]'s hold so the last map app comes back, same as it would after a restart. */
suspend fun reconnectNav(frame: CarEnvironment.Frame) {
navStopped = false
autostart(frame)
}
// --- browse (non-navigation templated apps) -------------------------------------------
/** Opens a templated app that isn't navigation, on its own screen - never on Home. */
fun connectBrowse(app: TemplateApp, frame: CarEnvironment.Frame) {
browse.connect(app, frame.width, frame.height, frame.densityDpi)
}
fun stopBrowse() {
browse.disconnect()
}
// --- media --------------------------------------------------------------------------- // --- media ---------------------------------------------------------------------------
fun openMedia(app: MediaApp, autoplay: Boolean = false) { fun openMedia(app: MediaApp, autoplay: Boolean = false) {
@@ -130,33 +62,11 @@ object CarServices {
val live = phase == CarMedia.Phase.READY || phase == CarMedia.Phase.CONNECTING val live = phase == CarMedia.Phase.READY || phase == CarMedia.Phase.CONNECTING
if (_mediaApp.value?.component == app.component && live) return if (_mediaApp.value?.component == app.component && live) return
CarAudio.release()
_mediaApp.value = app _mediaApp.value = app
autoplayPending = autoplay autoplayPending = autoplay
media.connect(app) media.connect(app)
// Not torn down and rebuilt per app: the capture covers whatever the phone plays, so if (CarSettings.pipeAudio.value) CarAudio.request(app.uid)
// switching media apps never costs the driver another consent dialog.
if (CarSettings.pipeAudio.value) CarAudio.request()
}
/**
* Reopens the media app used last, for the car's media button when nothing is open. False
* when there's none on record or it's been uninstalled since.
*/
suspend fun reopenLastMedia(): Boolean {
val ctx = context ?: return false
val last = CarSettings.lastMedia.value?.let(ComponentName::unflattenFromString) ?: return false
val app = withContext(Dispatchers.IO) { MediaCatalog.installed(ctx) }
.firstOrNull { it.component == last } ?: return false
openMedia(app)
return true
}
/** Closes the media app from the car: stops what it's playing and drops the connection. */
fun closeMedia() {
if (media.now.value.playing) media.togglePlay()
media.disconnect()
_mediaApp.value = null
autoplayPending = false
} }
/** Called once the media app is connected: starts playback if that was asked for. */ /** Called once the media app is connected: starts playback if that was asked for. */
@@ -173,93 +83,29 @@ object CarServices {
val ctx = context ?: return val ctx = context ?: return
if (!navStopped && nav.status.value.phase == CarAppConnection.Phase.IDLE) { if (!navStopped && nav.status.value.phase == CarAppConnection.Phase.IDLE) {
val navApps = withContext(Dispatchers.IO) { CarAppCatalog.installed(ctx) }
.filter { it.isNavigation }
_hasNavApps.value = navApps.isNotEmpty()
// Never auto-pick one already known to fail outright - a driver who plugs in should
// land on a map, not on the one tile marked with a red X.
val candidates = navApps.filterNot { KnownApps.isBroken(ctx, it.component.packageName) }
val last = CarSettings.lastNav.value val last = CarSettings.lastNav.value
// The one used last, or - first run, nothing on record yet - whichever comes first: val app = last?.let { id ->
// a driver who plugs in for the first time shouldn't have to go pick one by hand withContext(Dispatchers.IO) { CarAppCatalog.installed(ctx) }
// before the map shows up at all. .firstOrNull { it.component == ComponentName.unflattenFromString(id) }
val lastComponent = last?.let(ComponentName::unflattenFromString) }
val app = candidates.firstOrNull { it.component == lastComponent } ?: candidates.firstOrNull()
if (app != null) connectNav(app, frame) if (app != null) connectNav(app, frame)
} }
if (_mediaApp.value == null) { if (_mediaApp.value == null) {
val catalog = withContext(Dispatchers.IO) { MediaCatalog.installed(ctx) }
// Something already playing on the phone wins over whatever was last used in the car -
// a driver who started a song before plugging in shouldn't have to go open its tile by
// hand just to see what's already going.
val playing = withContext(Dispatchers.IO) { currentlyPlaying(ctx, catalog) }
if (playing != null) {
openMedia(playing)
} else {
val last = CarSettings.lastMedia.value val last = CarSettings.lastMedia.value
val app = last?.let { id -> catalog.firstOrNull { it.component == ComponentName.unflattenFromString(id) } } val app = last?.let { id ->
withContext(Dispatchers.IO) { MediaCatalog.installed(ctx) }
.firstOrNull { it.component == ComponentName.unflattenFromString(id) }
}
if (app != null) openMedia(app, autoplay = CarSettings.autoplay.value) if (app != null) openMedia(app, autoplay = CarSettings.autoplay.value)
} }
} }
}
/**
* Whichever known car media app has an actively playing session right now, system-wide - not
* just the one Gearslip itself last connected to. Reading another app's session needs
* notification access, the same permission [app.seb3thehacker.gearslip.media.CarMedia]
* already asks for to control apps that won't share their library.
*/
private fun currentlyPlaying(ctx: Context, catalog: List<MediaApp>): MediaApp? {
val manager = ctx.getSystemService(MediaSessionManager::class.java)
val listener = ComponentName(ctx, GearslipNotificationListener::class.java)
val sessions = try {
manager.getActiveSessions(listener)
} catch (e: SecurityException) {
return null
}
val playingPackages = sessions
.filter { it.playbackState?.state == PlaybackState.STATE_PLAYING }
.map { it.packageName }
return playingPackages.firstNotNullOfOrNull { pkg -> catalog.firstOrNull { it.component.packageName == pkg } }
}
/**
* The car went away mid-song: pause it, as Android Auto does, so it doesn't carry on out of
* the phone's speaker. Unplugging a USB accessory isn't "audio becoming noisy" the way
* headphones are, so the apps won't pause themselves. Every playing session is paused, not
* just the one Gearslip opened: anything the car was playing was going through the car.
*/
fun pausePhoneMedia(why: String = "the car left") {
val ctx = context ?: return
val manager = ctx.getSystemService(MediaSessionManager::class.java)
val listener = ComponentName(ctx, GearslipNotificationListener::class.java)
val playing = try {
manager.getActiveSessions(listener).filter { it.playbackState?.state == PlaybackState.STATE_PLAYING }
} catch (e: SecurityException) {
null
}
if (playing == null) {
// No notification access: the app Gearslip itself is driving is all it can reach.
mediaOrNull()?.let { if (it.now.value.playing) it.togglePlay() }
return
}
playing.forEach { runCatching { it.transportControls.pause() } }
if (playing.isNotEmpty()) {
app.seb3thehacker.gearslip.GearslipLog.i("media: paused ${playing.joinToString { it.packageName }}: $why")
}
}
/** The car went away: nothing should keep running for a screen that no longer exists. */ /** The car went away: nothing should keep running for a screen that no longer exists. */
fun shutdown() { fun shutdown() {
context?.let { app.seb3thehacker.gearslip.notify.CarMotion.stop(it) } context?.let { app.seb3thehacker.gearslip.notify.CarMotion.stop(it) }
app.seb3thehacker.gearslip.call.CarCalls.stop()
runCatching { nav.disconnect() } runCatching { nav.disconnect() }
runCatching { media.disconnect() } runCatching { media.disconnect() }
runCatching { browse.disconnect() }
CarAssistant.cancel()
// About 900 MB that nothing needs once the car's gone.
app.seb3thehacker.gearslip.speech.SpeechEngine.unload()
CarAudio.release() CarAudio.release()
_mediaApp.value = null _mediaApp.value = null
navStopped = false navStopped = false
@@ -2,19 +2,11 @@ package app.seb3thehacker.gearslip.car
import android.content.Context import android.content.Context
import app.seb3thehacker.gearslip.AppSettings import app.seb3thehacker.gearslip.AppSettings
import app.seb3thehacker.gearslip.audio.CarAudio
import app.seb3thehacker.gearslip.car.theme.GsTheme
import app.seb3thehacker.gearslip.car.theme.GsThemes
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
enum class NightMode { AUTO, DAY, NIGHT } enum class NightMode { AUTO, DAY, NIGHT }
/** Distances and temperatures. [AUTO] goes by the phone's region. */
enum class Units { AUTO, IMPERIAL, METRIC }
/** Where a new message shows: [NAV_BAR] turns the clock button into it, [CARD] floats a card top right. */
/** The car UI's own colours. Separate from [NightMode], which is about the light outside (the map). */ /** The car UI's own colours. Separate from [NightMode], which is about the light outside (the map). */
enum class AppTheme { PHONE, LIGHT, DARK } enum class AppTheme { PHONE, LIGHT, DARK }
@@ -28,29 +20,10 @@ object CarSettings {
private const val KEY_OPEN = "car_open_on_connect" private const val KEY_OPEN = "car_open_on_connect"
private const val KEY_NIGHT = "car_night_mode" private const val KEY_NIGHT = "car_night_mode"
private const val KEY_PIPE_AUDIO = "car_pipe_audio" private const val KEY_PIPE_AUDIO = "car_pipe_audio"
private const val KEY_SPEAK_DIRECTIONS = "car_speak_directions"
private const val KEY_BLUETOOTH_WARNING = "car_bluetooth_warning"
private const val KEY_LOCATION_WARNING = "car_location_warning"
private const val KEY_AUDIO_CHOICE_ASKED = "car_audio_choice_asked"
private const val KEY_LAST_NAV = "car_last_nav" private const val KEY_LAST_NAV = "car_last_nav"
private const val KEY_LAST_MEDIA = "car_last_media" private const val KEY_LAST_MEDIA = "car_last_media"
private const val KEY_AUTOPLAY = "car_autoplay" private const val KEY_AUTOPLAY = "car_autoplay"
private const val KEY_PLAYER_TITLE = "car_player_title"
private const val KEY_THEME = "car_app_theme" private const val KEY_THEME = "car_app_theme"
private const val KEY_UI_THEME = "car_ui_theme"
private const val KEY_PINNED = "car_pinned_apps"
private const val KEY_APP_ORDER = "car_app_order"
private const val KEY_EXPERIMENTAL_FEATURES = "car_experimental_features"
private const val KEY_SYSTEM_SPEECH = "car_system_speech"
private const val KEY_CAR_SENSORS = "car_sensors_enabled"
private const val KEY_SEEN_SAFETY_WARNING = "car_seen_safety_warning"
private const val KEY_UNITS = "car_units"
private const val KEY_WHATS_NEW = "car_whats_new_after_updates"
private const val KEY_WHATS_NEW_SEEN = "car_whats_new_seen_code"
/** How many shortcuts the nav bar makes room for; a driver reaching for one needs it to
* still be on the bar, not off the edge of a long list. */
const val MAX_PINNED = 3
/** Id of the app to open on connect; [HOME] opens the launcher. */ /** Id of the app to open on connect; [HOME] opens the launcher. */
const val HOME = "home" const val HOME = "home"
@@ -60,78 +33,12 @@ private const val KEY_LOCATION_WARNING = "car_location_warning"
private val scaleFlow = MutableStateFlow(1f) private val scaleFlow = MutableStateFlow(1f)
private val openFlow = MutableStateFlow(HOME) private val openFlow = MutableStateFlow(HOME)
private val nightFlow = MutableStateFlow(NightMode.AUTO) private val nightFlow = MutableStateFlow(NightMode.AUTO)
private val pipeAudioFlow = MutableStateFlow(true) private val pipeAudioFlow = MutableStateFlow(false)
private val speakDirectionsFlow = MutableStateFlow(true)
private val bluetoothWarningFlow = MutableStateFlow(true)
private val locationWarningFlow = MutableStateFlow(true)
private val lastNavFlow = MutableStateFlow<String?>(null) private val lastNavFlow = MutableStateFlow<String?>(null)
private val lastMediaFlow = MutableStateFlow<String?>(null) private val lastMediaFlow = MutableStateFlow<String?>(null)
private val autoplayFlow = MutableStateFlow(false) private val autoplayFlow = MutableStateFlow(false)
private val playerTitleFlow = MutableStateFlow(false)
private val themeFlow = MutableStateFlow(AppTheme.PHONE) private val themeFlow = MutableStateFlow(AppTheme.PHONE)
val appTheme: StateFlow<AppTheme> = themeFlow val appTheme: StateFlow<AppTheme> = themeFlow
private val uiThemeFlow = MutableStateFlow(GsThemes.default.id)
/** Id of the [GsTheme] controls are drawn in; an unknown id falls back to the default. */
val uiTheme: StateFlow<String> = uiThemeFlow
private val pinnedFlow = MutableStateFlow<Set<String>>(emptySet())
private val appOrderFlow = MutableStateFlow<List<String>>(emptyList())
private val experimentalFeaturesFlow = MutableStateFlow(false)
private val systemSpeechFlow = MutableStateFlow(false)
private val carSensorsFlow = MutableStateFlow(false)
private val seenSafetyWarningFlow = MutableStateFlow(false)
private val unitsFlow = MutableStateFlow(Units.AUTO)
val units: StateFlow<Units> = unitsFlow
private val whatsNewFlow = MutableStateFlow(true)
private val whatsNewSeenFlow = MutableStateFlow(0)
private val whatsNewOpenFlow = MutableStateFlow(false)
/** Whether the car screen shows what's new once after each update. */
val whatsNewAfterUpdates: StateFlow<Boolean> = whatsNewFlow
/** Version code whose notes the car screen last showed. */
val whatsNewSeen: StateFlow<Int> = whatsNewSeenFlow
/** Opened by hand from Settings, whatever the two above say. Not saved. */
val whatsNewOpen: StateFlow<Boolean> = whatsNewOpenFlow
fun setWhatsNewAfterUpdates(on: Boolean) {
whatsNewFlow.value = on
AppSettings.putString(app, KEY_WHATS_NEW, on.toString())
}
fun openWhatsNew() { whatsNewOpenFlow.value = true }
/** Closes the notes and marks [versionCode]'s as read. */
fun closeWhatsNew(versionCode: Int) {
whatsNewOpenFlow.value = false
whatsNewSeenFlow.value = versionCode
AppSettings.putString(app, KEY_WHATS_NEW_SEEN, versionCode.toString())
}
/** Whether to show miles, feet and °F; [Units.AUTO] follows the countries that still use them. */
fun imperial(): Boolean = when (unitsFlow.value) {
Units.IMPERIAL -> true
Units.METRIC -> false
Units.AUTO -> java.util.Locale.getDefault().country in setOf("US", "LR", "MM")
}
fun setUnits(units: Units) {
unitsFlow.value = units
AppSettings.putString(app, KEY_UNITS, units.name)
Weather.refresh(app, force = true)
}
/** Flattened component names of the apps long-pressed onto the nav bar as shortcuts. */
val pinnedApps: StateFlow<Set<String>> = pinnedFlow
/** The launcher's order once the driver has moved a tile; empty keeps the grouped default. */
val appOrder: StateFlow<List<String>> = appOrderFlow
/** Flattened component names of the map and media apps used last, brought back on connect. */ /** Flattened component names of the map and media apps used last, brought back on connect. */
val lastNav: StateFlow<String?> = lastNavFlow val lastNav: StateFlow<String?> = lastNavFlow
@@ -140,77 +47,17 @@ private const val KEY_LOCATION_WARNING = "car_location_warning"
/** Whether the media app starts playing by itself when the car connects. */ /** Whether the media app starts playing by itself when the car connects. */
val autoplay: StateFlow<Boolean> = autoplayFlow val autoplay: StateFlow<Boolean> = autoplayFlow
/**
* The nav bar's player keeps the song title up, with play/pause and the dock button, instead of
* settling to the skip buttons once a new song has announced itself.
*/
val playerTitle: StateFlow<Boolean> = playerTitleFlow
val scale: StateFlow<Float> = scaleFlow val scale: StateFlow<Float> = scaleFlow
val openOnConnect: StateFlow<String> = openFlow val openOnConnect: StateFlow<String> = openFlow
val nightMode: StateFlow<NightMode> = nightFlow val nightMode: StateFlow<NightMode> = nightFlow
/** /**
* Whether a media app's sound is captured and sent over the car link. On by default, since * Whether a media app's sound is captured and sent over the car link. Off by default: the
* sound in the car is the point of the exercise; the platform allows the capture only behind a * platform only allows that behind a screen-capture consent dialog, and without it the app
* consent dialog, which [app.seb3thehacker.gearslip.audio.CarAudio] raises once the car has * simply plays through the phone's normal output (e.g. Bluetooth to the car).
* somewhere to play it. Turned off ("Bluetooth" in the settings), the app plays through the
* phone's normal output instead, and Android never asks.
*/ */
val pipeAudio: StateFlow<Boolean> = pipeAudioFlow val pipeAudio: StateFlow<Boolean> = pipeAudioFlow
/** Gearslip reads the map app's turns aloud on the car's directions channel; see DirectionsVoice. */
val speakDirections: StateFlow<Boolean> = speakDirectionsFlow
/** With Bluetooth audio, warn when the phone isn't connected to the car; see BluetoothAudioCheck. */
val bluetoothWarning: StateFlow<Boolean> = bluetoothWarningFlow
/** Warn on the car when the phone's location is off; see LocationCheck. */
val locationWarning: StateFlow<Boolean> = locationWarningFlow
/**
* Whether the driver has already been offered Bluetooth after turning down the capture
* dialog. Offered once only: someone who chose to keep the USB route shouldn't be nagged.
*/
/** False until the driver picks USB or Bluetooth, in setup or in settings. */
val pipeAudioChosen: Boolean
get() = AppSettings.getString(app, KEY_PIPE_AUDIO, "") != ""
val audioChoiceAsked: Boolean
get() = AppSettings.getString(app, KEY_AUDIO_CHOICE_ASKED, "false") == "true"
fun markAudioChoiceAsked() = AppSettings.putString(app, KEY_AUDIO_CHOICE_ASKED, "true")
/**
* Off by default: a driver has to opt into experimental features as a whole before any of
* them - the voice assistant included - show up to turn on individually.
*/
val experimentalFeaturesEnabled: StateFlow<Boolean> = experimentalFeaturesFlow
/** Listen with the phone's own speech service instead of Gearslip's on-device model. */
val systemSpeech: StateFlow<Boolean> = systemSpeechFlow
/**
* Vehicle data is experimental and off by default: the launcher's tile for it, and the
* voice assistant's "vehicle data" command, only show up once this and
* [experimentalFeaturesEnabled] are both on. See [app.seb3thehacker.gearslip.car.CarSensors]
* for why the raw sensor feed it shows is worth gating - the field labels are unverified.
*/
val carSensorsEnabled: StateFlow<Boolean> = carSensorsFlow
/**
* Whether the car screen's own "drive safely" warning has already been shown and dismissed
* once, from this same install. Separate from the phone side's own compat/safety dialogs -
* a driver who only ever plugs in and never opens the phone app should still see this once,
* on the screen they are actually about to use while driving.
*/
val hasSeenSafetyWarning: StateFlow<Boolean> = seenSafetyWarningFlow
fun markSafetyWarningSeen() {
seenSafetyWarningFlow.value = true
AppSettings.putString(app, KEY_SEEN_SAFETY_WARNING, "true")
}
fun init(context: Context) { fun init(context: Context) {
app = context.applicationContext app = context.applicationContext
scaleFlow.value = AppSettings.getString(app, KEY_SCALE, "1.0").toFloatOrNull() ?: 1f scaleFlow.value = AppSettings.getString(app, KEY_SCALE, "1.0").toFloatOrNull() ?: 1f
@@ -220,31 +67,11 @@ private const val KEY_LOCATION_WARNING = "car_location_warning"
themeFlow.value = runCatching { themeFlow.value = runCatching {
AppTheme.valueOf(AppSettings.getString(app, KEY_THEME, AppTheme.PHONE.name)) AppTheme.valueOf(AppSettings.getString(app, KEY_THEME, AppTheme.PHONE.name))
}.getOrDefault(AppTheme.PHONE) }.getOrDefault(AppTheme.PHONE)
uiThemeFlow.value = AppSettings.getString(app, KEY_UI_THEME, GsThemes.default.id)
autoplayFlow.value = AppSettings.getString(app, KEY_AUTOPLAY, "false") == "true" autoplayFlow.value = AppSettings.getString(app, KEY_AUTOPLAY, "false") == "true"
playerTitleFlow.value = AppSettings.getString(app, KEY_PLAYER_TITLE, "false") == "true" pipeAudioFlow.value = AppSettings.getString(app, KEY_PIPE_AUDIO, "false") == "true"
pipeAudioFlow.value = AppSettings.getString(app, KEY_PIPE_AUDIO, "true") == "true"
// Until the driver sets it, on for USB audio and off for Bluetooth, where the map app's
// own voice already reaches the car.
speakDirectionsFlow.value = AppSettings.getString(app, KEY_SPEAK_DIRECTIONS, pipeAudioFlow.value.toString()) == "true"
bluetoothWarningFlow.value = AppSettings.getString(app, KEY_BLUETOOTH_WARNING, "true") == "true"
locationWarningFlow.value = AppSettings.getString(app, KEY_LOCATION_WARNING, "true") == "true"
nightFlow.value = runCatching { nightFlow.value = runCatching {
NightMode.valueOf(AppSettings.getString(app, KEY_NIGHT, NightMode.AUTO.name)) NightMode.valueOf(AppSettings.getString(app, KEY_NIGHT, NightMode.AUTO.name))
}.getOrDefault(NightMode.AUTO) }.getOrDefault(NightMode.AUTO)
pinnedFlow.value = AppSettings.getString(app, KEY_PINNED, "")
.split(",").filter { it.isNotEmpty() }.toSet()
appOrderFlow.value = AppSettings.getString(app, KEY_APP_ORDER, "")
.split(",").filter { it.isNotEmpty() }
experimentalFeaturesFlow.value = AppSettings.getString(app, KEY_EXPERIMENTAL_FEATURES, "false") == "true"
systemSpeechFlow.value = AppSettings.getString(app, KEY_SYSTEM_SPEECH, "false") == "true"
carSensorsFlow.value = AppSettings.getString(app, KEY_CAR_SENSORS, "false") == "true"
seenSafetyWarningFlow.value = AppSettings.getString(app, KEY_SEEN_SAFETY_WARNING, "false") == "true"
unitsFlow.value = runCatching {
Units.valueOf(AppSettings.getString(app, KEY_UNITS, Units.AUTO.name))
}.getOrDefault(Units.AUTO)
whatsNewFlow.value = AppSettings.getString(app, KEY_WHATS_NEW, "true") == "true"
whatsNewSeenFlow.value = AppSettings.getString(app, KEY_WHATS_NEW_SEEN, "0").toIntOrNull() ?: 0
} }
fun setScale(value: Float) { fun setScale(value: Float) {
@@ -272,62 +99,14 @@ private const val KEY_LOCATION_WARNING = "car_location_warning"
AppSettings.putString(app, KEY_THEME, theme.name) AppSettings.putString(app, KEY_THEME, theme.name)
} }
fun setUiTheme(id: String) {
uiThemeFlow.value = id
AppSettings.putString(app, KEY_UI_THEME, id)
}
fun setPlayerTitle(on: Boolean) {
playerTitleFlow.value = on
AppSettings.putString(app, KEY_PLAYER_TITLE, on.toString())
}
fun setAutoplay(on: Boolean) { fun setAutoplay(on: Boolean) {
autoplayFlow.value = on autoplayFlow.value = on
AppSettings.putString(app, KEY_AUTOPLAY, on.toString()) AppSettings.putString(app, KEY_AUTOPLAY, on.toString())
} }
/**
* Takes effect at once: switching to Bluetooth mid-drive stops the capture, and switching
* back asks for it again (or waits for the car, if none is connected).
*/
fun setPipeAudio(on: Boolean) { fun setPipeAudio(on: Boolean) {
// Saved even when unchanged, so picking the default still counts as a choice.
AppSettings.putString(app, KEY_PIPE_AUDIO, on.toString())
if (pipeAudioFlow.value == on) return
pipeAudioFlow.value = on pipeAudioFlow.value = on
if (AppSettings.getString(app, KEY_SPEAK_DIRECTIONS, "") == "") speakDirectionsFlow.value = on AppSettings.putString(app, KEY_PIPE_AUDIO, on.toString())
if (on) CarAudio.request() else CarAudio.release()
}
fun setSpeakDirections(on: Boolean) {
speakDirectionsFlow.value = on
AppSettings.putString(app, KEY_SPEAK_DIRECTIONS, on.toString())
}
fun setBluetoothWarning(on: Boolean) {
bluetoothWarningFlow.value = on
AppSettings.putString(app, KEY_BLUETOOTH_WARNING, on.toString())
}
fun setLocationWarning(on: Boolean) {
locationWarningFlow.value = on
AppSettings.putString(app, KEY_LOCATION_WARNING, on.toString())
}
fun setExperimentalFeaturesEnabled(on: Boolean) {
experimentalFeaturesFlow.value = on
AppSettings.putString(app, KEY_EXPERIMENTAL_FEATURES, on.toString())
}
fun setSystemSpeech(on: Boolean) {
systemSpeechFlow.value = on
AppSettings.putString(app, KEY_SYSTEM_SPEECH, on.toString())
}
fun setCarSensorsEnabled(on: Boolean) {
carSensorsFlow.value = on
AppSettings.putString(app, KEY_CAR_SENSORS, on.toString())
} }
fun setNightMode(mode: NightMode) { fun setNightMode(mode: NightMode) {
@@ -335,22 +114,4 @@ private const val KEY_LOCATION_WARNING = "car_location_warning"
AppSettings.putString(app, KEY_NIGHT, mode.name) AppSettings.putString(app, KEY_NIGHT, mode.name)
CarEnvironment.refresh() CarEnvironment.refresh()
} }
/** Long-pressed onto or off the nav bar. Silently does nothing past [MAX_PINNED] rather than
* bumping the oldest pin - a driver who filled the bar on purpose shouldn't lose one by accident. */
fun togglePin(component: String) {
val current = pinnedFlow.value
val next = when {
component in current -> current - component
current.size >= MAX_PINNED -> return
else -> current + component
}
pinnedFlow.value = next
AppSettings.putString(app, KEY_PINNED, next.joinToString(","))
}
fun setAppOrder(ids: List<String>) {
appOrderFlow.value = ids
AppSettings.putString(app, KEY_APP_ORDER, ids.joinToString(","))
}
} }
@@ -1,7 +1,5 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import android.os.Build import android.os.Build
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -11,13 +9,11 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
@@ -32,9 +28,6 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.car.theme.GsColors
import app.seb3thehacker.gearslip.car.theme.GsIconBox
import app.seb3thehacker.gearslip.car.theme.GsThemes
import app.seb3thehacker.gearslip.AppSettings import app.seb3thehacker.gearslip.AppSettings
import app.seb3thehacker.gearslip.ui.CertSummary import app.seb3thehacker.gearslip.ui.CertSummary
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -50,19 +43,9 @@ fun CarSettingsScreen() {
val scale by CarSettings.scale.collectAsState() val scale by CarSettings.scale.collectAsState()
val open by CarSettings.openOnConnect.collectAsState() val open by CarSettings.openOnConnect.collectAsState()
val night by CarSettings.nightMode.collectAsState() val night by CarSettings.nightMode.collectAsState()
val units by CarSettings.units.collectAsState()
val whatsNew by CarSettings.whatsNewAfterUpdates.collectAsState()
val pipeAudio by CarSettings.pipeAudio.collectAsState() val pipeAudio by CarSettings.pipeAudio.collectAsState()
val speakDirections by CarSettings.speakDirections.collectAsState()
val bluetoothWarning by CarSettings.bluetoothWarning.collectAsState()
val locationWarning by CarSettings.locationWarning.collectAsState()
val autoplay by CarSettings.autoplay.collectAsState() val autoplay by CarSettings.autoplay.collectAsState()
val playerTitle by CarSettings.playerTitle.collectAsState()
val theme by CarSettings.appTheme.collectAsState() val theme by CarSettings.appTheme.collectAsState()
val uiTheme by CarSettings.uiTheme.collectAsState()
val experimentalFeatures by CarSettings.experimentalFeaturesEnabled.collectAsState()
val carSensors by CarSettings.carSensorsEnabled.collectAsState()
val systemSpeech by CarSettings.systemSpeech.collectAsState()
val display by CarEnvironment.display.collectAsState() val display by CarEnvironment.display.collectAsState()
val vehicle by CarEnvironment.vehicle.collectAsState() val vehicle by CarEnvironment.vehicle.collectAsState()
val context = LocalContext.current val context = LocalContext.current
@@ -77,7 +60,7 @@ fun CarSettingsScreen() {
.padding(horizontal = 24.dp, vertical = 16.dp), .padding(horizontal = 24.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp),
) { ) {
ScreenHeader("Settings") Text("Settings", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
ChoiceRow( ChoiceRow(
"Open on connect", "Open on connect",
@@ -97,30 +80,12 @@ fun CarSettingsScreen() {
theme, theme,
) { CarSettings.setAppTheme(it) } ) { CarSettings.setAppTheme(it) }
ChoiceRow(
"Theme",
GsThemes.builtIn.map { it.id to it.name },
uiTheme,
) { CarSettings.setUiTheme(it) }
ChoiceRow( ChoiceRow(
"Map day/night", "Map day/night",
listOf(NightMode.AUTO to "Auto", NightMode.DAY to "Day", NightMode.NIGHT to "Night"), listOf(NightMode.AUTO to "Auto", NightMode.DAY to "Day", NightMode.NIGHT to "Night"),
night, night,
) { CarSettings.setNightMode(it) } ) { CarSettings.setNightMode(it) }
ChoiceRow(
"Units",
listOf(Units.AUTO to "Auto", Units.IMPERIAL to "Imperial (mi, ft, °F)", Units.METRIC to "Metric (km, m, °C)"),
units,
) { CarSettings.setUnits(it) }
ChoiceRow(
"Player in the nav bar",
listOf(false to "Skip buttons", true to "Song title"),
playerTitle,
) { CarSettings.setPlayerTitle(it) }
ChoiceRow( ChoiceRow(
"Autoplay on connect", "Autoplay on connect",
listOf(false to "Off", true to "On"), listOf(false to "Off", true to "On"),
@@ -128,63 +93,22 @@ fun CarSettingsScreen() {
) { CarSettings.setAutoplay(it) } ) { CarSettings.setAutoplay(it) }
ChoiceRow( ChoiceRow(
"Car audio", "Media audio",
listOf(false to "Bluetooth", true to "USB"), listOf(false to "Phone output", true to "Through Gearslip"),
pipeAudio, pipeAudio,
) { CarSettings.setPipeAudio(it) } ) { CarSettings.setPipeAudio(it) }
Text( Text(
"USB sends the phone's sound through Gearslip. Android asks to share your screen each " + "Phone output needs no permission: the app plays as it normally would, e.g. over " +
"drive, and a few apps block it. Bluetooth plays as the phone normally would, and " + "Bluetooth to the car. Through Gearslip sends the sound over the car link, and " +
"Android never asks.", "Android asks for screen-capture consent each time.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
if (!pipeAudio) {
ChoiceRow(
"Warn when Bluetooth isn't connected",
listOf(false to "Off", true to "On"),
bluetoothWarning,
) { CarSettings.setBluetoothWarning(it) }
}
ChoiceRow(
"Warn when location is off",
listOf(false to "Off", true to "On"),
locationWarning,
) { CarSettings.setLocationWarning(it) }
ChoiceRow(
"Spoken directions",
listOf(false to "Off", true to "On"),
speakDirections,
) { CarSettings.setSpeakDirections(it) }
Text(
"Gearslip reads each turn aloud through the car's speakers, and the music dips while it " +
"speaks. Turn it off if your map app's own voice already plays in the car.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
ExperimentalFeatureRow(
title = "Use the phone's speech recognition",
description = "Listens through the phone's own speech service instead of Gearslip's. On " +
"most phones that's Google's, which may send your voice to Google. GrapheneOS has " +
"none, so Gearslip keeps using its own.",
checked = systemSpeech,
) { CarSettings.setSystemSpeech(it) }
WebPageSetting() WebPageSetting()
ScreenFit(vehicle) ScreenFit(vehicle)
ChoiceRow(
"Experimental features",
listOf(false to "Hide", true to "Show"),
experimentalFeatures,
) { CarSettings.setExperimentalFeaturesEnabled(it) }
if (experimentalFeatures) {
ExperimentalFeaturesList(carSensors)
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Connection", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary) Text("Connection", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)
Info("Phone", "${Build.MANUFACTURER} ${Build.MODEL}") Info("Phone", "${Build.MANUFACTURER} ${Build.MODEL}")
@@ -192,20 +116,9 @@ fun CarSettingsScreen() {
Info("Video", display.ifEmpty { "-" }) Info("Video", display.ifEmpty { "-" })
Info("Certificate", cert?.headline ?: "Checking…") Info("Certificate", cert?.headline ?: "Checking…")
} }
val navigator = LocalCarNavigator.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { navigator.open("calibrate") }) { Text("Display test") }
Text("About", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary) Spacer(Modifier.height(8.dp))
Info("Version", app.seb3thehacker.gearslip.BuildConfig.VERSION_NAME)
Info("Build", app.seb3thehacker.gearslip.BuildConfig.VERSION_CODE.toString())
ExperimentalFeatureRow(
"What's new after updates",
"Show the list of changes once, the first time the car connects after an update.",
whatsNew,
) { CarSettings.setWhatsNewAfterUpdates(it) }
GsButton(onClick = CarSettings::openWhatsNew, tone = GsTone.Tonal, modifier = Modifier.height(56.dp)) {
Text("What's new", style = MaterialTheme.typography.titleMedium)
}
}
} }
} }
@@ -216,80 +129,25 @@ private fun <T> ChoiceRow(title: String, options: List<Pair<T, String>>, selecte
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
options.forEach { (value, label) -> options.forEach { (value, label) ->
val on = value == selected val on = value == selected
val scheme = MaterialTheme.colorScheme Surface(
GsIconBox(
onClick = { onSelect(value) }, onClick = { onSelect(value) },
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
.height(64.dp), .height(64.dp),
colors = if (on) GsColors(scheme.primaryContainer, scheme.onPrimaryContainer) shape = MaterialTheme.shapes.large,
else GsColors(scheme.surfaceContainerHigh, scheme.onSurface), color = if (on) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,
latched = on, contentColor = if (on) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
) { ) {
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {
Text(label, style = MaterialTheme.typography.titleMedium, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal) Text(label, style = MaterialTheme.typography.titleMedium, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal)
} }
} }
} }
} }
}
/**
* Individually-switched experimental features, shown once the driver has opted into
* experimental features as a whole. Each is its own row - a title, what it does, and a switch -
* so the list reads fine whether there's one entry or several.
*/
@Composable
private fun ExperimentalFeaturesList(carSensors: Boolean) {
Column(
Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
ExperimentalFeatureRow(
title = "Vehicle data",
description = "Adds a Vehicle data tile: a live, raw dump of the head unit's sensor " +
"channel. Field labels (speed, RPM, fuel...) are carried over from other " +
"reverse-engineering projects and unverified against this car - treat them as a " +
"guess, not a fact, until you've watched one change for yourself.",
checked = carSensors,
) { CarSettings.setCarSensorsEnabled(it) }
} }
} }
@Composable /** The URL (or raw HTML) the Web app shows. Edited with [CarKeyboard] - no phone in hand needed. */
private fun ExperimentalFeatureRow(
title: String,
description: String,
checked: Boolean,
warning: Boolean = false,
onCheckedChange: (Boolean) -> Unit,
) {
Surface(
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth(),
) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(
description,
style = MaterialTheme.typography.bodySmall,
color = if (warning) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
Spacer(Modifier.width(12.dp))
GsSwitch(checked, onCheckedChange)
}
}
}
/** The URL (or raw HTML) the Browser app shows. Edited with [CarKeyboard] - no phone in hand needed. */
@Composable @Composable
private fun WebPageSetting() { private fun WebPageSetting() {
val context = LocalContext.current val context = LocalContext.current
@@ -305,7 +163,7 @@ private fun WebPageSetting() {
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) { ) {
Text( Text(
url.ifEmpty { "DuckDuckGo (default) - tap to set a different page" }, url.ifEmpty { "Built-in test page - tap to set a URL" },
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
color = if (url.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface, color = if (url.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface,
maxLines = 1, maxLines = 1,
@@ -314,7 +172,7 @@ private fun WebPageSetting() {
) )
} }
Text( Text(
"Shown by the Browser app on the launcher. Applies on the next connection.", "Shown by the Web app on the launcher. Applies on the next connection.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -326,7 +184,6 @@ private fun WebPageSetting() {
AppSettings.setStartupUrl(context, it) AppSettings.setStartupUrl(context, it)
}, },
onSubmit = { editing = false }, onSubmit = { editing = false },
onDismiss = { editing = false },
) )
} }
} }
@@ -365,7 +222,7 @@ private fun ScreenFit(vehicle: String) {
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
GsButton( Button(
onClick = { onClick = {
val ok = app.seb3thehacker.gearslip.VehicleProfiles.saveInsets(context, vehicle, insets) val ok = app.seb3thehacker.gearslip.VehicleProfiles.saveInsets(context, vehicle, insets)
saved = if (ok) "Saved to $vehicle" else "Could not save" saved = if (ok) "Saved to $vehicle" else "Could not save"
@@ -396,13 +253,14 @@ private fun Stepper(label: String, value: Int, onStep: (Int) -> Unit) {
@Composable @Composable
private fun StepButton(text: String, modifier: Modifier, onClick: () -> Unit) { private fun StepButton(text: String, modifier: Modifier, onClick: () -> Unit) {
GsIconBox( Surface(
onClick = onClick, onClick = onClick,
modifier = modifier.height(64.dp), modifier = modifier.height(64.dp),
colors = GsColors(MaterialTheme.colorScheme.surfaceContainerHigh, MaterialTheme.colorScheme.onSurface),
shape = MaterialTheme.shapes.large, shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
) { ) {
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(text, style = MaterialTheme.typography.titleLarge) Text(text, style = MaterialTheme.typography.titleLarge)
} }
}
} }
@@ -1,62 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalAccessibilityManager
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull
/** Draw inside the encoded car display; a normal Android Toast would appear on the phone. */
@Composable
internal fun CarToastOverlay(modifier: Modifier = Modifier) {
val current by CarToasts.message.collectAsState()
val message = current ?: return
val accessibility = LocalAccessibilityManager.current
LaunchedEffect(message, accessibility) {
val timeout = accessibility?.calculateRecommendedTimeoutMillis(
message.durationMs, containsIcons = false, containsText = true, containsControls = false,
) ?: message.durationMs
// The full time, unless another toast is waiting: then it gives way after the minimum.
delay(minOf(timeout, CarToasts.MIN_SHOWN_MS))
withTimeoutOrNull((timeout - CarToasts.MIN_SHOWN_MS).coerceAtLeast(0)) {
CarToasts.waiting.first { it > 0 }
}
CarToasts.dismiss(message)
}
// A non-interactive overlay leaves the map's touch handling and focus intact.
Box(
modifier
.padding(horizontal = 24.dp, vertical = 16.dp)
.widthIn(max = 560.dp)
.clip(RoundedCornerShape(20.dp))
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
.semantics { liveRegion = LiveRegionMode.Polite },
) {
Text(
message.text,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.titleMedium,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
}
@@ -1,65 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.annotation.MainThread
import androidx.car.app.CarToast
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* One toast at a time across navigation and browse apps. A newer one waits its turn instead of
* replacing the one on screen, which gets at least [MIN_SHOWN_MS] before it gives way.
*/
@MainThread
internal object CarToasts {
// Identity matters: repeating identical text must restart its display timer.
class Message(val owner: Any, val text: String, val durationMs: Long)
/** Long enough to read a short toast at a glance; a waiting toast cuts the rest short. */
const val MIN_SHOWN_MS = 2_000L
/** A burst beyond this many is stale by the time it would show; the oldest waiting go first. */
private const val MAX_WAITING = 3
private val current = MutableStateFlow<Message?>(null)
val message: StateFlow<Message?> = current.asStateFlow()
private val queue = ArrayDeque<Message>()
private val _waiting = MutableStateFlow(0)
val waiting: StateFlow<Int> = _waiting.asStateFlow()
fun show(owner: Any, text: String, duration: Int) {
if (text.isBlank()) return
// Longer than a phone toast: the driver only glances at the screen now and then.
val durationMs = if (duration == CarToast.LENGTH_LONG) 7_000L else 4_000L
val next = Message(owner, text, durationMs)
val shown = current.value
when {
shown == null -> current.value = next
// The same words again restart the one on screen rather than queueing a copy.
shown.text == text -> current.value = next
queue.lastOrNull()?.text == text -> Unit
else -> {
queue.addLast(next)
while (queue.size > MAX_WAITING) queue.removeFirst()
}
}
_waiting.value = queue.size
}
fun dismiss(message: Message) {
// An old timer must not dismiss a newer toast, even if its text is identical.
if (current.value === message) advance()
}
fun clear(owner: Any) {
// Disconnecting the map must not clear a toast belonging to the browse app.
queue.removeAll { it.owner === owner }
if (current.value?.owner === owner) advance() else _waiting.value = queue.size
}
private fun advance() {
current.value = queue.removeFirstOrNull()
_waiting.value = queue.size
}
}
@@ -2,10 +2,8 @@ package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -14,29 +12,19 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.border
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Notifications
import androidx.compose.foundation.layout.BoxScope
import androidx.car.app.model.CarIcon
import androidx.car.app.navigation.model.NavigationTemplate
import androidx.car.app.navigation.model.RoutingInfo
import app.seb3thehacker.gearslip.host.CarAppConnection
import app.seb3thehacker.gearslip.host.display
import app.seb3thehacker.gearslip.host.text
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -44,41 +32,20 @@ import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.platform.LocalView
import androidx.compose.runtime.State import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.animation.animateContentSize
import android.media.session.PlaybackState
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.car.theme.GsColors
import app.seb3thehacker.gearslip.car.theme.GsIconBox
import app.seb3thehacker.gearslip.car.theme.GsIconButton
import app.seb3thehacker.gearslip.car.theme.GsButton
import app.seb3thehacker.gearslip.car.theme.GsTone
import app.seb3thehacker.gearslip.car.theme.gsColors
import app.seb3thehacker.gearslip.car.theme.GsThemes
import app.seb3thehacker.gearslip.car.theme.LocalGsTheme
import app.seb3thehacker.gearslip.media.CarMedia import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.media.MediaArt import app.seb3thehacker.gearslip.media.MediaArt
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
@@ -87,10 +54,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.notify.CarNotifications import app.seb3thehacker.gearslip.notify.CarNotifications
import androidx.core.graphics.drawable.toBitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.text.DateFormat import java.text.DateFormat
import java.util.Date import java.util.Date
@@ -105,7 +69,6 @@ fun CarUi() {
val scale by CarSettings.scale.collectAsState() val scale by CarSettings.scale.collectAsState()
val phoneDark by CarEnvironment.phoneDark.collectAsState() val phoneDark by CarEnvironment.phoneDark.collectAsState()
val appTheme by CarSettings.appTheme.collectAsState() val appTheme by CarSettings.appTheme.collectAsState()
val uiThemeId by CarSettings.uiTheme.collectAsState()
val mediaApp by CarServices.mediaApp.collectAsState() val mediaApp by CarServices.mediaApp.collectAsState()
val darkOutside by CarEnvironment.darkOutside.collectAsState() val darkOutside by CarEnvironment.darkOutside.collectAsState()
val appContext = LocalContext.current.applicationContext val appContext = LocalContext.current.applicationContext
@@ -118,90 +81,18 @@ fun CarUi() {
val base = LocalDensity.current val base = LocalDensity.current
val insets by CarEnvironment.insets.collectAsState() val insets by CarEnvironment.insets.collectAsState()
val navigator = remember { CarNavigator(CarSettings.openOnConnect.value) } val navigator = remember { CarNavigator(CarSettings.openOnConnect.value) }
val controlsWake = remember { MapControlsWake() } remember(appContext) { invalidateLauncherApps(); CarServices.init(appContext) }
LaunchedEffect(controlsWake) {
while (true) {
delay(250)
controlsWake.tick()
}
}
// The knob counts as a touch: the map's buttons can't be found while they're faded out.
LaunchedEffect(controlsWake) { CarKeys.focusMoves.collect { controlsWake.touch() } }
remember(appContext) { Prefetch.warm(appContext, force = true); CarServices.init(appContext) }
DisposableEffect(Unit) { onDispose { CarServices.shutdown() } } DisposableEffect(Unit) { onDispose { CarServices.shutdown() } }
// Ask for the phone's sound as soon as the car connects, not only when a media app opens:
// a video in the web browser or a map's voice needs it too. Asks once, after the car offers
// somewhere to play it.
LaunchedEffect(Unit) { if (CarSettings.pipeAudio.value) app.seb3thehacker.gearslip.audio.CarAudio.request() }
// A new version gets one card in the top right, a few seconds in and only while parked.
LaunchedEffect(Unit) { app.seb3thehacker.gearslip.update.UpdateChecker.onCarConnected(appContext) }
// The map follows the light outside, whatever the app's own theme is set to. // The map follows the light outside, whatever the app's own theme is set to.
LaunchedEffect(darkOutside) { CarServices.nav.pushConfiguration() } LaunchedEffect(darkOutside) { CarServices.nav.pushConfiguration() }
// The one place with a navigator and a frame to act a voice command on - CarAssistant itself
// only knows how to listen and speak, not what "open Spotify" means.
val frameForAssistant by CarEnvironment.frame.collectAsState()
LaunchedEffect(navigator) {
CarAssistant.pendingCommand.collect { heard ->
if (heard != null) {
val reply = AssistantCommands.handle(appContext, navigator, frameForAssistant, heard)
CarAssistant.reply(reply)
}
}
}
// The car's own back, home, map, media and phone keys.
LaunchedEffect(navigator) {
CarKeys.screenKeys.collect { key ->
when (key) {
CarKeys.ScreenKey.BACK -> when {
navigator.appMenu != null -> navigator.dismissAppMenu()
VoiceReply.state.value.phase != VoiceReply.Phase.IDLE -> VoiceReply.cancel()
else -> navigator.back()
}
// Home is the dashboard, over the map, so Back from it lands on the map.
CarKeys.ScreenKey.HOME -> { navigator.home(); navigator.dashboard() }
CarKeys.ScreenKey.MAP -> navigator.home()
CarKeys.ScreenKey.MEDIA ->
if (CarServices.mediaApp.value != null || CarServices.reopenLastMedia()) navigator.media()
else navigator.apps()
CarKeys.ScreenKey.PHONE -> BuiltInApps.Phone.open(navigator)
}
}
}
// The car screen is drawn on the phone, so every long press or text-handle drag would buzz
// the phone in its mount. Nobody feels that while driving; it's only noise.
val view = LocalView.current
DisposableEffect(view) {
view.isHapticFeedbackEnabled = false
onDispose { }
}
CompositionLocalProvider( CompositionLocalProvider(
LocalHapticFeedback provides NoHaptics,
LocalDensity provides Density(base.density * scale, base.fontScale), LocalDensity provides Density(base.density * scale, base.fontScale),
LocalCarNavigator provides navigator, LocalCarNavigator provides navigator,
LocalDarkOutside provides darkOutside, LocalDarkOutside provides darkOutside,
LocalMapControlsWake provides controlsWake,
LocalGsTheme provides GsThemes.byId(uiThemeId),
) { ) {
MaterialTheme(colorScheme = colors) { MaterialTheme(colorScheme = colors) {
CompositionLocalProvider(LocalIndication provides FocusRingIndication(MaterialTheme.colorScheme.primary)) { Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Surface(
Modifier
.fillMaxSize()
// Watches every touch without taking any: first in line, consumes nothing.
.pointerInput(controlsWake) {
awaitPointerEventScope {
while (true) {
awaitPointerEvent(PointerEventPass.Initial)
controlsWake.touch()
}
}
},
color = MaterialTheme.colorScheme.background,
) {
// Insets are in video-frame pixels, so convert with the un-scaled density. // Insets are in video-frame pixels, so convert with the un-scaled density.
val pad = with(base) { val pad = with(base) {
PaddingValues( PaddingValues(
@@ -209,74 +100,28 @@ fun CarUi() {
end = insets.right.toDp(), bottom = insets.bottom.toDp(), end = insets.right.toDp(), bottom = insets.bottom.toDp(),
) )
} }
// The calibration screen is the raw frame: no insets, no nav bar.
val screen = navigator.current val screen = navigator.current
val safetyWarningSeen by CarSettings.hasSeenSafetyWarning.collectAsState() if (screen == CarScreen.App("calibrate")) {
Box(Modifier.fillMaxSize().padding(pad)) { CarApps.find("calibrate")?.content?.invoke()
Column(Modifier.fillMaxSize()) { } else {
if (!safetyWarningSeen) { Column(Modifier.fillMaxSize().padding(pad)) {
CarSafetyWizard(onDone = CarSettings::markSafetyWarningSeen)
return@Column
}
// Header navigation (breadcrumb trail) - off for now, kept to tweak later.
// BreadcrumbBar(navigator)
Box(Modifier.weight(1f).fillMaxWidth()) { Box(Modifier.weight(1f).fillMaxWidth()) {
// Home never leaves the composition; other screens cover it. Dropping it
// would tear down the map's surface, and coming back would then show black
// while the nav app redrew on a new one.
CarHome()
if (screen != CarScreen.Home) {
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
// Keeps touches that miss this screen's controls off the map.
.pointerInput(Unit) { detectTapGestures { } },
) {
when (screen) { when (screen) {
CarScreen.Home -> Unit CarScreen.Home -> CarHome()
CarScreen.Apps -> CarLauncher() CarScreen.Apps -> CarLauncher()
CarScreen.Media -> mediaApp?.let { MediaScreen(it) { navigator.back() } } CarScreen.Media -> mediaApp?.let { MediaScreen(it) { navigator.home() } }
CarScreen.Browse -> BrowseAppScreen(navigator)
CarScreen.Settings -> CarSettingsScreen() CarScreen.Settings -> CarSettingsScreen()
CarScreen.Dashboard -> CarDashboardScreen() CarScreen.Dashboard -> CarDashboardScreen()
CarScreen.Weather -> WeatherScreen()
CarScreen.VehicleData -> VehicleDataScreen()
is CarScreen.Notifications -> NotificationsScreen(screen.replyTo) is CarScreen.Notifications -> NotificationsScreen(screen.replyTo)
is CarScreen.Messages -> MessagesScreen(screen.packageName)
is CarScreen.App -> CarApps.find(screen.id)?.content?.invoke() is CarScreen.App -> CarApps.find(screen.id)?.content?.invoke()
} }
// The history screen is already showing them, so it needs no popup.
if (screen !is CarScreen.Notifications) {
NotificationPopup(Modifier.align(Alignment.TopCenter))
} }
} }
CarToastOverlay(Modifier.align(Alignment.BottomCenter)) CarNavBar(navigator)
CallPromptOverlay()
BluetoothPairOverlay()
PopupTimer()
// The dashboard is already listing them, so it needs no popup.
NotificationPopup(
showNew = screen !is CarScreen.Notifications && screen != CarScreen.Dashboard,
modifier = Modifier.align(Alignment.TopEnd),
)
// Above the popup: a call is more urgent than any notification.
VoiceHelpOverlay(Modifier.align(Alignment.Center))
CallOverlay(Modifier.align(Alignment.TopCenter))
AssistantOverlay(Modifier.align(Alignment.BottomCenter))
if (app.seb3thehacker.gearslip.BuildConfig.DEBUG) {
// Bottom corner, not top: a screen's own header almost always puts
// something in the top-right (settings, search, a Liked Songs
// shortcut) and this badge used to sit right on top of it, hiding
// whatever the screen drew there.
DebugBuildBadge(Modifier.align(Alignment.BottomEnd))
}
}
// The keyboard takes the nav bar's row instead of squeezing in above it -
// nothing on the nav bar is useful mid-type, and the screen is too small to
// show both.
val keyboardVisible by CarKeyboardVisibility.state
if (!keyboardVisible) CarNavBar(navigator)
}
// Over everything, nav bar included: a long press on an app, anywhere.
AppMenu(navigator, rememberRunningApps())
if (safetyWarningSeen) CarWhatsNew()
} }
} }
} }
@@ -285,407 +130,74 @@ fun CarUi() {
} }
/** /**
* A single blocking screen, shown once per install before anything else the car screen can show - * Home and Apps on the left; now-playing pill in the middle; clock (tap for calendar and weather), phone battery and the
* Home included. The phone's own setup guide carries the same warning, but a driver who plugs in * darkness signal on the right. Icon-only: a driver reads a glyph faster than a label, and it
* without ever opening the phone app would otherwise never see it, on the one screen they are * keeps the bar short enough to leave the app underneath more room.
* actually about to use while driving. [onDone] fires once, from its own button; there is no way
* to skip past this without tapping it.
*/
@Composable
private fun CarSafetyWizard(onDone: () -> Unit) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
// The card and its button share one width, capped so neither sprawls across a wide screen.
Column(
Modifier.widthIn(max = 640.dp).fillMaxWidth().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Surface(
color = MaterialTheme.colorScheme.surfaceContainerLow,
shape = MaterialTheme.shapes.extraLarge,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Drive safely", style = ChromeType.headline, fontWeight = FontWeight.Bold)
Text(
"Gearslip is unofficial software: it is not made or reviewed by any " +
"carmaker, and it can fail without warning.",
style = ChromeType.body,
)
Text(
"Never interact with this screen while driving. Set the route or the " +
"song before you go, then keep your attention on the road.",
style = ChromeType.body,
)
}
}
Spacer(Modifier.height(24.dp))
GsButton(onClick = onDone, modifier = Modifier.fillMaxWidth().height(56.dp)) {
Text("I understand", style = ChromeType.body)
}
}
}
}
/**
* A templated app that isn't navigation, full size with its own title bar and Stop button - the
* same [CarAppStage] chrome the map uses on Home, just not embedded there. [CarServices.browse]
* is a connection of its own, so opening one of these never bumps the map off Home.
*/
@Composable
private fun BrowseAppScreen(navigator: CarNavigator) {
val status by CarServices.browse.status.collectAsState()
val frame by CarEnvironment.frame.collectAsState()
val template by CarServices.browse.template.collectAsState()
val leave = {
CarServices.stopBrowse()
navigator.back()
}
// An app that never answers is as stuck as one that says no; don't leave the driver on "Loading".
var timedOut by remember { mutableStateOf(false) }
LaunchedEffect(template == null) {
timedOut = false
if (template == null) {
delay(APP_START_TIMEOUT_MS)
timedOut = true
}
}
val failed = status.phase == CarAppConnection.Phase.REJECTED || status.phase == CarAppConnection.Phase.FAILED
if (failed || timedOut) {
AppWontStart(status.app ?: "This app", leave)
return
}
CarAppStage(CarServices.browse, status, frame, onDisconnect = leave)
}
private const val APP_START_TIMEOUT_MS = 15_000L
/** What a car app that won't run under Gearslip gets instead of a loading screen that never ends. */
@Composable
private fun AppWontStart(app: String, onBack: () -> Unit) {
Column(
Modifier.fillMaxSize().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("$app doesn't work with Gearslip yet.", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold)
Text(
"It didn't start. Some apps only run on Google's Android Auto.",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
GsButton(onClick = onBack, tone = GsTone.Tonal) { Text("Back") }
}
}
/**
* Marks a debug build on the car screen itself, not just the phone's Home screen - the one
* that matters while driving, since a debug build is slower and less tested than what ships.
*/
@Composable
private fun DebugBuildBadge(modifier: Modifier = Modifier) {
Surface(
modifier = modifier.padding(6.dp),
color = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError,
shape = MaterialTheme.shapes.small,
) {
Text(
"DEBUG BUILD",
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
)
}
}
/**
* "Home > Apps > Settings", like a file manager's address bar: hidden at Home itself (nothing to
* show yet), and grows by one crumb for every screen pushed from there. The back arrow undoes one
* step; a crumb jumps straight to it, dropping everything after - this is the only on-screen way
* back at all, since a car touchscreen has no hardware button for it.
*/
@Composable
private fun BreadcrumbBar(navigator: CarNavigator) {
val trail = navigator.trail
if (trail.size <= 1) return
Row(
Modifier.fillMaxWidth().height(40.dp).padding(start = 2.dp, end = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
GsIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", navigator::back, size = 32.dp, iconSize = 20.dp)
Spacer(Modifier.width(2.dp))
trail.forEachIndexed { index, crumb ->
val isLast = index == trail.lastIndex
Text(
crumb.label,
style = MaterialTheme.typography.labelLarge,
fontWeight = if (isLast) FontWeight.SemiBold else FontWeight.Normal,
color = if (isLast) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (isLast) Modifier else Modifier
.clip(RoundedCornerShape(6.dp))
.clickable { navigator.jumpTo(index) }
.padding(horizontal = 4.dp, vertical = 2.dp),
)
if (!isLast) {
Text(
"›",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 2.dp),
)
}
}
}
}
/**
* Apps and open/pinned shortcuts on the left; now-playing pill against them; clock (tap for
* calendar and weather), phone battery and the darkness signal on the right. Icon-only: a driver
* reads a glyph faster than a label, and it keeps the bar short enough to leave the app underneath
* more room.
*/ */
@Composable @Composable
private fun CarNavBar(navigator: CarNavigator) { private fun CarNavBar(navigator: CarNavigator) {
val battery by CarEnvironment.battery.collectAsState() val battery by CarEnvironment.battery.collectAsState()
val darkOutside by CarEnvironment.darkOutside.collectAsState()
val now by rememberNow() val now by rememberNow()
val weather by Weather.state.collectAsState()
val weatherData = (weather as? WeatherState.Ready)?.data
val pinnedIds by CarSettings.pinnedApps.collectAsState() // The home and media screens already show what's playing; everywhere else it lives in the
val entries = rememberAllEntries() // middle of this bar so it stays one tap away.
val pinnedEntries = remember(entries, pinnedIds) { val showNowPlaying = navigator.current != CarScreen.Home && navigator.current != CarScreen.Media
pinnedIds.mapNotNull { id -> entries.find { it.componentId == id } }
}
val frame by CarEnvironment.frame.collectAsState()
val running = rememberRunningApps()
Surface(color = MaterialTheme.colorScheme.surfaceContainer) { Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
BoxWithConstraints(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 10.dp)) { Box(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 10.dp)) {
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
// Home and Apps are two different places now, not a toggle on one button - the NavItem(Icons.Filled.Home, navigator.current == CarScreen.Home) { navigator.home() }
// breadcrumb trail is how you retrace your steps, but reaching for either of
// these two from three screens deep in a media app shouldn't mean reading it
// first.
NavHomeButton(navigator, entries, running)
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
NavItem(MediaIcons.Apps, navigator.current == CarScreen.Apps) { navigator.apps() } NavItem(MediaIcons.Apps, navigator.current == CarScreen.Apps) { navigator.apps() }
Spacer(Modifier.width(6.dp))
NavAssistantIcon()
// Pinned shortcuts, then whatever else is open right now. A pinned app that's also Spacer(Modifier.weight(1f))
// open stays in its pinned spot, marked with a dot, instead of showing up twice.
// The map app lives on the Home button, so it never gets a second icon here.
val runningEntries = running.keys
.filter { it !in pinnedIds && running[it] != RunningSlot.NAV }
.mapNotNull { id -> entries.find { it.componentId == id } }
val shownPins = pinnedEntries.filter { running[it.componentId] != RunningSlot.NAV }
if (shownPins.isNotEmpty() || runningEntries.isNotEmpty()) NavDivider()
shownPins.forEach { entry -> NavEntryIcon(entry, running, navigator, frame) }
if (shownPins.isNotEmpty() && runningEntries.isNotEmpty()) NavDivider()
runningEntries.forEach { entry -> NavEntryIcon(entry, running, navigator, frame) }
// Next turn first, off the map only; the player shares the space when it fits, Column(
// and gives way to the turn when it doesn't. horizontalAlignment = Alignment.End,
val turn = rememberNextTurn().takeIf { navigator.current != CarScreen.Home } modifier = Modifier
BoxWithConstraints(Modifier.weight(1f).padding(horizontal = 16.dp), contentAlignment = Alignment.Center) { .clip(RoundedCornerShape(16.dp))
val roomForBoth = maxWidth >= TURN_AND_PLAYER_MIN_WIDTH .clickable { navigator.dashboard() }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { .padding(horizontal = 8.dp, vertical = 2.dp),
turn?.let { NavTurnPill(it) { navigator.home() } }
if (turn == null || roomForBoth) {
NavNowPlaying(navigator, selected = navigator.current == CarScreen.Media, modifier = Modifier.weight(1f, fill = false))
}
}
}
// Weather no longer has its own chip - the temperature alone (no icon, no room
// for one) sits where "Night"/"Day" used to, freeing a whole chip's width for the
// Home button above.
// The clock is also the notifications button: the dashboard lists them under the
// calendar and weather, and a dot here marks anything unread.
val unread by CarNotifications.unread.collectAsState()
NavChip(
navigator.current == CarScreen.Dashboard || navigator.current is CarScreen.Notifications,
{ navigator.dashboard() },
) { ) {
if (unread > 0) {
Box(
Modifier
.align(Alignment.TopEnd)
.offset(x = 8.dp, y = (-2).dp)
.size(8.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary),
)
}
Column(horizontalAlignment = Alignment.End) {
Text( Text(
DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(now)), DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(now)),
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
) )
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { val phone = if (battery.percent >= 0) "${battery.percent}%${if (battery.charging) " charging" else ""}" else ""
if (battery.percent >= 0) { val light = if (darkOutside) "Night" else "Day"
Text( Text(
"${battery.percent}%", listOf(phone, light).filter { it.isNotEmpty() }.joinToString(" · "),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (battery.charging) {
ChargingGlyph(Modifier.size(13.dp))
}
}
weatherData?.let { w ->
Text(
" · ${w.temp}°",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
} }
Spacer(Modifier.width(10.dp))
NavItem(
Icons.Filled.Notifications, navigator.current is CarScreen.Notifications,
) { navigator.notifications() }
} }
}
} if (showNowPlaying) {
NavNowPlaying(navigator, Modifier.align(Alignment.Center))
} }
} }
} }
} }
/**
* Home: the map, with the player or lyrics beside it. While a map app runs, the button wears that
* app's icon and a long press offers to close it, so the app needs no icon of its own on the bar.
*/
@Composable
private fun NavHomeButton(navigator: CarNavigator, entries: List<Entry>, running: Map<String, RunningSlot>) {
val selected = navigator.current == CarScreen.Home
val navId = running.entries.firstOrNull { it.value == RunningSlot.NAV }?.key
val navEntry = navId?.let { id -> entries.find { it.componentId == id } }
GsIconBox(
{ navigator.home() },
colors = navColors(selected),
latched = selected,
onLongClick = navId?.let { id -> { navigator.showAppMenu(id) } },
) {
val icon = navEntry?.icon
if (icon != null) {
Box(Modifier.padding(NAV_ITEM_PADDING).size(28.dp), contentAlignment = Alignment.Center) {
Image(icon, navEntry.label, Modifier.size(28.dp).clip(RoundedCornerShape(7.dp)))
}
} else {
Icon(
ImageVector.vectorResource(R.drawable.navigation_24), contentDescription = "Home",
modifier = Modifier.padding(NAV_ITEM_PADDING).size(28.dp),
)
}
}
}
/** Splits the nav bar's sections: Home and Apps, pinned apps, open apps. */
@Composable
private fun NavDivider() {
Box(
Modifier
.padding(horizontal = 10.dp)
.width(1.dp)
.height(28.dp)
.background(MaterialTheme.colorScheme.outlineVariant),
)
}
/**
* A pinned or open app on the nav bar. Tapping brings it back without reconnecting if it's
* already open; a long press opens its menu (pin, unpin, close).
*/
@Composable
private fun NavEntryIcon(
entry: Entry,
running: Map<String, RunningSlot>,
navigator: CarNavigator,
frame: CarEnvironment.Frame,
) {
val id = entry.componentId ?: return
val slot = running[id]
Box(Modifier.padding(horizontal = 3.dp)) {
NavAppIcon(
entry,
open = slot != null,
showing = slot != null && slot.isShowing(navigator.current),
onLongClick = { navigator.showAppMenu(id) },
) { openApp(entry, slot, navigator, frame) }
}
}
/** One open or pinned app's icon on the nav bar - the same fixed size and shape either way. */
@Composable
private fun NavAppIcon(
entry: Entry,
open: Boolean,
showing: Boolean,
onLongClick: () -> Unit,
onClick: () -> Unit,
) {
val scheme = MaterialTheme.colorScheme
GsIconBox(
onClick,
Modifier.size(44.dp),
colors = if (showing) GsColors(scheme.secondaryContainer, scheme.onSecondaryContainer)
else GsColors(scheme.surfaceVariant, scheme.onSurfaceVariant),
latched = showing,
onLongClick = onLongClick,
) {
entry.icon?.let { Image(it, entry.label, Modifier.size(30.dp).clip(RoundedCornerShape(8.dp))) }
entry.builtIn?.let { Icon(it.glyph, entry.label, Modifier.size(26.dp)) }
// Only running apps get the line along the bottom edge, the usual taskbar mark for it.
if (open) {
Box(
Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 2.dp)
.size(width = 12.dp, height = 3.dp)
.clip(RoundedCornerShape(50))
.background(scheme.primary),
)
}
}
}
/** A tappable group in the bar that stays highlighted while its screen is open, like [NavItem]. */
@Composable
private fun NavChip(selected: Boolean, onClick: () -> Unit, content: @Composable BoxScope.() -> Unit) {
GsIconBox(onClick, colors = navColors(selected), latched = selected) {
Box(Modifier.padding(horizontal = 10.dp, vertical = 2.dp)) { content() }
}
}
/** Every nav bar item is raised, so it reads as pressable; the current screen's takes the accent colour. */
@Composable
private fun navColors(selected: Boolean): GsColors {
val s = MaterialTheme.colorScheme
return if (selected) GsColors(s.secondaryContainer, s.onSecondaryContainer)
else GsColors(s.surfaceContainerHighest, s.onSurface)
}
/**
* Between Apps and whatever's actually open, not with the clock/battery group on the right - a
* driver reaches for it right after deciding "not a tap for this", same gesture family as the
* two buttons beside it.
*/
@Composable
private fun NavAssistantIcon() {
val state by CarAssistant.state.collectAsState()
val active = state.phase != CarAssistant.Phase.IDLE
GsIconBox({ CarAssistant.start() }, colors = navColors(active), latched = active) {
MicGlyph(Modifier.padding(NAV_ITEM_PADDING).size(28.dp))
}
}
/** Inner padding of every icon on the nav bar, leaving each button room inside the 56dp bar. */
private val NAV_ITEM_PADDING = 8.dp
@Composable @Composable
private fun NavItem(icon: ImageVector, selected: Boolean, onClick: () -> Unit) { private fun NavItem(icon: ImageVector, selected: Boolean, onClick: () -> Unit) {
GsIconBox(onClick, colors = navColors(selected), latched = selected) { val scheme = MaterialTheme.colorScheme
Icon(icon, contentDescription = null, modifier = Modifier.padding(NAV_ITEM_PADDING).size(28.dp)) Box(
Modifier
.clip(RoundedCornerShape(18.dp))
.background(if (selected) scheme.secondaryContainer else scheme.surfaceContainer)
.clickable(onClick = onClick)
.padding(12.dp),
contentAlignment = Alignment.Center,
) {
Icon(icon, contentDescription = null, modifier = Modifier.size(28.dp))
} }
} }
@@ -698,213 +210,55 @@ internal fun rememberNow(): State<Long> = produceState(System.currentTimeMillis(
} }
} }
/** How long the pill shows a new song's title before settling to just the controls. */ /** Art, title and play/pause in the nav bar; tapping the art or title opens the full media screen. */
private const val TITLE_SHOWN_MS = 3_000L
/** Below this, the nav bar's middle only has room for the turn, not the player beside it. */
private val TURN_AND_PLAYER_MIN_WIDTH = 520.dp
/** The next manoeuvre, as the running nav app last described it. */
private class NextTurn(val icon: CarIcon?, val distance: String, val road: String)
/**
* Read straight off the nav app's own template: a navigation app keeps sending its routing card
* while it's running, whether or not the map is the screen being shown.
*/
@Composable @Composable
private fun rememberNextTurn(): NextTurn? { private fun NavNowPlaying(navigator: CarNavigator, modifier: Modifier) {
val status by CarServices.nav.status.collectAsState()
val template by CarServices.nav.template.collectAsState()
// Read so a change of units redraws the distance straight away, not at the next update.
CarSettings.units.collectAsState().value
if (status.phase != CarAppConnection.Phase.RUNNING) return null
val routing = (template as? NavigationTemplate)?.navigationInfo as? RoutingInfo ?: return null
if (routing.isLoading) return null
val step = routing.currentStep ?: return null
return NextTurn(
icon = step.maneuver?.icon,
distance = routing.currentDistance.display(),
road = step.road.text().ifEmpty { step.cue.text() },
)
}
/** The next turn in the nav bar: arrow, how far, onto what. Tapping goes back to the map. */
@Composable
private fun NavTurnPill(turn: NextTurn, onClick: () -> Unit) {
// Same finish as every other button on the bar, in the accent colour; the text runs a step
// bigger than anything else there, since it's the one thing worth a glance mid-drive.
GsIconBox(
onClick,
Modifier.widthIn(max = 340.dp).height(44.dp),
colors = gsColors(GsTone.Primary),
) {
Row(
Modifier.padding(NAV_ITEM_PADDING),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
CarGlyph(turn.icon, Modifier.size(28.dp))
if (turn.distance.isNotEmpty()) {
Text(turn.distance, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, maxLines = 1)
}
if (turn.road.isNotEmpty()) {
Text(
turn.road,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
/** "Title - Artist" on one line. The text itself cuts it off, and only where the pill runs out of room. */
private fun nowPlayingLabel(title: String, artist: String): String =
listOf(title.trim(), artist.trim()).filter { it.isNotEmpty() }.joinToString(" - ")
.ifEmpty { "Nothing playing" }
/**
* The player in the nav bar, on every screen. Art and title open the full media screen;
* play/pause and skip work right here. The dock button moves the player into the column beside
* the map on Home (see [CarHome]), and the pill steps aside there while it's docked - unless the
* column is showing lyrics instead, when the pill stays and its dock button swaps them back.
*/
@Composable
private fun NavNowPlaying(navigator: CarNavigator, selected: Boolean, modifier: Modifier = Modifier) {
val media = CarServices.media val media = CarServices.media
val phase by media.phase.collectAsState() val phase by media.phase.collectAsState()
val now by media.now.collectAsState() val now by media.now.collectAsState()
if (phase != CarMedia.Phase.READY || !now.isActive) return if (phase != CarMedia.Phase.READY || !now.hasTrack) return
// Docked beside the map, the player is already on screen - the pill steps aside for it.
if (navigator.sidePanel == SidePanel.CONTROLS && navigator.current == CarScreen.Home) return
// The media screen is the full player already; the pill would only repeat its controls.
if (navigator.current == CarScreen.Media) return
val context = LocalContext.current val context = LocalContext.current
val art by produceState(now.art, now.art, now.artUri) { value = now.art ?: MediaArt.load(context, now.artUri) } val art by produceState(now.art, now.art, now.artUri) { value = now.art ?: MediaArt.load(context, now.artUri) }
val position by produceState(now.currentPosition(), now) {
while (true) {
value = now.currentPosition()
if (!now.playing) break
delay(1000)
}
}
// A new song announces itself: title, play/pause and dock for a few seconds, then the title
// goes and the pill settles to just the controls - unless the driver keeps the title up.
val keepTitle by CarSettings.playerTitle.collectAsState()
var announcing by remember { mutableStateOf(true) }
LaunchedEffect(now.title, now.artist) {
announcing = true
delay(TITLE_SHOWN_MS)
announcing = false
}
val showTitle = keepTitle || announcing
val scheme = MaterialTheme.colorScheme
val onPill = if (selected) scheme.onPrimaryContainer else scheme.onSecondaryContainer
Surface( Surface(
modifier = modifier modifier = modifier,
.animateContentSize() shape = RoundedCornerShape(50),
// With the title up, all the room the bar has, so as much of it shows as can. color = MaterialTheme.colorScheme.secondaryContainer,
.then(if (showTitle) Modifier.fillMaxWidth() else Modifier) contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
.height(44.dp),
shape = RoundedCornerShape(14.dp),
color = if (selected) scheme.primaryContainer else scheme.secondaryContainer,
contentColor = onPill,
) { ) {
Box {
Row( Row(
Modifier.fillMaxHeight().padding(horizontal = 4.dp), Modifier.padding(start = 6.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
// Art (and the title while it shows) opens the full media screen.
Row( Row(
Modifier Modifier
.then(if (showTitle) Modifier.weight(1f) else Modifier) .clip(RoundedCornerShape(50))
.fillMaxHeight()
.clip(RoundedCornerShape(10.dp))
.clickable { navigator.media() }, .clickable { navigator.media() },
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(10.dp),
) { ) {
Box(Modifier.size(34.dp).clip(RoundedCornerShape(8.dp)).background(scheme.surfaceVariant)) { Box(Modifier.size(40.dp).clip(RoundedCornerShape(50)).background(MaterialTheme.colorScheme.surfaceVariant)) {
art?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } art?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) }
} }
if (showTitle) {
Text( Text(
nowPlayingLabel(now.title, now.artist), now.title.ifEmpty { "Nothing playing" }.let { if (it.length > 15) it.take(15) + "…" else it },
style = MaterialTheme.typography.titleSmall, style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
} }
} FilledIconButton(onClick = media::togglePlay, modifier = Modifier.size(44.dp)) {
if (!showTitle) { Icon(
GsIconButton(
MediaIcons.Previous, "Previous", media::previous,
enabled = now.canDo(PlaybackState.ACTION_SKIP_TO_PREVIOUS), size = 36.dp, iconSize = 22.dp,
)
}
GsIconButton(
if (now.playing) MediaIcons.Pause else Icons.Filled.PlayArrow, if (now.playing) MediaIcons.Pause else Icons.Filled.PlayArrow,
if (now.playing) "Pause" else "Play", if (now.playing) "Pause" else "Play",
media::togglePlay, Modifier.size(26.dp),
tone = GsTone.Primary, size = 36.dp, iconSize = 22.dp,
)
if (!showTitle) {
GsIconButton(
MediaIcons.Next, "Next", media::next,
enabled = now.canDo(PlaybackState.ACTION_SKIP_TO_NEXT), size = 36.dp, iconSize = 22.dp,
)
}
GsIconButton(
MediaIcons.DockRight, "Move the player beside the map", navigator::togglePlayerDock,
size = 36.dp, iconSize = 22.dp,
)
}
if (now.durationMs > 0) {
// matchParentSize, so the line follows the pill's width rather than widening it.
Box(Modifier.matchParentSize(), contentAlignment = Alignment.BottomStart) {
Box(
Modifier
.fillMaxWidth((position.toFloat() / now.durationMs).coerceIn(0f, 1f))
.height(2.dp)
.background(onPill.copy(alpha = 0.7f)),
) )
} }
IconButton(onClick = { media.next() }, modifier = Modifier.size(44.dp)) {
Icon(MediaIcons.Next, "Next", Modifier.size(28.dp))
} }
} }
} }
} }
/**
* A filled lightning bolt, next to the battery percentage instead of the word "charging" - the
* core Material icon set this project ships (no extended pack, to keep the app small) has no
* bolt, so this is drawn rather than a vector asset.
*/
@Composable
private fun ChargingGlyph(modifier: Modifier = Modifier, tint: Color = MaterialTheme.colorScheme.onSurfaceVariant) {
androidx.compose.foundation.Canvas(modifier) {
val w = size.width
val h = size.height
val bolt = androidx.compose.ui.graphics.Path().apply {
moveTo(w * 0.58f, 0f)
lineTo(w * 0.12f, h * 0.58f)
lineTo(w * 0.46f, h * 0.58f)
lineTo(w * 0.42f, h)
lineTo(w * 0.88f, h * 0.40f)
lineTo(w * 0.54f, h * 0.40f)
close()
}
drawPath(bolt, tint)
}
}
/** Stands in for the phone's vibration motor on the car screen: does nothing. */
private object NoHaptics : HapticFeedback {
override fun performHapticFeedback(hapticFeedbackType: HapticFeedbackType) {}
}
@@ -1,113 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import kotlinx.coroutines.delay
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.Changelog
import app.seb3thehacker.gearslip.car.theme.GsButton
import app.seb3thehacker.gearslip.car.theme.GsSwitch
import app.seb3thehacker.gearslip.notify.CarMotion
/**
* What's new in this build, once, the first time the car screen shows after an update - or any
* time from Settings > About. Held back while the car is moving: a list to read is for when
* parked. The switch turns the automatic showing off (or back on); it doesn't close the card.
*/
@Composable
fun CarWhatsNew() {
val release = Changelog.current ?: return
val afterUpdates by CarSettings.whatsNewAfterUpdates.collectAsState()
val seen by CarSettings.whatsNewSeen.collectAsState()
val open by CarSettings.whatsNewOpen.collectAsState()
// Polled: CarMotion is a plain value, and the card should appear once the car stops.
val moving by produceState(CarMotion.moving) {
while (true) {
value = CarMotion.moving
delay(5_000)
}
}
val due = afterUpdates && seen < release.versionCode && !moving
if (!open && !due) return
val close = { CarSettings.closeWhatsNew(release.versionCode) }
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.5f))
.clickable(remember { MutableInteractionSource() }, indication = null, onClick = close),
contentAlignment = Alignment.Center,
) {
Surface(
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
// Swallows taps on the card itself, so only the scrim around it closes.
modifier = Modifier
.padding(16.dp)
.widthIn(max = 640.dp)
.clickable(remember { MutableInteractionSource() }, indication = null) {},
) {
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Text(
"What's new in ${release.versionName}",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
)
Column(
Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
release.changes.forEach { change ->
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Box(
Modifier
.padding(top = 9.dp)
.size(7.dp)
.background(MaterialTheme.colorScheme.primary, CircleShape),
)
Text(change, style = MaterialTheme.typography.bodyLarge)
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
GsSwitch(afterUpdates, CarSettings::setWhatsNewAfterUpdates)
Text(
"Show after updates",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f),
)
GsButton(onClick = close, modifier = Modifier.height(56.dp)) {
Text("Got it", style = MaterialTheme.typography.titleMedium)
}
}
}
}
}
}
@@ -1,199 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.car.app.model.CarText
import androidx.car.app.model.Distance
import androidx.car.app.navigation.model.Maneuver
import androidx.car.app.navigation.model.NavigationTemplate
import androidx.car.app.navigation.model.RoutingInfo
import androidx.car.app.navigation.model.Step
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.Protobuf
/**
* The next turn on the car's instrument cluster, over its NavigationStatusService (Service
* field 8), the way Android Auto feeds it:
*
* -> NavigationStatus { status = 1 (1 active, 2 inactive, 3 rerouting) }
* -> NavigationNextTurnEvent { road = 1; turn_side = 2; event = 3; turn_number = 5; turn_angle = 6 }
* -> NavigationNextTurnDistanceEvent { distance_meters = 1; time_to_turn_seconds = 2;
* display_distance_e3 = 3; display_distance_unit = 4 }
*
* Newer cars also take a NavigationState message; the deprecated pair above is what a 2018
* Uconnect understands. The turn comes from the map app's trip (what the Car App Library hands
* to clusters), or from its routing card when it sends no trip.
*/
class ClusterNav(
val channelId: Int,
private val sendOnChannel: (messageId: Int, body: ByteArray) -> Unit,
) {
@Volatile private var running = false
private var sentStatus = -1
private var sentTurn: String? = null
private var sentDistance: String? = null
fun onMessage(messageId: Int, body: ByteArray) {
when (messageId) {
MSG_CHANNEL_OPEN_RESPONSE -> {
val status = Protobuf.readInt32Field(body, 1) ?: 0
GearslipLog.i("cluster: <- ChannelOpenResponse: status=$status")
if (status == 0) start()
}
// The car saying when it wants turns. Sending all along is harmless, so these are only logged.
MSG_START -> GearslipLog.i("cluster: <- start")
MSG_STOP -> GearslipLog.i("cluster: <- stop")
else -> GearslipLog.i("cluster: <- unhandled message id=$messageId (${body.size} bytes)")
}
}
private fun start() {
if (running) return
running = true
Thread({
while (running) {
runCatching { tick() }.onFailure { GearslipLog.w("cluster: ${it.message}") }
Thread.sleep(TICK_MS)
}
}, "gearslip-cluster").start()
}
fun stop() {
running = false
}
private fun tick() {
val turn = NavTurn.current()
val status = when {
turn == null -> STATUS_INACTIVE
turn.rerouting -> STATUS_REROUTING
else -> STATUS_ACTIVE
}
if (status != sentStatus) {
sendOnChannel(MSG_STATUS, Protobuf.varintField(1, status.toLong()))
GearslipLog.i("cluster: -> ${STATUS_NAMES[status]}")
sentStatus = status
if (status == STATUS_INACTIVE) { sentTurn = null; sentDistance = null }
}
if (turn == null || status == STATUS_REROUTING) return
sendTurn(turn.step)
turn.distance?.let { sendDistance(it, turn.seconds) }
}
private fun sendTurn(step: Step) {
val maneuver = step.maneuver
val (event, side) = maneuver?.let { eventFor(it.type) } ?: (EVENT_UNKNOWN to SIDE_UNSPECIFIED)
val road = step.road.text().ifBlank { step.cue.text() }
val key = "$road|$event|$side|${maneuver?.roundaboutExitNumber}"
if (key == sentTurn) return
sentTurn = key
var body = Protobuf.stringField(1, road) +
Protobuf.varintField(2, side.toLong()) +
Protobuf.varintField(3, event.toLong())
maneuver?.roundaboutExitNumber?.takeIf { it > 0 }?.let { body += Protobuf.varintField(5, it.toLong()) }
maneuver?.roundaboutExitAngle?.takeIf { it > 0 }?.let { body += Protobuf.varintField(6, it.toLong()) }
sendOnChannel(MSG_TURN, body)
GearslipLog.i("cluster: -> turn event=$event side=$side road=\"$road\"")
}
/**
* The Car App Library's distance units use the same numbers as the protocol's (1 metres ...
* 7 yards), so the app's own display choice passes straight through.
*/
private fun sendDistance(distance: Distance, seconds: Long?) {
val meters = NavTurn.toMeters(distance)
val key = "${distance.displayDistance}|${distance.displayUnit}|${seconds ?: -1}"
if (key == sentDistance) return
sentDistance = key
sendOnChannel(
MSG_DISTANCE,
Protobuf.varintField(1, meters.toLong()) +
Protobuf.varintField(2, (seconds ?: 0L).coerceAtLeast(0)) +
Protobuf.varintField(3, (distance.displayDistance * 1000).toLong()) +
Protobuf.varintField(4, distance.displayUnit.toLong()),
)
}
private fun CarText?.text() = this?.toString().orEmpty()
companion object {
private const val TICK_MS = 500L
private const val MSG_CHANNEL_OPEN_RESPONSE = 8
private const val MSG_START = 32769
private const val MSG_STOP = 32770
private const val MSG_STATUS = 32771
private const val MSG_TURN = 32772
private const val MSG_DISTANCE = 32773
private const val STATUS_ACTIVE = 1
private const val STATUS_INACTIVE = 2
private const val STATUS_REROUTING = 3
private val STATUS_NAMES = mapOf(1 to "navigating", 2 to "not navigating", 3 to "rerouting")
private const val SIDE_LEFT = 1
private const val SIDE_RIGHT = 2
private const val SIDE_UNSPECIFIED = 3
private const val EVENT_UNKNOWN = 0
/** The car's turn icon and side for a Car App Library manoeuvre. */
fun eventFor(type: Int): Pair<Int, Int> = when (type) {
Maneuver.TYPE_DEPART -> 1 to SIDE_UNSPECIFIED
Maneuver.TYPE_NAME_CHANGE -> 2 to SIDE_UNSPECIFIED
Maneuver.TYPE_KEEP_LEFT, Maneuver.TYPE_TURN_SLIGHT_LEFT -> 3 to SIDE_LEFT
Maneuver.TYPE_KEEP_RIGHT, Maneuver.TYPE_TURN_SLIGHT_RIGHT -> 3 to SIDE_RIGHT
Maneuver.TYPE_TURN_NORMAL_LEFT -> 4 to SIDE_LEFT
Maneuver.TYPE_TURN_NORMAL_RIGHT -> 4 to SIDE_RIGHT
Maneuver.TYPE_TURN_SHARP_LEFT -> 5 to SIDE_LEFT
Maneuver.TYPE_TURN_SHARP_RIGHT -> 5 to SIDE_RIGHT
Maneuver.TYPE_U_TURN_LEFT -> 6 to SIDE_LEFT
Maneuver.TYPE_U_TURN_RIGHT -> 6 to SIDE_RIGHT
Maneuver.TYPE_ON_RAMP_SLIGHT_LEFT, Maneuver.TYPE_ON_RAMP_NORMAL_LEFT, Maneuver.TYPE_ON_RAMP_SHARP_LEFT,
Maneuver.TYPE_ON_RAMP_U_TURN_LEFT -> 7 to SIDE_LEFT
Maneuver.TYPE_ON_RAMP_SLIGHT_RIGHT, Maneuver.TYPE_ON_RAMP_NORMAL_RIGHT, Maneuver.TYPE_ON_RAMP_SHARP_RIGHT,
Maneuver.TYPE_ON_RAMP_U_TURN_RIGHT -> 7 to SIDE_RIGHT
Maneuver.TYPE_OFF_RAMP_SLIGHT_LEFT, Maneuver.TYPE_OFF_RAMP_NORMAL_LEFT -> 8 to SIDE_LEFT
Maneuver.TYPE_OFF_RAMP_SLIGHT_RIGHT, Maneuver.TYPE_OFF_RAMP_NORMAL_RIGHT -> 8 to SIDE_RIGHT
Maneuver.TYPE_FORK_LEFT -> 9 to SIDE_LEFT
Maneuver.TYPE_FORK_RIGHT -> 9 to SIDE_RIGHT
Maneuver.TYPE_MERGE_LEFT -> 10 to SIDE_LEFT
Maneuver.TYPE_MERGE_RIGHT -> 10 to SIDE_RIGHT
Maneuver.TYPE_MERGE_SIDE_UNSPECIFIED -> 10 to SIDE_UNSPECIFIED
Maneuver.TYPE_ROUNDABOUT_ENTER_CW, Maneuver.TYPE_ROUNDABOUT_ENTER_CCW -> 11 to SIDE_UNSPECIFIED
Maneuver.TYPE_ROUNDABOUT_EXIT_CW, Maneuver.TYPE_ROUNDABOUT_EXIT_CCW -> 12 to SIDE_UNSPECIFIED
Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW, Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW_WITH_ANGLE,
Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW, Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE -> 13 to SIDE_UNSPECIFIED
Maneuver.TYPE_STRAIGHT -> 14 to SIDE_UNSPECIFIED
Maneuver.TYPE_FERRY_BOAT, Maneuver.TYPE_FERRY_BOAT_LEFT, Maneuver.TYPE_FERRY_BOAT_RIGHT -> 16 to SIDE_UNSPECIFIED
Maneuver.TYPE_FERRY_TRAIN, Maneuver.TYPE_FERRY_TRAIN_LEFT, Maneuver.TYPE_FERRY_TRAIN_RIGHT -> 17 to SIDE_UNSPECIFIED
Maneuver.TYPE_DESTINATION, Maneuver.TYPE_DESTINATION_STRAIGHT -> 19 to SIDE_UNSPECIFIED
Maneuver.TYPE_DESTINATION_LEFT -> 19 to SIDE_LEFT
Maneuver.TYPE_DESTINATION_RIGHT -> 19 to SIDE_RIGHT
else -> EVENT_UNKNOWN to SIDE_UNSPECIFIED
}
}
}
/** One turn as the car wants it, from whichever source the map app fills. */
internal class NavTurn(val step: Step, val distance: Distance?, val seconds: Long?, val rerouting: Boolean) {
companion object {
/** The map app's next turn: from its trip (what clusters get), or its routing card. */
fun current(): NavTurn? {
val nav = CarServices.navOrNull() ?: return null
nav.trip.value?.let { trip ->
val step = trip.steps.firstOrNull() ?: return@let
val estimate = trip.stepTravelEstimates.firstOrNull()
return NavTurn(step, estimate?.remainingDistance, estimate?.remainingTimeSeconds?.takeIf { it >= 0 }, trip.isLoading)
}
val info = (nav.template.value as? NavigationTemplate)?.navigationInfo as? RoutingInfo ?: return null
val step = info.currentStep ?: return null
return NavTurn(step, info.currentDistance, null, info.isLoading)
}
fun toMeters(d: Distance): Int = (d.displayDistance * when (d.displayUnit) {
Distance.UNIT_KILOMETERS, Distance.UNIT_KILOMETERS_P1 -> 1000.0
Distance.UNIT_MILES, Distance.UNIT_MILES_P1 -> 1609.344
Distance.UNIT_FEET -> 0.3048
Distance.UNIT_YARDS -> 0.9144
else -> 1.0
}).toInt()
}
}
@@ -1,326 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.content.Context
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import androidx.car.app.model.CarText
import androidx.car.app.model.Distance
import androidx.car.app.navigation.model.Maneuver
import androidx.car.app.navigation.model.Step
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.audio.AudioLink
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt
/**
* Spoken turn-by-turn on the car's directions channel (the GUIDANCE audio sink).
*
* A map app on the phone speaks its own prompts as navigation audio, which Android can't hand to
* Gearslip without root, and which the phone mutes while USB audio runs. So Gearslip reads the
* same turn the instrument cluster gets ([NavTurn]) and says it itself: once when the turn comes
* up, again a kilometre or so out on a long stretch, and once more just before it. The words are
* rendered with the phone's text-to-speech to a file, never played on the phone, and streamed to
* the car, which ducks the music under them the way it does for real Android Auto.
*
* Nothing spoken is logged: road names are where the driver is going.
*/
object DirectionsVoice {
private enum class Stage { FAR, PREPARED, DONE }
private var appContext: Context? = null
private var tts: TextToSpeech? = null
@Volatile private var ttsReady = false
private val pending = ConcurrentHashMap<String, CountDownLatch>()
@Volatile private var link: AudioLink? = null
@Volatile private var running = false
private val speaker = Executors.newSingleThreadExecutor { Thread(it, "gearslip-directions").apply { isDaemon = true } }
@Volatile private var latest = 0
private var turnKey: String? = null
private var stage = Stage.DONE
fun init(context: Context) {
if (tts != null) return
appContext = context.applicationContext
tts = TextToSpeech(appContext) { status -> ttsReady = status == TextToSpeech.SUCCESS }.apply {
setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) { pending.remove(utteranceId)?.countDown() }
@Deprecated("Deprecated in Java, no replacement on this API level")
override fun onError(utteranceId: String?) { pending.remove(utteranceId)?.countDown() }
})
}
}
/** The car opened its directions sink: start following the map app's turns. */
fun attach(link: AudioLink) {
this.link = link
GearslipLog.i("guidance: the car offered a directions sink at ${link.sampleRate}Hz x${link.channels}")
if (running) return
running = true
turnKey = null
Thread({
while (running) {
runCatching { tick() }.onFailure { GearslipLog.w("guidance: ${it.message}") }
Thread.sleep(TICK_MS)
}
}, "gearslip-directions-watch").apply { isDaemon = true }.start()
}
fun detach(link: AudioLink) {
if (this.link !== link) return
this.link = null
running = false
}
private fun tick() {
if (!CarSettings.speakDirections.value) return
val turn = NavTurn.current()
if (turn == null) {
turnKey = null
return
}
if (turn.rerouting) return
val step = turn.step
val instruction = instruction(step) ?: return
val meters = turn.distance?.let(NavTurn::toMeters)
val close = (turn.seconds != null && turn.seconds <= NEAR_SECONDS) || (meters != null && meters <= NEAR_METERS)
val key = "${step.road.text()}|${step.maneuver?.type}|${step.maneuver?.roundaboutExitNumber}|${step.cue.text()}"
if (key != turnKey) {
turnKey = key
if (step.maneuver?.type == Maneuver.TYPE_DEPART) {
stage = Stage.DONE
return
}
if (close || turn.distance == null) {
say(instruction)
stage = Stage.DONE
} else {
say("In ${spoken(turn.distance)}, $instruction")
stage = if (meters != null && meters > PREPARE_FROM_METERS) Stage.FAR else Stage.PREPARED
}
return
}
when {
stage != Stage.DONE && close -> {
say(instruction)
stage = Stage.DONE
}
stage == Stage.FAR && meters != null && meters <= PREPARE_AT_METERS -> {
say("In ${spoken(turn.distance)}, $instruction")
stage = Stage.PREPARED
}
}
}
/** What to do, in words: built from the manoeuvre when the app names one, else the app's own text. */
private fun instruction(step: Step): String? {
val road = step.road.text()
val onto = if (road.isBlank()) "" else " onto $road"
val toward = if (road.isBlank()) "" else " toward $road"
val maneuver = step.maneuver
val built = when (maneuver?.type) {
Maneuver.TYPE_TURN_SLIGHT_LEFT -> "Turn slightly left$onto"
Maneuver.TYPE_TURN_SLIGHT_RIGHT -> "Turn slightly right$onto"
Maneuver.TYPE_TURN_NORMAL_LEFT -> "Turn left$onto"
Maneuver.TYPE_TURN_NORMAL_RIGHT -> "Turn right$onto"
Maneuver.TYPE_TURN_SHARP_LEFT -> "Turn sharply left$onto"
Maneuver.TYPE_TURN_SHARP_RIGHT -> "Turn sharply right$onto"
Maneuver.TYPE_U_TURN_LEFT, Maneuver.TYPE_U_TURN_RIGHT -> "Make a U-turn"
Maneuver.TYPE_KEEP_LEFT -> "Keep left$toward"
Maneuver.TYPE_KEEP_RIGHT -> "Keep right$toward"
Maneuver.TYPE_FORK_LEFT -> "Keep left at the fork$toward"
Maneuver.TYPE_FORK_RIGHT -> "Keep right at the fork$toward"
Maneuver.TYPE_ON_RAMP_SLIGHT_LEFT, Maneuver.TYPE_ON_RAMP_NORMAL_LEFT, Maneuver.TYPE_ON_RAMP_SHARP_LEFT,
Maneuver.TYPE_ON_RAMP_U_TURN_LEFT -> "Take the ramp on the left$onto"
Maneuver.TYPE_ON_RAMP_SLIGHT_RIGHT, Maneuver.TYPE_ON_RAMP_NORMAL_RIGHT, Maneuver.TYPE_ON_RAMP_SHARP_RIGHT,
Maneuver.TYPE_ON_RAMP_U_TURN_RIGHT -> "Take the ramp on the right$onto"
Maneuver.TYPE_OFF_RAMP_SLIGHT_LEFT, Maneuver.TYPE_OFF_RAMP_NORMAL_LEFT -> "Take the exit on the left$toward"
Maneuver.TYPE_OFF_RAMP_SLIGHT_RIGHT, Maneuver.TYPE_OFF_RAMP_NORMAL_RIGHT -> "Take the exit on the right$toward"
Maneuver.TYPE_MERGE_LEFT -> "Merge left$onto"
Maneuver.TYPE_MERGE_RIGHT -> "Merge right$onto"
Maneuver.TYPE_MERGE_SIDE_UNSPECIFIED -> "Merge$onto"
Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW, Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CW_WITH_ANGLE,
Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW, Maneuver.TYPE_ROUNDABOUT_ENTER_AND_EXIT_CCW_WITH_ANGLE ->
maneuver.roundaboutExitNumber.takeIf { it in 1..ORDINALS.size }
?.let { "At the roundabout, take the ${ORDINALS[it - 1]} exit$onto" }
?: "Go through the roundabout$onto"
Maneuver.TYPE_ROUNDABOUT_ENTER_CW, Maneuver.TYPE_ROUNDABOUT_ENTER_CCW -> "Enter the roundabout"
Maneuver.TYPE_ROUNDABOUT_EXIT_CW, Maneuver.TYPE_ROUNDABOUT_EXIT_CCW -> "Exit the roundabout$onto"
Maneuver.TYPE_STRAIGHT -> "Continue straight$onto"
Maneuver.TYPE_NAME_CHANGE -> "Continue$onto"
Maneuver.TYPE_FERRY_BOAT, Maneuver.TYPE_FERRY_BOAT_LEFT, Maneuver.TYPE_FERRY_BOAT_RIGHT -> "Take the ferry"
Maneuver.TYPE_FERRY_TRAIN, Maneuver.TYPE_FERRY_TRAIN_LEFT, Maneuver.TYPE_FERRY_TRAIN_RIGHT -> "Take the train"
Maneuver.TYPE_DESTINATION, Maneuver.TYPE_DESTINATION_STRAIGHT -> "Your destination is ahead"
Maneuver.TYPE_DESTINATION_LEFT -> "Your destination is on the left"
Maneuver.TYPE_DESTINATION_RIGHT -> "Your destination is on the right"
else -> null
}
return built ?: step.cue.text().ifBlank { null }
}
/** The app's own rounded distance, read the way a person would say it. */
private fun spoken(d: Distance): String {
val n = d.displayDistance
val number = if (n % 1.0 == 0.0) n.toInt().toString() else "%.1f".format(n)
val one = n == 1.0
return when (d.displayUnit) {
Distance.UNIT_KILOMETERS, Distance.UNIT_KILOMETERS_P1 -> if (one) "1 kilometer" else "$number kilometers"
Distance.UNIT_MILES, Distance.UNIT_MILES_P1 -> when (n) {
0.25 -> "a quarter mile"
0.5 -> "half a mile"
0.75 -> "three quarters of a mile"
1.0 -> "1 mile"
else -> "$number miles"
}
Distance.UNIT_FEET -> "$number feet"
Distance.UNIT_YARDS -> "$number yards"
else -> "${n.roundToInt()} meters"
}
}
/** Newest wins: a prompt still waiting when the next one arrives is already out of date. */
private fun say(text: String) {
val id = ++latest
speaker.execute {
if (id != latest) return@execute
runCatching { play(text, id) }.onFailure { GearslipLog.w("guidance: could not speak a turn: ${it.message}") }
}
}
private fun play(text: String, id: Int) {
val engine = tts ?: return
val context = appContext ?: return
val sink = link ?: return
if (!ttsReady) {
GearslipLog.w("guidance: text-to-speech isn't ready, a turn went unspoken")
return
}
val file = File(context.cacheDir, "directions.wav")
val utterance = "gearslip-directions-$id"
val done = CountDownLatch(1)
pending[utterance] = done
if (engine.synthesizeToFile(text, Bundle(), file, utterance) != TextToSpeech.SUCCESS) {
pending.remove(utterance)
return
}
if (!done.await(SYNTH_TIMEOUT_S, TimeUnit.SECONDS)) {
pending.remove(utterance)
GearslipLog.w("guidance: text-to-speech took too long, a turn went unspoken")
return
}
val pcm = Wav.read(file)?.let { Wav.convert(it, sink.sampleRate, sink.channels) } ?: run {
GearslipLog.w("guidance: text-to-speech gave audio Gearslip can't read")
return
}
stream(sink, pcm)
GearslipLog.i("guidance: spoke a turn (${pcm.size / (2 * sink.channels) * 1000 / sink.sampleRate} ms)")
}
/** Start, the words in 20 ms chunks at about real time, a little silence, Stop. */
private fun stream(sink: AudioLink, pcm: ByteArray) {
val frame = 2 * sink.channels
val chunk = sink.sampleRate / 50 * frame
val chunkMs = 20L
val padded = pcm + ByteArray(sink.sampleRate / 5 * frame) // 200 ms tail so the last word isn't clipped
sink.start()
try {
val began = System.currentTimeMillis()
var offset = 0
var sent = 0
while (offset < padded.size && link === sink) {
val size = minOf(chunk, padded.size - offset)
sink.write(padded.copyOfRange(offset, offset + size), size)
offset += size
sent++
val ahead = sent * chunkMs - (System.currentTimeMillis() - began)
if (ahead > LEAD_MS) Thread.sleep(ahead - LEAD_MS)
}
// Let the car play what it has before closing the stream on it.
Thread.sleep(LEAD_MS)
} finally {
sink.stop()
}
}
private fun CarText?.text() = this?.toString().orEmpty()
/** 16-bit PCM from the WAV text-to-speech writes, reshaped for the car's sink. */
private object Wav {
class Pcm(val samples: ShortArray, val rate: Int, val channels: Int)
fun read(file: File): Pcm? {
val bytes = file.readBytes()
if (bytes.size < 12 || String(bytes, 0, 4) != "RIFF" || String(bytes, 8, 4) != "WAVE") return null
val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
var pos = 12
var rate = 0
var channels = 0
var bits = 0
while (pos + 8 <= bytes.size) {
val name = String(bytes, pos, 4)
val size = buf.getInt(pos + 4)
val body = pos + 8
// Some engines write a streaming WAV with a zero or oversized data length.
val end = if (size <= 0 || body + size > bytes.size) bytes.size else body + size
when (name) {
"fmt " -> {
channels = buf.getShort(body + 2).toInt()
rate = buf.getInt(body + 4)
bits = buf.getShort(body + 14).toInt()
}
"data" -> {
if (bits != 16 || rate <= 0 || channels <= 0) return null
val samples = ShortArray((end - body) / 2)
buf.position(body)
buf.asShortBuffer().get(samples, 0, samples.size)
return Pcm(samples, rate, channels)
}
}
pos = end + (end and 1)
}
return null
}
/** Mixes to mono, resamples linearly, then copies to each of the car's channels. */
fun convert(pcm: Pcm, rate: Int, channels: Int): ByteArray {
val frames = pcm.samples.size / pcm.channels
val mono = FloatArray(frames) { f ->
var sum = 0f
for (c in 0 until pcm.channels) sum += pcm.samples[f * pcm.channels + c]
sum / pcm.channels
}
val outFrames = (frames.toLong() * rate / pcm.rate).toInt()
val out = ByteBuffer.allocate(outFrames * channels * 2).order(ByteOrder.LITTLE_ENDIAN)
val step = pcm.rate.toDouble() / rate
for (i in 0 until outFrames) {
val at = i * step
val j = at.toInt().coerceAtMost(frames - 1)
val next = (j + 1).coerceAtMost(frames - 1)
val v = mono[j] + (mono[next] - mono[j]) * (at - j).toFloat()
val s = v.roundToInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()).toShort()
repeat(channels) { out.putShort(s) }
}
return out.array()
}
}
private const val TICK_MS = 500L
private const val NEAR_SECONDS = 12L
private const val NEAR_METERS = 120
private const val PREPARE_FROM_METERS = 2_500
private const val PREPARE_AT_METERS = 1_000
private const val LEAD_MS = 100L
private const val SYNTH_TIMEOUT_S = 10L
private val ORDINALS = listOf("first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth")
}
@@ -1,84 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.IndicationNodeFactory
import androidx.compose.foundation.interaction.FocusInteraction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.material3.ripple
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.node.DelegatableNode
import androidx.compose.ui.node.DelegatingNode
import androidx.compose.ui.node.DrawModifierNode
import androidx.compose.ui.node.invalidateDraw
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
/**
* What every car button shows: the usual ripple when pressed, and a ring in the accent color
* while the knob or D-pad is on it. Cars without a knob never see the ring, since nothing takes
* focus while the screen is in touch mode.
*
* It replaces the theme's ripple (LocalIndication) for the whole car UI, so any `clickable` that
* doesn't pass its own indication gets the ring for free.
*/
internal class FocusRingIndication(private val color: Color) : IndicationNodeFactory {
private val ripple = ripple()
override fun create(interactionSource: InteractionSource): DelegatableNode =
FocusRingNode(ripple.create(interactionSource), interactionSource, color)
override fun equals(other: Any?) = other is FocusRingIndication && other.color == color
override fun hashCode() = color.hashCode()
}
private class FocusRingNode(
rippleNode: DelegatableNode,
private val source: InteractionSource,
private val color: Color,
) : DelegatingNode(), DrawModifierNode {
private var focused = false
init { delegate(rippleNode) }
override fun onAttach() {
coroutineScope.launch {
var holding = 0
source.interactions.collect {
when (it) {
is FocusInteraction.Focus -> holding++
is FocusInteraction.Unfocus -> holding--
}
val now = holding > 0
if (now != focused) {
focused = now
invalidateDraw()
}
}
}
}
override fun ContentDrawScope.draw() {
drawContent()
if (!focused) return
// Inside the button's bounds, since most buttons clip to their shape: drawn outside, a
// rounded tile would cut its own ring off.
val width = RING_WIDTH.toPx()
val radius = minOf(CORNER.toPx(), size.minDimension / 2)
drawRoundRect(
color,
topLeft = Offset(width / 2, width / 2),
size = Size(size.width - width, size.height - width),
cornerRadius = CornerRadius(radius),
style = Stroke(width),
)
}
private companion object {
val RING_WIDTH = 3.dp
val CORNER = 16.dp
}
}
@@ -1,93 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.os.Handler
import android.os.Looper
import app.seb3thehacker.gearslip.GearslipLog
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* Map apps can't find the car with the phone's location turned off. Ten seconds after the car
* shows Gearslip, this checks, and the car says so until location comes on or the drive ends.
*/
object LocationCheck {
private val _off = MutableStateFlow(false)
/** True while the phone's location is turned off during a drive. */
val off: StateFlow<Boolean> = _off
private val _carDismissed = MutableStateFlow(false)
/** The driver tapped OK on the car's card; it stays away for the rest of this drive. */
val carDismissed: StateFlow<Boolean> = _carDismissed
private val log = GearslipLog.tagged("location")
private val main = Handler(Looper.getMainLooper())
private var appContext: Context? = null
private var armed = false
private var receiver: BroadcastReceiver? = null
fun init(context: Context) {
appContext = context.applicationContext
}
/** The car shows Gearslip. Called again whenever the video restarts, so it arms once per drive. */
fun onProjecting() = main.post {
if (armed) return@post
armed = true
main.postDelayed(::start, WAIT_MS)
}
fun onCarDisconnected() = main.post {
armed = false
main.removeCallbacksAndMessages(null)
stopWatching()
_off.value = false
_carDismissed.value = false
}
fun dismissOnCar() {
_carDismissed.value = true
}
/** "Don't show again" on the car: turns the warning off in Settings, for every car. */
fun neverAgain() {
CarSettings.setLocationWarning(false)
log.i("location warning turned off")
_carDismissed.value = true
_off.value = false
}
private fun start() {
if (!armed) return
check()
// Turning location on clears the warning, and turning it off again brings it back.
val context = appContext ?: return
val r = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) = check()
}
context.registerReceiver(r, IntentFilter(LocationManager.MODE_CHANGED_ACTION), Context.RECEIVER_EXPORTED)
receiver = r
}
private fun check() {
if (!armed) return
val manager = appContext?.getSystemService(LocationManager::class.java) ?: return
val off = CarSettings.locationWarning.value && !manager.isLocationEnabled
if (_off.value == off) return
_off.value = off
log.i(if (off) "the phone's location is off" else "the phone's location is on")
}
private fun stopWatching() {
val r = receiver ?: return
receiver = null
runCatching { appContext?.unregisterReceiver(r) }
}
private const val WAIT_MS = 10_000L
}
@@ -1,38 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import android.os.SystemClock
/**
* Whether the map's buttons (settings, pan, zoom, locate) are showing.
*
* They fade out after [IDLE_MS] with no touch anywhere on the car screen, to leave the map clear,
* and any touch brings them back. [touch] is called for every pointer event and is cheap: it only
* writes state when the buttons were actually hidden.
*/
class MapControlsWake {
var awake by mutableStateOf(true)
private set
private var lastTouch = SystemClock.uptimeMillis()
fun touch() {
lastTouch = SystemClock.uptimeMillis()
if (!awake) awake = true
}
/** Called on a timer; hides the buttons once nothing has touched the screen for [IDLE_MS]. */
fun tick() {
if (awake && SystemClock.uptimeMillis() - lastTouch >= IDLE_MS) awake = false
}
companion object {
const val IDLE_MS = 4_000L
}
}
val LocalMapControlsWake = staticCompositionLocalOf { MapControlsWake() }
@@ -1,17 +1,9 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import app.seb3thehacker.gearslip.car.theme.*
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import android.provider.Settings
import android.content.Intent
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -30,14 +22,15 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search import androidx.compose.material3.Button
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -49,9 +42,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.SolidColor
import androidx.compose.foundation.layout.widthIn
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.addPathNodes import androidx.compose.ui.graphics.vector.addPathNodes
@@ -61,6 +52,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.seb3thehacker.gearslip.audio.CarAudio
import app.seb3thehacker.gearslip.media.CarMedia import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.media.MediaApp import app.seb3thehacker.gearslip.media.MediaApp
import app.seb3thehacker.gearslip.media.MediaArt import app.seb3thehacker.gearslip.media.MediaArt
@@ -68,11 +60,7 @@ import app.seb3thehacker.gearslip.media.LyricsResult
import app.seb3thehacker.gearslip.media.Lyrics import app.seb3thehacker.gearslip.media.Lyrics
import app.seb3thehacker.gearslip.media.MediaEntry import app.seb3thehacker.gearslip.media.MediaEntry
import app.seb3thehacker.gearslip.media.NowPlaying import app.seb3thehacker.gearslip.media.NowPlaying
import app.seb3thehacker.gearslip.media.QueueTrack
import android.media.session.PlaybackState import android.media.session.PlaybackState
import kotlinx.coroutines.delay
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.PaddingValues
/** /**
* A media app on the car screen: what it is playing and its controls on the left, the tree it * A media app on the car screen: what it is playing and its controls on the left, the tree it
@@ -84,118 +72,43 @@ fun MediaScreen(app: MediaApp, onExit: () -> Unit) {
val media = CarServices.media val media = CarServices.media
val phase by media.phase.collectAsStateWithLifecycle() val phase by media.phase.collectAsStateWithLifecycle()
val now by media.now.collectAsStateWithLifecycle() val now by media.now.collectAsStateWithLifecycle()
val queue by media.queue.collectAsStateWithLifecycle()
val browse by media.browse.collectAsStateWithLifecycle() val browse by media.browse.collectAsStateWithLifecycle()
val rejection by media.rejection.collectAsStateWithLifecycle() val capture by CarAudio.capture.collectAsStateWithLifecycle()
val search by media.search.collectAsStateWithLifecycle() var tab by remember { mutableStateOf(Tab.BROWSE) }
var tab by remember { mutableStateOf(Tab.NOW_PLAYING) }
var searching by remember { mutableStateOf(false) }
// The connection outlives this screen: the home screen's player is the same one. // The connection outlives this screen: the home screen's player is the same one.
LaunchedEffect(app) { CarServices.openMedia(app) } LaunchedEffect(app) { CarServices.openMedia(app) }
val art = rememberArt(now) Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
// The art's colour behind everything, header included; the buttons keep their own. IconButton(onClick = onExit) { Icon(Icons.Filled.ArrowBack, contentDescription = "Back to apps") }
Surface(Modifier.fillMaxSize(), color = rememberArtColor(art, MaterialTheme.colorScheme.background, darkLightness = 0.15f, lightLightness = 0.9f)) { Text(app.label, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold)
if (phase != CarMedia.Phase.READY) { Spacer(Modifier.weight(1f))
Column(Modifier.fillMaxSize()) { AudioBadge(capture)
AppIdentity(app, onExit, Modifier.padding(horizontal = 16.dp, vertical = 10.dp))
when (phase) {
CarMedia.Phase.REJECTED -> when (rejection) {
CarMedia.Rejection.NEEDS_NOTIFICATION_ACCESS -> Notice(
"${app.label} keeps its library to itself.",
"Gearslip can still control it once it has Notification access on the phone. " +
"Allow it under Settings > Notifications > Notification access.",
action = "Open on phone" to {
val app = context.applicationContext
runCatching {
app.startActivity(
Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
} }
},
) when (phase) {
CarMedia.Rejection.NEEDS_APP_RUNNING -> Notice( CarMedia.Phase.REJECTED -> Notice(
"${app.label} isn't running.",
"${app.label} plays through Gearslip's own player, but only while it's " +
"open on the phone. Open it once and it keeps playing here in the car.",
action = "Open ${app.label}" to { media.launchAndConnect(app) },
)
CarMedia.Rejection.REFUSED -> Notice(
"${app.label} would not let Gearslip browse it.", "${app.label} would not let Gearslip browse it.",
"Some media apps only accept Google's own host.", "Some media apps only accept Google's own host.",
) )
} CarMedia.Phase.CONNECTING, CarMedia.Phase.IDLE -> Notice("Connecting to ${app.label}…", null)
else -> Notice("Connecting to ${app.label}…", null) CarMedia.Phase.READY -> Row(
} Modifier.fillMaxSize().padding(top = 6.dp),
} horizontalArrangement = Arrangement.spacedBy(16.dp),
return@Surface
}
if (searching) {
SearchPanel(
appLabel = app.label,
media = media,
canPickForYou = now.canSearch,
onPlayed = {
searching = false
tab = Tab.NOW_PLAYING
},
onOpened = {
searching = false
tab = Tab.BROWSE
},
onPickForYou = { query ->
media.search(query)
searching = false
tab = Tab.NOW_PLAYING
},
onClose = { searching = false },
)
return@Surface
}
// Two columns, split the same way on every tab so nothing jumps when switching: the app
// and the art (or, beside a list, the compact player) on the left; the tabs across the
// top of the right column, over whatever the tab shows.
Row(
Modifier.fillMaxSize().padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 8.dp),
horizontalArrangement = Arrangement.spacedBy(24.dp),
) { ) {
Column(Modifier.weight(0.8f).fillMaxHeight()) { NowPlayingPanel(now, media, Modifier.width(250.dp).fillMaxHeight())
AppIdentity(app, onExit) Column(Modifier.weight(1f).fillMaxHeight()) {
Spacer(Modifier.height(12.dp)) Row {
if (tab == Tab.NOW_PLAYING) { TextButton(onClick = { tab = Tab.BROWSE }) {
CoverArt(art, Modifier.weight(1f).fillMaxWidth()) Text("Browse", fontWeight = if (tab == Tab.BROWSE) FontWeight.Bold else FontWeight.Normal)
} else { }
CompactPlayer(now, media, Modifier.weight(1f).fillMaxWidth()) TextButton(onClick = { tab = Tab.LYRICS }) {
Text("Lyrics", fontWeight = if (tab == Tab.LYRICS) FontWeight.Bold else FontWeight.Normal)
} }
} }
Column(Modifier.weight(1.2f).fillMaxHeight()) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
MediaTab("Now playing", tab == Tab.NOW_PLAYING, Modifier.weight(1f)) { tab = Tab.NOW_PLAYING }
MediaTab("Browse", tab == Tab.BROWSE, Modifier.weight(1f)) { tab = Tab.BROWSE }
MediaTab("Up next", tab == Tab.QUEUE, Modifier.weight(1f)) { tab = Tab.QUEUE }
MediaTab("Lyrics", tab == Tab.LYRICS, Modifier.weight(1f)) { tab = Tab.LYRICS }
if (now.canSearch || media.canSearchLibrary) {
GsIconButton(
Icons.Filled.Search,
"Search ${app.label}",
{ searching = true },
colors = GsColors(MaterialTheme.colorScheme.surfaceContainerHigh, MaterialTheme.colorScheme.onSurface),
size = 44.dp,
shape = MaterialTheme.shapes.large,
)
}
}
search?.let { SearchStatus(it, app.label, media::dismissSearch) }
Spacer(Modifier.height(12.dp))
Box(Modifier.weight(1f).fillMaxWidth()) {
when (tab) { when (tab) {
Tab.NOW_PLAYING -> NowPlayingControls(now, media, Modifier.fillMaxSize()) Tab.BROWSE -> BrowsePanel(browse, media, Modifier.fillMaxSize())
Tab.BROWSE -> BrowsePanel(browse, media, app.label, Modifier.fillMaxSize())
Tab.QUEUE -> QueuePanel(queue, now, media, Modifier.fillMaxSize())
Tab.LYRICS -> LyricsPanel(now, Modifier.fillMaxSize()) Tab.LYRICS -> LyricsPanel(now, Modifier.fillMaxSize())
} }
} }
@@ -204,196 +117,17 @@ fun MediaScreen(app: MediaApp, onExit: () -> Unit) {
} }
} }
/** private enum class Tab { BROWSE, LYRICS }
* Back, then which app this is: its own icon and its name, quieter than the song title - the
* name alone in big bold type read as one more heading fighting the track for attention.
*/
@Composable
private fun AppIdentity(app: MediaApp, onExit: () -> Unit, modifier: Modifier = Modifier) {
val icon = remember(app) { findEntry(app.component.flattenToString())?.icon }
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
GsIconButton(Icons.Filled.ArrowBack, "Back", onExit, size = 44.dp)
Spacer(Modifier.width(14.dp))
icon?.let {
Image(it, null, Modifier.size(26.dp).clip(RoundedCornerShape(7.dp)))
Spacer(Modifier.width(10.dp))
}
Text(
app.label.lowercase().replaceFirstChar { it.titlecase() },
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
private enum class Tab { NOW_PLAYING, BROWSE, QUEUE, LYRICS }
// --- search ----------------------------------------------------------------------------------
/**
* Types a search for the app to play. The app picks the result and plays it, the way it would
* for "play X" from a voice assistant, so there's no list to choose from.
*/
/**
* Search inside the media app. It asks the app's library for matches half a second after the
* driver stops typing and lists them, so the driver picks exactly what plays: a song plays, an
* album or artist opens in Browse. The search key hides the keyboard to show more results; the
* field brings it back. An app with no library search can still be told to play its own best
* match, which is all the panel could do before.
*/
@Composable
private fun SearchPanel(
appLabel: String,
media: CarMedia,
canPickForYou: Boolean,
onPlayed: () -> Unit,
onOpened: () -> Unit,
onPickForYou: (String) -> Unit,
onClose: () -> Unit,
) {
var query by remember { mutableStateOf("") }
var typing by remember { mutableStateOf(true) }
val results by media.results.collectAsStateWithLifecycle()
LaunchedEffect(query) {
delay(SEARCH_PAUSE_MS)
media.searchLibrary(query)
}
DisposableEffect(Unit) { onDispose { media.clearResults() } }
val trimmed = query.trim()
val current = results?.takeIf { it.query == trimmed }
val unsupported = current?.supported == false
Column(Modifier.fillMaxSize()) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
GsIconButton(Icons.Filled.ArrowBack, "Back", onClose, size = ICON_BUTTON_SIZE)
SearchField(
query,
"Search $appLabel",
Modifier.weight(1f).clickable { typing = true },
onClear = {
query = ""
typing = true
},
)
}
Box(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp)) {
val entries = current?.entries
when {
trimmed.isEmpty() -> SearchNote("Type a song, artist, album, or playlist.")
unsupported && canPickForYou ->
SearchNote("$appLabel can't list results. Press search, and $appLabel picks what to play.")
unsupported -> SearchNote("$appLabel can't search from the car.")
entries == null -> SearchNote("Searching $appLabel…")
entries.isEmpty() -> SearchNote("$appLabel found nothing for \"$trimmed\".")
else -> LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(bottom = 8.dp)) {
items(entries) { entry ->
EntryRow(entry, media) {
if (entry.browsable) {
media.select(entry)
onOpened()
} else {
media.playAll(entry)
onPlayed()
}
}
}
}
}
}
if (typing) {
CarKeyboard(
text = query,
onTextChange = { query = it },
onSubmit = {
when {
trimmed.isEmpty() -> Unit
unsupported && canPickForYou -> onPickForYou(trimmed)
else -> typing = false
}
},
onDismiss = { if (trimmed.isEmpty()) onClose() else typing = false },
)
}
}
}
@Composable
private fun SearchNote(text: String) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
text,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
)
}
}
/** How long typing has to pause before the library is searched. */
private const val SEARCH_PAUSE_MS = 1_000L
/** A line under the tabs while the app works on a search, and if it plays nothing for it. */
@Composable
private fun SearchStatus(search: CarMedia.Search, appLabel: String, onDismiss: () -> Unit) {
Surface(
onClick = onDismiss,
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
) {
Text(
if (search.ignored) "$appLabel didn't play anything for \"${search.query}\"."
else "Searching $appLabel for \"${search.query}\"…",
style = MaterialTheme.typography.bodyLarge,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
)
}
}
/** A bigger, easier-to-hit tab than a plain [TextButton] - this row is the only navigation on the screen. */
@Composable
private fun MediaTab(label: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {
GsIconBox(
onClick = onClick,
modifier = modifier.height(44.dp),
colors = if (selected) GsColors(MaterialTheme.colorScheme.primaryContainer, MaterialTheme.colorScheme.onPrimaryContainer)
else GsColors(MaterialTheme.colorScheme.surfaceContainerHigh, MaterialTheme.colorScheme.onSurface),
shape = MaterialTheme.shapes.large,
latched = selected,
) {
Text(
label,
style = MaterialTheme.typography.titleSmall,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
/** /**
* The song's lyrics, fetched when this tab opens. Synced lyrics follow the playback position with * The song's lyrics, fetched when this tab opens. Synced lyrics follow the playback position with
* the current line in the accent colour; unsynced ones are plain scrolling text. * the current line in the accent colour; unsynced ones are plain scrolling text.
*/ */
@Composable @Composable
internal fun LyricsPanel( private fun LyricsPanel(now: NowPlaying, modifier: Modifier) {
now: NowPlaying,
modifier: Modifier,
lineStyle: androidx.compose.ui.text.TextStyle = MaterialTheme.typography.titleLarge,
) {
val context = LocalContext.current
val lyrics by produceState<LyricsState>(LyricsState.Loading, now.title, now.artist, now.album, now.durationMs) { val lyrics by produceState<LyricsState>(LyricsState.Loading, now.title, now.artist, now.album, now.durationMs) {
value = LyricsState.Loading value = LyricsState.Loading
value = Lyrics.find(context, now.title, now.artist, now.album, now.durationMs) value = Lyrics.find(now.title, now.artist, now.album, now.durationMs)
?.let { LyricsState.Found(it) } ?: LyricsState.Missing ?.let { LyricsState.Found(it) } ?: LyricsState.Missing
} }
val list = rememberLazyListState() val list = rememberLazyListState()
@@ -423,7 +157,7 @@ internal fun LyricsPanel(
itemsIndexed(lines) { index, line -> itemsIndexed(lines) { index, line ->
Text( Text(
line.text.ifEmpty { " " }, line.text.ifEmpty { " " },
style = lineStyle, style = MaterialTheme.typography.titleLarge,
fontWeight = if (index == current) FontWeight.Bold else FontWeight.Normal, fontWeight = if (index == current) FontWeight.Bold else FontWeight.Normal,
color = when { color = when {
!state.result.synced -> MaterialTheme.colorScheme.onSurface !state.result.synced -> MaterialTheme.colorScheme.onSurface
@@ -444,143 +178,113 @@ private sealed interface LyricsState {
} }
@Composable @Composable
private fun Notice(title: String, detail: String?, action: Pair<String, () -> Unit>? = null) { private fun AudioBadge(capture: CarAudio.Capture) {
Column( val text = when (capture) {
Modifier.fillMaxSize().padding(horizontal = 24.dp), CarAudio.Capture.ON -> "Audio to car"
verticalArrangement = Arrangement.Center, CarAudio.Capture.ASKING -> "Allow audio capture on the phone"
horizontalAlignment = Alignment.CenterHorizontally, CarAudio.Capture.DENIED -> "Audio stays on the phone"
) { CarAudio.Capture.OFF -> return
Text(title, style = MaterialTheme.typography.titleMedium, textAlign = androidx.compose.ui.text.style.TextAlign.Center)
detail?.let {
Text(
it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
)
}
action?.let { (label, run) ->
Spacer(Modifier.height(12.dp))
GsButton(onClick = run, tone = GsTone.Tonal) { Text(label) }
} }
Text(text, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun Notice(title: String, detail: String?) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, style = MaterialTheme.typography.titleMedium)
detail?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) }
} }
} }
// --- now playing ----------------------------------------------------------------------------- // --- now playing -----------------------------------------------------------------------------
/**
* The now-playing view on its own, for places with no tabs around it (an app's own
* now-playing template): the cover on the left, [NowPlayingControls] on the right.
*/
@Composable @Composable
internal fun NowPlayingPage(now: NowPlaying, media: CarMedia, modifier: Modifier) { private fun NowPlayingPanel(now: NowPlaying, media: CarMedia, modifier: Modifier) {
Row( val context = LocalContext.current
modifier.padding(horizontal = 24.dp, vertical = 8.dp), val art by produceState(now.art, now.art, now.artUri) {
horizontalArrangement = Arrangement.spacedBy(24.dp), value = now.art ?: MediaArt.load(context, now.artUri)
) { }
CoverArt(rememberArt(now), Modifier.weight(0.8f).fillMaxHeight()) var position by remember { mutableLongStateOf(0L) }
NowPlayingControls(now, media, Modifier.weight(1.2f).fillMaxHeight()) LaunchedEffect(now) {
while (true) {
position = now.currentPosition()
kotlinx.coroutines.delay(500)
}
} }
}
/** The cover, as big a square as its space allows, centred in it. */ Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {
@Composable
private fun CoverArt(art: android.graphics.Bitmap?, modifier: Modifier) {
BoxWithConstraints(modifier, contentAlignment = Alignment.Center) {
Surface( Surface(
shape = MaterialTheme.shapes.large, shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceVariant, color = MaterialTheme.colorScheme.surfaceVariant,
shadowElevation = 6.dp, modifier = Modifier.size(170.dp),
modifier = Modifier.size(minOf(maxWidth, maxHeight)),
) { ) {
art?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } art?.let {
Image(it.asImageBitmap(), null, Modifier.fillMaxSize().clip(MaterialTheme.shapes.large), contentScale = ContentScale.Crop)
} }
} }
} Spacer(Modifier.height(8.dp))
/**
* Everything about the track and every control for it, read top to bottom: title and artist,
* the seek bar, the transport, then like, shuffle and repeat as big icon-only buttons.
*/
@Composable
private fun NowPlayingControls(now: NowPlaying, media: CarMedia, modifier: Modifier) {
Column(
modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterVertically),
) {
Column {
Text( Text(
now.title.ifEmpty { "Nothing playing" }, now.title.ifEmpty { "Nothing playing" },
style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
maxLines = 2, overflow = TextOverflow.Ellipsis, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
Text( Text(
listOf(now.artist, now.album).filter { it.isNotEmpty() }.joinToString(" - "), listOf(now.artist, now.album).filter { it.isNotEmpty() }.joinToString(" - "),
style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
now.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, maxLines = 2) } now.error?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, maxLines = 2) }
}
PlayerProgress(now, media, Modifier.fillMaxWidth())
TransportRow(now, media, skip = 60.dp, modifier = Modifier.fillMaxWidth())
PlayModeRow(now, media, size = 56.dp, modifier = Modifier.fillMaxWidth(), maxOther = 2)
}
}
/** if (now.durationMs > 0) {
* The player beside the browse list, the queue and the lyrics: no art, which the list needs the WavyProgress(
* room for, just what's playing, the seek bar and the controls. fraction = position.toFloat() / now.durationMs,
*/ playing = now.state == PlaybackState.STATE_PLAYING,
@Composable onSeek = { media.seek((it * now.durationMs).toLong()) },
private fun CompactPlayer(now: NowPlaying, media: CarMedia, modifier: Modifier) { modifier = Modifier.padding(vertical = 4.dp),
Column(
modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Column {
Text(
now.title.ifEmpty { "Nothing playing" },
style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold,
maxLines = 2, overflow = TextOverflow.Ellipsis,
)
Text(
now.artist,
style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
} else {
Spacer(Modifier.height(14.dp))
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
IconButton(onClick = media::previous, enabled = now.canDo(PlaybackState.ACTION_SKIP_TO_PREVIOUS), modifier = Modifier.size(56.dp)) {
Icon(MediaIcons.Previous, "Previous", Modifier.size(32.dp))
}
FilledIconButton(onClick = media::togglePlay, modifier = Modifier.size(68.dp)) {
Icon(if (now.playing) MediaIcons.Pause else Icons.Filled.PlayArrow, if (now.playing) "Pause" else "Play", Modifier.size(40.dp))
}
IconButton(onClick = media::next, enabled = now.canDo(PlaybackState.ACTION_SKIP_TO_NEXT), modifier = Modifier.size(56.dp)) {
Icon(MediaIcons.Next, "Next", Modifier.size(32.dp))
}
}
// Whatever extra buttons the app publishes (shuffle, repeat, like), by name: their
// icons are resources inside the app's own package.
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
now.custom.take(3).forEach { action ->
TextButton(onClick = { media.custom(action) }) { Text(action.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }
}
} }
PlayerProgress(now, media, Modifier.fillMaxWidth())
TransportRow(now, media, skip = 52.dp, modifier = Modifier.fillMaxWidth())
PlayModeRow(now, media, size = 48.dp, modifier = Modifier.fillMaxWidth())
} }
} }
// --- browsing -------------------------------------------------------------------------------- // --- browsing --------------------------------------------------------------------------------
@Composable @Composable
private fun BrowsePanel(browse: app.seb3thehacker.gearslip.media.BrowseState, media: CarMedia, appLabel: String, modifier: Modifier) { private fun BrowsePanel(browse: app.seb3thehacker.gearslip.media.BrowseState, media: CarMedia, modifier: Modifier) {
Column(modifier) { Column(modifier) {
// At the library root there's no trail and nowhere to go up to, so there's nothing this
// row could say that the app's name in the top-left corner hasn't already - showing it
// again here (as "Browse", or as the app's own name) was just the same label twice.
if (media.canGoUp || browse.trail.isNotEmpty()) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
if (media.canGoUp) { if (media.canGoUp) {
GsIconButton(Icons.Filled.ArrowBack, "Up", media::up) IconButton(onClick = media::up) { Icon(Icons.Filled.ArrowBack, "Up") }
} }
browse.trail.lastOrNull()?.let {
Text( Text(
it, browse.trail.lastOrNull() ?: "Browse",
style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
maxLines = 1, overflow = TextOverflow.Ellipsis, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
} }
}
}
when { when {
browse.loading -> Notice("Loading…", null) browse.loading -> Notice("Loading…", null)
browse.unavailable -> Notice(
"$appLabel keeps its library to itself.",
"Start music in the app on your phone. Play, pause, skip and seek work from here.",
)
browse.failed -> Notice("Could not load this list.", null) browse.failed -> Notice("Could not load this list.", null)
browse.entries.isEmpty() -> Notice("Nothing here.", null) browse.entries.isEmpty() -> Notice("Nothing here.", null)
else -> LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) { else -> LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -590,75 +294,20 @@ private fun BrowsePanel(browse: app.seb3thehacker.gearslip.media.BrowseState, me
} }
} }
// --- up next -----------------------------------------------------------------------------------
/**
* Whatever the app has queued up, starting right after the track that's playing now - not the
* whole queue from the top, which would just repeat what the player beside it already shows. Apps
* that never publish a queue (many don't) show an empty notice rather than a permanently blank tab.
*/
@Composable @Composable
private fun QueuePanel(queue: List<QueueTrack>, now: NowPlaying, media: CarMedia, modifier: Modifier) { private fun EntryRow(entry: MediaEntry, media: CarMedia) {
val upNext = remember(queue, now.activeQueueItemId) {
val current = queue.indexOfFirst { it.queueId == now.activeQueueItemId }
if (current >= 0) queue.drop(current + 1) else queue
}
Column(modifier) {
if (upNext.isEmpty()) {
Notice(
"Nothing queued.",
"${if (now.title.isEmpty()) "Nothing playing" else "Only what's already playing"} - " +
"not every app tells Gearslip what comes next.",
)
} else {
LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(upNext, key = { it.queueId }) { track -> QueueRow(track, media) }
}
}
}
}
@Composable
private fun QueueRow(track: QueueTrack, media: CarMedia) {
val context = LocalContext.current
val icon by produceState(track.iconBitmap, track.iconUri) {
value = track.iconBitmap ?: MediaArt.load(context, track.iconUri)
}
Surface(
onClick = { media.playQueueItem(track) },
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Row(Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(62.dp).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surface)) {
icon?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) }
}
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
Text(track.title, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (track.subtitle.isNotEmpty()) {
Text(track.subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.PlayArrow, "Play", tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
private fun EntryRow(entry: MediaEntry, media: CarMedia, onClick: () -> Unit = { media.select(entry) }) {
val context = LocalContext.current val context = LocalContext.current
val icon by produceState(entry.iconBitmap, entry.iconUri) { val icon by produceState(entry.iconBitmap, entry.iconUri) {
value = entry.iconBitmap ?: MediaArt.load(context, entry.iconUri) value = entry.iconBitmap ?: MediaArt.load(context, entry.iconUri)
} }
Surface( Surface(
onClick = onClick, onClick = { media.select(entry) },
shape = MaterialTheme.shapes.large, shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceVariant, color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) { ) {
Row(Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(62.dp).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surface)) { Box(Modifier.size(52.dp).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surface)) {
icon?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } icon?.let { Image(it.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) }
} }
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
@@ -668,7 +317,7 @@ private fun EntryRow(entry: MediaEntry, media: CarMedia, onClick: () -> Unit = {
} }
} }
if (entry.browsable && entry.playable) { if (entry.browsable && entry.playable) {
GsIconButton(Icons.Filled.PlayArrow, "Play", { media.playAll(entry) }) IconButton(onClick = { media.playAll(entry) }) { Icon(Icons.Filled.PlayArrow, "Play") }
} }
if (entry.browsable) Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null) if (entry.browsable) Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null)
} }
@@ -682,14 +331,8 @@ internal object MediaIcons {
/** The 3x3 app grid; not in material-icons-core. */ /** The 3x3 app grid; not in material-icons-core. */
val Apps = icon("Apps", "M4,8h4L8,4L4,4v4zM10,20h4v-4h-4v4zM4,20h4v-4L4,16v4zM4,14h4v-4L4,10v4zM10,14h4v-4h-4v4zM16,4v4h4L20,4h-4zM10,8h4L14,4h-4v4zM16,14h4v-4h-4v4zM16,20h4v-4h-4v4z") val Apps = icon("Apps", "M4,8h4L8,4L4,4v4zM10,20h4v-4h-4v4zM4,20h4v-4L4,16v4zM4,14h4v-4L4,10v4zM10,14h4v-4h-4v4zM16,4v4h4L20,4h-4zM10,8h4L14,4h-4v4zM16,14h4v-4h-4v4zM16,20h4v-4h-4v4z")
val Previous = icon("SkipPrevious", "M6,6h2v12L6,18zM9.5,12l8.5,6V6z") val Previous = icon("SkipPrevious", "M6,6h2v12L6,18zM9.5,12l8.5,6V6z")
val Equalizer = icon("Equalizer", "M10,20h4L14,4h-4v16zM4,20h4v-8L4,12v8zM16,9v11h4L20,9h-4z")
val Shuffle = icon("Shuffle", "M10.59,9.17L5.41,4 4,5.41l5.17,5.17 1.42,-1.41zM14.5,4l2.04,2.04L4,18.59 5.41,20 17.96,7.46 20,9.5L20,4h-5.5zM14.83,13.41l-1.41,1.41 3.13,3.13L14.5,20L20,20v-5.5l-2.04,2.04 -3.13,-3.13z")
val Repeat = icon("Repeat", "M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z")
val RepeatOne = icon("RepeatOne", "M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4zM13,15L13,9h-1l-2,1v1h1.5v4L13,15z")
/** A screen with a filled right-hand panel: "put the player beside the map". */
val DockRight = icon("DockRight", "M2,4h20v16H2zM4,6h10v12H4z", PathFillType.EvenOdd)
private fun icon(name: String, path: String, fillType: PathFillType = PathFillType.NonZero) = ImageVector.Builder( private fun icon(name: String, path: String) = ImageVector.Builder(
name, 24.dp, 24.dp, 24f, 24f, name, 24.dp, 24.dp, 24f, 24f,
).addPath(addPathNodes(path), pathFillType = fillType, fill = SolidColor(androidx.compose.ui.graphics.Color.Black)).build() ).addPath(addPathNodes(path), fill = SolidColor(androidx.compose.ui.graphics.Color.Black)).build()
} }
@@ -1,274 +0,0 @@
package app.seb3thehacker.gearslip.car
import android.os.SystemClock
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.withFrameMillis
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.car.theme.GsButton
import app.seb3thehacker.gearslip.car.theme.GsIconButton
import app.seb3thehacker.gearslip.car.theme.GsProgressBar
import app.seb3thehacker.gearslip.car.theme.GsTone
import app.seb3thehacker.gearslip.notify.CarNotification
import app.seb3thehacker.gearslip.notify.CarNotifications
import kotlinx.coroutines.delay
/*
* A new message on the car screen: a card at the top right, over the player beside the map on
* Home, so the road stays in view. It offers two things - hear it, or answer it by voice - and
* shows [VoiceReply]'s progress once either starts. A bar along its bottom empties as the card
* runs out of time, whatever it's waiting to do: go away, or send.
*/
/** How long a new message stays up on its own. */
private const val POPUP_MS = 5_000L
/** When [this] popup goes away on its own. */
private fun CarNotification.until() = shownAt + POPUP_MS
/**
* Times the popup out. Each new message in the same chat starts the clock again. A voice reply
* covers the card while it runs; if the popup's time ran out meanwhile, it goes when the reply ends.
*/
@Composable
internal fun PopupTimer() {
val popup by CarNotifications.popup.collectAsState()
val voice by VoiceReply.state.collectAsState()
val n = popup ?: return
val busy = voice.phase != VoiceReply.Phase.IDLE
LaunchedEffect(n.id, n.shownAt, busy) {
if (busy) return@LaunchedEffect
delay((n.until() - SystemClock.uptimeMillis()).coerceAtLeast(0L))
CarNotifications.dismissPopup(n.id)
}
}
@Composable
internal fun ReadGlyph(modifier: Modifier = Modifier) =
Icon(ImageVector.vectorResource(R.drawable.volume_up_24), null, modifier)
@Composable
internal fun ReplyGlyph(modifier: Modifier = Modifier) =
Icon(ImageVector.vectorResource(R.drawable.voice_selection_24), null, modifier)
/** "Alex", or "Alex · 3 new" when a burst of messages from one chat has been merged. */
private fun CarNotification.heading(): String {
val who = title.ifBlank { appLabel }
return if (burst > 1) "$who · $burst new" else who
}
/** The card. It shows the voice reply too, wherever that was started from. */
@Composable
fun NotificationPopup(showNew: Boolean, modifier: Modifier = Modifier) {
val popup by CarNotifications.popup.collectAsState()
val voice by VoiceReply.state.collectAsState()
val target = voice.target
if (voice.phase != VoiceReply.Phase.IDLE && target != null) {
PopupCard(voice.until, voice.span, modifier, held = voice.held) { VoiceReplyBody(voice, target) }
return
}
val n = popup?.takeIf { showNew } ?: return
PopupCard(n.until(), POPUP_MS, modifier) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
NotificationIcon(n, size = 44.dp)
Column(Modifier.weight(1f)) {
Text(n.heading(), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(n.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
GsIconButton(Icons.Filled.Close, "Dismiss", { CarNotifications.dismissPopup(n.id) }, size = 40.dp, iconSize = 20.dp)
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
GsButton(onClick = { VoiceReply.read(n) }, tone = GsTone.Neutral, modifier = Modifier.weight(1f)) {
ReadGlyph(Modifier.size(20.dp))
Text("Read", Modifier.padding(start = 8.dp))
}
if (n.reply != null) {
GsButton(onClick = { VoiceReply.reply(n) }, modifier = Modifier.weight(1f)) {
ReplyGlyph(Modifier.size(20.dp))
Text("Reply", Modifier.padding(start = 8.dp))
}
}
}
}
}
/**
* The card's frame. When [until] is set, a bar along the bottom empties over [span] ms, so the
* driver sees at a glance how long is left before the card acts. A [held] countdown shows its bar
* standing still.
*/
@Composable
private fun PopupCard(until: Long, span: Long, modifier: Modifier, held: Float = 0f, content: @Composable () -> Unit) {
Surface(
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
contentColor = MaterialTheme.colorScheme.onSurface,
shadowElevation = 8.dp,
modifier = modifier.padding(12.dp).widthIn(min = 300.dp, max = 400.dp).fillMaxWidth(0.34f),
) {
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
content()
if (until > 0L && span > 0L) {
val left by rememberTimeLeft(until, span)
GsProgressBar(left, Modifier.fillMaxWidth(), height = 14.dp)
} else if (held > 0f) {
GsProgressBar(held, Modifier.fillMaxWidth(), height = 14.dp)
}
}
}
}
/** The share of [span] still to go before [until], updated every frame so the bar moves smoothly. */
@Composable
private fun rememberTimeLeft(until: Long, span: Long) = produceState(fractionLeft(until, span), until, span) {
// The state outlives a change of deadline, so start from the new one rather than the old value.
value = fractionLeft(until, span)
while (value > 0f) {
withFrameMillis { value = fractionLeft(until, span) }
}
}
private fun fractionLeft(until: Long, span: Long): Float =
((until - SystemClock.uptimeMillis()).toFloat() / span).coerceIn(0f, 1f)
/** Each step of a voice reply, with the buttons that fit it. */
@Composable
private fun VoiceReplyBody(s: VoiceReply.State, n: CarNotification) {
val navigator = LocalCarNavigator.current
val who = n.title.ifBlank { n.appLabel }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
when (s.phase) {
VoiceReply.Phase.OFFERING, VoiceReply.Phase.ASKING, VoiceReply.Phase.LISTENING -> ListeningDot()
VoiceReply.Phase.SENT -> Icon(Icons.Filled.Check, null, Modifier.size(32.dp), tint = MaterialTheme.colorScheme.primary)
else -> NotificationIcon(n, size = 44.dp)
}
Column(Modifier.weight(1f)) {
Text(voiceHeading(s, who), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
voiceDetail(s, n)?.let {
Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
}
if (s.phase == VoiceReply.Phase.CONFIRMING) {
Text("Say “cancel” or “change it”", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
}
if ((s.phase == VoiceReply.Phase.READ || s.phase == VoiceReply.Phase.OFFERING) && n.reply != null) {
QuickReplies(n)
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
val wide = Modifier.weight(1f)
when (s.phase) {
VoiceReply.Phase.READING, VoiceReply.Phase.READ -> {
GsButton(onClick = VoiceReply::cancel, tone = GsTone.Neutral, modifier = wide) {
Text(if (s.phase == VoiceReply.Phase.READING) "Stop" else "Close")
}
if (n.reply != null) {
GsButton(onClick = { VoiceReply.reply(n, readFirst = false) }, modifier = wide) {
ReplyGlyph(Modifier.size(20.dp))
Text("Reply", Modifier.padding(start = 8.dp))
}
}
}
VoiceReply.Phase.OFFERING -> {
GsButton(onClick = VoiceReply::cancel, tone = GsTone.Neutral, modifier = wide) { Text("No") }
GsButton(onClick = { VoiceReply.reply(n, readFirst = false) }, modifier = wide) {
ReplyGlyph(Modifier.size(20.dp))
Text("Reply", Modifier.padding(start = 8.dp))
}
}
VoiceReply.Phase.ASKING, VoiceReply.Phase.LISTENING ->
GsButton(onClick = VoiceReply::cancel, tone = GsTone.Neutral, modifier = wide) { Text("Cancel") }
VoiceReply.Phase.CONFIRMING -> {
GsButton(onClick = VoiceReply::cancel, tone = GsTone.Neutral, modifier = wide) { Text("Cancel") }
GsButton(onClick = VoiceReply::sendNow, modifier = wide) { Text("Send now") }
}
VoiceReply.Phase.ERROR -> {
GsButton(onClick = VoiceReply::cancel, tone = GsTone.Neutral, modifier = wide) { Text("Close") }
if (n.reply != null) {
GsButton(onClick = { VoiceReply.reply(n, readFirst = false) }, tone = GsTone.Tonal, modifier = wide) { Text("Try again") }
GsButton(
onClick = { VoiceReply.cancel(); navigator.notifications(replyTo = n.key) },
tone = GsTone.Neutral, modifier = wide,
) { Text("Type") }
}
}
VoiceReply.Phase.SENT, VoiceReply.Phase.IDLE -> Unit
}
}
}
private fun voiceHeading(s: VoiceReply.State, who: String): String = when (s.phase) {
VoiceReply.Phase.READING, VoiceReply.Phase.READ -> who
VoiceReply.Phase.OFFERING, VoiceReply.Phase.ASKING -> "Reply to $who"
VoiceReply.Phase.LISTENING -> "Listening"
VoiceReply.Phase.CONFIRMING -> "Sending to $who"
VoiceReply.Phase.SENT -> "Sent to $who"
VoiceReply.Phase.ERROR -> "Couldn't reply"
VoiceReply.Phase.IDLE -> ""
}
private fun voiceDetail(s: VoiceReply.State, n: CarNotification): String? = when (s.phase) {
VoiceReply.Phase.READING, VoiceReply.Phase.READ -> n.text
VoiceReply.Phase.OFFERING -> s.heard.ifBlank { "Do you want to reply? Say yes or no." }
VoiceReply.Phase.ASKING -> "Get ready to say your reply."
VoiceReply.Phase.LISTENING -> s.heard.ifBlank { "Say your reply" }
VoiceReply.Phase.CONFIRMING, VoiceReply.Phase.SENT -> "“${s.heard}”"
VoiceReply.Phase.ERROR -> s.error
VoiceReply.Phase.IDLE -> null
}
/** Ready-made answers, one tap each: sent at once, with no voice. */
@Composable
internal fun QuickReplies(n: CarNotification, modifier: Modifier = Modifier) {
Row(
modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
VoiceReply.quickReplies().forEach { text ->
GsButton(onClick = { VoiceReply.quickReply(n, text) }, tone = GsTone.Neutral) {
Text(text, style = MaterialTheme.typography.labelLarge, maxLines = 1)
}
}
}
}
@Composable
private fun ListeningDot(modifier: Modifier = Modifier) {
Box(
modifier.size(44.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary),
contentAlignment = Alignment.Center,
) {
MicGlyph(Modifier.size(24.dp))
}
}
@@ -1,198 +0,0 @@
package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import android.content.Intent
import android.provider.Settings
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.notify.CarNotification
import app.seb3thehacker.gearslip.notify.CarNotifications
import app.seb3thehacker.gearslip.notify.ChatLine
import java.text.DateFormat
import java.util.Date
/** Lines a collapsed conversation shows; tapping it shows the rest the app sent. */
private const val COLLAPSED_LINES = 2
/**
* A messaging app's recent conversations, the way Android Auto shows them: the app has no car
* screen of its own, so each thread comes from the notification it has on the phone, newest
* first, with reply and mark-as-read when the app offers them.
*/
@Composable
fun MessagesScreen(packageName: String) {
val history by CarNotifications.history.collectAsState()
val listening by CarNotifications.listening.collectAsState()
val navigator = LocalCarNavigator.current
val context = LocalContext.current.applicationContext
val entry = remember(packageName) { findEntry(MESSAGING_PREFIX + packageName) }
val label = entry?.label ?: history.firstOrNull { it.packageName == packageName }?.appLabel ?: "Messages"
val threads = history.filter { it.packageName == packageName }
LaunchedEffect(history) { CarNotifications.dismissPopupFrom(packageName) }
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
GsIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", navigator::back)
entry?.icon?.let { Image(it, contentDescription = null, modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp))) }
Text(label, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
}
if (!listening) {
AccessBanner {
context.startActivity(
Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
}
if (threads.isEmpty()) {
Text(
"No recent messages. New $label messages appear here as they arrive on the phone.",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(bottom = 16.dp),
) {
items(threads, key = { it.key }) { n ->
ConversationCard(
n,
onRead = { VoiceReply.read(n) },
onReply = { VoiceReply.reply(n) },
onMarkRead = { CarNotifications.markThreadRead(context, n) },
)
}
}
}
}
}
@Composable
private fun ConversationCard(n: CarNotification, onRead: () -> Unit, onReply: () -> Unit, onMarkRead: () -> Unit) {
var expanded by rememberSaveable(n.key) { mutableStateOf(false) }
// An app that posts plain notifications instead of a conversation still gets one line.
val lines = n.lines.ifEmpty { listOf(ChatLine(n.title.ifBlank { n.appLabel }, n.text.ifBlank { n.title }, n.postedAt)) }
val shown = if (expanded) lines else lines.takeLast(COLLAPSED_LINES)
val dim = n.read || n.replied
var quick by rememberSaveable(n.key) { mutableStateOf(false) }
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceContainer,
modifier = Modifier
.fillMaxWidth()
.animateContentSize()
.clickable(enabled = lines.size > COLLAPSED_LINES) { expanded = !expanded },
) {
Row(
Modifier.padding(14.dp),
verticalAlignment = Alignment.Top,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
NotificationIcon(n, size = 52.dp)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
n.title.ifBlank { n.appLabel },
style = MaterialTheme.typography.titleLarge,
fontWeight = if (dim) FontWeight.Medium else FontWeight.Bold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
Text(
" · ${DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(n.postedAt))}",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
if (!expanded && lines.size > COLLAPSED_LINES) {
Text(
"${lines.size - COLLAPSED_LINES} earlier",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
shown.forEach { MessageLine(it, showSender = n.isGroup) }
if (quick) QuickReplies(n, Modifier.padding(top = 6.dp))
}
Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (n.replied) {
Icon(Icons.Filled.Check, contentDescription = "Replied", tint = MaterialTheme.colorScheme.primary)
}
GsButton(onClick = onRead, tone = GsTone.Neutral) {
ReadGlyph(Modifier.size(20.dp))
Text("Read", Modifier.padding(start = 8.dp))
}
if (n.reply != null) {
GsButton(onClick = onReply, tone = GsTone.Tonal) {
ReplyGlyph(Modifier.size(20.dp))
Text("Reply", Modifier.padding(start = 8.dp))
}
}
if (n.reply != null) {
GsButton(onClick = { quick = !quick }, tone = GsTone.Neutral) {
Text(if (quick) "Hide quick replies" else "Quick reply")
}
}
if (n.markRead != null) {
GsButton(onClick = onMarkRead, tone = GsTone.Neutral) { Text("Mark read") }
}
}
}
}
}
@Composable
private fun MessageLine(line: ChatLine, showSender: Boolean) {
val who = when {
line.sender == null -> "You: "
showSender -> "${line.sender}: "
else -> ""
}
Text(
who + line.text,
style = MaterialTheme.typography.bodyLarge,
color = if (line.sender == null) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
@@ -1,299 +0,0 @@
package app.seb3thehacker.gearslip.car
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.car.theme.GsButton
import app.seb3thehacker.gearslip.car.theme.GsTone
import app.seb3thehacker.gearslip.host.CarAppConnection
import app.seb3thehacker.gearslip.media.CarMedia
import app.seb3thehacker.gearslip.CarFocus
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.PathParser
/** What a built-in app's id carries in a pin, so it can't collide with an installed app's component. */
internal const val BUILT_IN_PREFIX = "gearslip:"
/** Material's "directions car", drawn here because only the core icon set is bundled. */
private val CarGlyph: ImageVector = ImageVector.Builder("Car", 24.dp, 24.dp, 24f, 24f).addPath(
PathParser().parsePathString(
"M18.92,6.01C18.72,5.42 18.16,5 17.5,5h-11c-0.66,0 -1.21,0.42 -1.42,1.01L3,12v8c0,0.55 0.45,1 1,1h1" +
"c0.55,0 1,-0.45 1,-1v-1h12v1c0,0.55 0.45,1 1,1h1c0.55,0 1,-0.45 1,-1v-8l-2.08,-5.99z" +
"M6.5,16c-0.83,0 -1.5,-0.67 -1.5,-1.5S5.67,13 6.5,13s1.5,0.67 1.5,1.5S7.33,16 6.5,16z" +
"M17.5,16c-0.83,0 -1.5,-0.67 -1.5,-1.5s0.67,-1.5 1.5,-1.5 1.5,0.67 1.5,1.5 -0.67,1.5 -1.5,1.5z" +
"M5,11l1.5,-4.5h11L19,11L5,11z",
).toNodes(),
fill = SolidColor(Color.Black),
).build()
/**
* One of Gearslip's own apps: a screen, with nothing running behind it once you leave. [screen] is
* null for an action like Exit, which has no screen and so never shows as open.
*/
internal class BuiltInApp(
val id: String,
val label: String,
val glyph: ImageVector,
val screen: CarScreen?,
val open: (CarNavigator) -> Unit,
)
internal object BuiltInApps {
val Web = BuiltInApp("web", "Browser", Icons.Filled.Search, CarScreen.App("web")) { it.open("web") }
val ScreenSharing = BuiltInApp("phone", "Screen sharing", Icons.Filled.Share, CarScreen.App("phone")) { it.open("phone") }
val Phone = BuiltInApp("dialer", "Phone", Icons.Filled.Call, CarScreen.App("dialer")) { it.open("dialer") }
val VehicleData = BuiltInApp("vehicle", "Vehicle data", Icons.Filled.Info, CarScreen.VehicleData) { it.vehicleData() }
val Settings = BuiltInApp("settings", "Settings", Icons.Filled.Settings, CarScreen.Settings) { it.settings() }
/** Hands the screen back to the car's own interface, like Android Auto's Exit. */
val Exit = BuiltInApp("exit", "Exit", CarGlyph, screen = null) { CarFocus.exitToCar() }
val all = listOf(Web, ScreenSharing, Phone, VehicleData, Settings, Exit)
val entries: List<Entry> = all.map { Entry(it.label, icon = null, builtIn = it) }
}
/** Vehicle data is experimental: raw, unverified sensor labels (see [CarSensors]). */
@Composable
internal fun rememberVehicleDataShown(): Boolean {
val experimental by CarSettings.experimentalFeaturesEnabled.collectAsState()
val sensors by CarSettings.carSensorsEnabled.collectAsState()
return experimental && sensors
}
/**
* Where an open app lives - decides where tapping it goes and how it closes. Gearslip's own
* apps have no connection behind them, so [SCREEN] is simply "on screen right now".
*/
internal enum class RunningSlot { NAV, BROWSE, MEDIA, SCREEN }
/**
* Apps open right now, as component id to where they live, in the order the nav bar shows them:
* the map, then a browsed templated app, then the media app, then whichever built-in app is on
* screen. The map and a browsed app count from the moment they start connecting until they're
* closed. The media app counts while it has something loaded to play - the same rule the nav
* bar's player follows, so the two always show up together - or while its own screen is up.
*/
@Composable
internal fun rememberRunningApps(): Map<String, RunningSlot> {
val navStatus by CarServices.nav.status.collectAsState()
val browseStatus by CarServices.browse.status.collectAsState()
val mediaApp by CarServices.mediaApp.collectAsState()
val mediaPhase by CarServices.media.phase.collectAsState()
val now by CarServices.media.now.collectAsState()
val current = LocalCarNavigator.current.current
fun CarAppConnection.liveId(phase: CarAppConnection.Phase) =
connectedComponent?.flattenToString()?.takeIf {
phase == CarAppConnection.Phase.BINDING ||
phase == CarAppConnection.Phase.HANDSHAKE ||
phase == CarAppConnection.Phase.RUNNING
}
return buildMap {
CarServices.nav.liveId(navStatus.phase)?.let { put(it, RunningSlot.NAV) }
CarServices.browse.liveId(browseStatus.phase)?.let { put(it, RunningSlot.BROWSE) }
val mediaLive = when (mediaPhase) {
CarMedia.Phase.CONNECTING -> true
CarMedia.Phase.READY -> now.isActive || current == CarScreen.Media
else -> false
}
mediaApp?.component?.flattenToString()?.takeIf { mediaLive }?.let { put(it, RunningSlot.MEDIA) }
BuiltInApps.all.firstOrNull { it.screen != null && it.screen == current }?.let { put(BUILT_IN_PREFIX + it.id, RunningSlot.SCREEN) }
(current as? CarScreen.Messages)?.let { put(MESSAGING_PREFIX + it.packageName, RunningSlot.SCREEN) }
}
}
/** The screen an open app is showing on, so its nav bar icon can stay pressed in while it's up. */
internal fun RunningSlot.isShowing(current: CarScreen): Boolean = when (this) {
RunningSlot.NAV -> current == CarScreen.Home
RunningSlot.BROWSE -> current == CarScreen.Browse
RunningSlot.MEDIA -> current == CarScreen.Media
RunningSlot.SCREEN -> true
}
/**
* Brings an app up: back to its screen if it's already open - never a reconnect, which would
* throw away the route or restart the session - otherwise a fresh launch.
*/
internal fun openApp(entry: Entry, slot: RunningSlot?, navigator: CarNavigator, frame: CarEnvironment.Frame) {
when (slot) {
RunningSlot.NAV -> navigator.home()
RunningSlot.BROWSE -> navigator.browse(entry.label)
RunningSlot.MEDIA -> navigator.media()
RunningSlot.SCREEN -> Unit
null -> launchEntry(entry, navigator, frame)
}
}
internal fun closeApp(slot: RunningSlot, navigator: CarNavigator) {
when (slot) {
RunningSlot.NAV -> CarServices.stopNav()
RunningSlot.BROWSE -> CarServices.stopBrowse()
RunningSlot.MEDIA -> CarServices.closeMedia()
RunningSlot.SCREEN -> Unit
}
if (slot != RunningSlot.NAV && slot.isShowing(navigator.current)) navigator.back()
}
/**
* What a long press on an app offers - pin it to or unpin it from the nav bar, move it along the
* launcher, and close it if it's open - as a card in the middle of the screen with car-sized buttons, over a scrim that
* dismisses it. Drawn in the car UI's own layout rather than a system popup window, which the
* car's virtual display has no reason to host well.
*/
@Composable
internal fun AppMenu(navigator: CarNavigator, running: Map<String, RunningSlot>) {
val id = navigator.appMenu ?: return
val entry = findEntry(id)
if (entry == null) {
navigator.dismissAppMenu()
return
}
val pinned by CarSettings.pinnedApps.collectAsState()
val isPinned = id in pinned
val barFull = !isPinned && pinned.size >= CarSettings.MAX_PINNED
val slot = running[id]
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.5f))
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = navigator::dismissAppMenu,
),
contentAlignment = Alignment.Center,
) {
Surface(
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
// Swallows taps on the card itself, so only the scrim around it dismisses.
modifier = Modifier
.widthIn(max = 420.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = {},
),
) {
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
entry.icon?.let { Image(it, null, Modifier.size(44.dp).clip(RoundedCornerShape(10.dp))) }
entry.builtIn?.let { Icon(it.glyph, null, Modifier.size(36.dp)) }
Text(
entry.label,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = 14.dp),
)
}
GsButton(
onClick = {
CarSettings.togglePin(id)
navigator.dismissAppMenu()
},
tone = GsTone.Tonal,
enabled = !barFull,
modifier = Modifier.fillMaxWidth().height(56.dp),
) {
Text(
when {
isPinned -> "Unpin from nav bar"
barFull -> "Nav bar is full (${CarSettings.MAX_PINNED} pinned)"
else -> "Pin to nav bar"
},
style = MaterialTheme.typography.titleMedium,
)
}
if (navigator.current == CarScreen.Apps) MoveButtons(id)
if (slot != null) {
GsButton(
onClick = {
closeApp(slot, navigator)
navigator.dismissAppMenu()
},
tone = GsTone.Danger,
modifier = Modifier.fillMaxWidth().height(56.dp),
) { Text("Close app", style = MaterialTheme.typography.titleMedium) }
}
GsButton(
onClick = navigator::dismissAppMenu,
tone = GsTone.Neutral,
modifier = Modifier.fillMaxWidth().height(56.dp),
) { Text("Cancel", style = MaterialTheme.typography.titleMedium) }
}
}
}
}
/**
* Moves the app one place left or right on the launcher. The menu stays open so a tile can be
* walked several places, and the grid behind the scrim shows where it went.
*/
@Composable
private fun MoveButtons(id: String) {
val custom by CarSettings.appOrder.collectAsState()
val order = launcherOrder(rememberAllEntries(), rememberVehicleDataShown(), custom).mapNotNull { it.componentId }
val index = order.indexOf(id)
if (index < 0) return
fun move(by: Int) {
val next = order.toMutableList()
java.util.Collections.swap(next, index, index + by)
CarSettings.setAppOrder(next)
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
GsButton(
onClick = { move(-1) },
tone = GsTone.Tonal,
enabled = index > 0,
modifier = Modifier.weight(1f).height(56.dp),
) { Text("Move left", style = MaterialTheme.typography.titleMedium) }
GsButton(
onClick = { move(1) },
tone = GsTone.Tonal,
enabled = index < order.lastIndex,
modifier = Modifier.weight(1f).height(56.dp),
) { Text("Move right", style = MaterialTheme.typography.titleMedium) }
}
if (custom.isNotEmpty()) {
GsButton(
onClick = { CarSettings.setAppOrder(emptyList()) },
tone = GsTone.Neutral,
modifier = Modifier.fillMaxWidth().height(56.dp),
) { Text("Reset app order", style = MaterialTheme.typography.titleMedium) }
}
}
@@ -1,9 +1,9 @@
package app.seb3thehacker.gearslip.car package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.car.theme.*
import android.content.Intent import android.content.Intent
import android.provider.Settings import android.provider.Settings
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -13,6 +13,8 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowBack
@@ -21,7 +23,10 @@ import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Notifications import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Warning import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -30,7 +35,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -48,40 +52,34 @@ import kotlinx.coroutines.delay
import java.text.DateFormat import java.text.DateFormat
import java.util.Date import java.util.Date
/** /** The notification history, with a reply pane for anything the sending app lets us answer. */
* Replying to one notification. The list itself lives on the dashboard (see
* [NotificationsSection]); with nothing to reply to, this is just the dashboard.
*/
@Composable @Composable
fun NotificationsScreen(replyTo: String?) { fun NotificationsScreen(replyTo: String?) {
val history by CarNotifications.history.collectAsState() val history by CarNotifications.history.collectAsState()
val navigator = LocalCarNavigator.current var replying by remember(replyTo) { mutableStateOf(replyTo) }
val target = history.firstOrNull { it.key == replyTo && it.reply != null }
// Anything arriving while this is open is being looked at, so it never counts as unread.
LaunchedEffect(history) { CarNotifications.markRead() }
val target = history.firstOrNull { it.key == replying && it.reply != null }
if (target != null) { if (target != null) {
ReplyPane(target, onDone = navigator::back) ReplyPane(target, onDone = { replying = null })
} else { } else {
CarDashboardScreen() NotificationList(history, onReply = { replying = it.key })
} }
} }
/**
* The notification history, under the calendar on the dashboard. Replying opens its own pane.
* Anything arriving while this is on screen is being looked at, so it never counts as unread.
*/
@Composable @Composable
fun NotificationsSection() { private fun NotificationList(history: List<CarNotification>, onReply: (CarNotification) -> Unit) {
val history by CarNotifications.history.collectAsState()
val listening by CarNotifications.listening.collectAsState() val listening by CarNotifications.listening.collectAsState()
val navigator = LocalCarNavigator.current
val context = LocalContext.current.applicationContext val context = LocalContext.current.applicationContext
LaunchedEffect(history) { CarNotifications.markRead() }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(Modifier.fillMaxSize().padding(horizontal = 20.dp, vertical = 12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
"Notifications", "Notifications",
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
if (history.isNotEmpty()) TextButton(onClick = CarNotifications::clear) { Text("Clear all") } if (history.isNotEmpty()) TextButton(onClick = CarNotifications::clear) { Text("Clear all") }
@@ -96,21 +94,22 @@ fun NotificationsSection() {
} }
if (history.isEmpty()) { if (history.isEmpty()) {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text( Text(
"Nothing yet. New notifications from the phone will show up here.", "Nothing yet. New notifications from the phone will show up here.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
}
} else { } else {
history.forEach { n -> LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
key(n.key) { NotificationRow(n) { navigator.notifications(replyTo = it.key) } } items(history, key = { it.key }) { NotificationRow(it, onReply) }
} }
} }
} }
} }
@Composable @Composable
internal fun AccessBanner(onOpen: () -> Unit) { private fun AccessBanner(onOpen: () -> Unit) {
Surface( Surface(
shape = MaterialTheme.shapes.large, shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.errorContainer, color = MaterialTheme.colorScheme.errorContainer,
@@ -128,7 +127,7 @@ internal fun AccessBanner(onOpen: () -> Unit) {
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
GsButton(onClick = onOpen) { Text("Open") } Button(onClick = onOpen) { Text("Open") }
} }
} }
} }
@@ -161,17 +160,14 @@ private fun NotificationRow(n: CarNotification, onReply: (CarNotification) -> Un
} }
when { when {
n.replied -> Icon(Icons.Filled.Check, contentDescription = "Replied", tint = MaterialTheme.colorScheme.primary) n.replied -> Icon(Icons.Filled.Check, contentDescription = "Replied", tint = MaterialTheme.colorScheme.primary)
n.reply != null -> GsButton(onClick = { VoiceReply.reply(n) }, tone = GsTone.Tonal) { n.reply != null -> FilledTonalButton(onClick = { onReply(n) }) { Text("Reply") }
ReplyGlyph(Modifier.size(20.dp))
Text("Reply", Modifier.padding(start = 8.dp))
}
} }
} }
} }
} }
@Composable @Composable
internal fun NotificationIcon(n: CarNotification, size: androidx.compose.ui.unit.Dp = 44.dp) { private fun NotificationIcon(n: CarNotification, size: androidx.compose.ui.unit.Dp = 44.dp) {
val icon = n.icon val icon = n.icon
if (icon != null) { if (icon != null) {
Image(icon.asImageBitmap(), contentDescription = null, modifier = Modifier.size(size).clip(RoundedCornerShape(10.dp))) Image(icon.asImageBitmap(), contentDescription = null, modifier = Modifier.size(size).clip(RoundedCornerShape(10.dp)))
@@ -198,7 +194,7 @@ private fun ReplyPane(n: CarNotification, onDone: () -> Unit) {
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
GsIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", onDone) IconButton(onClick = onDone) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") }
Surface( Surface(
shape = RoundedCornerShape(24.dp), shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest, color = MaterialTheme.colorScheme.surfaceContainerHighest,
@@ -224,9 +220,58 @@ private fun ReplyPane(n: CarNotification, onDone: () -> Unit) {
Text(n.text.ifBlank { n.title }, style = MaterialTheme.typography.bodyLarge, maxLines = 3, overflow = TextOverflow.Ellipsis) Text(n.text.ifBlank { n.title }, style = MaterialTheme.typography.bodyLarge, maxLines = 3, overflow = TextOverflow.Ellipsis)
} }
CarKeyboard( CarKeyboard(text, onTextChange = { text = it }, onSubmit = ::send, submitImage = Icons.AutoMirrored.Filled.Send)
text, onTextChange = { text = it }, onSubmit = ::send,
submitImage = Icons.AutoMirrored.Filled.Send, onDismiss = onDone,
)
} }
} }
/**
* The popup shown over whatever the car is displaying. It times itself out, and tapping it opens
* the history - or straight into a reply, when the app allows one.
*/
@Composable
fun NotificationPopup(modifier: Modifier = Modifier) {
val popup by CarNotifications.popup.collectAsState()
val navigator = LocalCarNavigator.current
val n = popup ?: return
LaunchedEffect(n.id) {
delay(POPUP_MS)
CarNotifications.dismissPopup(n.id)
}
Surface(
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
contentColor = MaterialTheme.colorScheme.onSurface,
shadowElevation = 8.dp,
modifier = modifier
.padding(top = 8.dp)
.fillMaxWidth(0.7f)
.clickable { navigator.notifications() },
) {
Row(
Modifier.padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
NotificationIcon(n)
Column(Modifier.weight(1f)) {
Text(n.appLabel, style = MaterialTheme.typography.labelMedium, maxLines = 1)
if (n.title.isNotBlank()) {
Text(n.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (n.text.isNotBlank()) {
Text(n.text, style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
if (n.reply != null) {
FilledTonalButton(onClick = { navigator.notifications(replyTo = n.key) }) { Text("Reply") }
}
IconButton(onClick = { CarNotifications.dismissPopup(n.id) }) {
Icon(Icons.Filled.Close, contentDescription = "Dismiss")
}
}
}
}
private const val POPUP_MS = 8_000L
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more