diff --git a/.github/workflows/compile_bluescreens.yaml b/.github/workflows/compile_bluescreens.yaml index 1c113ed86..2f5d59494 100644 --- a/.github/workflows/compile_bluescreens.yaml +++ b/.github/workflows/compile_bluescreens.yaml @@ -23,11 +23,6 @@ on: type: boolean default: true required: false - build_ui: - description: "Build UI (selfdrive/ui)" - type: boolean - default: true - required: false build_params: description: "Build params Python extension" type: boolean @@ -156,7 +151,6 @@ jobs: fi TARGETS=() - [[ "${{ inputs.build_ui }}" == "true" ]] && TARGETS+=("selfdrive/ui/ui") [[ "${{ inputs.build_params }}" == "true" ]] && TARGETS+=("common/params_pyx.so") [[ "${{ inputs.build_cereal }}" == "true" ]] && TARGETS+=("cereal/messaging/bridge") if [[ "${{ inputs.build_panda }}" == "true" ]]; then @@ -184,8 +178,8 @@ jobs: fi if [[ ${#TARGETS[@]} -eq 0 ]]; then - echo "No partial targets selected; defaulting to UI + panda" - TARGETS=("selfdrive/ui/ui" "panda/board/obj/panda.bin.signed") + echo "No partial targets selected; defaulting to panda" + TARGETS=("panda/board/obj/panda.bin.signed") fi echo "Running partial build for targets: ${TARGETS[*]}" diff --git a/.gitignore b/.gitignore index 619d33d96..1c7ced51a 100644 --- a/.gitignore +++ b/.gitignore @@ -54,9 +54,6 @@ cereal/gen selfdrive/ui/translations/tmp selfdrive/car/tests/cars_dump system/camerad/test/ae_gray_test -selfdrive/ui/ui.macos -selfdrive/ui/ui.larch64 - .coverage* coverage.xml htmlcov diff --git a/.vscode/launch.json b/.vscode/launch.json index f090061c4..6f4fb86a6 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -11,14 +11,6 @@ "tools/sim/run_bridge.py" ] }, - { - "id": "cpp_process", - "type": "pickString", - "description": "Select the process to debug", - "options": [ - "selfdrive/ui/ui" - ] - }, { "id": "args", "description": "Arguments to pass to the process", @@ -40,13 +32,6 @@ "justMyCode": true, "args": "${input:args}" }, - { - "name": "C++: openpilot Process", - "type": "cppdbg", - "request": "launch", - "program": "${workspaceFolder}/${input:cpp_process}", - "cwd": "${workspaceFolder}" - }, { "name": "Attach LLDB to Replay drive", "type": "lldb", @@ -82,4 +67,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/SConstruct b/SConstruct index d2354f868..7147ecdc1 100644 --- a/SConstruct +++ b/SConstruct @@ -37,10 +37,6 @@ AddOption('--coverage', action='store_true', help='build with test coverage options') -AddOption('--clazy', - action='store_true', - help='build with clazy') - AddOption('--ccflags', action='store', type='string', @@ -354,116 +350,7 @@ else: np_version = SCons.Script.Value(np.__version__) Export('envCython', 'np_version') -# Qt build environment -qt_env = env.Clone() -qt_modules = ["Widgets", "Gui", "Core", "Network", "Concurrent", "DBus", "Xml"] - -qt_libs = [] -if arch == "Darwin": - qt_env['QTDIR'] = f"{brew_prefix}/opt/qt@5" - qt_dirs = [ - os.path.join(qt_env['QTDIR'], "include"), - ] - qt_dirs += [f"{qt_env['QTDIR']}/include/Qt{m}" for m in qt_modules] - qt_env["LINKFLAGS"] += ["-F" + os.path.join(qt_env['QTDIR'], "lib")] - qt_env["FRAMEWORKS"] += [f"Qt{m}" for m in qt_modules] + ["OpenGL"] - qt_env.AppendENVPath('PATH', os.path.join(qt_env['QTDIR'], "bin")) -else: - if arch == "larch64": - qt_env.PrependENVPath('PATH', Dir("#third_party/qt5/larch64/bin/").abspath) - # For laptop/device builds that mount an AGNOS sysroot, always prefer Qt - # headers from that sysroot to keep headers/libs ABI-matched (Qt 5.12.x). - if arch == "larch64" and os.environ.get("SP_TICI_SYSROOT"): - qt_install_prefix = tici_libpath("/usr") - qt_install_headers = tici_libpath("/usr/include/aarch64-linux-gnu/qt5") - else: - qmake = os.environ.get("SP_QMAKE", "qmake") - qt_install_prefix = subprocess.check_output([qmake, '-query', 'QT_INSTALL_PREFIX'], encoding='utf8').strip() - qt_install_headers = subprocess.check_output([qmake, '-query', 'QT_INSTALL_HEADERS'], encoding='utf8').strip() - - qt_env['QTDIR'] = qt_install_prefix - qt_dirs = [ - f"{qt_install_headers}", - ] - - qt_gui_path = os.path.join(qt_install_headers, "QtGui") - qt_gui_dirs = [d for d in os.listdir(qt_gui_path) if os.path.isdir(os.path.join(qt_gui_path, d))] - qt_dirs += [f"{qt_install_headers}/QtGui/{qt_gui_dirs[0]}/QtGui", ] if qt_gui_dirs else [] - qt_dirs += [f"{qt_install_headers}/Qt{m}" for m in qt_modules] - - qt_libs = [f"Qt5{m}" for m in qt_modules] - if arch == "larch64": - qt_libs += ["GLESv2", "wayland-client"] - elif arch != "Darwin": - qt_libs += ["GL"] -qt_env['QT3DIR'] = qt_env['QTDIR'] -qt_env.Tool('qt3') -if arch == "larch64" and os.environ.get("SP_TICI_SYSROOT"): - qt_tool_bin = tici_libpath("/usr/lib/qt5/bin") - qt_tool_root = tici_libpath("/") - qt_arm_moc = os.path.join(qt_tool_bin, "moc") - qt_arm_uic = os.path.join(qt_tool_bin, "uic") - qt_arm_rcc = os.path.join(qt_tool_bin, "rcc") - qt_host_bin = os.environ.get("SP_QT_HOST_BIN", "/usr/lib/qt5/bin") - qt_host_moc = os.environ.get("SP_QT_HOST_MOC", os.path.join(qt_host_bin, "moc")) - qt_host_uic = os.environ.get("SP_QT_HOST_UIC", os.path.join(qt_host_bin, "uic")) - qt_host_rcc = os.environ.get("SP_QT_HOST_RCC", "rcc") - if platform.machine() in ("aarch64", "arm64"): - if "SP_QT_HOST_MOC" in os.environ: - qt_env['QT3_MOC'] = qt_host_moc - elif os.path.isfile(qt_arm_moc): - qt_env['QT3_MOC'] = qt_arm_moc - if "SP_QT_HOST_UIC" in os.environ: - qt_env['QT3_UIC'] = qt_host_uic - elif os.path.isfile(qt_arm_uic): - qt_env['QT3_UIC'] = qt_arm_uic - if "SP_QT_HOST_RCC" in os.environ: - qt_env['SP_QT_RCC'] = qt_host_rcc - elif os.path.isfile(qt_arm_rcc): - qt_env['SP_QT_RCC'] = qt_arm_rcc - else: - qt_qemu = shutil.which("qemu-aarch64-static") or shutil.which("qemu-aarch64") - - if qt_qemu and os.path.isfile(qt_arm_moc): - qt_env['QT3_MOC'] = f"{qt_qemu} -L {qt_tool_root} {qt_arm_moc}" - else: - qt_env['QT3_MOC'] = qt_host_moc - - if qt_qemu and os.path.isfile(qt_arm_uic): - qt_env['QT3_UIC'] = f"{qt_qemu} -L {qt_tool_root} {qt_arm_uic}" - else: - qt_env['QT3_UIC'] = qt_host_uic - - if qt_qemu and os.path.isfile(qt_arm_rcc): - qt_env['SP_QT_RCC'] = f"{qt_qemu} -L {qt_tool_root} {qt_arm_rcc}" - else: - qt_env['SP_QT_RCC'] = qt_host_rcc - -qt_env['CPPPATH'] += qt_dirs + ["#third_party/qrcode"] -qt_flags = [ - "-D_REENTRANT", - "-DQT_NO_DEBUG", - "-DQT_WIDGETS_LIB", - "-DQT_GUI_LIB", - "-DQT_CORE_LIB", - "-DQT_MESSAGELOGCONTEXT", -] -qt_env['CXXFLAGS'] += qt_flags -qt_env['LIBPATH'] += ['#selfdrive/ui', ] -qt_env['LIBS'] = qt_libs - -if GetOption("clazy"): - checks = [ - "level0", - "level1", - "no-range-loop", - "no-non-pod-global-static", - ] - qt_env['CXX'] = 'clazy' - qt_env['ENV']['CLAZY_IGNORE_DIRS'] = qt_dirs[0] - qt_env['ENV']['CLAZY_CHECKS'] = ','.join(checks) - -Export('env', 'qt_env', 'arch', 'real_arch') +Export('env', 'arch', 'real_arch') # Build common module SConscript(['common/SConscript']) diff --git a/build b/build index c39d925b5..d8da0a3ba 100755 --- a/build +++ b/build @@ -46,9 +46,6 @@ while [[ $# -gt 0 ]]; do shortcut_includes_panda=1 add_panda_targets ;; - --ui|-ui) - shortcut_targets+=("selfdrive/ui/ui") - ;; --cereal|-cereal) shortcut_targets+=( "cereal/libcereal.a" diff --git a/common/params_keys.h b/common/params_keys.h index 68cf7ea8c..e1a924167 100644 --- a/common/params_keys.h +++ b/common/params_keys.h @@ -137,8 +137,6 @@ inline static std::unordered_map keys = { {"SecOCKey", {PERSISTENT | DONT_LOG, STRING}}, {"ShowDebugInfo", {PERSISTENT, BOOL}}, {"ShowAllToggles", {PERSISTENT, BOOL, "0", "0", 3}}, - {"TryRaylibUI", {PERSISTENT, BOOL, "1"}}, - {"UseOldUI", {PERSISTENT, BOOL, "0", std::nullopt, 0, SETTINGS_SIMPLE}}, {"UsePrebuilt", {PERSISTENT, BOOL, "1"}}, {"RouteCount", {PERSISTENT, INT, "0"}}, {"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, diff --git a/common/spinner.py b/common/spinner.py index 829aba32a..8050054ce 100755 --- a/common/spinner.py +++ b/common/spinner.py @@ -7,19 +7,6 @@ class Spinner: def __init__(self): self.spinner_proc = None - # Prefer the legacy compiled spinner on device. - legacy_spinner = os.path.join(BASEDIR, "selfdrive", "ui", "spinner") - if os.path.isfile("/TICI") and os.path.isfile(legacy_spinner) and os.access(legacy_spinner, os.X_OK): - try: - self.spinner_proc = subprocess.Popen([legacy_spinner], - stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "selfdrive", "ui"), - close_fds=True) - return - except OSError: - self.spinner_proc = None - - # Raylib spinner requires Python deps from the repo virtualenv. spinner_cwd = os.path.join(BASEDIR, "system", "ui") venv_python = os.path.join(BASEDIR, ".venv", "bin", "python") python_exec = venv_python if os.path.isfile(venv_python) else "python3" diff --git a/common/text_window.py b/common/text_window.py index 11b51cc9c..c38414c03 100755 --- a/common/text_window.py +++ b/common/text_window.py @@ -9,18 +9,6 @@ class TextWindow: def __init__(self, text): self.text_proc = None - # Prefer the legacy compiled text window on device. - legacy_text = os.path.join(BASEDIR, "selfdrive", "ui", "text") - if os.path.isfile("/TICI") and os.path.isfile(legacy_text) and os.access(legacy_text, os.X_OK): - try: - self.text_proc = subprocess.Popen([legacy_text, text], - stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "selfdrive", "ui"), - close_fds=True) - return - except OSError: - self.text_proc = None - text_cwd = os.path.join(BASEDIR, "system", "ui") venv_python = os.path.join(BASEDIR, ".venv", "bin", "python") python_exec = venv_python if os.path.isfile(venv_python) else "python3" diff --git a/docs/MODEL_REBUILD.md b/docs/MODEL_REBUILD.md index af1a25de9..b803bc75c 100644 --- a/docs/MODEL_REBUILD.md +++ b/docs/MODEL_REBUILD.md @@ -203,6 +203,6 @@ Compilation validates JIT capture/replay, pickle round-trip, finite outputs, met 2. Confirm `modeld` stays running. 3. Confirm finite `modelV2` path, lane-line, lead, pose, and action data. 4. Confirm `driverStateV2` on both supported camera resolutions. -5. Test download, selection, deletion, randomization, migration, and fallback in QT, raylib/mici, and Galaxy. +5. Test download, selection, deletion, randomization, migration, and fallback in both device UIs and Galaxy. The built-in RDF artifact is `selfdrive/modeld/models/driving_tinygrad.pkl`. If migration cannot download the selected v23 artifact, StarPilot switches to that built-in model. diff --git a/docs/contributing/contribute.md b/docs/contributing/contribute.md index 42712d950..ced41acd3 100644 --- a/docs/contributing/contribute.md +++ b/docs/contributing/contribute.md @@ -48,7 +48,7 @@ Use `./dev` for host-native tools. It creates and reuses an isolated environment ./dev shell ``` -For desktop UI work, use `./c3`, `./c4`, or `./raybig`. These commands use the same isolated host environment. +For desktop UI work, use `./c3` or `./c4`. These commands use the same isolated host environment. Use `./build` when you need comma-compatible device artifacts. This is the expected validation for changes that affect compiled device code or runtime behavior: diff --git a/docs/how-to/laptop-device-build.md b/docs/how-to/laptop-device-build.md index 8bddc4f26..aa49a38b8 100644 --- a/docs/how-to/laptop-device-build.md +++ b/docs/how-to/laptop-device-build.md @@ -2,7 +2,7 @@ This flow builds **device-target (`larch64`) binaries on your laptop** using a Linux/aarch64 container and a synced comma sysroot. -For the full StarPilot branch workflow, including host-native shorthand tools such as `./dev`, `./c3`, `./c4`, and `./raybig`, see the [StarPilot development guide](https://github.com/firestar5683/StarPilot/blob/Dom/tools/STARPILOT_DEVELOPMENT.md). +For the full StarPilot branch workflow, including host-native shorthand tools such as `./dev`, `./c3`, and `./c4`, see the [StarPilot development guide](https://github.com/firestar5683/StarPilot/blob/Dom/tools/STARPILOT_DEVELOPMENT.md). ## Prerequisites @@ -71,10 +71,10 @@ This runs: - `SP_TICI_SYSROOT=/opt/tici-sysroot` - `touch prebuilt` -To run `scons` targets explicitly in the same device-compatible environment: +To run SCons targets explicitly in the same device-compatible environment: ```bash -scripts/laptop_device_build.sh scons selfdrive/ui/ui +scripts/laptop_device_build.sh scons common/params_pyx.so ``` On macOS, once `.comma_sysroot` is present, plain `scons ...` auto-routes to this containerized device build. @@ -112,7 +112,6 @@ Preferred host-side shorthand commands on this branch: ```bash ./c3 ./c4 -./raybig ./dev replay ./dev cabana ./dev plotjuggler @@ -120,10 +119,9 @@ Preferred host-side shorthand commands on this branch: These commands use the isolated `.host_runtime` cache so host-native artifacts do not churn the main tree. -Legacy direct script entrypoints still exist if needed: +Direct script entrypoints are also available: ```bash -scripts/launch_ui_desktop.sh +scripts/launch_ui_c3_desktop.sh scripts/launch_ui_c4_desktop.sh -scripts/launch_ui_raybig_desktop.sh ``` diff --git a/raybig b/raybig deleted file mode 100755 index 618a8ef20..000000000 --- a/raybig +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -exec "${ROOT_DIR}/scripts/host_tool_runner.sh" raybig "$@" diff --git a/scripts/debug_ui_freeze.sh b/scripts/debug_ui_freeze.sh index 000fc8858..f97664251 100755 --- a/scripts/debug_ui_freeze.sh +++ b/scripts/debug_ui_freeze.sh @@ -21,7 +21,7 @@ mkdir -p "${OUT_DIR}" echo echo "=== Process Snapshot ===" - ps -eo pid,ppid,stat,ni,etime,comm,args | grep -E "(manager.py|selfdrive.ui.ui|/selfdrive/ui/ui|weston|loggerd|encoderd|modeld|dmonitoringmodeld)" || true + ps -eo pid,ppid,stat,ni,etime,comm,args | grep -E "(manager.py|selfdrive.ui.ui|/selfdrive/ui/ui.py|weston|loggerd|encoderd|modeld|dmonitoringmodeld)" || true echo echo "=== Manager State (tmux service output) ===" @@ -35,7 +35,7 @@ mkdir -p "${OUT_DIR}" echo echo "=== UI PID + Watchdog Timestamp Delta ===" - for ui_pid in $(pgrep -f "selfdrive.ui.ui|/selfdrive/ui/ui" 2>/dev/null || true); do + for ui_pid in $(pgrep -f "selfdrive.ui.ui|/selfdrive/ui/ui.py" 2>/dev/null || true); do echo "ui_pid=${ui_pid}" wd_file="/dev/shm/wd_${ui_pid}" if [[ -f "${wd_file}" ]]; then @@ -74,7 +74,7 @@ PY echo echo "=== open files for UI process(es) ===" - for ui_pid in $(pgrep -f "selfdrive.ui.ui|/selfdrive/ui/ui" 2>/dev/null || true); do + for ui_pid in $(pgrep -f "selfdrive.ui.ui|/selfdrive/ui/ui.py" 2>/dev/null || true); do echo "--- lsof for pid ${ui_pid} ---" lsof -p "${ui_pid}" 2>/dev/null | tail -n 200 || true done diff --git a/scripts/host_tool_runner.sh b/scripts/host_tool_runner.sh index 7f10d7cad..415c6a616 100755 --- a/scripts/host_tool_runner.sh +++ b/scripts/host_tool_runner.sh @@ -24,9 +24,8 @@ Usage: ./tools/host [args...] Commands: - c3 Launch the desktop Qt UI from the isolated host cache. + c3 Launch the large raylib UI from the isolated host cache. c4 Launch the small raylib UI from the isolated host cache. - raybig Launch the large raylib UI from the isolated host cache. onroad Launch replay plus desktop UI(s) from the isolated host cache. replay Build and run replay from the isolated host cache. cabana Build and run cabana from the isolated host cache. @@ -43,9 +42,8 @@ Notes: - `cabana` uses its own host-runtime bucket, so it can run together with `plotjuggler`. - Other commands that share a bucket still wait on that bucket's lock. - `./build` remains the device-target flow. - - For c3/c4/raybig, pass the jobs count first to preserve existing shorthand: + - For c3/c4, pass the jobs count first to preserve existing shorthand: ./dev c3 8 - ./dev raybig 12 - `./onroad --c3 f08912a233c1584f/2022-08-11--18-02-41/1` launches replay plus the selected desktop UI. - `./dev sync` refreshes all host buckets. Use `./dev sync cabana` to sync one. EOF @@ -65,7 +63,7 @@ resolve_host_bucket() { local name="${1:-shared}" case "${name}" in - shared|default|ui|c3|c4|raybig|onroad|replay|shell) + shared|default|ui|c3|c4|onroad|replay|shell) echo "shared" ;; cabana) @@ -235,16 +233,13 @@ purge_host_foreign_platform_artifacts() { esac } -purge_host_desktop_ui_artifacts() { - rm -f \ - "${WORK_DIR}/selfdrive/ui/libqt_widgets.a" \ - "${WORK_DIR}/selfdrive/ui/libqt_util.a" \ - "${WORK_DIR}/selfdrive/ui/assets.o" \ - "${WORK_DIR}/selfdrive/ui/main.o" \ - "${WORK_DIR}/selfdrive/ui/moc_ui.o" \ - "${WORK_DIR}/selfdrive/ui/ui.o" \ - "${WORK_DIR}/selfdrive/ui/ui" \ - "${WORK_DIR}/cereal/gen/cpp/"*.capnp.o +purge_host_generated_objects() { + rm -f "${WORK_DIR}/cereal/gen/cpp/"*.capnp.o +} + +purge_host_obsolete_ui_artifacts() { + find "${WORK_DIR}/selfdrive/ui" -maxdepth 1 -type f \ + \( -name 'ui' -o -name 'ui.macos' -o -name 'ui.larch64' -o -name '*.o' -o -name '*.a' \) -delete } ensure_host_python_tools() { @@ -333,11 +328,6 @@ sync_worktree() { "tools/replay/tests/test_replay" "tools/cabana/cabana" "tools/cabana/tests/test_cabana" - "selfdrive/ui/ui" - "selfdrive/ui/ui.macos" - "selfdrive/ui/ui.larch64" - "selfdrive/ui/libqt_widgets.a" - "selfdrive/ui/libqt_util.a" "cereal/libcereal.a" "cereal/libsocketmaster.a" "cereal/messaging/bridge" @@ -388,7 +378,8 @@ sync_worktree() { if [[ "${_capnp_before}" != "${_capnp_after}" ]]; then rm -rf "${SP_SCONS_CACHE_DIR:-${HOST_ROOT}/scons_cache}" fi - purge_host_desktop_ui_artifacts + purge_host_generated_objects + purge_host_obsolete_ui_artifacts purge_host_foreign_platform_artifacts rm -f "${WORK_DIR}/third_party/libjson11.a" "${WORK_DIR}/third_party/libkaitai.a" sync_host_generated_headers @@ -478,7 +469,7 @@ launch_c3() { fi sync_worktree - run_in_worktree "${WORK_DIR}/scripts/launch_ui_desktop.sh" "${jobs}" "$@" + run_in_worktree "${WORK_DIR}/scripts/launch_ui_c3_desktop.sh" "${jobs}" "$@" } launch_c4() { @@ -493,18 +484,6 @@ launch_c4() { run_in_worktree "${WORK_DIR}/scripts/launch_ui_c4_desktop.sh" "${jobs}" "$@" } -launch_raybig() { - local jobs - jobs="$(default_jobs)" - if [[ "${1:-}" =~ ^[0-9]+$ ]]; then - jobs="$1" - shift || true - fi - - sync_worktree - run_in_worktree "${WORK_DIR}/scripts/launch_ui_raybig_desktop.sh" "${jobs}" "$@" -} - launch_onroad() { local jobs jobs="$(default_jobs)" @@ -609,7 +588,7 @@ main() { help|-h|--help) usage ;; - c3|c4|raybig|onroad|replay|shell|python|pytest) + c3|c4|onroad|replay|shell|python|pytest) set_host_bucket "shared" acquire_host_lock "${command} $*" ;; @@ -650,9 +629,6 @@ main() { c4) launch_c4 "$@" ;; - raybig) - launch_raybig "$@" - ;; onroad) launch_onroad "$@" ;; diff --git a/scripts/laptop_device_build.sh b/scripts/laptop_device_build.sh index 343870c71..1f25ba54b 100755 --- a/scripts/laptop_device_build.sh +++ b/scripts/laptop_device_build.sh @@ -527,8 +527,7 @@ manager_artifacts_ready() { [[ -f "${ROOT_DIR}/selfdrive/controls/lib/lateral_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so" ]] && [[ -f "${ROOT_DIR}/selfdrive/controls/lib/lateral_mpc_lib/c_generated_code/libacados_ocp_solver_lat.so" ]] && [[ -f "${ROOT_DIR}/selfdrive/controls/lib/longitudinal_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so" ]] && - [[ -f "${ROOT_DIR}/selfdrive/controls/lib/longitudinal_mpc_lib/c_generated_code/libacados_ocp_solver_long.so" ]] && - [[ -f "${ROOT_DIR}/selfdrive/ui/ui" ]] + [[ -f "${ROOT_DIR}/selfdrive/controls/lib/longitudinal_mpc_lib/c_generated_code/libacados_ocp_solver_long.so" ]] } run_manager() { diff --git a/scripts/launch_onroad_desktop.sh b/scripts/launch_onroad_desktop.sh index 1c21cbf5e..3440c67e9 100755 --- a/scripts/launch_onroad_desktop.sh +++ b/scripts/launch_onroad_desktop.sh @@ -27,24 +27,24 @@ env_var_truthy() { usage() { cat <<'EOF' Usage: - ./onroad [jobs] [--c3 | --c4 | --raybig | --all | --replay-only] [--galaxy] [-nav] [--offroad] [-alert] [--cem] [--prefix name] + ./onroad [jobs] [--c3 | --c4 | --all | --replay-only] [--galaxy] [-nav] [--offroad] [-alert] [--cem] [--prefix name] Examples: ./onroad ./onroad --c3 ./onroad --c4 --start 30 ./onroad --c4 -nav - ./onroad --raybig --nav --offroad --demo + ./onroad --c3 --nav --offroad --demo ./onroad --c4 --cem --demo - ./onroad --raybig --cem --demo - ./onroad --raybig --cem -alert --demo --no-loop + ./onroad --c3 --cem --demo + ./onroad --c3 --cem -alert --demo --no-loop ./onroad --all ./onroad --replay-only --demo --no-vipc --no-loop Notes: - This is host/dev only. It uses the isolated host worktree and does not touch the device path. - A private comma connect route still requires tools/lib/auth.py before replay can download it. - - If no UI flag is provided, the route's logged device type selects the UI: mici/c4 -> c4, tici/tizi -> raybig unless UseOldUI was enabled. + - If no UI flag is provided, the route's logged device type selects the UI: mici/c4 -> c4, all big devices -> c3. - Use multiple UI flags together if you want more than one desktop UI at once. - --galaxy starts a local Galaxy web session with the same preview params and prints the localhost URL. It blocks replay's logged customReserved9 stream so Galaxy can own the live Testing Grounds publisher. - -nav injects a fake navigation demo stream and blocks replay from publishing navInstruction/navRoute. @@ -101,13 +101,8 @@ parse_args() { UI_SELECTION_EXPLICIT=1 shift ;; - --raybig) - UI_TARGETS+=(raybig) - UI_SELECTION_EXPLICIT=1 - shift - ;; --all) - UI_TARGETS+=(c3 c4 raybig) + UI_TARGETS+=(c3 c4) UI_SELECTION_EXPLICIT=1 shift ;; @@ -183,7 +178,7 @@ expand_ui_targets() { case "${selection,,}" in all|"") - UI_TARGETS=(c3 c4 raybig) + UI_TARGETS=(c3 c4) return ;; none) @@ -199,18 +194,18 @@ expand_ui_targets() { local raw="" for raw in "${raw_targets[@]}"; do case "${raw,,}" in - c3|c4|raybig) + c3|c4) normalized+=("${raw,,}") ;; *) echo "Unknown UI target in --ui: ${raw}" >&2 - echo "Valid values: all, none, c3, c4, raybig" >&2 + echo "Valid values: all, none, c3, c4" >&2 exit 1 ;; esac done - local ordered_targets=(c3 c4 raybig) + local ordered_targets=(c3 c4) local target="" for target in "${ordered_targets[@]}"; do local candidate="" @@ -224,7 +219,7 @@ expand_ui_targets() { } dedupe_ui_targets() { - local ordered_targets=(c3 c4 raybig) + local ordered_targets=(c3 c4) local deduped=() local target="" for target in "${ordered_targets[@]}"; do @@ -402,7 +397,6 @@ prepare_env() { export USE_WEBCAM=1 export SP_C3_FAKE_WIFI=0 export SP_C4_FAKE_WIFI=0 - export SP_RAYBIG_FAKE_WIFI=0 export SP_ALLOW_DESKTOP_FAKE_WIFI=0 export SP_ONROAD_NAV_DEMO="${NAV_DEMO}" export SP_ONROAD_OFFROAD_DEMO="${OFFROAD_DEMO}" @@ -448,7 +442,7 @@ build_replay() { } prepare_c3_runtime() { - SP_C3_COMPILE_ONLY=1 "${ROOT_DIR}/scripts/launch_ui_desktop.sh" "${jobs}" + SP_KEEP_DESKTOP_RUNTIME_ARTIFACTS=1 SP_C3_COMPILE_ONLY=1 "${ROOT_DIR}/scripts/launch_ui_c3_desktop.sh" "${jobs}" } prepare_python_ui_runtime() { @@ -589,22 +583,6 @@ launch_galaxy() { echo "Access Galaxy with ${GALAXY_URL}" } -launch_c3_ui() { - local os_ext="linux" - if [[ "$(uname -s)" == "Darwin" ]]; then - os_ext="macos" - fi - - local host_ui="${ROOT_DIR}/selfdrive/ui/ui.${os_ext}" - if [[ ! -x "${host_ui}" ]]; then - echo "Missing ${host_ui}. C3 build did not produce the desktop binary." >&2 - return 1 - fi - - "${host_ui}" & - UI_PIDS+=("$!") -} - launch_python_ui() { local big="$1" ( @@ -680,7 +658,7 @@ if [[ "${REPLAY_ONLY}" != "1" && "${UI_SELECTION_EXPLICIT}" == "0" && ${#UI_TARG fi if [[ "${REPLAY_ONLY}" != "1" && ${#UI_TARGETS[@]} -eq 0 ]]; then - echo "Select at least one UI with --c3, --c4, --raybig, or use --replay-only." >&2 + echo "Select at least one UI with --c3, --c4, or use --replay-only." >&2 exit 1 fi @@ -695,7 +673,7 @@ case " ${UI_TARGETS[*]-} " in esac case " ${UI_TARGETS[*]-} " in - *" c4 "*|*" raybig "*) + *" c4 "*) prepare_python_ui_runtime ;; esac @@ -739,16 +717,13 @@ has_raylib=0 for local_target in "${UI_TARGETS[@]}"; do case "${local_target}" in c3) - launch_c3_ui + launch_python_ui 1 + has_raylib=1 ;; c4) launch_python_ui 0 has_raylib=1 ;; - raybig) - launch_python_ui 1 - has_raylib=1 - ;; esac done diff --git a/scripts/launch_ui_raybig_desktop.sh b/scripts/launch_ui_c3_desktop.sh similarity index 95% rename from scripts/launch_ui_raybig_desktop.sh rename to scripts/launch_ui_c3_desktop.sh index 3fe592381..a41229f0c 100755 --- a/scripts/launch_ui_raybig_desktop.sh +++ b/scripts/launch_ui_c3_desktop.sh @@ -47,19 +47,19 @@ export PATH="${ROOT_DIR}/.venv/bin:${PATH}" export PYTHONPATH="${ROOT_DIR}:${ROOT_DIR}/starpilot/third_party" for d in "${ROOT_DIR}"/*_repo; do [[ -d "$d" ]] && export PYTHONPATH="${PYTHONPATH}:$d"; done [[ -d "${ROOT_DIR}/third_party/acados" ]] && export PYTHONPATH="${PYTHONPATH}:${ROOT_DIR}/third_party/acados" -export OPENPILOT_ZMQ_NAMESPACE="${OPENPILOT_ZMQ_NAMESPACE:-desktop-raybig-$$}" +export OPENPILOT_ZMQ_NAMESPACE="${OPENPILOT_ZMQ_NAMESPACE:-desktop-c3-$$}" export BIG=1 export NOBOARD=1 export SIMULATION=1 export SKIP_FW_QUERY=1 export USE_WEBCAM=1 export PRIME_TYPE="${PRIME_TYPE:-0}" -export SP_RAYBIG_FAKE_DRIVE_STATS="${SP_RAYBIG_FAKE_DRIVE_STATS:-1}" +export SP_C3_FAKE_DRIVE_STATS="${SP_C3_FAKE_DRIVE_STATS:-1}" -backup_dir="$(mktemp -d /tmp/starpilot_raybig_ui_backup.XXXXXX)" +backup_dir="$(mktemp -d /tmp/starpilot_c3_ui_backup.XXXXXX)" backup_manifest="${backup_dir}/.artifact_manifest" -PRE_TRACKED_DIRTY="$(mktemp /tmp/starpilot_raybig_pretracked.XXXXXX)" -POST_TRACKED_DIRTY="$(mktemp /tmp/starpilot_raybig_posttracked.XXXXXX)" +PRE_TRACKED_DIRTY="$(mktemp /tmp/starpilot_c3_pretracked.XXXXXX)" +POST_TRACKED_DIRTY="$(mktemp /tmp/starpilot_c3_posttracked.XXXXXX)" FAKE_WIFI_PID="" runtime_artifacts=( @@ -175,7 +175,7 @@ prepare_common_host_artifacts() { prepare_msgq_host_artifacts() { # Clear mixed-arch Python extension objects from both msgq trees. These - # commonly conflict after switching between ./build (larch64) and ./raybig (macOS). + # commonly conflict after switching between ./build (larch64) and ./c3 (macOS). remove_if_elf "msgq/ipc_pyx.o" remove_if_elf "msgq/visionipc/visionipc_pyx.o" remove_if_elf "msgq_repo/msgq/ipc_pyx.o" @@ -268,12 +268,12 @@ run_scons() { fi } -kill_stale_raybig_ui() { +kill_stale_c3_ui() { pkill -f "selfdrive/ui/ui.py" >/dev/null 2>&1 || true } start_fake_wifi() { - if [[ ! "${SP_RAYBIG_FAKE_WIFI:-1}" =~ ^(1|true|yes|on)$ ]]; then + if [[ ! "${SP_C3_FAKE_WIFI:-1}" =~ ^(1|true|yes|on)$ ]]; then export SP_ALLOW_DESKTOP_FAKE_WIFI=0 return fi @@ -339,8 +339,8 @@ PY exit 1 fi -if [[ "${SP_RAYBIG_COMPILE_ONLY:-0}" == "1" ]]; then - echo "Raybig runtime artifacts prepared." +if [[ "${SP_C3_COMPILE_ONLY:-0}" == "1" ]]; then + echo "C3 runtime artifacts prepared." exit 0 fi @@ -356,6 +356,6 @@ params.put_bool("IsDriverViewEnabled", False) PY seed_starpilot_theme -kill_stale_raybig_ui +kill_stale_c3_ui start_fake_wifi "${PY_BIN}" selfdrive/ui/ui.py "$@" diff --git a/scripts/launch_ui_desktop.sh b/scripts/launch_ui_desktop.sh deleted file mode 100755 index 11d69edd9..000000000 --- a/scripts/launch_ui_desktop.sh +++ /dev/null @@ -1,265 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "${ROOT_DIR}" - -if [[ ! -f .venv/bin/activate ]]; then - echo "Missing .venv. Run tools/install_python_dependencies.sh first." - exit 1 -fi - -default_jobs() { - if command -v nproc >/dev/null 2>&1; then - nproc - elif command -v sysctl >/dev/null 2>&1; then - sysctl -n hw.ncpu - else - echo 8 - fi -} - -jobs="$(default_jobs)" -if [[ "${1:-}" =~ ^[0-9]+$ ]]; then - jobs="$1" - shift || true -fi - -OS_EXT="linux" -if [[ "$(uname -s)" == "Darwin" ]]; then - OS_EXT="macos" -fi -HOST_UI="${ROOT_DIR}/selfdrive/ui/ui.${OS_EXT}" -PRE_TRACKED_DIRTY="$(mktemp /tmp/starpilot_c3_pretracked.XXXXXX)" -POST_TRACKED_DIRTY="$(mktemp /tmp/starpilot_c3_posttracked.XXXXXX)" -BACKUP_DIR="$(mktemp -d /tmp/starpilot_c3_backup.XXXXXX)" -BACKUP_MANIFEST="${BACKUP_DIR}/.artifact_manifest" -FAKE_WIFI_PID="" - -runtime_artifacts=( - "selfdrive/ui/ui" - "common/libcommon.a" - "common/transformations/libtransformations.a" - "cereal/libsocketmaster.a" - "msgq_repo/libmsgq.a" - "msgq_repo/libvisionipc.a" - "common/params_pyx.so" - "common/transformations/transformations.so" - "msgq_repo/msgq/ipc_pyx.so" - "msgq_repo/msgq/visionipc/visionipc_pyx.so" -) - -collect_tracked_dirty() { - if ! command -v git >/dev/null 2>&1; then - return 1 - fi - if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then - return 1 - fi - git -C "${ROOT_DIR}" status --porcelain --untracked-files=no | sed -E 's/^.. //' -} - -backup_artifact() { - local rel="$1" - local src="${ROOT_DIR}/${rel}" - echo "${rel}" >> "${BACKUP_MANIFEST}" - if [[ -f "${src}" ]]; then - mkdir -p "${BACKUP_DIR}/$(dirname "${rel}")" - cp -f "${src}" "${BACKUP_DIR}/${rel}" - fi -} - -restore_runtime_artifacts() { - if [[ ! -d "${BACKUP_DIR}" ]]; then - return - fi - - if [[ -f "${BACKUP_MANIFEST}" ]]; then - while IFS= read -r rel; do - [[ -z "${rel}" ]] && continue - if [[ -f "${BACKUP_DIR}/${rel}" ]]; then - cp -f "${BACKUP_DIR}/${rel}" "${ROOT_DIR}/${rel}" - else - rm -f "${ROOT_DIR}/${rel}" - fi - done < "${BACKUP_MANIFEST}" - fi - - rm -rf "${BACKUP_DIR}" -} - -restore_new_tracked_changes() { - if ! collect_tracked_dirty > "${POST_TRACKED_DIRTY}"; then - return - fi - - while IFS= read -r path; do - [[ -z "${path}" ]] && continue - if ! grep -Fxq "${path}" "${PRE_TRACKED_DIRTY}"; then - git -C "${ROOT_DIR}" checkout -- "${path}" >/dev/null 2>&1 || true - fi - done < "${POST_TRACKED_DIRTY}" -} - -cleanup() { - restore_runtime_artifacts - restore_new_tracked_changes - stop_fake_wifi - rm -f "${PRE_TRACKED_DIRTY}" "${POST_TRACKED_DIRTY}" -} - -start_fake_wifi() { - if [[ ! "${SP_C3_FAKE_WIFI:-1}" =~ ^(1|true|yes|on)$ ]]; then - export SP_ALLOW_DESKTOP_FAKE_WIFI=0 - return - fi - - export SP_ALLOW_DESKTOP_FAKE_WIFI=1 - "${ROOT_DIR}/.venv/bin/python3" selfdrive/debug/fake_wifi.py --network wifi --strength great --interval 0.2 & - FAKE_WIFI_PID=$! -} - -seed_starpilot_theme() { - "${ROOT_DIR}/.venv/bin/python3" - <<'PY' -from openpilot.starpilot.common.starpilot_functions import seed_desktop_theme_assets - -seed_desktop_theme_assets() -PY -} - -starpilot_theme_runtime_ok() { - "${ROOT_DIR}/.venv/bin/python3" - <<'PY' -import openpilot.selfdrive.controls.lib.lateral_mpc_lib.c_generated_code.acados_ocp_solver_pyx # noqa: F401 -import openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx # noqa: F401 -PY -} - -ensure_starpilot_theme_runtime() { - if starpilot_theme_runtime_ok >/dev/null 2>&1; then - return - fi - - echo "Preparing C3 StarPilot theme runtime extensions..." - remove_if_elf "selfdrive/controls/lib/lateral_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so" - remove_if_elf "selfdrive/controls/lib/longitudinal_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so" - scons -j"${jobs}" \ - selfdrive/controls/lib/lateral_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so \ - selfdrive/controls/lib/longitudinal_mpc_lib/c_generated_code/acados_ocp_solver_pyx.so -} - -stop_fake_wifi() { - if [[ -n "${FAKE_WIFI_PID}" ]]; then - kill "${FAKE_WIFI_PID}" >/dev/null 2>&1 || true - FAKE_WIFI_PID="" - fi -} - -archive_is_aarch64_elf() { - local path="$1" - [[ -f "${path}" ]] || return 1 - if command -v readelf >/dev/null 2>&1; then - readelf -h "${path}" 2>/dev/null | grep -iq "aarch64" - else - objdump -a "${path}" 2>/dev/null | head -n 12 | grep -iqE "elf64-littleaarch64|aarch64" - fi -} - -remove_if_elf() { - local rel="$1" - local path="${ROOT_DIR}/${rel}" - if [[ -f "${path}" ]] && file "${path}" | grep -q "ELF"; then - rm -f "${path}" - fi -} - -purge_objects() { - local root="$1" - if [[ -d "${root}" ]]; then - find "${root}" -type f \( -name '*.o' -o -name '*.os' \) -delete - fi -} - -prepare_host_artifacts() { - if archive_is_aarch64_elf "${ROOT_DIR}/common/libcommon.a"; then - rm -f "${ROOT_DIR}/common/libcommon.a" "${ROOT_DIR}/common/params_pyx.o" - purge_objects "${ROOT_DIR}/common" - fi - - if archive_is_aarch64_elf "${ROOT_DIR}/cereal/libsocketmaster.a"; then - rm -f "${ROOT_DIR}/cereal/libsocketmaster.a" - purge_objects "${ROOT_DIR}/cereal/messaging" - fi - - if archive_is_aarch64_elf "${ROOT_DIR}/common/transformations/libtransformations.a"; then - rm -f "${ROOT_DIR}/common/transformations/libtransformations.a" \ - "${ROOT_DIR}/common/transformations/transformations.o" - purge_objects "${ROOT_DIR}/common/transformations" - fi - - if archive_is_aarch64_elf "${ROOT_DIR}/msgq_repo/libmsgq.a" || archive_is_aarch64_elf "${ROOT_DIR}/msgq_repo/libvisionipc.a"; then - rm -f "${ROOT_DIR}/msgq_repo/libmsgq.a" "${ROOT_DIR}/msgq_repo/libvisionipc.a" - purge_objects "${ROOT_DIR}/msgq_repo/msgq" - purge_objects "${ROOT_DIR}/msgq_repo/msgq/visionipc" - fi - - remove_if_elf "common/params_pyx.so" - remove_if_elf "common/transformations/transformations.so" - remove_if_elf "msgq_repo/msgq/ipc_pyx.so" - remove_if_elf "msgq_repo/msgq/visionipc/visionipc_pyx.so" - - purge_objects "${ROOT_DIR}/selfdrive/ui" - purge_objects "${ROOT_DIR}/starpilot/ui" - rm -f "${ROOT_DIR}/selfdrive/ui/libqt_widgets.a" "${ROOT_DIR}/selfdrive/ui/libqt_util.a" - rm -f "${ROOT_DIR}/selfdrive/ui/ui" -} - -collect_tracked_dirty > "${PRE_TRACKED_DIRTY}" || true -trap cleanup EXIT - -for rel in "${runtime_artifacts[@]}"; do - backup_artifact "${rel}" -done - -source .venv/bin/activate -if [[ -d /opt/homebrew/bin ]]; then - export PATH="/opt/homebrew/bin:${PATH}" -fi - -if [[ "$(uname -s)" == "Darwin" ]]; then - # Keep desktop host builds on Apple toolchain even if shell exports Homebrew llvm. - export CC="/usr/bin/clang" - export CXX="/usr/bin/clang++" - export AR="/usr/bin/ar" - export RANLIB="/usr/bin/ranlib" -fi -unset CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH CPPFLAGS CFLAGS CXXFLAGS LDFLAGS - -prepare_host_artifacts - -export PYTHONPATH="${ROOT_DIR}:${ROOT_DIR}/starpilot/third_party" -for d in "${ROOT_DIR}"/*_repo; do [[ -d "$d" ]] && export PYTHONPATH="${PYTHONPATH}:$d"; done -[[ -d "${ROOT_DIR}/third_party/acados" ]] && export PYTHONPATH="${PYTHONPATH}:${ROOT_DIR}/third_party/acados" -export OPENPILOT_ZMQ_NAMESPACE="${OPENPILOT_ZMQ_NAMESPACE:-desktop-c3-$$}" - -export SP_DISABLE_AUTO_DEVICE_SCONS=1 -scons -j"${jobs}" selfdrive/ui/ui - -cp -f "${ROOT_DIR}/selfdrive/ui/ui" "${HOST_UI}" -cleanup -trap - EXIT - -if [[ "${SP_C3_COMPILE_ONLY:-0}" == "1" ]]; then - echo "C3 UI binary prepared." - exit 0 -fi - -ensure_starpilot_theme_runtime -seed_starpilot_theme -start_fake_wifi -trap stop_fake_wifi EXIT -"${HOST_UI}" "$@" -rc=$? -stop_fake_wifi -trap - EXIT -exit "${rc}" diff --git a/scripts/starpilot_build_flow.sh b/scripts/starpilot_build_flow.sh index 7837d8779..89ca7b70b 100755 --- a/scripts/starpilot_build_flow.sh +++ b/scripts/starpilot_build_flow.sh @@ -9,14 +9,14 @@ usage() { cat <<'EOF' Usage: scripts/starpilot_build_flow.sh verify - scripts/starpilot_build_flow.sh mac [jobs] + scripts/starpilot_build_flow.sh mac scripts/starpilot_build_flow.sh device [jobs] scripts/starpilot_build_flow.sh laptop-setup [device-host] scripts/starpilot_build_flow.sh laptop-device [jobs] Modes: verify Check critical StarPilot parity build guards in-tree. - mac Run macOS developer validation build (Qt UI + Python compile checks). + mac Run macOS developer Python validation checks. device Run full on-device build (comma hardware only) and set prebuilt flag. laptop-setup Prepare laptop device-build environment (venv + image + sysroot). laptop-device Run full device-target build in Linux/aarch64 container on laptop. @@ -61,20 +61,6 @@ verify_tree() { echo "OK: timed.py guards timezonefinder usage." fi - if ! rg -q "if os.path.isfile\\(\"/TICI\"\\)" common/spinner.py; then - echo "FAIL: common/spinner.py missing device-only legacy spinner path." - failed=1 - else - echo "OK: spinner uses device-only legacy fallback." - fi - - if ! rg -q "if os.path.isfile\\(\"/TICI\"\\)" common/text_window.py; then - echo "FAIL: common/text_window.py missing device-only legacy text path." - failed=1 - else - echo "OK: text window uses device-only legacy fallback." - fi - if ! source .venv/bin/activate >/dev/null 2>&1; then echo "FAIL: .venv is required for loggerd import checks." failed=1 @@ -107,7 +93,6 @@ PY } build_mac() { - local jobs="${1:-8}" require_venv source .venv/bin/activate @@ -129,8 +114,6 @@ build_mac() { starpilot/system/the_galaxy \ starpilot/system/galaxy - SP_DISABLE_AUTO_DEVICE_SCONS=1 scons -j"${jobs}" selfdrive/ui/ui - echo "mac build validation complete." } @@ -166,7 +149,7 @@ main() { verify_tree ;; mac) - build_mac "${1:-8}" + build_mac ;; device) build_device "${1:-$(nproc)}" diff --git a/selfdrive/assets/.gitignore b/selfdrive/assets/.gitignore index fffd4b4ed..2d97f8b11 100644 --- a/selfdrive/assets/.gitignore +++ b/selfdrive/assets/.gitignore @@ -1,4 +1,2 @@ -*.cc fonts/*.fnt fonts/*.png -translations_assets.qrc diff --git a/selfdrive/assets/assets.qrc b/selfdrive/assets/assets.qrc deleted file mode 100644 index 26a7d998e..000000000 --- a/selfdrive/assets/assets.qrc +++ /dev/null @@ -1,20 +0,0 @@ - - - ../../third_party/bootstrap/bootstrap-icons.svg - images/button_continue_triangle.svg - icons/circled_check.svg - icons/circled_slash.svg - icons/eye_open.svg - icons/eye_closed.svg - icons/close.svg - icons/lock_closed.svg - icons/checkmark.svg - icons/warning.png - icons/wifi_strength_low.svg - icons/wifi_strength_medium.svg - icons/wifi_strength_high.svg - icons/wifi_strength_full.svg - - ../ui/translations/languages.json - - diff --git a/selfdrive/controls/lib/longcontrol_vehicle_tunes.py b/selfdrive/controls/lib/longcontrol_vehicle_tunes.py index c9450b365..74b3d4e7e 100644 --- a/selfdrive/controls/lib/longcontrol_vehicle_tunes.py +++ b/selfdrive/controls/lib/longcontrol_vehicle_tunes.py @@ -52,6 +52,9 @@ HYUNDAI_ELANTRA_STOPPED_LEAD_MAX_EGO_SPEED = 2.0 HYUNDAI_ELANTRA_STOPPED_LEAD_MAX_SPEED = 0.5 HYUNDAI_ELANTRA_STOPPED_LEAD_MIN_CLOSING_SPEED = 0.25 HYUNDAI_ELANTRA_STOPPED_LEAD_MAX_CREEP_ACCEL = 0.05 +HYUNDAI_SANTA_FE_FINAL_STOP_MAX_SPEED = 1.0 +HYUNDAI_SANTA_FE_FINAL_STOP_CAP_BP = [0.0, 0.2, 0.5, HYUNDAI_SANTA_FE_FINAL_STOP_MAX_SPEED] +HYUNDAI_SANTA_FE_FINAL_STOP_CAP_V = [-0.25, -0.30, -0.50, -0.90] def get_bolt_acc_pedal_friction_bias(output_accel, a_target, v_ego): @@ -131,6 +134,9 @@ class LongControlVehicleTuning: self.is_hyundai_elantra_2021 = bool( CP.brand == "hyundai" and str(getattr(CP, "carFingerprint", "")) == "HYUNDAI_ELANTRA_2021" ) + self.is_hyundai_santa_fe_2022 = bool( + CP.brand == "hyundai" and str(getattr(CP, "carFingerprint", "")) == "HYUNDAI_SANTA_FE_2022" + ) self.is_bolt_acc_pedal_friction_car = bool( CP.brand == "gm" and CP.enableGasInterceptorDEPRECATED and @@ -153,6 +159,14 @@ class LongControlVehicleTuning: def shape_stopping_accel(self, output_accel, a_target, should_stop, v_ego, has_lead, stop_accel): """Release a stale hard lead brake once the stop target has eased.""" + if ( + self.is_hyundai_santa_fe_2022 and + v_ego <= HYUNDAI_SANTA_FE_FINAL_STOP_MAX_SPEED and + a_target <= 0.1 + ): + final_stop_cap = float(interp(v_ego, HYUNDAI_SANTA_FE_FINAL_STOP_CAP_BP, HYUNDAI_SANTA_FE_FINAL_STOP_CAP_V)) + return max(float(output_accel), final_stop_cap) + if ( not self.is_hyundai_elantra_2021 or not has_lead or not should_stop or v_ego > 2.0 or diff --git a/selfdrive/controls/tests/test_longcontrol.py b/selfdrive/controls/tests/test_longcontrol.py index b85a3cedd..ef4566524 100644 --- a/selfdrive/controls/tests/test_longcontrol.py +++ b/selfdrive/controls/tests/test_longcontrol.py @@ -1217,6 +1217,15 @@ def test_gm_stock_truck_target_filter_bypasses_low_speed_and_other_cars(): assert bolt_tuning.shape_gm_truck_accel_target(-0.10, 20.0, False) == pytest.approx(-0.10) +def test_santa_fe_final_stop_cap_softens_only_last_kmh(): + CP = make_longcontrol_cp(brand="hyundai", carFingerprint="HYUNDAI_SANTA_FE_2022") + tuning = LongControl(CP).vehicle_tuning + + assert tuning.shape_stopping_accel(-2.0, -0.2, True, 0.2, False, -2.0) == pytest.approx(-0.30) + assert tuning.shape_stopping_accel(-2.0, -0.2, True, 1.5, False, -2.0) == pytest.approx(-2.0) + assert tuning.shape_stopping_accel(-2.0, 0.3, False, 0.2, False, -2.0) == pytest.approx(-2.0) + + def test_toyota_sienna_target_filter_smooths_mild_high_speed_handoffs(): CP = make_longcontrol_cp(brand="toyota", carFingerprint=TOYOTA_CAR.TOYOTA_SIENNA_4TH_GEN) tuning = vehicle_tunes.LongControlVehicleTuning(CP) diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript index 3046f99e5..6177692d9 100644 --- a/selfdrive/ui/SConscript +++ b/selfdrive/ui/SConscript @@ -1,128 +1,33 @@ -import json -import os -Import('env', 'qt_env', 'arch', 'common', 'messaging', 'visionipc', 'transformations') +Import('env', 'arch', 'common') -base_libs = [common, messaging, visionipc, transformations, - 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] +if GetOption('extras') and arch != "Darwin": + raylib_env = env.Clone() + raylib_env['LIBPATH'] += [f'#third_party/raylib/{arch}/'] + raylib_env['LINKFLAGS'].append('-Wl,-strip-debug') -base_libs += ['avcodec', 'avformat', 'avutil', 'swresample', 'yuv'] + raylib_libs = common + ["raylib"] + if arch == "larch64": + raylib_libs += ["GLESv2", "wayland-client", "wayland-egl", "EGL"] + else: + raylib_libs += ["GL"] -# OpenMAX is only available in the device-target runtime/sysroot. Host desktop -# UI builds on Linux should not need or link it. -if arch == 'larch64': - base_libs.append('OmxCore') + release = "release3" + installers = [ + ("openpilot", release), + ("openpilot_test", f"{release}-staging"), + ("openpilot_nightly", "nightly"), + ("openpilot_internal", "nightly-dev"), + ] -if arch == 'larch64': - base_libs.append('EGL') + cont = raylib_env.Command("installer/continue_openpilot.o", "installer/continue_openpilot.sh", + "ld -r -b binary -o $TARGET $SOURCE") + inter = raylib_env.Command("installer/inter_ttf.o", "installer/inter-ascii.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + for name, branch in installers: + defines = {'BRANCH': f"'\"{branch}\"'"} + if "internal" in name: + defines['INTERNAL'] = "1" -if arch == "Darwin": - del base_libs[base_libs.index('OpenCL')] - qt_env['FRAMEWORKS'] += ['OpenCL'] - -# FIXME: remove this once we're on 5.15 (24.04) -qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] - -qt_util = qt_env.Library("qt_util", ["#selfdrive/ui/qt/api.cc", "#selfdrive/ui/qt/util.cc"], LIBS=base_libs) -widgets_src = ["qt/widgets/input.cc", "qt/prime_state.cc", - "qt/widgets/ssh_keys.cc", "qt/widgets/toggle.cc", "qt/widgets/controls.cc", - "qt/widgets/offroad_alerts.cc", "qt/widgets/prime.cc", "qt/widgets/keyboard.cc", - "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", - "qt/request_repeater.cc", "qt/qt_window.cc", "qt/network/networking.cc", "qt/network/wifi_manager.cc"] - -starpilot_widgets_src = ["../../starpilot/ui/qt/widgets/starpilot_controls.cc"] -widgets_src += starpilot_widgets_src - -widgets = qt_env.Library("qt_widgets", widgets_src, LIBS=base_libs) -Export('widgets') -qt_libs = [widgets, qt_util] + base_libs - -qt_src = ["main.cc", "ui.cc", "qt/sidebar.cc", "qt/body.cc", - "qt/window.cc", "qt/home.cc", "qt/offroad/settings.cc", - "qt/offroad/software_settings.cc", "qt/offroad/developer_panel.cc", "qt/offroad/onboarding.cc", - "qt/offroad/driverview.cc", "qt/offroad/experimental_mode.cc", - "qt/onroad/onroad_home.cc", "qt/onroad/annotated_camera.cc", "qt/onroad/model.cc", - "qt/onroad/buttons.cc", "qt/onroad/alerts.cc", "qt/onroad/driver_monitoring.cc", "qt/onroad/hud.cc"] - -qt_env['CPPPATH'] += ["../../starpilot/ui/screenrecorder/openmax/include/"] - -starpilot_src = ["../../starpilot/ui/starpilot_ui.cc", "../../starpilot/ui/qt/offroad/data_settings.cc", - "../../starpilot/ui/qt/offroad/device_settings.cc", "../../starpilot/ui/qt/offroad/starpilot_settings.cc", - "../../starpilot/ui/qt/offroad/expandable_multi_option_dialog.cc", - "../../starpilot/ui/qt/offroad/lateral_settings.cc", "../../starpilot/ui/qt/offroad/longitudinal_settings.cc", - "../../starpilot/ui/qt/offroad/maps_settings.cc", "../../starpilot/ui/qt/offroad/model_settings.cc", - "../../starpilot/ui/qt/offroad/navigation_settings.cc", "../../starpilot/ui/qt/offroad/sounds_settings.cc", - "../../starpilot/ui/qt/offroad/theme_settings.cc", "../../starpilot/ui/qt/offroad/utilities.cc", - "../../starpilot/ui/qt/offroad/vehicle_settings.cc", "../../starpilot/ui/qt/offroad/visual_settings.cc", - "../../starpilot/ui/qt/offroad/wheel_settings.cc", "../../starpilot/ui/qt/onroad/starpilot_annotated_camera.cc", - "../../starpilot/ui/qt/onroad/starpilot_buttons.cc", "../../starpilot/ui/qt/onroad/starpilot_onroad.cc", - "../../starpilot/ui/qt/widgets/developer_sidebar.cc", "../../starpilot/ui/qt/widgets/drive_stats.cc", - "../../starpilot/ui/qt/widgets/drive_summary.cc", - "../../starpilot/ui/qt/widgets/navigation_functions.cc", - "../../starpilot/ui/screenrecorder/omx_encoder.cc", "../../starpilot/ui/screenrecorder/screenrecorder.cc"] -qt_src += starpilot_src - -# build translation files -with open(File("translations/languages.json").abspath) as f: - languages = json.loads(f.read()) -translation_sources = [f"#selfdrive/ui/translations/{l}.ts" for l in languages.values()] -translation_targets = [src.replace(".ts", ".qm") for src in translation_sources] -lrelease_bin = os.environ.get("SP_QT_HOST_LRELEASE", "lrelease") if arch == 'larch64' else 'lrelease' - -lrelease = qt_env.Command(translation_targets, translation_sources, f"{lrelease_bin} $SOURCES") -qt_env.NoClean(translation_sources) -qt_env.Precious(translation_sources) - -# create qrc file for compiled translations to include with assets -translations_assets_src = "#selfdrive/assets/translations_assets.qrc" -with open(File(translations_assets_src).abspath, 'w') as f: - f.write('\n\n') - f.write('\n'.join([f'../ui/translations/{l}.qm' for l in languages.values()])) - f.write('\n\n') - -# build assets -assets = "#selfdrive/assets/assets.cc" -assets_src = "#selfdrive/assets/assets.qrc" -rcc_bin = qt_env.get("SP_QT_RCC", "rcc") -qt_env.Command(assets, [assets_src, translations_assets_src], f"{rcc_bin} $SOURCES -o $TARGET") -qt_env.Depends(assets, Glob('#selfdrive/assets/*', exclude=[assets, assets_src, translations_assets_src, "#selfdrive/assets/assets.o"]) + [lrelease]) -asset_obj = qt_env.Object("assets", assets) - -# build main UI -qt_env.Program("ui", qt_src + [asset_obj], LIBS=qt_libs) -if GetOption('extras'): - qt_src.remove("main.cc") # replaced by test_runner - qt_env.Program('tests/test_translations', [asset_obj, 'tests/test_runner.cc', 'tests/test_translations.cc'] + qt_src, LIBS=qt_libs) - - # build installers - if arch != "Darwin": - raylib_env = env.Clone() - raylib_env['LIBPATH'] += [f'#third_party/raylib/{arch}/'] - raylib_env['LINKFLAGS'].append('-Wl,-strip-debug') - - raylib_libs = common + ["raylib"] - if arch == "larch64": - raylib_libs += ["GLESv2", "wayland-client", "wayland-egl", "EGL"] - else: - raylib_libs += ["GL"] - - release = "release3" - installers = [ - ("openpilot", release), - ("openpilot_test", f"{release}-staging"), - ("openpilot_nightly", "nightly"), - ("openpilot_internal", "nightly-dev"), - ] - - cont = raylib_env.Command("installer/continue_openpilot.o", "installer/continue_openpilot.sh", - "ld -r -b binary -o $TARGET $SOURCE") - inter = raylib_env.Command("installer/inter_ttf.o", "installer/inter-ascii.ttf", - "ld -r -b binary -o $TARGET $SOURCE") - for name, branch in installers: - d = {'BRANCH': f"'\"{branch}\"'"} - if "internal" in name: - d['INTERNAL'] = "1" - - obj = raylib_env.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) - f = raylib_env.Program(f"installer/installers/installer_{name}", [obj, cont, inter], LIBS=raylib_libs) - # keep installers small - assert f[0].get_size() < 1900*1e3, f[0].get_size() + obj = raylib_env.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=defines) + installer = raylib_env.Program(f"installer/installers/installer_{name}", [obj, cont, inter], LIBS=raylib_libs) + assert installer[0].get_size() < 1900*1e3, installer[0].get_size() diff --git a/selfdrive/ui/layouts/settings/starpilot/appearance.py b/selfdrive/ui/layouts/settings/starpilot/appearance.py index 470a344a2..5a9f1d200 100644 --- a/selfdrive/ui/layouts/settings/starpilot/appearance.py +++ b/selfdrive/ui/layouts/settings/starpilot/appearance.py @@ -32,7 +32,6 @@ THEME_KEY_CONFIG = { COLOR_PRESETS = ["Stock", "#FFFFFF", "#178644", "#3B82F6", "#E63956", "#8B5CF6", "#F59E0B"] CAMERA_VIEWS = ["Auto", "Driver", "Standard", "Wide"] -# Mirrors starpilot/ui/qt/offroad/developer_panel.cc:200-218. # Keys are the int values stored in DeveloperSidebarMetric{1..7}; values are the # human-readable labels shown in both the row value and the picker dialog. DEVELOPER_SIDEBAR_METRIC_OPTIONS: dict[int, str] = { diff --git a/selfdrive/ui/layouts/settings/starpilot/panel.py b/selfdrive/ui/layouts/settings/starpilot/panel.py index 6cc8cf682..4ea42a6e6 100644 --- a/selfdrive/ui/layouts/settings/starpilot/panel.py +++ b/selfdrive/ui/layouts/settings/starpilot/panel.py @@ -355,7 +355,7 @@ class _SettingsPage(StarPilotPanel): def _show_labeled_select(self, title, key, options, current_value): """Integer-based multi-option selector with label/value pairs (puts int). - Mirrors Qt's ButtonParamControl: resolve by index so no KeyError is possible. + Resolve by index so no KeyError is possible. """ option_labels = [tr(label) for _, label in options] option_values = [value for value, _ in options] diff --git a/selfdrive/ui/main.cc b/selfdrive/ui/main.cc deleted file mode 100644 index 9c1103211..000000000 --- a/selfdrive/ui/main.cc +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include - -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/window.h" - -// Qt 5.12.8's qErrnoWarning() emits QtCriticalMsg then calls abort() directly, -// bypassing the fatal-message path. Intercept critical+fatal Wayland messages -// before the unconditional abort() fires and clean-exit so the manager restarts -// us quickly instead of going through the slow abort/crash-handler path. -void waylandAwareMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - if (type == QtCriticalMsg || type == QtFatalMsg) { - QByteArray bytes = msg.toUtf8(); - if (bytes.contains("ayland") || bytes.contains("wl_display")) { - swagLogMessageHandler(type, context, msg); - LOGE("UI WAYLAND EXIT: %s", bytes.constData()); - _exit(0); // clean exit; manager restarts us - } - } - swagLogMessageHandler(type, context, msg); - // Non-Wayland fatal: let Qt abort normally; crash_handler will capture it. -} - -int main(int argc, char *argv[]) { - setpriority(PRIO_PROCESS, 0, -20); - - qInstallMessageHandler(waylandAwareMessageHandler); - initApp(argc, argv); - - QTranslator translator; - QString translation_file = QString::fromStdString(Params().get("LanguageSetting")); - if (!translator.load(QString(":/%1").arg(translation_file)) && translation_file.length()) { - qCritical() << "Failed to load translation file:" << translation_file; - } - - QApplication a(argc, argv); - a.installTranslator(&translator); - - MainWindow w; - setMainWindow(&w); - a.installEventFilter(&w); - - // Pin the UI to the little cores (0-3) AFTER startup. The realtime control - // loop (card/controlsd) runs SCHED_FIFO on core 4; this keeps the steady-state - // UI off it so a UI stall can't preempt the control loop. Deliberately done - // after MainWindow init so startup — and crucially restart recovery — can use - // all cores; pinning before init starved the restarting UI on the contended - // little cores and stretched recovery from ~30s to minutes. The per-second - // reaffine in UIState::update keeps it pinned thereafter. - if (!Hardware::PC()) { - util::set_core_affinity({0, 1, 2, 3}); - } - - return a.exec(); -} diff --git a/selfdrive/ui/mici/widgets/button.py b/selfdrive/ui/mici/widgets/button.py index 3ad6efde3..8f3c4e09d 100644 --- a/selfdrive/ui/mici/widgets/button.py +++ b/selfdrive/ui/mici/widgets/button.py @@ -105,7 +105,7 @@ class BigButton(Widget): LABEL_HORIZONTAL_PADDING = 40 LABEL_VERTICAL_PADDING = 23 # visually matches 30 in figma - """A lightweight stand-in for the Qt BigButton, drawn & updated each frame.""" + """A lightweight large action button, drawn and updated each frame.""" def __init__(self, text: str, value: str = "", icon: Union[rl.Texture, None] = None, scroll: bool = False): super().__init__() diff --git a/selfdrive/ui/moc_ui.cc b/selfdrive/ui/moc_ui.cc deleted file mode 100644 index 72421f5f2..000000000 --- a/selfdrive/ui/moc_ui.cc +++ /dev/null @@ -1,338 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'ui.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "ui.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'ui.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_UIState_t { - QByteArrayData data[11]; - char stringdata0[96]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_UIState_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_UIState_t qt_meta_stringdata_UIState = { - { -QT_MOC_LITERAL(0, 0, 7), // "UIState" -QT_MOC_LITERAL(1, 8, 8), // "uiUpdate" -QT_MOC_LITERAL(2, 17, 0), // "" -QT_MOC_LITERAL(3, 18, 1), // "s" -QT_MOC_LITERAL(4, 20, 16), // "StarPilotUIState" -QT_MOC_LITERAL(5, 37, 2), // "fs" -QT_MOC_LITERAL(6, 40, 17), // "offroadTransition" -QT_MOC_LITERAL(7, 58, 7), // "offroad" -QT_MOC_LITERAL(8, 66, 14), // "engagedChanged" -QT_MOC_LITERAL(9, 81, 7), // "engaged" -QT_MOC_LITERAL(10, 89, 6) // "update" - - }, - "UIState\0uiUpdate\0\0s\0StarPilotUIState\0" - "fs\0offroadTransition\0offroad\0" - "engagedChanged\0engaged\0update" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_UIState[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 4, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 34, 2, 0x06 /* Public */, - 6, 1, 39, 2, 0x06 /* Public */, - 8, 1, 42, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 10, 0, 45, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, 0x80000000 | 0, 0x80000000 | 4, 3, 5, - QMetaType::Void, QMetaType::Bool, 7, - QMetaType::Void, QMetaType::Bool, 9, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void UIState::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->uiUpdate((*reinterpret_cast< const UIState(*)>(_a[1])),(*reinterpret_cast< const StarPilotUIState(*)>(_a[2]))); break; - case 1: _t->offroadTransition((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 2: _t->engagedChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 3: _t->update(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (UIState::*)(const UIState & , const StarPilotUIState & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&UIState::uiUpdate)) { - *result = 0; - return; - } - } - { - using _t = void (UIState::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&UIState::offroadTransition)) { - *result = 1; - return; - } - } - { - using _t = void (UIState::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&UIState::engagedChanged)) { - *result = 2; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject UIState::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_UIState.data, - qt_meta_data_UIState, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *UIState::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *UIState::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_UIState.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int UIState::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 4) - qt_static_metacall(this, _c, _id, _a); - _id -= 4; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 4) - *reinterpret_cast(_a[0]) = -1; - _id -= 4; - } - return _id; -} - -// SIGNAL 0 -void UIState::uiUpdate(const UIState & _t1, const StarPilotUIState & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void UIState::offroadTransition(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 1, _a); -} - -// SIGNAL 2 -void UIState::engagedChanged(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 2, _a); -} -struct qt_meta_stringdata_Device_t { - QByteArrayData data[13]; - char stringdata0[134]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_Device_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_Device_t qt_meta_stringdata_Device = { - { -QT_MOC_LITERAL(0, 0, 6), // "Device" -QT_MOC_LITERAL(1, 7, 19), // "displayPowerChanged" -QT_MOC_LITERAL(2, 27, 0), // "" -QT_MOC_LITERAL(3, 28, 2), // "on" -QT_MOC_LITERAL(4, 31, 18), // "interactiveTimeout" -QT_MOC_LITERAL(5, 50, 23), // "resetInteractiveTimeout" -QT_MOC_LITERAL(6, 74, 7), // "timeout" -QT_MOC_LITERAL(7, 82, 14), // "timeout_onroad" -QT_MOC_LITERAL(8, 97, 6), // "update" -QT_MOC_LITERAL(9, 104, 7), // "UIState" -QT_MOC_LITERAL(10, 112, 1), // "s" -QT_MOC_LITERAL(11, 114, 16), // "StarPilotUIState" -QT_MOC_LITERAL(12, 131, 2) // "fs" - - }, - "Device\0displayPowerChanged\0\0on\0" - "interactiveTimeout\0resetInteractiveTimeout\0" - "timeout\0timeout_onroad\0update\0UIState\0" - "s\0StarPilotUIState\0fs" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_Device[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 6, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 44, 2, 0x06 /* Public */, - 4, 0, 47, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 5, 2, 48, 2, 0x0a /* Public */, - 5, 1, 53, 2, 0x2a /* Public | MethodCloned */, - 5, 0, 56, 2, 0x2a /* Public | MethodCloned */, - 8, 2, 57, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Bool, 3, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Int, QMetaType::Int, 6, 7, - QMetaType::Void, QMetaType::Int, 6, - QMetaType::Void, - QMetaType::Void, 0x80000000 | 9, 0x80000000 | 11, 10, 12, - - 0 // eod -}; - -void Device::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->displayPowerChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 1: _t->interactiveTimeout(); break; - case 2: _t->resetInteractiveTimeout((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; - case 3: _t->resetInteractiveTimeout((*reinterpret_cast< int(*)>(_a[1]))); break; - case 4: _t->resetInteractiveTimeout(); break; - case 5: _t->update((*reinterpret_cast< const UIState(*)>(_a[1])),(*reinterpret_cast< const StarPilotUIState(*)>(_a[2]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (Device::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Device::displayPowerChanged)) { - *result = 0; - return; - } - } - { - using _t = void (Device::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Device::interactiveTimeout)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject Device::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_Device.data, - qt_meta_data_Device, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *Device::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *Device::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_Device.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int Device::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 6) - qt_static_metacall(this, _c, _id, _a); - _id -= 6; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 6) - *reinterpret_cast(_a[0]) = -1; - _id -= 6; - } - return _id; -} - -// SIGNAL 0 -void Device::displayPowerChanged(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void Device::interactiveTimeout() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/onroad/starpilot/path.py b/selfdrive/ui/onroad/starpilot/path.py index 7b74423ea..204e00887 100644 --- a/selfdrive/ui/onroad/starpilot/path.py +++ b/selfdrive/ui/onroad/starpilot/path.py @@ -130,7 +130,6 @@ def render_adjacent_lanes(renderer) -> None: def render_path_edges(renderer) -> None: """Draw colored edge strips along the driving path. - Qt reference: paintPathEdges in starpilot_annotated_camera.cc:732-769 Path edges are the area between track_edge_vertices (outer) and track_vertices (inner). Color selection on Python UIs: diff --git a/selfdrive/ui/onroad/starpilot/rainbow_path.py b/selfdrive/ui/onroad/starpilot/rainbow_path.py index 693fe21be..ddc3379b4 100644 --- a/selfdrive/ui/onroad/starpilot/rainbow_path.py +++ b/selfdrive/ui/onroad/starpilot/rainbow_path.py @@ -19,7 +19,7 @@ def _hsla_to_color(h: float, s: float, l: float, a: float) -> rl.Color: class RainbowPath: - """Rainbow path renderer ported from the FrogPilot/StarPilot Qt C++ UI implementation.""" + """Rainbow path renderer for the StarPilot onroad UI.""" def __init__(self) -> None: self._hue_offset: float = 0.0 diff --git a/selfdrive/ui/qt/api.cc b/selfdrive/ui/qt/api.cc deleted file mode 100644 index 6889b40e5..000000000 --- a/selfdrive/ui/qt/api.cc +++ /dev/null @@ -1,142 +0,0 @@ -#include "selfdrive/ui/qt/api.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" - -namespace CommaApi { - -RSA *get_rsa_private_key() { - static std::unique_ptr rsa_private(nullptr, RSA_free); - if (!rsa_private) { - FILE *fp = fopen(Path::rsa_file().c_str(), "rb"); - if (!fp) { - qDebug() << "No RSA private key found, please run manager.py or registration.py"; - return nullptr; - } - rsa_private.reset(PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)); - fclose(fp); - } - return rsa_private.get(); -} - -QByteArray rsa_sign(const QByteArray &data) { - RSA *rsa_private = get_rsa_private_key(); - if (!rsa_private) return {}; - - QByteArray sig(RSA_size(rsa_private), Qt::Uninitialized); - unsigned int sig_len; - int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private); - assert(ret == 1); - assert(sig.size() == sig_len); - return sig; -} - -QString create_jwt(const QJsonObject &payloads, int expiry) { - QJsonObject header = {{"alg", "RS256"}}; - - auto t = QDateTime::currentSecsSinceEpoch(); - QJsonObject payload = {{"identity", getDongleId().value_or("")}, {"nbf", t}, {"iat", t}, {"exp", t + expiry}}; - for (auto it = payloads.begin(); it != payloads.end(); ++it) { - payload.insert(it.key(), it.value()); - } - - auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals; - QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' + - QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts); - - auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); - return jwt + "." + rsa_sign(hash).toBase64(b64_opts); -} - -} // namespace CommaApi - -HttpRequest::HttpRequest(QObject *parent, bool create_jwt, int timeout) : create_jwt(create_jwt), QObject(parent) { - networkTimer = new QTimer(this); - networkTimer->setSingleShot(true); - networkTimer->setInterval(timeout); - connect(networkTimer, &QTimer::timeout, this, &HttpRequest::requestTimeout); -} - -bool HttpRequest::active() const { - return reply != nullptr; -} - -bool HttpRequest::timeout() const { - return reply && reply->error() == QNetworkReply::OperationCanceledError; -} - -void HttpRequest::sendRequest(const QString &requestURL, const HttpRequest::Method method) { - if (active()) { - qDebug() << "HttpRequest is active"; - return; - } - QString token; - if (create_jwt) { - token = CommaApi::create_jwt(); - } else { - QString token_json = QString::fromStdString(util::read_file(util::getenv("HOME") + "/.comma/auth.json")); - QJsonDocument json_d = QJsonDocument::fromJson(token_json.toUtf8()); - token = json_d["access_token"].toString(); - } - - QNetworkRequest request; - request.setUrl(QUrl(requestURL)); - request.setRawHeader("User-Agent", getUserAgent().toUtf8()); - - if (!token.isEmpty()) { - request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8()); - } - - if (method == HttpRequest::Method::GET) { - reply = nam()->get(request); - } else if (method == HttpRequest::Method::DELETE) { - reply = nam()->deleteResource(request); - } - - networkTimer->start(); - connect(reply, &QNetworkReply::finished, this, &HttpRequest::requestFinished); -} - -void HttpRequest::requestTimeout() { - reply->abort(); -} - -void HttpRequest::requestFinished() { - networkTimer->stop(); - - if (reply->error() == QNetworkReply::NoError) { - emit requestDone(reply->readAll(), true, reply->error()); - } else { - QString error; - if (reply->error() == QNetworkReply::OperationCanceledError) { - nam()->clearAccessCache(); - nam()->clearConnectionCache(); - error = "Request timed out"; - } else { - error = reply->errorString(); - } - emit requestDone(error, false, reply->error()); - } - - reply->deleteLater(); - reply = nullptr; -} - -QNetworkAccessManager *HttpRequest::nam() { - static QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(qApp); - return networkAccessManager; -} diff --git a/selfdrive/ui/qt/api.h b/selfdrive/ui/qt/api.h deleted file mode 100644 index 2b7d70f13..000000000 --- a/selfdrive/ui/qt/api.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "common/util.h" - -#include "starpilot/ui/qt/widgets/starpilot_controls.h" - -namespace CommaApi { - -const QString BASE_URL = util::getenv("API_HOST", useKonikServer() ? "https://api.konik.ai" : "https://api.commadotai.com").c_str(); -QByteArray rsa_sign(const QByteArray &data); -QString create_jwt(const QJsonObject &payloads = {}, int expiry = 3600); - -} // namespace CommaApi - -/** - * Makes a request to the request endpoint. - */ - -class HttpRequest : public QObject { - Q_OBJECT - -public: - enum class Method {GET, DELETE}; - - explicit HttpRequest(QObject* parent, bool create_jwt = true, int timeout = 20000); - void sendRequest(const QString &requestURL, const Method method = Method::GET); - bool active() const; - bool timeout() const; - -signals: - void requestDone(const QString &response, bool success, QNetworkReply::NetworkError error); - -protected: - QNetworkReply *reply = nullptr; - -private: - static QNetworkAccessManager *nam(); - QTimer *networkTimer = nullptr; - bool create_jwt; - -private slots: - void requestTimeout(); - void requestFinished(); -}; diff --git a/selfdrive/ui/qt/body.cc b/selfdrive/ui/qt/body.cc deleted file mode 100644 index e01adbe06..000000000 --- a/selfdrive/ui/qt/body.cc +++ /dev/null @@ -1,161 +0,0 @@ -#include "selfdrive/ui/qt/body.h" - -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/timing.h" - -RecordButton::RecordButton(QWidget *parent) : QPushButton(parent) { - setCheckable(true); - setChecked(false); - setFixedSize(148, 148); - - QObject::connect(this, &QPushButton::toggled, [=]() { - setEnabled(false); - }); -} - -void RecordButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - QPoint center(width() / 2, height() / 2); - - QColor bg(isChecked() ? "#FFFFFF" : "#737373"); - QColor accent(isChecked() ? "#FF0000" : "#FFFFFF"); - if (!isEnabled()) { - bg = QColor("#404040"); - accent = QColor("#FFFFFF"); - } - - if (isDown()) { - accent.setAlphaF(0.7); - } - - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, 74, 74); - - p.setPen(QPen(accent, 6)); - p.setBrush(Qt::NoBrush); - p.drawEllipse(center, 42, 42); - - p.setPen(Qt::NoPen); - p.setBrush(accent); - p.drawEllipse(center, 22, 22); -} - - -BodyWindow::BodyWindow(QWidget *parent) : fuel_filter(1.0, 5., 1. / UI_FREQ), QWidget(parent) { - QStackedLayout *layout = new QStackedLayout(this); - layout->setStackingMode(QStackedLayout::StackAll); - - QWidget *w = new QWidget; - QVBoxLayout *vlayout = new QVBoxLayout(w); - vlayout->setMargin(45); - layout->addWidget(w); - - // face - face = new QLabel(); - face->setAlignment(Qt::AlignCenter); - layout->addWidget(face); - awake = new QMovie("../assets/body/awake.gif", {}, this); - awake->setCacheMode(QMovie::CacheAll); - sleep = new QMovie("../assets/body/sleep.gif", {}, this); - sleep->setCacheMode(QMovie::CacheAll); - - // record button - btn = new RecordButton(this); - vlayout->addWidget(btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(btn, &QPushButton::clicked, [=](bool checked) { - btn->setEnabled(false); - Params().putBool("DisableLogging", !checked); - last_button = nanos_since_boot(); - }); - w->raise(); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &BodyWindow::updateState); -} - -void BodyWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(0, 0, 0)); - - // battery outline + detail - p.translate(width() - 136, 16); - const QColor gray = QColor("#737373"); - p.setBrush(Qt::NoBrush); - p.setPen(QPen(gray, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - p.drawRoundedRect(2, 2, 78, 36, 8, 8); - - p.setPen(Qt::NoPen); - p.setBrush(gray); - p.drawRoundedRect(84, 12, 6, 16, 4, 4); - p.drawRect(84, 12, 3, 16); - - // battery level - double fuel = std::clamp(fuel_filter.x(), 0.2f, 1.0f); - const int m = 5; // manual margin since we can't do an inner border - p.setPen(Qt::NoPen); - p.setBrush(fuel > 0.25 ? QColor("#32D74B") : QColor("#FF453A")); - p.drawRoundedRect(2 + m, 2 + m, (78 - 2*m)*fuel, 36 - 2*m, 4, 4); - - // charging status - if (charging) { - p.setPen(Qt::NoPen); - p.setBrush(Qt::white); - const QPolygonF charger({ - QPointF(12.31, 0), - QPointF(12.31, 16.92), - QPointF(18.46, 16.92), - QPointF(6.15, 40), - QPointF(6.15, 23.08), - QPointF(0, 23.08), - }); - p.drawPolygon(charger.translated(98, 0)); - } -} - -void BodyWindow::offroadTransition(bool offroad) { - btn->setChecked(true); - btn->setEnabled(true); - fuel_filter.reset(1.0); -} - -void BodyWindow::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - const SubMaster &sm = *(s.sm); - auto cs = sm["carState"].getCarState(); - - charging = cs.getCharging(); - fuel_filter.update(cs.getFuelGauge()); - - // TODO: use carState.standstill when that's fixed - const bool standstill = std::abs(cs.getVEgo()) < 0.01; - QMovie *m = standstill ? sleep : awake; - if (m != face->movie()) { - face->setMovie(m); - face->movie()->start(); - } - - // update record button state - if (sm.updated("managerState") && (sm.rcv_time("managerState") - last_button)*1e-9 > 0.5) { - for (auto proc : sm["managerState"].getManagerState().getProcesses()) { - if (proc.getName() == "loggerd") { - btn->setEnabled(true); - btn->setChecked(proc.getRunning()); - } - } - } - - update(); -} diff --git a/selfdrive/ui/qt/body.h b/selfdrive/ui/qt/body.h deleted file mode 100644 index 567a54d49..000000000 --- a/selfdrive/ui/qt/body.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "common/util.h" -#include "selfdrive/ui/ui.h" - -class RecordButton : public QPushButton { - Q_OBJECT - -public: - RecordButton(QWidget* parent = 0); - -private: - void paintEvent(QPaintEvent*) override; -}; - -class BodyWindow : public QWidget { - Q_OBJECT - -public: - BodyWindow(QWidget* parent = 0); - -private: - bool charging = false; - uint64_t last_button = 0; - FirstOrderFilter fuel_filter; - QLabel *face; - QMovie *awake, *sleep; - RecordButton *btn; - void paintEvent(QPaintEvent*) override; - -private slots: - void updateState(const UIState &s); - void offroadTransition(bool onroad); -}; diff --git a/selfdrive/ui/qt/home.cc b/selfdrive/ui/qt/home.cc deleted file mode 100644 index e04c6e8bd..000000000 --- a/selfdrive/ui/qt/home.cc +++ /dev/null @@ -1,344 +0,0 @@ -#include "selfdrive/ui/qt/home.h" - -#include -#include -#include -#include - -#include "selfdrive/ui/qt/offroad/experimental_mode.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/prime.h" - -#include "starpilot/ui/qt/widgets/drive_stats.h" -#include "starpilot/ui/qt/widgets/drive_summary.h" - -// HomeWindow: the container for the offroad and onroad UIs - -HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) { - QHBoxLayout *main_layout = new QHBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - sidebar = new Sidebar(this); - main_layout->addWidget(sidebar); - QObject::connect(sidebar, &Sidebar::openSettings, this, &HomeWindow::openSettings); - - slayout = new QStackedLayout(); - main_layout->addLayout(slayout); - - home = new OffroadHome(this); - QObject::connect(home, &OffroadHome::openSettings, this, &HomeWindow::openSettings); - slayout->addWidget(home); - - onroad = new OnroadWindow(this); - slayout->addWidget(onroad); - - body = new BodyWindow(this); - slayout->addWidget(body); - - driver_view = new DriverViewWindow(this); - connect(driver_view, &DriverViewWindow::done, [=] { - showDriverView(false); - }); - slayout->addWidget(driver_view); - setAttribute(Qt::WA_NoSystemBackground); - QObject::connect(uiState(), &UIState::uiUpdate, this, &HomeWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &HomeWindow::offroadTransition); - QObject::connect(uiState(), &UIState::offroadTransition, sidebar, &Sidebar::offroadTransition); - - developer_sidebar = new DeveloperSidebar(this); - main_layout->addWidget(developer_sidebar); - developer_sidebar->setVisible(false); -} - -void HomeWindow::showSidebar(bool show) { - sidebar->setVisible(show); -} - -void HomeWindow::updateState(const UIState &s, const StarPilotUIState &fs) { - const SubMaster &sm = *(s.sm); - - // switch to the generic robot UI - if (onroad->isVisible() && !body->isEnabled() && sm["carParams"].getCarParams().getNotCar()) { - body->setEnabled(true); - slayout->setCurrentWidget(body); - } - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - if (s.scene.started) { - if (starpilot_scene.driver_camera_timer >= UI_FREQ / 2) { - showDriverView(true, true); - } else { - if (driver_view->isVisible()) { - sidebar->setVisible(params.getBool("Sidebar") || starpilot_toggles.value("debug_mode").toBool()); - slayout->setCurrentWidget(onroad); - } - - developer_sidebar->setVisible(starpilot_toggles.value("developer_sidebar").toBool()); - - starpilotUIState()->starpilot_scene.sidebars_open = developer_sidebar->isVisible() && sidebar->isVisible(); - } - } -} - -void HomeWindow::offroadTransition(bool offroad) { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - body->setEnabled(false); - sidebar->setVisible(offroad || params.getBool("SidebarOpen") || starpilot_toggles.value("debug_mode").toBool()); - if (offroad) { - slayout->setCurrentWidget(home); - - developer_sidebar->setVisible(false); - } else { - slayout->setCurrentWidget(onroad); - } -} - -void HomeWindow::showDriverView(bool show, bool started) { - if (show) { - if (!started) { - emit closeSettings(); - } - slayout->setCurrentWidget(driver_view); - } else { - slayout->setCurrentWidget(home); - } - sidebar->setVisible(show == false); - - developer_sidebar->setVisible(false); -} - -void HomeWindow::mousePressEvent(QMouseEvent* e) { - // Handle sidebar collapsing - if ((onroad->isVisible() || body->isVisible()) && (!sidebar->isVisible() || e->x() > sidebar->width())) { - sidebar->setVisible(!sidebar->isVisible()); - - params.putBool("SidebarOpen", sidebar->isVisible()); - } -} - -void HomeWindow::mouseDoubleClickEvent(QMouseEvent* e) { - HomeWindow::mousePressEvent(e); - const SubMaster &sm = *(uiState()->sm); - if (sm["carParams"].getCarParams().getNotCar()) { - if (onroad->isVisible()) { - slayout->setCurrentWidget(body); - } else if (body->isVisible()) { - slayout->setCurrentWidget(onroad); - } - showSidebar(false); - } -} - -// OffroadHome: the offroad home page - -OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(40, 40, 40, 40); - - // top header - QHBoxLayout* header_layout = new QHBoxLayout(); - header_layout->setContentsMargins(0, 0, 0, 0); - header_layout->setSpacing(16); - - date = new ElidedLabel(); - header_layout->addWidget(date, 0, Qt::AlignHCenter | Qt::AlignLeft); - - update_notif = new QPushButton(tr("UPDATE")); - update_notif->setVisible(false); - update_notif->setStyleSheet("background-color: #364DEF;"); - QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); }); - header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - alert_notif = new QPushButton(); - alert_notif->setVisible(false); - alert_notif->setStyleSheet("background-color: #E22C2C;"); - QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); }); - header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - version = new ElidedLabel(); - header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight); - - main_layout->addLayout(header_layout); - - // main content - main_layout->addSpacing(25); - center_layout = new QStackedLayout(); - - QWidget *home_widget = new QWidget(this); - { - QHBoxLayout *home_layout = new QHBoxLayout(home_widget); - home_layout->setContentsMargins(0, 0, 0, 0); - home_layout->setSpacing(30); - - // left: stock prime card in simple mode, StarPilot drive stats otherwise - left_widget = new QStackedWidget(this); - - stock_left_widget = new QStackedWidget(this); - QVBoxLayout *left_prime_layout = new QVBoxLayout(); - left_prime_layout->setContentsMargins(0, 0, 0, 0); - QWidget *prime_user = new PrimeUserWidget(); - prime_user->setStyleSheet(R"( - border-radius: 10px; - background-color: #333333; - )"); - left_prime_layout->addWidget(prime_user); - left_prime_layout->addStretch(); - stock_left_widget->addWidget(new LayoutWidget(left_prime_layout)); - stock_left_widget->addWidget(new PrimeAdWidget); - stock_left_widget->setStyleSheet("border-radius: 10px;"); - QObject::connect(uiState()->prime_state, &PrimeState::changed, this, [this]() { - stock_left_widget->setCurrentIndex(uiState()->prime_state->isSubscribed() ? 0 : 1); - }); - left_widget->addWidget(stock_left_widget); - - QWidget *custom_left_widget = new QWidget(this); - custom_left_stack = new QStackedLayout(custom_left_widget); - custom_left_stack->setContentsMargins(0, 0, 0, 0); - custom_left_stack->addWidget(new DriveStats()); - StarPilotDriveSummary *drive_summary = new StarPilotDriveSummary(this); - custom_left_stack->addWidget(drive_summary); - left_widget->addWidget(custom_left_widget); - left_widget->setCurrentIndex(params.getBool("SimpleMode") ? 0 : 1); - - QObject::connect(drive_summary, &StarPilotDriveSummary::panelClosed, [this]() { - custom_left_stack->setCurrentIndex(0); - }); - QObject::connect(uiState(), &UIState::offroadTransition, [this](bool offroad) { - static bool previouslyOnroad = false; - if (offroad && previouslyOnroad && !params.getBool("SimpleMode")) { - custom_left_stack->setCurrentIndex(1); - } - previouslyOnroad = !offroad; - }); - - home_layout->addWidget(left_widget, 1); - - // right: ExperimentalModeButton, SetupWidget, Random Events Summary - right_widget = new QStackedWidget(this); - right_widget->setFixedWidth(750); - - QWidget *default_right = new QWidget(this); - QVBoxLayout *right_column = new QVBoxLayout(default_right); - right_column->setContentsMargins(0, 0, 0, 0); - right_column->setSpacing(30); - - ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this); - QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(experimental_mode, 1); - - SetupWidget *setup_widget = new SetupWidget; - QObject::connect(setup_widget, &SetupWidget::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(setup_widget, 1); - - right_widget->addWidget(default_right); - - StarPilotDriveSummary *random_events_summary = new StarPilotDriveSummary(this, true); - right_widget->addWidget(random_events_summary); - right_widget->setCurrentIndex(0); - - QObject::connect(random_events_summary, &StarPilotDriveSummary::panelClosed, [=]() { - right_widget->setCurrentIndex(0); - }); - QObject::connect(uiState(), &UIState::offroadTransition, [this](bool offroad) { - static bool previouslyOnroad = false; - if (offroad && previouslyOnroad && !params.getBool("SimpleMode") && - starpilotUIState()->starpilot_scene.starpilot_toggles.value("random_events").toBool()) { - right_widget->setCurrentIndex(1); - } - previouslyOnroad = !offroad; - }); - - home_layout->addWidget(right_widget, 0); - } - center_layout->addWidget(home_widget); - - // add update & alerts widgets - update_widget = new UpdateAlert(); - QObject::connect(update_widget, &UpdateAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(update_widget); - alerts_widget = new OffroadAlert(); - QObject::connect(alerts_widget, &OffroadAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(alerts_widget); - - main_layout->addLayout(center_layout, 1); - - // set up refresh timer - timer = new QTimer(this); - timer->callOnTimeout(this, &OffroadHome::refresh); - - setStyleSheet(R"( - * { - color: white; - } - OffroadHome { - background-color: black; - } - OffroadHome > QPushButton { - padding: 15px 30px; - border-radius: 5px; - font-size: 40px; - font-weight: 500; - } - OffroadHome > QLabel { - font-size: 55px; - } - )"); -} - -void OffroadHome::showEvent(QShowEvent *event) { - refresh(); - timer->start(10 * 1000); -} - -void OffroadHome::hideEvent(QHideEvent *event) { - timer->stop(); -} - -void OffroadHome::refresh() { - bool updateAvailable = update_widget->refresh(); - int alerts = alerts_widget->refresh(); - - // pop-up new notification - int idx = center_layout->currentIndex(); - if (!updateAvailable && !alerts) { - idx = 0; - } else if (updateAvailable && (!update_notif->isVisible() || (!alerts && idx == 2))) { - idx = 1; - } else if (alerts && (!alert_notif->isVisible() || (!updateAvailable && idx == 1))) { - idx = 2; - } - center_layout->setCurrentIndex(idx); - - update_notif->setVisible(updateAvailable); - alert_notif->setVisible(alerts); - if (alerts) { - alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT"))); - } - - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool simple_mode = params.getBool("SimpleMode"); - - stock_left_widget->setCurrentIndex(uiState()->prime_state->isSubscribed() ? 0 : 1); - left_widget->setCurrentIndex(simple_mode ? 0 : 1); - if (simple_mode) { - custom_left_stack->setCurrentIndex(0); - right_widget->setCurrentIndex(0); - } - - date->setText(QLocale(uiState()->language.mid(5)).toString(QDateTime::currentDateTime(), "dddd, MMMM d")); - date->setVisible(util::system_time_valid() && !simple_mode); - - if (simple_mode) { - version->setText(getBrand() + " " + formatStarPilotDisplayVersionDescription(QString::fromStdString(params.get("UpdaterCurrentDescription")))); - } else { - version->setText(getBrand() + " - " + getStarPilotDisplayVersion() + " - " + cleanModelName(starpilot_toggles.value("model_name").toString())); - } -} diff --git a/selfdrive/ui/qt/home.h b/selfdrive/ui/qt/home.h deleted file mode 100644 index f0931b394..000000000 --- a/selfdrive/ui/qt/home.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/offroad/driverview.h" -#include "selfdrive/ui/qt/body.h" -#include "selfdrive/ui/qt/onroad/onroad_home.h" -#include "selfdrive/ui/qt/sidebar.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" -#include "selfdrive/ui/ui.h" - -#include "starpilot/ui/qt/widgets/developer_sidebar.h" - -class OffroadHome : public QFrame { - Q_OBJECT - -public: - explicit OffroadHome(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -private: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void refresh(); - - Params params; - - QTimer* timer; - ElidedLabel* version; - QStackedLayout* center_layout; - UpdateAlert *update_widget; - OffroadAlert* alerts_widget; - QPushButton* alert_notif; - QPushButton* update_notif; - - ElidedLabel* date; - QStackedWidget *left_widget; - QStackedWidget *stock_left_widget; - QStackedLayout *custom_left_stack; - QStackedWidget *right_widget; -}; - -class HomeWindow : public QWidget { - Q_OBJECT - -public: - explicit HomeWindow(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void closeSettings(); - -public slots: - void offroadTransition(bool offroad); - void showDriverView(bool show, bool started=false); - void showSidebar(bool show); - -protected: - void mousePressEvent(QMouseEvent* e) override; - void mouseDoubleClickEvent(QMouseEvent* e) override; - -private: - Sidebar *sidebar; - OffroadHome *home; - OnroadWindow *onroad; - BodyWindow *body; - DriverViewWindow *driver_view; - QStackedLayout *slayout; - - DeveloperSidebar *developer_sidebar; - - Params params; - -private slots: - void updateState(const UIState &s, const StarPilotUIState &fs); -}; diff --git a/selfdrive/ui/qt/moc_api.cc b/selfdrive/ui/qt/moc_api.cc deleted file mode 100644 index e56142ebe..000000000 --- a/selfdrive/ui/qt/moc_api.cc +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'api.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "api.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'api.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_HttpRequest_t { - QByteArrayData data[9]; - char stringdata0[107]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_HttpRequest_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_HttpRequest_t qt_meta_stringdata_HttpRequest = { - { -QT_MOC_LITERAL(0, 0, 11), // "HttpRequest" -QT_MOC_LITERAL(1, 12, 11), // "requestDone" -QT_MOC_LITERAL(2, 24, 0), // "" -QT_MOC_LITERAL(3, 25, 8), // "response" -QT_MOC_LITERAL(4, 34, 7), // "success" -QT_MOC_LITERAL(5, 42, 27), // "QNetworkReply::NetworkError" -QT_MOC_LITERAL(6, 70, 5), // "error" -QT_MOC_LITERAL(7, 76, 14), // "requestTimeout" -QT_MOC_LITERAL(8, 91, 15) // "requestFinished" - - }, - "HttpRequest\0requestDone\0\0response\0" - "success\0QNetworkReply::NetworkError\0" - "error\0requestTimeout\0requestFinished" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_HttpRequest[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 3, 29, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 7, 0, 36, 2, 0x08 /* Private */, - 8, 0, 37, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, QMetaType::QString, QMetaType::Bool, 0x80000000 | 5, 3, 4, 6, - - // slots: parameters - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void HttpRequest::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->requestDone((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< QNetworkReply::NetworkError(*)>(_a[3]))); break; - case 1: _t->requestTimeout(); break; - case 2: _t->requestFinished(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (HttpRequest::*)(const QString & , bool , QNetworkReply::NetworkError ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&HttpRequest::requestDone)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject HttpRequest::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_HttpRequest.data, - qt_meta_data_HttpRequest, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *HttpRequest::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *HttpRequest::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_HttpRequest.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int HttpRequest::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void HttpRequest::requestDone(const QString & _t1, bool _t2, QNetworkReply::NetworkError _t3) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_body.cc b/selfdrive/ui/qt/moc_body.cc deleted file mode 100644 index 4a3cdd82a..000000000 --- a/selfdrive/ui/qt/moc_body.cc +++ /dev/null @@ -1,195 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'body.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "body.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'body.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_RecordButton_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_RecordButton_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_RecordButton_t qt_meta_stringdata_RecordButton = { - { -QT_MOC_LITERAL(0, 0, 12) // "RecordButton" - - }, - "RecordButton" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_RecordButton[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void RecordButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject RecordButton::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_RecordButton.data, - qt_meta_data_RecordButton, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *RecordButton::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *RecordButton::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_RecordButton.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int RecordButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_BodyWindow_t { - QByteArrayData data[7]; - char stringdata0[59]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_BodyWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_BodyWindow_t qt_meta_stringdata_BodyWindow = { - { -QT_MOC_LITERAL(0, 0, 10), // "BodyWindow" -QT_MOC_LITERAL(1, 11, 11), // "updateState" -QT_MOC_LITERAL(2, 23, 0), // "" -QT_MOC_LITERAL(3, 24, 7), // "UIState" -QT_MOC_LITERAL(4, 32, 1), // "s" -QT_MOC_LITERAL(5, 34, 17), // "offroadTransition" -QT_MOC_LITERAL(6, 52, 6) // "onroad" - - }, - "BodyWindow\0updateState\0\0UIState\0s\0" - "offroadTransition\0onroad" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_BodyWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 1, 24, 2, 0x08 /* Private */, - 5, 1, 27, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, 0x80000000 | 3, 4, - QMetaType::Void, QMetaType::Bool, 6, - - 0 // eod -}; - -void BodyWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->updateState((*reinterpret_cast< const UIState(*)>(_a[1]))); break; - case 1: _t->offroadTransition((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } -} - -QT_INIT_METAOBJECT const QMetaObject BodyWindow::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_BodyWindow.data, - qt_meta_data_BodyWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *BodyWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *BodyWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_BodyWindow.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int BodyWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_home.cc b/selfdrive/ui/qt/moc_home.cc deleted file mode 100644 index a2580d778..000000000 --- a/selfdrive/ui/qt/moc_home.cc +++ /dev/null @@ -1,309 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'home.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "home.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'home.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_OffroadHome_t { - QByteArrayData data[5]; - char stringdata0[38]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_OffroadHome_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_OffroadHome_t qt_meta_stringdata_OffroadHome = { - { -QT_MOC_LITERAL(0, 0, 11), // "OffroadHome" -QT_MOC_LITERAL(1, 12, 12), // "openSettings" -QT_MOC_LITERAL(2, 25, 0), // "" -QT_MOC_LITERAL(3, 26, 5), // "index" -QT_MOC_LITERAL(4, 32, 5) // "param" - - }, - "OffroadHome\0openSettings\0\0index\0param" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_OffroadHome[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 29, 2, 0x06 /* Public */, - 1, 1, 34, 2, 0x26 /* Public | MethodCloned */, - 1, 0, 37, 2, 0x26 /* Public | MethodCloned */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, QMetaType::QString, 3, 4, - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, - - 0 // eod -}; - -void OffroadHome::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSettings((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - case 1: _t->openSettings((*reinterpret_cast< int(*)>(_a[1]))); break; - case 2: _t->openSettings(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (OffroadHome::*)(int , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&OffroadHome::openSettings)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject OffroadHome::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_OffroadHome.data, - qt_meta_data_OffroadHome, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *OffroadHome::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *OffroadHome::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_OffroadHome.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int OffroadHome::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void OffroadHome::openSettings(int _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_HomeWindow_t { - QByteArrayData data[17]; - char stringdata0[159]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_HomeWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_HomeWindow_t qt_meta_stringdata_HomeWindow = { - { -QT_MOC_LITERAL(0, 0, 10), // "HomeWindow" -QT_MOC_LITERAL(1, 11, 12), // "openSettings" -QT_MOC_LITERAL(2, 24, 0), // "" -QT_MOC_LITERAL(3, 25, 5), // "index" -QT_MOC_LITERAL(4, 31, 5), // "param" -QT_MOC_LITERAL(5, 37, 13), // "closeSettings" -QT_MOC_LITERAL(6, 51, 17), // "offroadTransition" -QT_MOC_LITERAL(7, 69, 7), // "offroad" -QT_MOC_LITERAL(8, 77, 14), // "showDriverView" -QT_MOC_LITERAL(9, 92, 4), // "show" -QT_MOC_LITERAL(10, 97, 7), // "started" -QT_MOC_LITERAL(11, 105, 11), // "showSidebar" -QT_MOC_LITERAL(12, 117, 11), // "updateState" -QT_MOC_LITERAL(13, 129, 7), // "UIState" -QT_MOC_LITERAL(14, 137, 1), // "s" -QT_MOC_LITERAL(15, 139, 16), // "StarPilotUIState" -QT_MOC_LITERAL(16, 156, 2) // "fs" - - }, - "HomeWindow\0openSettings\0\0index\0param\0" - "closeSettings\0offroadTransition\0offroad\0" - "showDriverView\0show\0started\0showSidebar\0" - "updateState\0UIState\0s\0StarPilotUIState\0" - "fs" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_HomeWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 9, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 4, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 59, 2, 0x06 /* Public */, - 1, 1, 64, 2, 0x26 /* Public | MethodCloned */, - 1, 0, 67, 2, 0x26 /* Public | MethodCloned */, - 5, 0, 68, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 6, 1, 69, 2, 0x0a /* Public */, - 8, 2, 72, 2, 0x0a /* Public */, - 8, 1, 77, 2, 0x2a /* Public | MethodCloned */, - 11, 1, 80, 2, 0x0a /* Public */, - 12, 2, 83, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, QMetaType::QString, 3, 4, - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Bool, 7, - QMetaType::Void, QMetaType::Bool, QMetaType::Bool, 9, 10, - QMetaType::Void, QMetaType::Bool, 9, - QMetaType::Void, QMetaType::Bool, 9, - QMetaType::Void, 0x80000000 | 13, 0x80000000 | 15, 14, 16, - - 0 // eod -}; - -void HomeWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSettings((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - case 1: _t->openSettings((*reinterpret_cast< int(*)>(_a[1]))); break; - case 2: _t->openSettings(); break; - case 3: _t->closeSettings(); break; - case 4: _t->offroadTransition((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 5: _t->showDriverView((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; - case 6: _t->showDriverView((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 7: _t->showSidebar((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 8: _t->updateState((*reinterpret_cast< const UIState(*)>(_a[1])),(*reinterpret_cast< const StarPilotUIState(*)>(_a[2]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (HomeWindow::*)(int , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&HomeWindow::openSettings)) { - *result = 0; - return; - } - } - { - using _t = void (HomeWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&HomeWindow::closeSettings)) { - *result = 3; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject HomeWindow::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_HomeWindow.data, - qt_meta_data_HomeWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *HomeWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *HomeWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_HomeWindow.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int HomeWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 9) - qt_static_metacall(this, _c, _id, _a); - _id -= 9; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 9) - *reinterpret_cast(_a[0]) = -1; - _id -= 9; - } - return _id; -} - -// SIGNAL 0 -void HomeWindow::openSettings(int _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 3 -void HomeWindow::closeSettings() -{ - QMetaObject::activate(this, &staticMetaObject, 3, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_prime_state.cc b/selfdrive/ui/qt/moc_prime_state.cc deleted file mode 100644 index c9f6c414c..000000000 --- a/selfdrive/ui/qt/moc_prime_state.cc +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'prime_state.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "prime_state.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'prime_state.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_PrimeState_t { - QByteArrayData data[5]; - char stringdata0[48]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_PrimeState_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_PrimeState_t qt_meta_stringdata_PrimeState = { - { -QT_MOC_LITERAL(0, 0, 10), // "PrimeState" -QT_MOC_LITERAL(1, 11, 7), // "changed" -QT_MOC_LITERAL(2, 19, 0), // "" -QT_MOC_LITERAL(3, 20, 16), // "PrimeState::Type" -QT_MOC_LITERAL(4, 37, 10) // "prime_type" - - }, - "PrimeState\0changed\0\0PrimeState::Type\0" - "prime_type" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_PrimeState[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, 0x80000000 | 3, 4, - - 0 // eod -}; - -void PrimeState::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->changed((*reinterpret_cast< PrimeState::Type(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (PrimeState::*)(PrimeState::Type ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&PrimeState::changed)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject PrimeState::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_PrimeState.data, - qt_meta_data_PrimeState, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *PrimeState::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *PrimeState::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_PrimeState.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int PrimeState::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void PrimeState::changed(PrimeState::Type _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_sidebar.cc b/selfdrive/ui/qt/moc_sidebar.cc deleted file mode 100644 index 8531d4b5d..000000000 --- a/selfdrive/ui/qt/moc_sidebar.cc +++ /dev/null @@ -1,323 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'sidebar.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "sidebar.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'sidebar.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_Sidebar_t { - QByteArrayData data[23]; - char stringdata0[236]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_Sidebar_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_Sidebar_t qt_meta_stringdata_Sidebar = { - { -QT_MOC_LITERAL(0, 0, 7), // "Sidebar" -QT_MOC_LITERAL(1, 8, 12), // "openSettings" -QT_MOC_LITERAL(2, 21, 0), // "" -QT_MOC_LITERAL(3, 22, 5), // "index" -QT_MOC_LITERAL(4, 28, 5), // "param" -QT_MOC_LITERAL(5, 34, 12), // "valueChanged" -QT_MOC_LITERAL(6, 47, 17), // "offroadTransition" -QT_MOC_LITERAL(7, 65, 7), // "offroad" -QT_MOC_LITERAL(8, 73, 11), // "updateState" -QT_MOC_LITERAL(9, 85, 7), // "UIState" -QT_MOC_LITERAL(10, 93, 1), // "s" -QT_MOC_LITERAL(11, 95, 16), // "StarPilotUIState" -QT_MOC_LITERAL(12, 112, 2), // "fs" -QT_MOC_LITERAL(13, 115, 13), // "connectStatus" -QT_MOC_LITERAL(14, 129, 10), // "ItemStatus" -QT_MOC_LITERAL(15, 140, 11), // "pandaStatus" -QT_MOC_LITERAL(16, 152, 10), // "tempStatus" -QT_MOC_LITERAL(17, 163, 7), // "netType" -QT_MOC_LITERAL(18, 171, 11), // "netStrength" -QT_MOC_LITERAL(19, 183, 14), // "recordingAudio" -QT_MOC_LITERAL(20, 198, 10), // "chipStatus" -QT_MOC_LITERAL(21, 209, 12), // "memoryStatus" -QT_MOC_LITERAL(22, 222, 13) // "storageStatus" - - }, - "Sidebar\0openSettings\0\0index\0param\0" - "valueChanged\0offroadTransition\0offroad\0" - "updateState\0UIState\0s\0StarPilotUIState\0" - "fs\0connectStatus\0ItemStatus\0pandaStatus\0" - "tempStatus\0netType\0netStrength\0" - "recordingAudio\0chipStatus\0memoryStatus\0" - "storageStatus" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_Sidebar[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 6, 14, // methods - 9, 62, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 4, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 44, 2, 0x06 /* Public */, - 1, 1, 49, 2, 0x26 /* Public | MethodCloned */, - 1, 0, 52, 2, 0x26 /* Public | MethodCloned */, - 5, 0, 53, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 6, 1, 54, 2, 0x0a /* Public */, - 8, 2, 57, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, QMetaType::QString, 3, 4, - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Bool, 7, - QMetaType::Void, 0x80000000 | 9, 0x80000000 | 11, 10, 12, - - // properties: name, type, flags - 13, 0x80000000 | 14, 0x0049500b, - 15, 0x80000000 | 14, 0x0049500b, - 16, 0x80000000 | 14, 0x0049500b, - 17, QMetaType::QString, 0x00495003, - 18, QMetaType::Int, 0x00495003, - 19, QMetaType::Bool, 0x00495003, - 20, 0x80000000 | 14, 0x0049500b, - 21, 0x80000000 | 14, 0x0049500b, - 22, 0x80000000 | 14, 0x0049500b, - - // properties: notify_signal_id - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - - 0 // eod -}; - -void Sidebar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSettings((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - case 1: _t->openSettings((*reinterpret_cast< int(*)>(_a[1]))); break; - case 2: _t->openSettings(); break; - case 3: _t->valueChanged(); break; - case 4: _t->offroadTransition((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 5: _t->updateState((*reinterpret_cast< const UIState(*)>(_a[1])),(*reinterpret_cast< const StarPilotUIState(*)>(_a[2]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (Sidebar::*)(int , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Sidebar::openSettings)) { - *result = 0; - return; - } - } - { - using _t = void (Sidebar::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Sidebar::valueChanged)) { - *result = 3; - return; - } - } - } else if (_c == QMetaObject::RegisterPropertyMetaType) { - switch (_id) { - default: *reinterpret_cast(_a[0]) = -1; break; - case 8: - case 7: - case 6: - case 2: - case 1: - case 0: - *reinterpret_cast(_a[0]) = qRegisterMetaType< ItemStatus >(); break; - } - } - -#ifndef QT_NO_PROPERTIES - else if (_c == QMetaObject::ReadProperty) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - void *_v = _a[0]; - switch (_id) { - case 0: *reinterpret_cast< ItemStatus*>(_v) = _t->connect_status; break; - case 1: *reinterpret_cast< ItemStatus*>(_v) = _t->panda_status; break; - case 2: *reinterpret_cast< ItemStatus*>(_v) = _t->temp_status; break; - case 3: *reinterpret_cast< QString*>(_v) = _t->net_type; break; - case 4: *reinterpret_cast< int*>(_v) = _t->net_strength; break; - case 5: *reinterpret_cast< bool*>(_v) = _t->recording_audio; break; - case 6: *reinterpret_cast< ItemStatus*>(_v) = _t->chip_status; break; - case 7: *reinterpret_cast< ItemStatus*>(_v) = _t->memory_status; break; - case 8: *reinterpret_cast< ItemStatus*>(_v) = _t->storage_status; break; - default: break; - } - } else if (_c == QMetaObject::WriteProperty) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - void *_v = _a[0]; - switch (_id) { - case 0: - if (_t->connect_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->connect_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 1: - if (_t->panda_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->panda_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 2: - if (_t->temp_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->temp_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 3: - if (_t->net_type != *reinterpret_cast< QString*>(_v)) { - _t->net_type = *reinterpret_cast< QString*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 4: - if (_t->net_strength != *reinterpret_cast< int*>(_v)) { - _t->net_strength = *reinterpret_cast< int*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 5: - if (_t->recording_audio != *reinterpret_cast< bool*>(_v)) { - _t->recording_audio = *reinterpret_cast< bool*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 6: - if (_t->chip_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->chip_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 7: - if (_t->memory_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->memory_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - case 8: - if (_t->storage_status != *reinterpret_cast< ItemStatus*>(_v)) { - _t->storage_status = *reinterpret_cast< ItemStatus*>(_v); - Q_EMIT _t->valueChanged(); - } - break; - default: break; - } - } else if (_c == QMetaObject::ResetProperty) { - } -#endif // QT_NO_PROPERTIES -} - -QT_INIT_METAOBJECT const QMetaObject Sidebar::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_Sidebar.data, - qt_meta_data_Sidebar, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *Sidebar::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *Sidebar::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_Sidebar.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int Sidebar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 6) - qt_static_metacall(this, _c, _id, _a); - _id -= 6; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 6) - *reinterpret_cast(_a[0]) = -1; - _id -= 6; - } -#ifndef QT_NO_PROPERTIES - else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty - || _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) { - qt_static_metacall(this, _c, _id, _a); - _id -= 9; - } else if (_c == QMetaObject::QueryPropertyDesignable) { - _id -= 9; - } else if (_c == QMetaObject::QueryPropertyScriptable) { - _id -= 9; - } else if (_c == QMetaObject::QueryPropertyStored) { - _id -= 9; - } else if (_c == QMetaObject::QueryPropertyEditable) { - _id -= 9; - } else if (_c == QMetaObject::QueryPropertyUser) { - _id -= 9; - } -#endif // QT_NO_PROPERTIES - return _id; -} - -// SIGNAL 0 -void Sidebar::openSettings(int _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 3 -void Sidebar::valueChanged() -{ - QMetaObject::activate(this, &staticMetaObject, 3, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_util.cc b/selfdrive/ui/qt/moc_util.cc deleted file mode 100644 index 6dcabe07a..000000000 --- a/selfdrive/ui/qt/moc_util.cc +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'util.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "util.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'util.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ParamWatcher_t { - QByteArrayData data[5]; - char stringdata0[50]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ParamWatcher_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ParamWatcher_t qt_meta_stringdata_ParamWatcher = { - { -QT_MOC_LITERAL(0, 0, 12), // "ParamWatcher" -QT_MOC_LITERAL(1, 13, 12), // "paramChanged" -QT_MOC_LITERAL(2, 26, 0), // "" -QT_MOC_LITERAL(3, 27, 10), // "param_name" -QT_MOC_LITERAL(4, 38, 11) // "param_value" - - }, - "ParamWatcher\0paramChanged\0\0param_name\0" - "param_value" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ParamWatcher[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::QString, QMetaType::QString, 3, 4, - - 0 // eod -}; - -void ParamWatcher::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->paramChanged((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (ParamWatcher::*)(const QString & , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ParamWatcher::paramChanged)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject ParamWatcher::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_ParamWatcher.data, - qt_meta_data_ParamWatcher, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ParamWatcher::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ParamWatcher::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ParamWatcher.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int ParamWatcher::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void ParamWatcher::paramChanged(const QString & _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/moc_window.cc b/selfdrive/ui/qt/moc_window.cc deleted file mode 100644 index 8d4f6b7bf..000000000 --- a/selfdrive/ui/qt/moc_window.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'window.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "window.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'window.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_MainWindow_t { - QByteArrayData data[1]; - char stringdata0[11]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { - { -QT_MOC_LITERAL(0, 0, 10) // "MainWindow" - - }, - "MainWindow" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_MainWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_MainWindow.data, - qt_meta_data_MainWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *MainWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *MainWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/network/moc_networking.cc b/selfdrive/ui/qt/network/moc_networking.cc deleted file mode 100644 index 1943db1a4..000000000 --- a/selfdrive/ui/qt/network/moc_networking.cc +++ /dev/null @@ -1,519 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'networking.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "networking.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'networking.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_WifiItem_t { - QByteArrayData data[6]; - char stringdata0[51]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_WifiItem_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_WifiItem_t qt_meta_stringdata_WifiItem = { - { -QT_MOC_LITERAL(0, 0, 8), // "WifiItem" -QT_MOC_LITERAL(1, 9, 16), // "connectToNetwork" -QT_MOC_LITERAL(2, 26, 0), // "" -QT_MOC_LITERAL(3, 27, 7), // "Network" -QT_MOC_LITERAL(4, 35, 1), // "n" -QT_MOC_LITERAL(5, 37, 13) // "forgotNetwork" - - }, - "WifiItem\0connectToNetwork\0\0Network\0n\0" - "forgotNetwork" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_WifiItem[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 24, 2, 0x06 /* Public */, - 5, 1, 27, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, 0x80000000 | 3, 4, - QMetaType::Void, 0x80000000 | 3, 4, - - 0 // eod -}; - -void WifiItem::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->connectToNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; - case 1: _t->forgotNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (WifiItem::*)(const Network ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiItem::connectToNetwork)) { - *result = 0; - return; - } - } - { - using _t = void (WifiItem::*)(const Network ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiItem::forgotNetwork)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject WifiItem::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_WifiItem.data, - qt_meta_data_WifiItem, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *WifiItem::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *WifiItem::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_WifiItem.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int WifiItem::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void WifiItem::connectToNetwork(const Network _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void WifiItem::forgotNetwork(const Network _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 1, _a); -} -struct qt_meta_stringdata_WifiUI_t { - QByteArrayData data[6]; - char stringdata0[43]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_WifiUI_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_WifiUI_t qt_meta_stringdata_WifiUI = { - { -QT_MOC_LITERAL(0, 0, 6), // "WifiUI" -QT_MOC_LITERAL(1, 7, 16), // "connectToNetwork" -QT_MOC_LITERAL(2, 24, 0), // "" -QT_MOC_LITERAL(3, 25, 7), // "Network" -QT_MOC_LITERAL(4, 33, 1), // "n" -QT_MOC_LITERAL(5, 35, 7) // "refresh" - - }, - "WifiUI\0connectToNetwork\0\0Network\0n\0" - "refresh" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_WifiUI[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 24, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 5, 0, 27, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, 0x80000000 | 3, 4, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void WifiUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->connectToNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; - case 1: _t->refresh(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (WifiUI::*)(const Network ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiUI::connectToNetwork)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject WifiUI::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_WifiUI.data, - qt_meta_data_WifiUI, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *WifiUI::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *WifiUI::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_WifiUI.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int WifiUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void WifiUI::connectToNetwork(const Network _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_AdvancedNetworking_t { - QByteArrayData data[7]; - char stringdata0[75]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_AdvancedNetworking_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_AdvancedNetworking_t qt_meta_stringdata_AdvancedNetworking = { - { -QT_MOC_LITERAL(0, 0, 18), // "AdvancedNetworking" -QT_MOC_LITERAL(1, 19, 9), // "backPress" -QT_MOC_LITERAL(2, 29, 0), // "" -QT_MOC_LITERAL(3, 30, 17), // "requestWifiScreen" -QT_MOC_LITERAL(4, 48, 15), // "toggleTethering" -QT_MOC_LITERAL(5, 64, 2), // "id" -QT_MOC_LITERAL(6, 67, 7) // "refresh" - - }, - "AdvancedNetworking\0backPress\0\0" - "requestWifiScreen\0toggleTethering\0id\0" - "refresh" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_AdvancedNetworking[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 4, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 34, 2, 0x06 /* Public */, - 3, 0, 35, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 4, 1, 36, 2, 0x0a /* Public */, - 6, 0, 39, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Int, 5, - QMetaType::Void, - - 0 // eod -}; - -void AdvancedNetworking::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->backPress(); break; - case 1: _t->requestWifiScreen(); break; - case 2: _t->toggleTethering((*reinterpret_cast< int(*)>(_a[1]))); break; - case 3: _t->refresh(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (AdvancedNetworking::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AdvancedNetworking::backPress)) { - *result = 0; - return; - } - } - { - using _t = void (AdvancedNetworking::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AdvancedNetworking::requestWifiScreen)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject AdvancedNetworking::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_AdvancedNetworking.data, - qt_meta_data_AdvancedNetworking, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *AdvancedNetworking::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *AdvancedNetworking::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_AdvancedNetworking.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int AdvancedNetworking::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 4) - qt_static_metacall(this, _c, _id, _a); - _id -= 4; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 4) - *reinterpret_cast(_a[0]) = -1; - _id -= 4; - } - return _id; -} - -// SIGNAL 0 -void AdvancedNetworking::backPress() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void AdvancedNetworking::requestWifiScreen() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -struct qt_meta_stringdata_Networking_t { - QByteArrayData data[8]; - char stringdata0[66]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_Networking_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_Networking_t qt_meta_stringdata_Networking = { - { -QT_MOC_LITERAL(0, 0, 10), // "Networking" -QT_MOC_LITERAL(1, 11, 7), // "refresh" -QT_MOC_LITERAL(2, 19, 0), // "" -QT_MOC_LITERAL(3, 20, 16), // "connectToNetwork" -QT_MOC_LITERAL(4, 37, 7), // "Network" -QT_MOC_LITERAL(5, 45, 1), // "n" -QT_MOC_LITERAL(6, 47, 13), // "wrongPassword" -QT_MOC_LITERAL(7, 61, 4) // "ssid" - - }, - "Networking\0refresh\0\0connectToNetwork\0" - "Network\0n\0wrongPassword\0ssid" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_Networking[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 0, 29, 2, 0x0a /* Public */, - 3, 1, 30, 2, 0x08 /* Private */, - 6, 1, 33, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, - QMetaType::Void, 0x80000000 | 4, 5, - QMetaType::Void, QMetaType::QString, 7, - - 0 // eod -}; - -void Networking::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->refresh(); break; - case 1: _t->connectToNetwork((*reinterpret_cast< const Network(*)>(_a[1]))); break; - case 2: _t->wrongPassword((*reinterpret_cast< const QString(*)>(_a[1]))); break; - default: ; - } - } -} - -QT_INIT_METAOBJECT const QMetaObject Networking::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_Networking.data, - qt_meta_data_Networking, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *Networking::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *Networking::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_Networking.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int Networking::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/network/moc_wifi_manager.cc b/selfdrive/ui/qt/network/moc_wifi_manager.cc deleted file mode 100644 index 24b7f360a..000000000 --- a/selfdrive/ui/qt/network/moc_wifi_manager.cc +++ /dev/null @@ -1,201 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'wifi_manager.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "wifi_manager.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'wifi_manager.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_WifiManager_t { - QByteArrayData data[22]; - char stringdata0[276]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_WifiManager_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_WifiManager_t qt_meta_stringdata_WifiManager = { - { -QT_MOC_LITERAL(0, 0, 11), // "WifiManager" -QT_MOC_LITERAL(1, 12, 13), // "wrongPassword" -QT_MOC_LITERAL(2, 26, 0), // "" -QT_MOC_LITERAL(3, 27, 4), // "ssid" -QT_MOC_LITERAL(4, 32, 13), // "refreshSignal" -QT_MOC_LITERAL(5, 46, 11), // "stateChange" -QT_MOC_LITERAL(6, 58, 9), // "new_state" -QT_MOC_LITERAL(7, 68, 14), // "previous_state" -QT_MOC_LITERAL(8, 83, 13), // "change_reason" -QT_MOC_LITERAL(9, 97, 14), // "propertyChange" -QT_MOC_LITERAL(10, 112, 9), // "interface" -QT_MOC_LITERAL(11, 122, 5), // "props" -QT_MOC_LITERAL(12, 128, 17), // "invalidated_props" -QT_MOC_LITERAL(13, 146, 11), // "deviceAdded" -QT_MOC_LITERAL(14, 158, 15), // "QDBusObjectPath" -QT_MOC_LITERAL(15, 174, 4), // "path" -QT_MOC_LITERAL(16, 179, 17), // "connectionRemoved" -QT_MOC_LITERAL(17, 197, 13), // "newConnection" -QT_MOC_LITERAL(18, 211, 15), // "refreshFinished" -QT_MOC_LITERAL(19, 227, 24), // "QDBusPendingCallWatcher*" -QT_MOC_LITERAL(20, 252, 4), // "call" -QT_MOC_LITERAL(21, 257, 18) // "tetheringActivated" - - }, - "WifiManager\0wrongPassword\0\0ssid\0" - "refreshSignal\0stateChange\0new_state\0" - "previous_state\0change_reason\0" - "propertyChange\0interface\0props\0" - "invalidated_props\0deviceAdded\0" - "QDBusObjectPath\0path\0connectionRemoved\0" - "newConnection\0refreshFinished\0" - "QDBusPendingCallWatcher*\0call\0" - "tetheringActivated" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_WifiManager[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 9, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 59, 2, 0x06 /* Public */, - 4, 0, 62, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 5, 3, 63, 2, 0x08 /* Private */, - 9, 3, 70, 2, 0x08 /* Private */, - 13, 1, 77, 2, 0x08 /* Private */, - 16, 1, 80, 2, 0x08 /* Private */, - 17, 1, 83, 2, 0x08 /* Private */, - 18, 1, 86, 2, 0x08 /* Private */, - 21, 1, 89, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, QMetaType::QString, 3, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::UInt, QMetaType::UInt, QMetaType::UInt, 6, 7, 8, - QMetaType::Void, QMetaType::QString, QMetaType::QVariantMap, QMetaType::QStringList, 10, 11, 12, - QMetaType::Void, 0x80000000 | 14, 15, - QMetaType::Void, 0x80000000 | 14, 15, - QMetaType::Void, 0x80000000 | 14, 15, - QMetaType::Void, 0x80000000 | 19, 20, - QMetaType::Void, 0x80000000 | 19, 20, - - 0 // eod -}; - -void WifiManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->wrongPassword((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 1: _t->refreshSignal(); break; - case 2: _t->stateChange((*reinterpret_cast< uint(*)>(_a[1])),(*reinterpret_cast< uint(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3]))); break; - case 3: _t->propertyChange((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QVariantMap(*)>(_a[2])),(*reinterpret_cast< const QStringList(*)>(_a[3]))); break; - case 4: _t->deviceAdded((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break; - case 5: _t->connectionRemoved((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break; - case 6: _t->newConnection((*reinterpret_cast< const QDBusObjectPath(*)>(_a[1]))); break; - case 7: _t->refreshFinished((*reinterpret_cast< QDBusPendingCallWatcher*(*)>(_a[1]))); break; - case 8: _t->tetheringActivated((*reinterpret_cast< QDBusPendingCallWatcher*(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (WifiManager::*)(const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiManager::wrongPassword)) { - *result = 0; - return; - } - } - { - using _t = void (WifiManager::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WifiManager::refreshSignal)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject WifiManager::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_WifiManager.data, - qt_meta_data_WifiManager, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *WifiManager::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *WifiManager::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_WifiManager.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int WifiManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 9) - qt_static_metacall(this, _c, _id, _a); - _id -= 9; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 9) - *reinterpret_cast(_a[0]) = -1; - _id -= 9; - } - return _id; -} - -// SIGNAL 0 -void WifiManager::wrongPassword(const QString & _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void WifiManager::refreshSignal() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/network/networking.cc b/selfdrive/ui/qt/network/networking.cc deleted file mode 100644 index 55895bb26..000000000 --- a/selfdrive/ui/qt/network/networking.cc +++ /dev/null @@ -1,420 +0,0 @@ -#include "selfdrive/ui/qt/network/networking.h" - -#include - -#include -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -static const int ICON_WIDTH = 49; - -// Networking functions - -Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { - main_layout = new QStackedLayout(this); - - wifi = new WifiManager(this); - connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh); - connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword); - - wifiScreen = new QWidget(this); - QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen); - vlayout->setContentsMargins(20, 20, 20, 20); - if (show_advanced) { - QPushButton* advancedSettings = new QPushButton(tr("Advanced")); - advancedSettings->setObjectName("advanced_btn"); - advancedSettings->setStyleSheet("margin-right: 30px;"); - advancedSettings->setFixedSize(400, 100); - connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); }); - vlayout->addSpacing(10); - vlayout->addWidget(advancedSettings, 0, Qt::AlignRight); - vlayout->addSpacing(10); - } - - wifiWidget = new WifiUI(this, wifi); - wifiWidget->setObjectName("wifiWidget"); - connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork); - - ScrollView *wifiScroller = new ScrollView(wifiWidget, this); - wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - vlayout->addWidget(wifiScroller, 1); - main_layout->addWidget(wifiScreen); - - an = new AdvancedNetworking(this, wifi); - connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - connect(an, &AdvancedNetworking::requestWifiScreen, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - main_layout->addWidget(an); - - QPalette pal = palette(); - pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29)); - setAutoFillBackground(true); - setPalette(pal); - - setStyleSheet(R"( - #wifiWidget > QPushButton, #back_btn, #advanced_btn { - font-size: 50px; - margin: 0px; - padding: 15px; - border-width: 0; - border-radius: 30px; - color: #dddddd; - background-color: #393939; - } - #back_btn:pressed, #advanced_btn:pressed { - background-color: #4a4a4a; - } - )"); - main_layout->setCurrentWidget(wifiScreen); -} - -void Networking::setPrimeType(PrimeState::Type type) { - an->setGsmVisible(type == PrimeState::PRIME_TYPE_NONE || type == PrimeState::PRIME_TYPE_LITE); - wifi->ipv4_forward = (type == PrimeState::PRIME_TYPE_NONE || type == PrimeState::PRIME_TYPE_LITE); -} - -void Networking::refresh() { - wifiWidget->refresh(); - an->refresh(); -} - -void Networking::connectToNetwork(const Network n) { - if (wifi->isKnownConnection(n.ssid)) { - wifi->activateWifiConnection(n.ssid); - } else if (n.security_type == SecurityType::OPEN) { - wifi->connect(n, false); - } else if (n.security_type == SecurityType::WPA) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::wrongPassword(const QString &ssid) { - if (wifi->seenNetworks.contains(ssid)) { - const Network &n = wifi->seenNetworks.value(ssid); - QString pass = InputDialog::getText(tr("Wrong password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::showEvent(QShowEvent *event) { - wifi->start(); -} - -void Networking::hideEvent(QHideEvent *event) { - main_layout->setCurrentWidget(wifiScreen); - wifi->stop(); -} - -// AdvancedNetworking functions - -AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) { - - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(40); - main_layout->setSpacing(20); - - // Back button - QPushButton* back = new QPushButton(tr("Back")); - back->setObjectName("back_btn"); - back->setFixedSize(400, 100); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - ListWidget *list = new ListWidget(this); - // Enable tethering layout - std::vector tetheringSelection{tr("Off"), tr("Always"), tr("Only Onroad"), tr("Until Reboot")}; - tetheringToggle = new ButtonParamControl("TetheringEnabled", tr("Enable Tethering"), - tr("Share your device's internet connection with other devices, either all the time or only while driving."), - "", tetheringSelection); - if (params.getInt("TetheringEnabled") == 3) { - params.remove("TetheringEnabled"); - tetheringToggle->setCheckedButton(0); - } - list->addItem(tetheringToggle); - QObject::connect(tetheringToggle, &MultiButtonControl::buttonClicked, this, &AdvancedNetworking::toggleTethering); - - // Change tethering password - ButtonControl *editPasswordButton = new ButtonControl(tr("Tethering Password"), tr("EDIT")); - connect(editPasswordButton, &ButtonControl::clicked, [=]() { - QString pass = InputDialog::getText(tr("Enter new tethering password"), this, "", true, 8, wifi->getTetheringPassword()); - if (!pass.isEmpty()) { - wifi->changeTetheringPassword(pass); - } - }); - list->addItem(editPasswordButton); - - // IP address - ipLabel = new LabelControl(tr("IP Address"), wifi->ipv4_address); - list->addItem(ipLabel); - - // Roaming toggle - const bool roamingEnabled = params.getBool("GsmRoaming"); - roamingToggle = new ToggleControl(tr("Enable Roaming"), "", "", roamingEnabled); - QObject::connect(roamingToggle, &ToggleControl::toggleFlipped, [=](bool state) { - params.putBool("GsmRoaming", state); - wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")), params.getBool("GsmMetered")); - }); - list->addItem(roamingToggle); - - // APN settings - editApnButton = new ButtonControl(tr("APN Setting"), tr("EDIT")); - connect(editApnButton, &ButtonControl::clicked, [=]() { - const QString cur_apn = QString::fromStdString(params.get("GsmApn")); - QString apn = InputDialog::getText(tr("Enter APN"), this, tr("leave blank for automatic configuration"), false, -1, cur_apn).trimmed(); - - if (apn.isEmpty()) { - params.remove("GsmApn"); - } else { - params.put("GsmApn", apn.toStdString()); - } - wifi->updateGsmSettings(params.getBool("GsmRoaming"), apn, params.getBool("GsmMetered")); - }); - list->addItem(editApnButton); - - // Cellular metered toggle (prime lite or none) - const bool metered = params.getBool("GsmMetered"); - cellularMeteredToggle = new ToggleControl(tr("Cellular Metered"), tr("Prevent large data uploads when on a metered cellular connection"), "", metered); - QObject::connect(cellularMeteredToggle, &SshToggle::toggleFlipped, [=](bool state) { - params.putBool("GsmMetered", state); - wifi->updateGsmSettings(params.getBool("GsmRoaming"), QString::fromStdString(params.get("GsmApn")), state); - }); - list->addItem(cellularMeteredToggle); - - // Wi-Fi metered toggle - std::vector metered_button_texts{tr("default"), tr("metered"), tr("unmetered")}; - wifiMeteredToggle = new MultiButtonControl(tr("Wi-Fi Network Metered"), tr("Prevent large data uploads when on a metered Wi-Fi connection"), "", metered_button_texts); - QObject::connect(wifiMeteredToggle, &MultiButtonControl::buttonClicked, [=](int id) { - wifiMeteredToggle->setEnabled(false); - MeteredType metered = MeteredType::UNKNOWN; - if (id == NM_METERED_YES) { - metered = MeteredType::YES; - } else if (id == NM_METERED_NO) { - metered = MeteredType::NO; - } - auto pending_call = wifi->setCurrentNetworkMetered(metered); - if (pending_call) { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=]() { - refresh(); - watcher->deleteLater(); - }); - } - }); - list->addItem(wifiMeteredToggle); - - // Hidden Network - hiddenNetworkButton = new ButtonControl(tr("Hidden Network"), tr("CONNECT")); - connect(hiddenNetworkButton, &ButtonControl::clicked, [=]() { - QString ssid = InputDialog::getText(tr("Enter SSID"), this, "", false, 1); - if (!ssid.isEmpty()) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(ssid), true, -1); - Network hidden_network; - hidden_network.ssid = ssid.toUtf8(); - if (!pass.isEmpty()) { - hidden_network.security_type = SecurityType::WPA; - wifi->connect(hidden_network, true, pass); - } else { - wifi->connect(hidden_network, true); - } - emit requestWifiScreen(); - } - }); - list->addItem(hiddenNetworkButton); - - // Set initial config - wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")), metered); - - main_layout->addWidget(new ScrollView(list, this)); - main_layout->addStretch(1); -} - -void AdvancedNetworking::setGsmVisible(bool visible) { - roamingToggle->setVisible(visible); - editApnButton->setVisible(visible); - cellularMeteredToggle->setVisible(visible); -} - -void AdvancedNetworking::refresh() { - ipLabel->setText(wifi->ipv4_address); - tetheringToggle->setEnabled(true); - - if (wifi->isTetheringEnabled() || wifi->ipv4_address == "") { - wifiMeteredToggle->setEnabled(false); - wifiMeteredToggle->setCheckedButton(0); - } else if (wifi->ipv4_address != "") { - MeteredType metered = wifi->currentNetworkMetered(); - wifiMeteredToggle->setEnabled(true); - wifiMeteredToggle->setCheckedButton(static_cast(metered)); - } - - update(); -} - -void AdvancedNetworking::toggleTethering(int id) { - wifi->setTetheringEnabled(id == 1 || id == 2 && uiState()->scene.started || id == 3); - tetheringToggle->setEnabled(false); - if (id != 0) { - wifiMeteredToggle->setEnabled(false); - wifiMeteredToggle->setCheckedButton(0); - } -} - -// WifiUI functions - -WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(0, 0, 0, 0); - main_layout->setSpacing(0); - - // load imgs - for (const auto &s : {"low", "medium", "high", "full"}) { - QPixmap pix(ASSET_PATH + "/icons/wifi_strength_" + s + ".svg"); - strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation)); - } - lock = QPixmap(ASSET_PATH + "icons/lock_closed.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - checkmark = QPixmap(ASSET_PATH + "icons/checkmark.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - circled_slash = QPixmap(ASSET_PATH + "icons/circled_slash.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - - scanningLabel = new QLabel(tr("Scanning for networks...")); - scanningLabel->setStyleSheet("font-size: 65px;"); - main_layout->addWidget(scanningLabel, 0, Qt::AlignCenter); - - wifi_list_widget = new ListWidget(this); - wifi_list_widget->setVisible(false); - main_layout->addWidget(wifi_list_widget); - - setStyleSheet(R"( - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 4px; - background-color: #8A8A8A; - } - #forgetBtn { - font-size: 32px; - font-weight: 600; - color: #292929; - background-color: #BDBDBD; - border-width: 1px solid #828282; - border-radius: 5px; - padding: 40px; - padding-bottom: 16px; - padding-top: 16px; - } - #forgetBtn:pressed { - background-color: #828282; - } - #connecting { - font-size: 32px; - font-weight: 600; - color: white; - border-radius: 0; - padding: 27px; - padding-left: 43px; - padding-right: 43px; - background-color: black; - } - #ssidLabel { - text-align: left; - border: none; - padding-top: 50px; - padding-bottom: 50px; - } - #ssidLabel:disabled { - color: #696969; - } - )"); -} - -void WifiUI::refresh() { - bool is_empty = wifi->seenNetworks.isEmpty(); - scanningLabel->setVisible(is_empty); - wifi_list_widget->setVisible(!is_empty); - if (is_empty) return; - - setUpdatesEnabled(false); - - const bool is_tethering_enabled = wifi->isTetheringEnabled(); - QList sortedNetworks = wifi->seenNetworks.values(); - std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength); - - int n = 0; - for (Network &network : sortedNetworks) { - QPixmap status_icon; - if (network.connected == ConnectedType::CONNECTED) { - status_icon = checkmark; - } else if (network.security_type == SecurityType::UNSUPPORTED) { - status_icon = circled_slash; - } else if (network.security_type == SecurityType::WPA) { - status_icon = lock; - } - bool show_forget_btn = wifi->isKnownConnection(network.ssid) && !is_tethering_enabled; - QPixmap strength = strengths[strengthLevel(network.strength)]; - - auto item = getItem(n++); - item->setItem(network, status_icon, show_forget_btn, strength); - item->setVisible(true); - } - for (; n < wifi_items.size(); ++n) wifi_items[n]->setVisible(false); - - setUpdatesEnabled(true); -} - -WifiItem *WifiUI::getItem(int n) { - auto item = n < wifi_items.size() ? wifi_items[n] : wifi_items.emplace_back(new WifiItem(tr("CONNECTING..."), tr("FORGET"))); - if (!item->parentWidget()) { - QObject::connect(item, &WifiItem::connectToNetwork, this, &WifiUI::connectToNetwork); - QObject::connect(item, &WifiItem::forgotNetwork, [this](const Network n) { - if (ConfirmationDialog::confirm(tr("Forget Wi-Fi Network \"%1\"?").arg(QString::fromUtf8(n.ssid)), tr("Forget"), this)) - wifi->forgetConnection(n.ssid); - }); - wifi_list_widget->addItem(item); - } - return item; -} - -// WifiItem - -WifiItem::WifiItem(const QString &connecting_text, const QString &forget_text, QWidget *parent) : QWidget(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(44, 0, 73, 0); - hlayout->setSpacing(50); - - hlayout->addWidget(ssidLabel = new ElidedLabel()); - ssidLabel->setObjectName("ssidLabel"); - ssidLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - hlayout->addWidget(connecting = new QPushButton(connecting_text), 0, Qt::AlignRight); - connecting->setObjectName("connecting"); - hlayout->addWidget(forgetBtn = new QPushButton(forget_text), 0, Qt::AlignRight); - forgetBtn->setObjectName("forgetBtn"); - hlayout->addWidget(iconLabel = new QLabel(), 0, Qt::AlignRight); - hlayout->addWidget(strengthLabel = new QLabel(), 0, Qt::AlignRight); - - iconLabel->setFixedWidth(ICON_WIDTH); - QObject::connect(forgetBtn, &QPushButton::clicked, [this]() { emit forgotNetwork(network); }); - QObject::connect(ssidLabel, &ElidedLabel::clicked, [this]() { - if (network.connected == ConnectedType::DISCONNECTED) emit connectToNetwork(network); - }); -} - -void WifiItem::setItem(const Network &n, const QPixmap &status_icon, bool show_forget_btn, const QPixmap &strength_icon) { - network = n; - - ssidLabel->setText(n.ssid); - ssidLabel->setEnabled(n.security_type != SecurityType::UNSUPPORTED); - ssidLabel->setFont(InterFont(55, network.connected == ConnectedType::DISCONNECTED ? QFont::Normal : QFont::Bold)); - - connecting->setVisible(n.connected == ConnectedType::CONNECTING); - forgetBtn->setVisible(show_forget_btn); - - iconLabel->setPixmap(status_icon); - strengthLabel->setPixmap(strength_icon); -} diff --git a/selfdrive/ui/qt/network/networking.h b/selfdrive/ui/qt/network/networking.h deleted file mode 100644 index e66e431cf..000000000 --- a/selfdrive/ui/qt/network/networking.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/qt/network/wifi_manager.h" -#include "selfdrive/ui/qt/prime_state.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" -#include "selfdrive/ui/qt/widgets/toggle.h" -#include "selfdrive/ui/ui.h" - -class WifiItem : public QWidget { - Q_OBJECT -public: - explicit WifiItem(const QString &connecting_text, const QString &forget_text, QWidget* parent = nullptr); - void setItem(const Network& n, const QPixmap &icon, bool show_forget_btn, const QPixmap &strength); - -signals: - // Cannot pass Network by reference. it may change after the signal is sent. - void connectToNetwork(const Network n); - void forgotNetwork(const Network n); - -protected: - ElidedLabel* ssidLabel; - QPushButton* connecting; - QPushButton* forgetBtn; - QLabel* iconLabel; - QLabel* strengthLabel; - Network network; -}; - -class WifiUI : public QWidget { - Q_OBJECT - -public: - explicit WifiUI(QWidget *parent = 0, WifiManager* wifi = 0); - -private: - WifiItem *getItem(int n); - - WifiManager *wifi = nullptr; - QLabel *scanningLabel = nullptr; - QPixmap lock; - QPixmap checkmark; - QPixmap circled_slash; - QVector strengths; - ListWidget *wifi_list_widget = nullptr; - std::vector wifi_items; - -signals: - void connectToNetwork(const Network n); - -public slots: - void refresh(); -}; - -class AdvancedNetworking : public QWidget { - Q_OBJECT -public: - explicit AdvancedNetworking(QWidget* parent = 0, WifiManager* wifi = 0); - void setGsmVisible(bool visible); - -private: - LabelControl* ipLabel; - ButtonParamControl* tetheringToggle; - ToggleControl* roamingToggle; - ButtonControl* editApnButton; - ButtonControl* hiddenNetworkButton; - ToggleControl* cellularMeteredToggle; - MultiButtonControl* wifiMeteredToggle; - WifiManager* wifi = nullptr; - Params params; - -signals: - void backPress(); - void requestWifiScreen(); - -public slots: - void toggleTethering(int id); - void refresh(); -}; - -class Networking : public QFrame { - Q_OBJECT - -public: - explicit Networking(QWidget* parent = 0, bool show_advanced = true); - void setPrimeType(PrimeState::Type type); - WifiManager* wifi = nullptr; - -private: - QStackedLayout* main_layout = nullptr; - QWidget* wifiScreen = nullptr; - AdvancedNetworking* an = nullptr; - WifiUI* wifiWidget; - - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; - -public slots: - void refresh(); - -private slots: - void connectToNetwork(const Network n); - void wrongPassword(const QString &ssid); -}; diff --git a/selfdrive/ui/qt/network/networkmanager.h b/selfdrive/ui/qt/network/networkmanager.h deleted file mode 100644 index 8bdeaf3bb..000000000 --- a/selfdrive/ui/qt/network/networkmanager.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -/** - * We are using a NetworkManager DBUS API : https://developer.gnome.org/NetworkManager/1.26/spec.html - * */ - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags -const int NM_802_11_AP_FLAGS_NONE = 0x00000000; -const int NM_802_11_AP_FLAGS_PRIVACY = 0x00000001; -const int NM_802_11_AP_FLAGS_WPS = 0x00000002; - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags -const int NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001; -const int NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002; -const int NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010; -const int NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020; -const int NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100; -const int NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200; - -const QString NM_DBUS_PATH = "/org/freedesktop/NetworkManager"; -const QString NM_DBUS_PATH_SETTINGS = "/org/freedesktop/NetworkManager/Settings"; - -const QString NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"; -const QString NM_DBUS_INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties"; -const QString NM_DBUS_INTERFACE_SETTINGS = "org.freedesktop.NetworkManager.Settings"; -const QString NM_DBUS_INTERFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManager.Settings.Connection"; -const QString NM_DBUS_INTERFACE_DEVICE = "org.freedesktop.NetworkManager.Device"; -const QString NM_DBUS_INTERFACE_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"; -const QString NM_DBUS_INTERFACE_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"; -const QString NM_DBUS_INTERFACE_ACTIVE_CONNECTION = "org.freedesktop.NetworkManager.Connection.Active"; -const QString NM_DBUS_INTERFACE_IP4_CONFIG = "org.freedesktop.NetworkManager.IP4Config"; - -const QString NM_DBUS_SERVICE = "org.freedesktop.NetworkManager"; - -const int NM_DEVICE_STATE_UNKNOWN = 0; -const int NM_DEVICE_STATE_ACTIVATED = 100; -const int NM_DEVICE_STATE_NEED_AUTH = 60; -const int NM_DEVICE_TYPE_WIFI = 2; -const int NM_DEVICE_TYPE_MODEM = 8; -const int NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8; -const int DBUS_TIMEOUT = 100; - -// https://developer-old.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMMetered -const int NM_METERED_UNKNOWN = 0; -const int NM_METERED_YES = 1; -const int NM_METERED_NO = 2; -const int NM_METERED_GUESS_YES = 3; -const int NM_METERED_GUESS_NO = 4; diff --git a/selfdrive/ui/qt/network/wifi_manager.cc b/selfdrive/ui/qt/network/wifi_manager.cc deleted file mode 100644 index d4ad8974b..000000000 --- a/selfdrive/ui/qt/network/wifi_manager.cc +++ /dev/null @@ -1,539 +0,0 @@ -#include "selfdrive/ui/qt/network/wifi_manager.h" - -#include - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -bool compare_by_strength(const Network &a, const Network &b) { - return std::tuple(a.connected, strengthLevel(a.strength), b.ssid) > - std::tuple(b.connected, strengthLevel(b.strength), a.ssid); -} - -template -T call(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - nm.setTimeout(DBUS_TIMEOUT); - - QDBusMessage response = nm.call(method, std::forward(args)...); - if (response.type() == QDBusMessage::ErrorMessage) { - qCritical() << "DBus call error:" << response.errorMessage(); - return T(); - } - - if constexpr (std::is_same_v) { - return response; - } else if (response.arguments().count() >= 1) { - QVariant vFirst = response.arguments().at(0).value().variant(); - if (vFirst.canConvert()) { - return vFirst.value(); - } - QDebug critical = qCritical(); - critical << "Variant unpacking failure :" << method << ','; - (critical << ... << args); - } - return T(); -} - -template -QDBusPendingCall asyncCall(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm = QDBusInterface(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - return nm.asyncCall(method, args...); -} - -bool emptyPath(const QString &path) { - return path == "" || path == "/"; -} - -WifiManager::WifiManager(QObject *parent) : QObject(parent) { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - - // Set tethering ssid as "weedle" + first 4 characters of a dongle id - tethering_ssid = "weedle"; - if (auto dongle_id = getDongleId()) { - tethering_ssid += "-" + dongle_id->left(4); - } - - adapter = getAdapter(); - if (!adapter.isEmpty()) { - setup(); - } else { - QDBusConnection::systemBus().connect(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeviceAdded", this, SLOT(deviceAdded(QDBusObjectPath))); - } - - timer.callOnTimeout(this, &WifiManager::requestScan); - - initConnections(); -} - -void WifiManager::setup() { - auto bus = QDBusConnection::systemBus(); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_DEVICE, "StateChanged", this, SLOT(stateChange(unsigned int, unsigned int, unsigned int))); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_PROPERTIES, "PropertiesChanged", this, SLOT(propertyChange(QString, QVariantMap, QStringList))); - - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ConnectionRemoved", this, SLOT(connectionRemoved(QDBusObjectPath))); - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "NewConnection", this, SLOT(newConnection(QDBusObjectPath))); - - raw_adapter_state = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "State"); - activeAp = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE_WIRELESS, "ActiveAccessPoint").path(); - - requestScan(); -} - -void WifiManager::start() { - timer.start(5000); - refreshNetworks(); -} - -void WifiManager::stop() { - timer.stop(); -} - -void WifiManager::refreshNetworks() { - if (adapter.isEmpty() || !timer.isActive()) return; - - QDBusPendingCall pending_call = asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "GetAllAccessPoints"); - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::refreshFinished); -} - -void WifiManager::refreshFinished(QDBusPendingCallWatcher *watcher) { - ipv4_address = getIp4Address(); - seenNetworks.clear(); - - const QDBusReply> watcher_reply = *watcher; - if (!watcher_reply.isValid()) { - qCritical() << "Failed to refresh"; - watcher->deleteLater(); - return; - } - - for (const QDBusObjectPath &path : watcher_reply.value()) { - QDBusReply reply = call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "GetAll", NM_DBUS_INTERFACE_ACCESS_POINT); - if (!reply.isValid()) { - qCritical() << "Failed to retrieve properties for path:" << path.path(); - continue; - } - - auto properties = reply.value(); - const QByteArray ssid = properties["Ssid"].toByteArray(); - if (ssid.isEmpty()) continue; - - // May be multiple access points for each SSID. - // Use first for ssid and security type, then update connected status and strength using all - if (!seenNetworks.contains(ssid)) { - seenNetworks[ssid] = {ssid, 0U, ConnectedType::DISCONNECTED, getSecurityType(properties)}; - } - - if (path.path() == activeAp) { - seenNetworks[ssid].connected = (ssid == connecting_to_network) ? ConnectedType::CONNECTING : ConnectedType::CONNECTED; - } - - uint32_t strength = properties["Strength"].toUInt(); - if (seenNetworks[ssid].strength < strength) { - seenNetworks[ssid].strength = strength; - } - } - - emit refreshSignal(); - watcher->deleteLater(); -} - -QString WifiManager::getIp4Address() { - if (raw_adapter_state != NM_DEVICE_STATE_ACTIVATED) return ""; - - for (const auto &p : getActiveConnections()) { - QString type = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - auto ip4config = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Ip4Config"); - const auto &arr = call(ip4config.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_IP4_CONFIG, "AddressData"); - QVariantMap path; - arr.beginArray(); - while (!arr.atEnd()) { - arr >> path; - arr.endArray(); - return path.value("address").value(); - } - arr.endArray(); - } - } - return ""; -} - -SecurityType WifiManager::getSecurityType(const QVariantMap &properties) { - int sflag = properties["Flags"].toUInt(); - int wpaflag = properties["WpaFlags"].toUInt(); - int rsnflag = properties["RsnFlags"].toUInt(); - int wpa_props = wpaflag | rsnflag; - - // obtained by looking at flags of networks in the office as reported by an Android phone - const int supports_wpa = NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK; - - if ((sflag == NM_802_11_AP_FLAGS_NONE) || ((sflag & NM_802_11_AP_FLAGS_WPS) && !(wpa_props & supports_wpa))) { - return SecurityType::OPEN; - } else if ((sflag & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_props & supports_wpa) && !(wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { - return SecurityType::WPA; - } else { - LOGW("Unsupported network! sflag: %d, wpaflag: %d, rsnflag: %d", sflag, wpaflag, rsnflag); - return SecurityType::UNSUPPORTED; - } -} - -void WifiManager::connect(const Network &n, const bool is_hidden, const QString &password, const QString &username) { - setCurrentConnecting(n.ssid); - forgetConnection(n.ssid); // Clear all connections that may already exist to the network we are connecting - Connection connection; - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["id"] = "openpilot connection " + QString::fromStdString(n.ssid.toStdString()); - connection["connection"]["autoconnect-retries"] = 0; - - connection["802-11-wireless"]["ssid"] = n.ssid; - connection["802-11-wireless"]["hidden"] = is_hidden; - connection["802-11-wireless"]["mode"] = "infrastructure"; - - if (n.security_type == SecurityType::WPA) { - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["auth-alg"] = "open"; - connection["802-11-wireless-security"]["psk"] = password; - } - - connection["ipv4"]["method"] = "auto"; - connection["ipv4"]["dns-priority"] = 600; - connection["ipv6"]["method"] = "ignore"; - - asyncCall(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); -} - -void WifiManager::deactivateConnectionBySsid(const QString &ssid) { - for (QDBusObjectPath active_connection : getActiveConnections()) { - auto pth = call(active_connection.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "SpecificObject"); - if (!emptyPath(pth.path())) { - QString Ssid = get_property(pth.path(), "Ssid"); - if (Ssid == ssid) { - deactivateConnection(active_connection); - return; - } - } - } -} - -void WifiManager::deactivateConnection(const QDBusObjectPath &path) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeactivateConnection", QVariant::fromValue(path)); -} - -QVector WifiManager::getActiveConnections() { - auto result = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "ActiveConnections"); - return qdbus_cast>(result); -} - -bool WifiManager::isKnownConnection(const QString &ssid) { - return !getConnectionPath(ssid).path().isEmpty(); -} - -void WifiManager::forgetConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Delete"); - } -} - -void WifiManager::setCurrentConnecting(const QString &ssid) { - connecting_to_network = ssid; - for (auto &network : seenNetworks) { - network.connected = (network.ssid == ssid) ? ConnectedType::CONNECTING : ConnectedType::DISCONNECTED; - } - emit refreshSignal(); -} - -uint WifiManager::getAdapterType(const QDBusObjectPath &path) { - return call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "DeviceType"); -} - -void WifiManager::requestScan() { - if (!adapter.isEmpty()) { - asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "RequestScan", QVariantMap()); - } -} - -QByteArray WifiManager::get_property(const QString &network_path , const QString &property) { - return call(network_path, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACCESS_POINT, property); -} - -QString WifiManager::getAdapter(const uint adapter_type) { - QDBusReply> response = call(NM_DBUS_PATH, NM_DBUS_INTERFACE, "GetDevices"); - for (const QDBusObjectPath &path : response.value()) { - if (getAdapterType(path) == adapter_type) { - return path.path(); - } - } - return ""; -} - -void WifiManager::stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason) { - raw_adapter_state = new_state; - if (new_state == NM_DEVICE_STATE_NEED_AUTH && change_reason == NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT && !connecting_to_network.isEmpty()) { - forgetConnection(connecting_to_network); - emit wrongPassword(connecting_to_network); - } else if (new_state == NM_DEVICE_STATE_ACTIVATED) { - connecting_to_network = ""; - refreshNetworks(); - } -} - -// https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.Device.Wireless.html -void WifiManager::propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props) { - if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("LastScan")) { - refreshNetworks(); - } else if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("ActiveAccessPoint")) { - activeAp = props.value("ActiveAccessPoint").value().path(); - } -} - -void WifiManager::deviceAdded(const QDBusObjectPath &path) { - if (getAdapterType(path) == NM_DEVICE_TYPE_WIFI && emptyPath(adapter)) { - adapter = path.path(); - setup(); - } -} - -void WifiManager::connectionRemoved(const QDBusObjectPath &path) { - knownConnections.remove(path); -} - -void WifiManager::newConnection(const QDBusObjectPath &path) { - Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - if (knownConnections[path] != tethering_ssid) { - activateWifiConnection(knownConnections[path]); - } - } -} - -QDBusObjectPath WifiManager::getConnectionPath(const QString &ssid) { - return knownConnections.key(ssid); -} - -Connection WifiManager::getConnectionSettings(const QDBusObjectPath &path) { - return QDBusReply(call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSettings")).value(); -} - -void WifiManager::initConnections() { - const QDBusReply> response = call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ListConnections"); - for (const QDBusObjectPath &path : response.value()) { - const Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - } else if (settings.value("connection").value("id") == "lte") { - lteConnectionPath = path; - } - } - - if (!isKnownConnection(tethering_ssid)) { - addTetheringConnection(); - } -} - -std::optional WifiManager::activateWifiConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - setCurrentConnecting(ssid); - return asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(adapter)), QVariant::fromValue(QDBusObjectPath("/"))); - } - return std::nullopt; -} - -void WifiManager::activateModemConnection(const QDBusObjectPath &path) { - QString modem = getAdapter(NM_DEVICE_TYPE_MODEM); - if (!path.path().isEmpty() && !modem.isEmpty()) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(modem)), QVariant::fromValue(QDBusObjectPath("/"))); - } -} - -// function matches tici/hardware.py -// FIXME: it can mistakenly show CELL when connected to WIFI -NetworkType WifiManager::currentNetworkType() { - auto primary_conn = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "PrimaryConnection"); - auto primary_type = call(primary_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - - if (primary_type == "802-3-ethernet") { - return NetworkType::ETHERNET; - } else if (primary_type == "802-11-wireless" && !isTetheringEnabled()) { - return NetworkType::WIFI; - } else { - for (const QDBusObjectPath &conn : getActiveConnections()) { - auto type = call(conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "gsm") { - return NetworkType::CELL; - } - } - } - return NetworkType::NONE; -} - -MeteredType WifiManager::currentNetworkMetered() { - MeteredType metered = MeteredType::UNKNOWN; - for (const auto &active_conn : getActiveConnections()) { - QString type = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - QDBusObjectPath conn = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Connection"); - if (!conn.path().isEmpty()) { - Connection settings = getConnectionSettings(conn); - int metered_prop = settings.value("connection").value("metered").toInt(); - if (metered_prop == NM_METERED_YES) { - metered = MeteredType::YES; - } else if (metered_prop == NM_METERED_NO) { - metered = MeteredType::NO; - } - } - break; - } - } - return metered; -} - -std::optional WifiManager::setCurrentNetworkMetered(MeteredType metered) { - for (const auto &active_conn : getActiveConnections()) { - QString type = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - if (!isTetheringEnabled()) { - QDBusObjectPath conn = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Connection"); - if (!conn.path().isEmpty()) { - Connection settings = getConnectionSettings(conn); - settings["connection"]["metered"] = static_cast(metered); - return asyncCall(conn.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); - } - } - } - } - return std::nullopt; -} - -void WifiManager::updateGsmSettings(bool roaming, QString apn, bool metered) { - if (!lteConnectionPath.path().isEmpty()) { - bool changes = false; - bool auto_config = apn.isEmpty(); - Connection settings = getConnectionSettings(lteConnectionPath); - if (settings.value("gsm").value("auto-config").toBool() != auto_config) { - qWarning() << "Changing gsm.auto-config to" << auto_config; - settings["gsm"]["auto-config"] = auto_config; - changes = true; - } - - if (settings.value("gsm").value("apn").toString() != apn) { - qWarning() << "Changing gsm.apn to" << apn; - settings["gsm"]["apn"] = apn; - changes = true; - } - - if (settings.value("gsm").value("home-only").toBool() == roaming) { - qWarning() << "Changing gsm.home-only to" << !roaming; - settings["gsm"]["home-only"] = !roaming; - changes = true; - } - - int meteredInt = metered ? NM_METERED_UNKNOWN : NM_METERED_NO; - if (settings.value("connection").value("metered").toInt() != meteredInt) { - qWarning() << "Changing connection.metered to" << meteredInt; - settings["connection"]["metered"] = meteredInt; - changes = true; - } - - if (changes) { - QDBusPendingCall pending_call = asyncCall(lteConnectionPath.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "UpdateUnsaved", QVariant::fromValue(settings)); // update is temporary - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher]() { - deactivateConnection(lteConnectionPath); - activateModemConnection(lteConnectionPath); - watcher->deleteLater(); - }); - } - } -} - -// Functions for tethering -void WifiManager::addTetheringConnection() { - Connection connection; - connection["connection"]["id"] = "Hotspot"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["interface-name"] = "wlan0"; - connection["connection"]["autoconnect"] = false; - - connection["802-11-wireless"]["band"] = "bg"; - connection["802-11-wireless"]["mode"] = "ap"; - connection["802-11-wireless"]["ssid"] = tethering_ssid.toUtf8(); - - connection["802-11-wireless-security"]["group"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["pairwise"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["proto"] = QStringList("rsn"); - connection["802-11-wireless-security"]["psk"] = defaultTetheringPassword; - - connection["ipv4"]["method"] = "shared"; - QVariantMap address; - address["address"] = "192.168.43.1"; - address["prefix"] = 24u; - connection["ipv4"]["address-data"] = QVariant::fromValue(IpConfig() << address); - connection["ipv4"]["gateway"] = "192.168.43.1"; - connection["ipv4"]["never-default"] = true; - connection["ipv6"]["method"] = "ignore"; - - asyncCall(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); -} - -void WifiManager::tetheringActivated(QDBusPendingCallWatcher *call) { - if (!ipv4_forward) { - QTimer::singleShot(5000, this, [=] { - qWarning() << "net.ipv4.ip_forward = 0"; - std::system("sudo sysctl net.ipv4.ip_forward=0"); - }); - } - call->deleteLater(); - tethering_on = true; -} - -void WifiManager::setTetheringEnabled(bool enabled) { - if (enabled) { - auto pending_call = activateWifiConnection(tethering_ssid); - - if (pending_call) { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::tetheringActivated); - } - - } else { - deactivateConnectionBySsid(tethering_ssid); - tethering_on = false; - } -} - -bool WifiManager::isTetheringEnabled() { - if (!emptyPath(activeAp)) { - return get_property(activeAp, "Ssid") == tethering_ssid; - } - return false; -} - -QString WifiManager::getTetheringPassword() { - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - QDBusReply> response = call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSecrets", "802-11-wireless-security"); - return response.value().value("802-11-wireless-security").value("psk").toString(); - } - return ""; -} - -void WifiManager::changeTetheringPassword(const QString &newPassword) { - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - Connection settings = getConnectionSettings(path); - settings["802-11-wireless-security"]["psk"] = newPassword; - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); - if (isTetheringEnabled()) { - activateWifiConnection(tethering_ssid); - } - } -} diff --git a/selfdrive/ui/qt/network/wifi_manager.h b/selfdrive/ui/qt/network/wifi_manager.h deleted file mode 100644 index 70e15f45b..000000000 --- a/selfdrive/ui/qt/network/wifi_manager.h +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "selfdrive/ui/qt/network/networkmanager.h" - -enum class SecurityType { - OPEN, - WPA, - UNSUPPORTED -}; -enum class ConnectedType { - DISCONNECTED, - CONNECTING, - CONNECTED -}; -enum class NetworkType { - NONE, - WIFI, - CELL, - ETHERNET -}; -enum class MeteredType { - UNKNOWN, - YES, - NO -}; - -typedef QMap Connection; -typedef QVector IpConfig; - -struct Network { - QByteArray ssid; - unsigned int strength; - ConnectedType connected; - SecurityType security_type; -}; -bool compare_by_strength(const Network &a, const Network &b); -inline int strengthLevel(unsigned int strength) { return std::clamp((int)round(strength / 33.), 0, 3); } - -class WifiManager : public QObject { - Q_OBJECT - -public: - QMap seenNetworks; - QMap knownConnections; - QString ipv4_address; - bool tethering_on = false; - bool ipv4_forward = false; - - explicit WifiManager(QObject* parent); - void start(); - void stop(); - void requestScan(); - void forgetConnection(const QString &ssid); - bool isKnownConnection(const QString &ssid); - std::optional activateWifiConnection(const QString &ssid); - NetworkType currentNetworkType(); - MeteredType currentNetworkMetered(); - std::optional setCurrentNetworkMetered(MeteredType metered); - void updateGsmSettings(bool roaming, QString apn, bool metered); - void connect(const Network &ssid, const bool is_hidden = false, const QString &password = {}, const QString &username = {}); - - // Tethering functions - void setTetheringEnabled(bool enabled); - bool isTetheringEnabled(); - void changeTetheringPassword(const QString &newPassword); - QString getTetheringPassword(); - - QString getIp4Address(); - -private: - QString adapter; // Path to network manager wifi-device - QTimer timer; - unsigned int raw_adapter_state = NM_DEVICE_STATE_UNKNOWN; // Connection status https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMDeviceState - QString connecting_to_network; - QString tethering_ssid; - const QString defaultTetheringPassword = "swagswagcomma"; - QString activeAp; - QDBusObjectPath lteConnectionPath; - - QString getAdapter(const uint = NM_DEVICE_TYPE_WIFI); - uint getAdapterType(const QDBusObjectPath &path); - void deactivateConnectionBySsid(const QString &ssid); - void deactivateConnection(const QDBusObjectPath &path); - QVector getActiveConnections(); - QByteArray get_property(const QString &network_path, const QString &property); - SecurityType getSecurityType(const QVariantMap &properties); - QDBusObjectPath getConnectionPath(const QString &ssid); - Connection getConnectionSettings(const QDBusObjectPath &path); - void initConnections(); - void setup(); - void refreshNetworks(); - void activateModemConnection(const QDBusObjectPath &path); - void addTetheringConnection(); - void setCurrentConnecting(const QString &ssid); - -signals: - void wrongPassword(const QString &ssid); - void refreshSignal(); - -private slots: - void stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason); - void propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props); - void deviceAdded(const QDBusObjectPath &path); - void connectionRemoved(const QDBusObjectPath &path); - void newConnection(const QDBusObjectPath &path); - void refreshFinished(QDBusPendingCallWatcher *call); - void tetheringActivated(QDBusPendingCallWatcher *call); -}; diff --git a/selfdrive/ui/qt/offroad/developer_panel.cc b/selfdrive/ui/qt/offroad/developer_panel.cc deleted file mode 100644 index a9c3b6890..000000000 --- a/selfdrive/ui/qt/offroad/developer_panel.cc +++ /dev/null @@ -1,401 +0,0 @@ -#include "selfdrive/ui/qt/offroad/developer_panel.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -DeveloperPanel::DeveloperPanel(SettingsWindow *parent) : QFrame(parent) { - mainLayout = new QStackedLayout(this); - - mainWidget = new QWidget(this); - QVBoxLayout *mainListLayout = new QVBoxLayout(mainWidget); - - mainListLayout->setContentsMargins(50, 25, 50, 25); - mainListLayout->setSpacing(20); - - StarPilotListWidget *mainList = new StarPilotListWidget(mainWidget); - mainListLayout->addWidget(mainList); - - adbToggle = new ParamControl("AdbEnabled", tr("Enable ADB"), - tr("ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info."), ""); - mainList->addItem(adbToggle); - - auto *usePrebuiltToggle = new ParamControl("UsePrebuilt", tr("Use Prebuilt Binaries"), - tr("When enabled (default), the device skips source compilation on boot if a prebuilt artifact exists. Disable this if you plan to edit code and rebuild on-device."), ""); - mainList->addItem(usePrebuiltToggle); - - auto *showAllToggles = new ParamControl("ShowAllToggles", tr("Show All Toggles"), - tr("Show every toggle in Settings and StarPilot, even when it would normally be hidden by tuning level, car support, or related feature gating."), ""); - QObject::connect(showAllToggles, &ParamControl::toggleFlipped, [this](bool) { - updateToggles(offroad); - emit showAllTogglesChanged(); - }); - mainList->addItem(showAllToggles); - - // SSH keys - mainList->addItem(new SshToggle()); - mainList->addItem(new SshControl()); - - joystickToggle = new ParamControl("JoystickDebugMode", tr("Joystick Debug Mode"), "", ""); - QObject::connect(joystickToggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("LongitudinalManeuverMode", false); - longManeuverToggle->refresh(); - }); - mainList->addItem(joystickToggle); - - longManeuverToggle = new ParamControl("LongitudinalManeuverMode", tr("Longitudinal Maneuver Mode"), "", ""); - QObject::connect(longManeuverToggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("JoystickDebugMode", false); - joystickToggle->refresh(); - }); - mainList->addItem(longManeuverToggle); - - experimentalLongitudinalToggle = new ParamControl( - "AlphaLongitudinalEnabled", - tr("openpilot Longitudinal Control (Alpha)"), - QString("%1

%2") - .arg(tr("WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).")) - .arg(tr("On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " - "Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha.")), - "" - ); - experimentalLongitudinalToggle->setConfirmation(true, false); - QObject::connect(experimentalLongitudinalToggle, &ParamControl::toggleFlipped, [=]() { - updateToggles(offroad); - }); - mainList->addItem(experimentalLongitudinalToggle); - - // Joystick and longitudinal maneuvers should be hidden on release branches - is_release = false; - - // Toggles should be not available to change in onroad state - QObject::connect(uiState(), &UIState::offroadTransition, this, &DeveloperPanel::updateToggles); - - QJsonObject shownDescriptions = QJsonDocument::fromJson(QString::fromStdString(params.get("ShownToggleDescriptions")).toUtf8()).object(); - QString className = this->metaObject()->className(); - - if (!shownDescriptions.value(className).toBool(false)) { - forceOpenDescriptions = true; - } - - std::vector keys = params.allKeys(); - for (const std::string &key : keys) { - starpilotToggleLevels[QString::fromStdString(key)] = params.getTuningLevel(key); - } - - developerUIToggle = new StarPilotManageControl("DeveloperUI", tr("Developer UI"), tr("Detailed information about openpilot's internal operations."), ""); - QObject::connect(developerUIToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - mainLayout->setCurrentWidget(developerUIPanel); - emit openSubPanel(); - }); - mainList->insertItem(0, developerUIToggle); - - mainLayout->addWidget(mainWidget); - - StarPilotListWidget *developerUIList = new StarPilotListWidget(this); - developerUIList->setContentsMargins(50, 25, 50, 25); - developerUIPanel = new ScrollView(developerUIList, this); - mainLayout->addWidget(developerUIPanel); - - StarPilotListWidget *developerMetricList = new StarPilotListWidget(this); - developerMetricList->setContentsMargins(50, 25, 50, 25); - developerMetricPanel = new ScrollView(developerMetricList, this); - mainLayout->addWidget(developerMetricPanel); - - StarPilotListWidget *developerSidebarList = new StarPilotListWidget(this); - developerSidebarList->setContentsMargins(50, 25, 50, 25); - developerSidebarPanel = new ScrollView(developerSidebarList, this); - mainLayout->addWidget(developerSidebarPanel); - - StarPilotListWidget *developerWidgetList = new StarPilotListWidget(this); - developerWidgetList->setContentsMargins(50, 25, 50, 25); - developerWidgetPanel = new ScrollView(developerWidgetList, this); - mainLayout->addWidget(developerWidgetPanel); - - std::vector> developerToggles { - {"DeveloperMetrics", tr("Developer Metrics"), tr("Performance data, sensor readings, and system metrics for debugging and optimizing openpilot."), ""}, - {"AdjacentPathMetrics", tr("Adjacent Lane Metrics"), tr("Show the width of the adjacent lanes."), ""}, - {"BorderMetrics", tr("Border Metrics"), tr("Show statuses along the border of the driving screen.

Blind Spot: The border turns red when a vehicle is in a blind spot
Steering Torque: The border goes from green to red according to how much steering torque is being used
Turn Signal: The border flashes yellow when a turn signal is on"), ""}, - {"FPSCounter", tr("FPS Display"), tr("Show the frames per second (FPS) at the bottom of the driving screen."), ""}, - {"LeadInfo", tr("Lead Info"), tr("Show each tracked vehicle's distance and speed below its marker."), ""}, - {"NumericalTemp", tr("Numerical Temperature Gauge"), tr("Show a numerical temperature in the sidebar instead of the status labels."), ""}, - {"SidebarMetrics", tr("Sidebar Metrics"), tr("Display system information (CPU, GPU, RAM usage, IP address, device storage) in the sidebar."), ""}, - {"UseSI", tr("Use International System of Units"), tr("Display measurements using the \"International System of Units\" (SI) standard."), ""}, - - {"DeveloperSidebar", tr("Developer Sidebar"), tr("Display debugging info and metrics in a dedicated sidebar on the right side of the screen."), ""}, - {"DeveloperSidebarMetric1", tr("Metric #1"), tr("Select the metric shown in the first \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric2", tr("Metric #2"), tr("Select the metric shown in the second \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric3", tr("Metric #3"), tr("Select the metric shown in the third \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric4", tr("Metric #4"), tr("Select the metric shown in the fourth \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric5", tr("Metric #5"), tr("Select the metric shown in the fifth \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric6", tr("Metric #6"), tr("Select the metric shown in the sixth \"Developer Sidebar\" widget."), ""}, - {"DeveloperSidebarMetric7", tr("Metric #7"), tr("Select the metric shown in the seventh \"Developer Sidebar\" widget."), ""}, - - {"DeveloperWidgets", tr("Developer Widgets"), tr("Overlays for debugging visuals, internal states, and model predictions on the driving screen."), ""}, - {"AdjacentLeadsUI", tr("Adjacent Leads Tracking"), tr("Display adjacent leads detected by the car's radar to the left and right of the current driving path."), ""}, - {"ShowStoppingPoint", tr("Model Stopping Point"), tr("Show a stop-sign marker where the model intends to stop."), ""}, - {"RadarTracksUI", tr("Radar Tracks"), tr("Display all radar points produced by the car's radar."), ""}, - }; - - for (const auto &[param, title, desc, icon] : developerToggles) { - AbstractControl *developerToggle; - - if (param == "DeveloperMetrics") { - StarPilotManageControl *developerMetricsToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(developerMetricsToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - mainLayout->setCurrentWidget(developerMetricPanel); - emit openSubSubPanel(); - }); - developerToggle = developerMetricsToggle; - } else if (param == "BorderMetrics") { - std::vector borderToggles{"BlindSpotMetrics", "ShowSteering", "SignalMetrics"}; - std::vector borderToggleNames{tr("Blind Spot"), tr("Steering Torque"), tr("Turn Signal")}; - borderMetricsButton = new StarPilotButtonToggleControl(param, title, desc, icon, borderToggles, borderToggleNames); - developerToggle = borderMetricsButton; - } else if (param == "NumericalTemp") { - std::vector temperatureToggles{"Fahrenheit"}; - std::vector temperatureToggleNames{tr("Fahrenheit")}; - developerToggle = new StarPilotButtonToggleControl(param, title, desc, icon, temperatureToggles, temperatureToggleNames); - } else if (param == "SidebarMetrics") { - sidebarMetricsToggles = {"ShowCPU", "ShowGPU", "ShowIP", "ShowMemoryUsage", "ShowStorageLeft", "ShowStorageUsed"}; - std::vector sidebarMetricsToggleNames{tr("CPU"), tr("GPU"), tr("IP"), tr("RAM"), tr("SSD Left"), tr("SSD Used")}; - sidebarMetricsToggle = new StarPilotButtonsControl(title, desc, icon, sidebarMetricsToggleNames, true, false, 150); - for (int i = 0; i < sidebarMetricsToggles.size(); ++i) { - if (params.getBool(sidebarMetricsToggles[i].toStdString())) { - sidebarMetricsToggle->setCheckedButton(i); - } - } - QObject::connect(sidebarMetricsToggle, &StarPilotButtonsControl::buttonClicked, [this](int id) { - params.putBool(sidebarMetricsToggles[id].toStdString(), !params.getBool(sidebarMetricsToggles[id].toStdString())); - - if (id == 0) { - params.putBool("ShowGPU", false); - } else if (id == 1) { - params.putBool("ShowCPU", false); - } else if (id == 3) { - params.putBool("ShowStorageLeft", false); - params.putBool("ShowStorageUsed", false); - } else if (id == 4) { - params.putBool("ShowMemoryUsage", false); - params.putBool("ShowStorageUsed", false); - } else if (id == 5) { - params.putBool("ShowMemoryUsage", false); - params.putBool("ShowStorageLeft", false); - } - - sidebarMetricsToggle->clearCheckedButtons(); - for (int i = 0; i < sidebarMetricsToggles.size(); ++i) { - if (params.getBool(sidebarMetricsToggles[i].toStdString())) { - sidebarMetricsToggle->setCheckedButton(i); - } - } - }); - developerToggle = sidebarMetricsToggle; - } else if (param == "DeveloperSidebar") { - StarPilotManageControl *developerSidebarToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(developerSidebarToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - mainLayout->setCurrentWidget(developerSidebarPanel); - emit openSubSubPanel(); - }); - developerToggle = developerSidebarToggle; - } else if (developerSidebarKeys.contains(param)) { - QMap developerSidebarMetricOptions { - {0, tr("None")}, - {1, tr("Acceleration: Current")}, - {2, tr("Acceleration: Max")}, - {3, tr("Auto Tune: Actuator Delay")}, - {4, tr("Auto Tune: Friction")}, - {5, tr("Auto Tune: Lateral Acceleration")}, - {6, tr("Auto Tune: Steer Ratio")}, - {7, tr("Auto Tune: Stiffness Factor")}, - {8, tr("Engagement %: Lateral")}, - {9, tr("Engagement %: Longitudinal")}, - {10, tr("Lateral Control: Steering Angle")}, - {11, tr("Lateral Control: Torque % Used")}, - {12, tr("Longitudinal Control: Actuator Acceleration Output")}, - {13, tr("Longitudinal MPC: Danger Factor")}, - {14, tr("Longitudinal MPC Jerk: Acceleration")}, - {15, tr("Longitudinal MPC Jerk: Danger Zone")}, - {16, tr("Longitudinal MPC Jerk: Speed Control")}, - {17, tr("Model Name")}, - }; - - ButtonControl *metricToggle = new ButtonControl(title, tr("SELECT"), desc); - QObject::connect(metricToggle, &ButtonControl::clicked, [metricToggle, key = param, developerSidebarMetricOptions, this]() mutable { - QString current = developerSidebarMetricOptions.value(params.getInt(key.toStdString()), tr("None")); - QString selection = MultiOptionDialog::getSelection(tr("Select a metric to display"), developerSidebarMetricOptions.values(), current, this); - - if (!selection.isEmpty()) { - int selectedMetric = developerSidebarMetricOptions.key(selection); - - params.putInt(key.toStdString(), selectedMetric); - - metricToggle->setValue(selection); - } - }); - metricToggle->setValue(developerSidebarMetricOptions.value(params.getInt(param.toStdString()), tr("None"))); - developerToggle = metricToggle; - } else if (param == "DeveloperWidgets") { - StarPilotManageControl *developerWidgetsToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(developerWidgetsToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - mainLayout->setCurrentWidget(developerWidgetPanel); - emit openSubSubPanel(); - }); - developerToggle = developerWidgetsToggle; - } else if (param == "ShowStoppingPoint") { - std::vector stoppingPointToggles{"ShowStoppingPointMetrics"}; - std::vector stoppingPointToggleNames{tr("Show Distance")}; - developerToggle = new StarPilotButtonToggleControl(param, title, desc, icon, stoppingPointToggles, stoppingPointToggleNames); - } else { - developerToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = developerToggle; - - if (developerMetricKeys.contains(param)) { - developerMetricList->addItem(developerToggle); - } else if (developerSidebarKeys.contains(param)) { - developerSidebarList->addItem(developerToggle); - } else if (developerWidgetKeys.contains(param)) { - developerWidgetList->addItem(developerToggle); - } else { - developerUIList->addItem(developerToggle); - - parentKeys.insert(param); - } - } - - QObject::connect(parent, &SettingsWindow::closeSubPanel, [this]() {mainLayout->setCurrentWidget(mainWidget);}); - QObject::connect(parent, &SettingsWindow::closeSubSubPanel, [this]() {mainLayout->setCurrentWidget(developerUIPanel);}); -} - -void DeveloperPanel::updateToggles(bool _offroad) { - const bool showAllToggles = params.getBool("ShowAllToggles"); - - for (auto btn : findChildren()) { - btn->setVisible(showAllToggles || !is_release); - - /* - * experimentalLongitudinalToggle should be toggelable when: - * - visible, and - * - during onroad & offroad states - */ - if (btn != experimentalLongitudinalToggle) { - btn->setEnabled(_offroad); - } - - for (auto &[key, toggle] : toggles) { - if (toggle == btn) { - btn->setEnabled(true); - break; - } - } - if (developerUIToggle == btn) { - btn->setEnabled(true); - } - } - - // longManeuverToggle and experimentalLongitudinalToggle should not be toggleable if the car does not have longitudinal control - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if ((!CP.getAlphaLongitudinalAvailable() || is_release) && !showAllToggles) { - params.remove("AlphaLongitudinalEnabled"); - experimentalLongitudinalToggle->setEnabled(false); - } else { - experimentalLongitudinalToggle->setEnabled(true); - } - - /* - * experimentalLongitudinalToggle should be visible when: - * - is not a release branch, and - * - the car supports experimental longitudinal control (alpha) - */ - experimentalLongitudinalToggle->setVisible(showAllToggles || (CP.getAlphaLongitudinalAvailable() && !is_release)); - - longManeuverToggle->setEnabled((showAllToggles || hasLongitudinalControl(CP)) && _offroad); - - hasOpenpilotLongitudinal = hasLongitudinalControl(CP); - hasRadar = !CP.getRadarUnavailable(); - - borderMetricsButton->setVisibleButton(0, showAllToggles || CP.getEnableBsm()); - } else { - longManeuverToggle->setEnabled(showAllToggles && _offroad); - experimentalLongitudinalToggle->setEnabled(showAllToggles); - experimentalLongitudinalToggle->setVisible(showAllToggles); - } - experimentalLongitudinalToggle->refresh(); - - offroad = _offroad; - - tuningLevel = params.getInt("TuningLevel"); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || tuningLevel >= starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "AdjacentLeadsUI") { - setVisible &= hasRadar && !(params.getBool("AdvancedCustomUI") && params.getBool("HideLeadMarker")); - } - - else if (key == "RadarTracksUI") { - setVisible &= hasRadar; - } - - else if (key == "ShowStoppingPoint") { - setVisible &= hasOpenpilotLongitudinal; - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (developerMetricKeys.contains(key)) { - toggles["DeveloperMetrics"]->setVisible(true); - } else if (developerSidebarKeys.contains(key)) { - toggles["DeveloperSidebar"]->setVisible(true); - } else if (developerUIKeys.contains(key)) { - toggles["DeveloperUI"]->setVisible(true); - } else if (developerWidgetKeys.contains(key)) { - toggles["DeveloperWidgets"]->setVisible(true); - } - } - } - - borderMetricsButton->setVisibleButton(0, showAllToggles || hasBSM); - - developerUIToggle->setVisible(showAllToggles || tuningLevel >= starpilotToggleLevels["DeveloperUI"].toDouble()); - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} - -void DeveloperPanel::showEvent(QShowEvent *event) { - updateToggles(offroad); - - for (int i = 0; i < sidebarMetricsToggles.size(); ++i) { - if (params.getBool(sidebarMetricsToggles[i].toStdString())) { - sidebarMetricsToggle->setCheckedButton(i); - } - } - - QJsonObject shownDescriptions = QJsonDocument::fromJson(QString::fromStdString(params.get("ShownToggleDescriptions")).toUtf8()).object(); - QString className = this->metaObject()->className(); - - if (!shownDescriptions.value(className).toBool(false)) { - shownDescriptions.insert(className, true); - params.put("ShownToggleDescriptions", QJsonDocument(shownDescriptions).toJson(QJsonDocument::Compact).toStdString()); - } -} diff --git a/selfdrive/ui/qt/offroad/developer_panel.h b/selfdrive/ui/qt/offroad/developer_panel.h deleted file mode 100644 index dc9665b9a..000000000 --- a/selfdrive/ui/qt/offroad/developer_panel.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/offroad/settings.h" - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class DeveloperPanel : public QFrame { - Q_OBJECT -public: - explicit DeveloperPanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -signals: - void openSubPanel(); - void openSubSubPanel(); - void showAllTogglesChanged(); - -private: - Params params; - ParamControl* adbToggle; - ParamControl* joystickToggle; - ParamControl* longManeuverToggle; - ParamControl* experimentalLongitudinalToggle; - bool is_release; - bool offroad = false; - - bool forceOpenDescriptions = false; - bool hasBSM = true; - bool hasOpenpilotLongitudinal = true; - bool hasRadar = true; - - int tuningLevel; - - std::map toggles; - - std::vector sidebarMetricsToggles; - - StarPilotButtonsControl *sidebarMetricsToggle; - - StarPilotButtonToggleControl *borderMetricsButton; - - StarPilotManageControl *developerUIToggle; - - QJsonObject starpilotToggleLevels; - - QSet developerMetricKeys = {"AdjacentPathMetrics", "BorderMetrics", "FPSCounter", "LeadInfo", "NumericalTemp", "SidebarMetrics", "UseSI"}; - QSet developerSidebarKeys = {"DeveloperSidebarMetric1", "DeveloperSidebarMetric2", "DeveloperSidebarMetric3", "DeveloperSidebarMetric4", "DeveloperSidebarMetric5", "DeveloperSidebarMetric6", "DeveloperSidebarMetric7"}; - QSet developerUIKeys = {"DeveloperMetrics", "DeveloperSidebar", "DeveloperWidgets"}; - QSet developerWidgetKeys = {"AdjacentLeadsUI", "RadarTracksUI", "ShowStoppingPoint"}; - - QSet parentKeys; - - QStackedLayout *mainLayout; - - QWidget *mainWidget; - - ScrollView *developerMetricPanel; - ScrollView *developerSidebarPanel; - ScrollView *developerUIPanel; - ScrollView *developerWidgetPanel; - -private slots: - void updateToggles(bool _offroad); -}; diff --git a/selfdrive/ui/qt/offroad/driverview.cc b/selfdrive/ui/qt/offroad/driverview.cc deleted file mode 100644 index 9010227f1..000000000 --- a/selfdrive/ui/qt/offroad/driverview.cc +++ /dev/null @@ -1,82 +0,0 @@ -#include "selfdrive/ui/qt/offroad/driverview.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -DriverViewWindow::DriverViewWindow(QWidget* parent) : CameraWidget("camerad", VISION_STREAM_DRIVER, parent) { - QObject::connect(this, &CameraWidget::clicked, this, &DriverViewWindow::done); - QObject::connect(device(), &Device::interactiveTimeout, this, [this]() { - if (isVisible()) { - emit done(); - } - }); -} - -void DriverViewWindow::showEvent(QShowEvent* event) { - params.putBool("IsDriverViewEnabled", true); - device()->resetInteractiveTimeout(60); - CameraWidget::showEvent(event); -} - -void DriverViewWindow::hideEvent(QHideEvent* event) { - params.putBool("IsDriverViewEnabled", false); - stopVipcThread(); - CameraWidget::hideEvent(event); -} - -void DriverViewWindow::paintGL() { - CameraWidget::paintGL(); - - std::lock_guard lk(frame_lock); - QPainter p(this); - // startup msg - if (frames.empty()) { - p.setPen(Qt::white); - p.setRenderHint(QPainter::TextAntialiasing); - p.setFont(InterFont(100, QFont::Bold)); - p.drawText(geometry(), Qt::AlignCenter, tr("camera starting")); - return; - } - - const auto &sm = *(uiState()->sm); - cereal::DriverStateV2::Reader driver_state = sm["driverStateV2"].getDriverStateV2(); - bool is_rhd = driver_state.getWheelOnRightProb() > 0.5; - auto driver_data = is_rhd ? driver_state.getRightDriverData() : driver_state.getLeftDriverData(); - - bool face_detected = driver_data.getFaceProb() > 0.7; - if (face_detected) { - auto fxy_list = driver_data.getFacePosition(); - auto std_list = driver_data.getFaceOrientationStd(); - float face_x = fxy_list[0]; - float face_y = fxy_list[1]; - float face_std = std::max(std_list[0], std_list[1]); - - float alpha = 0.7; - if (face_std > 0.15) { - alpha = std::max(0.7 - (face_std-0.15)*3.5, 0.0); - } - const int box_size = 220; - // use approx instead of distort_points - int fbox_x = 1080.0 - 1714.0 * face_x; - int fbox_y = -135.0 + (504.0 + std::abs(face_x)*112.0) + (1205.0 - std::abs(face_x)*724.0) * face_y; - p.setPen(QPen(QColor(255, 255, 255, alpha * 255), 10)); - p.drawRoundedRect(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size, 35.0, 35.0); - } - - driver_monitor.updateState(*uiState()); - driver_monitor.draw(p, rect()); -} - -mat4 DriverViewWindow::calcFrameMatrix() { - const float driver_view_ratio = 2.0; - const float yscale = stream_height * driver_view_ratio / stream_width; - const float xscale = yscale * glHeight() / glWidth() * stream_width / stream_height; - return mat4{{ - xscale, 0.0, 0.0, 0.0, - 0.0, yscale, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} diff --git a/selfdrive/ui/qt/offroad/driverview.h b/selfdrive/ui/qt/offroad/driverview.h deleted file mode 100644 index f6eb752fe..000000000 --- a/selfdrive/ui/qt/offroad/driverview.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/widgets/cameraview.h" -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" - -class DriverViewWindow : public CameraWidget { - Q_OBJECT - -public: - explicit DriverViewWindow(QWidget *parent); - -signals: - void done(); - -protected: - mat4 calcFrameMatrix() override; - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void paintGL() override; - - Params params; - DriverMonitorRenderer driver_monitor; -}; diff --git a/selfdrive/ui/qt/offroad/experimental_mode.cc b/selfdrive/ui/qt/offroad/experimental_mode.cc deleted file mode 100644 index fcfc892e6..000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.cc +++ /dev/null @@ -1,95 +0,0 @@ -#include "selfdrive/ui/qt/offroad/experimental_mode.h" - -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" - -ExperimentalModeButton::ExperimentalModeButton(QWidget *parent) : QPushButton(parent) { - chill_pixmap = QPixmap("../assets/icons/couch.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - experimental_pixmap = QPixmap("../assets/icons/experimental_grey.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - - // go to toggles and expand whichever mode control is actually active - connect(this, &QPushButton::clicked, [=]() { - const QString toggle = params.getBool("ConditionalExperimental") ? "ConditionalExperimental" : - params.getBool("ConditionalChill") ? "ConditionalChill" : - "ExperimentalMode"; - emit openSettings(2, toggle); - }); - - setFixedHeight(125); - QHBoxLayout *main_layout = new QHBoxLayout; - main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); - - mode_label = new QLabel; - mode_icon = new QLabel; - mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - - main_layout->addWidget(mode_label, 1, Qt::AlignLeft); - main_layout->addWidget(mode_icon, 0, Qt::AlignRight); - - setLayout(main_layout); - - setStyleSheet(R"( - QPushButton { - border: none; - } - - QLabel { - font-size: 45px; - font-weight: 300; - text-align: left; - font-family: JetBrainsMono; - color: #000000; - } - )"); -} - -void ExperimentalModeButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - QPainterPath path; - path.addRoundedRect(rect(), 10, 10); - - // gradient - bool pressed = isDown(); - QLinearGradient gradient(rect().left(), 0, rect().right(), 0); - if (experimental_mode) { - gradient.setColorAt(0, QColor(255, 155, 63, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(219, 56, 34, pressed ? 0xcc : 0xff)); - } else { - gradient.setColorAt(0, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); - } - p.fillPath(path, gradient); - - // vertical line - p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); - int line_x = rect().right() - img_width - (2 * horizontal_padding); - p.drawLine(line_x, rect().bottom(), line_x, rect().top()); -} - -void ExperimentalModeButton::showEvent(QShowEvent *event) { - if (params.getBool("ConditionalExperimental")) { - int status = params_memory.getInt("CEStatus"); - if ((status != 1 && status != 2) && params.getBool("PersistExperimentalState")) { - status = params.getInt("PersistedCEStatus"); - } - experimental_mode = !params.getBool("SafeMode") && status == 2; - } else if (params.getBool("ConditionalChill")) { - int status = params_memory.getInt("CCStatus"); - if ((status != 1 && status != 2) && params.getBool("PersistChillState")) { - status = params.getInt("PersistedCCStatus"); - } - experimental_mode = !params.getBool("SafeMode") && (status == 0 || status == 1); - } else { - experimental_mode = params.getBool("ExperimentalMode") && !params.getBool("SafeMode"); - } - mode_icon->setPixmap(experimental_mode ? experimental_pixmap : chill_pixmap); - mode_label->setText(experimental_mode ? tr("EXPERIMENTAL MODE ON") : tr("CHILL MODE ON")); -} diff --git a/selfdrive/ui/qt/offroad/experimental_mode.h b/selfdrive/ui/qt/offroad/experimental_mode.h deleted file mode 100644 index 6b15f52dd..000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" - -class ExperimentalModeButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalModeButton(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString &toggle = ""); - -private: - void showEvent(QShowEvent *event) override; - - Params params; - Params params_memory{"", true}; - bool experimental_mode; - int img_width = 100; - int horizontal_padding = 30; - QPixmap experimental_pixmap; - QPixmap chill_pixmap; - QLabel *mode_label; - QLabel *mode_icon; - -protected: - void paintEvent(QPaintEvent *event) override; -}; diff --git a/selfdrive/ui/qt/offroad/moc_developer_panel.cc b/selfdrive/ui/qt/offroad/moc_developer_panel.cc deleted file mode 100644 index f13e27b61..000000000 --- a/selfdrive/ui/qt/offroad/moc_developer_panel.cc +++ /dev/null @@ -1,177 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'developer_panel.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "developer_panel.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'developer_panel.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DeveloperPanel_t { - QByteArrayData data[7]; - char stringdata0[90]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DeveloperPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DeveloperPanel_t qt_meta_stringdata_DeveloperPanel = { - { -QT_MOC_LITERAL(0, 0, 14), // "DeveloperPanel" -QT_MOC_LITERAL(1, 15, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 28, 0), // "" -QT_MOC_LITERAL(3, 29, 15), // "openSubSubPanel" -QT_MOC_LITERAL(4, 45, 21), // "showAllTogglesChanged" -QT_MOC_LITERAL(5, 67, 13), // "updateToggles" -QT_MOC_LITERAL(6, 81, 8) // "_offroad" - - }, - "DeveloperPanel\0openSubPanel\0\0" - "openSubSubPanel\0showAllTogglesChanged\0" - "updateToggles\0_offroad" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DeveloperPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 4, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 34, 2, 0x06 /* Public */, - 3, 0, 35, 2, 0x06 /* Public */, - 4, 0, 36, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 5, 1, 37, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Bool, 6, - - 0 // eod -}; - -void DeveloperPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - case 1: _t->openSubSubPanel(); break; - case 2: _t->showAllTogglesChanged(); break; - case 3: _t->updateToggles((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (DeveloperPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DeveloperPanel::openSubPanel)) { - *result = 0; - return; - } - } - { - using _t = void (DeveloperPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DeveloperPanel::openSubSubPanel)) { - *result = 1; - return; - } - } - { - using _t = void (DeveloperPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DeveloperPanel::showAllTogglesChanged)) { - *result = 2; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject DeveloperPanel::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_DeveloperPanel.data, - qt_meta_data_DeveloperPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DeveloperPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DeveloperPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DeveloperPanel.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int DeveloperPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 4) - qt_static_metacall(this, _c, _id, _a); - _id -= 4; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 4) - *reinterpret_cast(_a[0]) = -1; - _id -= 4; - } - return _id; -} - -// SIGNAL 0 -void DeveloperPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void DeveloperPanel::openSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} - -// SIGNAL 2 -void DeveloperPanel::showAllTogglesChanged() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/offroad/moc_driverview.cc b/selfdrive/ui/qt/offroad/moc_driverview.cc deleted file mode 100644 index 39e4d4208..000000000 --- a/selfdrive/ui/qt/offroad/moc_driverview.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'driverview.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "driverview.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'driverview.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DriverViewWindow_t { - QByteArrayData data[3]; - char stringdata0[23]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DriverViewWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DriverViewWindow_t qt_meta_stringdata_DriverViewWindow = { - { -QT_MOC_LITERAL(0, 0, 16), // "DriverViewWindow" -QT_MOC_LITERAL(1, 17, 4), // "done" -QT_MOC_LITERAL(2, 22, 0) // "" - - }, - "DriverViewWindow\0done\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DriverViewWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void DriverViewWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->done(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (DriverViewWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DriverViewWindow::done)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject DriverViewWindow::staticMetaObject = { { - &CameraWidget::staticMetaObject, - qt_meta_stringdata_DriverViewWindow.data, - qt_meta_data_DriverViewWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DriverViewWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DriverViewWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DriverViewWindow.stringdata0)) - return static_cast(this); - return CameraWidget::qt_metacast(_clname); -} - -int DriverViewWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = CameraWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void DriverViewWindow::done() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/offroad/moc_experimental_mode.cc b/selfdrive/ui/qt/offroad/moc_experimental_mode.cc deleted file mode 100644 index 0156162fa..000000000 --- a/selfdrive/ui/qt/offroad/moc_experimental_mode.cc +++ /dev/null @@ -1,142 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'experimental_mode.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "experimental_mode.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'experimental_mode.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ExperimentalModeButton_t { - QByteArrayData data[5]; - char stringdata0[50]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ExperimentalModeButton_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ExperimentalModeButton_t qt_meta_stringdata_ExperimentalModeButton = { - { -QT_MOC_LITERAL(0, 0, 22), // "ExperimentalModeButton" -QT_MOC_LITERAL(1, 23, 12), // "openSettings" -QT_MOC_LITERAL(2, 36, 0), // "" -QT_MOC_LITERAL(3, 37, 5), // "index" -QT_MOC_LITERAL(4, 43, 6) // "toggle" - - }, - "ExperimentalModeButton\0openSettings\0" - "\0index\0toggle" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ExperimentalModeButton[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 29, 2, 0x06 /* Public */, - 1, 1, 34, 2, 0x26 /* Public | MethodCloned */, - 1, 0, 37, 2, 0x26 /* Public | MethodCloned */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, QMetaType::QString, 3, 4, - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, - - 0 // eod -}; - -void ExperimentalModeButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSettings((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - case 1: _t->openSettings((*reinterpret_cast< int(*)>(_a[1]))); break; - case 2: _t->openSettings(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (ExperimentalModeButton::*)(int , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ExperimentalModeButton::openSettings)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject ExperimentalModeButton::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_ExperimentalModeButton.data, - qt_meta_data_ExperimentalModeButton, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ExperimentalModeButton::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ExperimentalModeButton::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ExperimentalModeButton.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int ExperimentalModeButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void ExperimentalModeButton::openSettings(int _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/offroad/moc_onboarding.cc b/selfdrive/ui/qt/offroad/moc_onboarding.cc deleted file mode 100644 index 437d9d097..000000000 --- a/selfdrive/ui/qt/offroad/moc_onboarding.cc +++ /dev/null @@ -1,477 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'onboarding.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "onboarding.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'onboarding.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_TrainingGuide_t { - QByteArrayData data[3]; - char stringdata0[33]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_TrainingGuide_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_TrainingGuide_t qt_meta_stringdata_TrainingGuide = { - { -QT_MOC_LITERAL(0, 0, 13), // "TrainingGuide" -QT_MOC_LITERAL(1, 14, 17), // "completedTraining" -QT_MOC_LITERAL(2, 32, 0) // "" - - }, - "TrainingGuide\0completedTraining\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_TrainingGuide[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void TrainingGuide::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->completedTraining(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (TrainingGuide::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TrainingGuide::completedTraining)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject TrainingGuide::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_TrainingGuide.data, - qt_meta_data_TrainingGuide, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *TrainingGuide::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *TrainingGuide::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_TrainingGuide.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int TrainingGuide::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void TrainingGuide::completedTraining() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_TermsPage_t { - QByteArrayData data[4]; - char stringdata0[39]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_TermsPage_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_TermsPage_t qt_meta_stringdata_TermsPage = { - { -QT_MOC_LITERAL(0, 0, 9), // "TermsPage" -QT_MOC_LITERAL(1, 10, 13), // "acceptedTerms" -QT_MOC_LITERAL(2, 24, 0), // "" -QT_MOC_LITERAL(3, 25, 13) // "declinedTerms" - - }, - "TermsPage\0acceptedTerms\0\0declinedTerms" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_TermsPage[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 24, 2, 0x06 /* Public */, - 3, 0, 25, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void TermsPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->acceptedTerms(); break; - case 1: _t->declinedTerms(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (TermsPage::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TermsPage::acceptedTerms)) { - *result = 0; - return; - } - } - { - using _t = void (TermsPage::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TermsPage::declinedTerms)) { - *result = 1; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject TermsPage::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_TermsPage.data, - qt_meta_data_TermsPage, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *TermsPage::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *TermsPage::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_TermsPage.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int TermsPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void TermsPage::acceptedTerms() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void TermsPage::declinedTerms() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -struct qt_meta_stringdata_DeclinePage_t { - QByteArrayData data[3]; - char stringdata0[21]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DeclinePage_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DeclinePage_t qt_meta_stringdata_DeclinePage = { - { -QT_MOC_LITERAL(0, 0, 11), // "DeclinePage" -QT_MOC_LITERAL(1, 12, 7), // "getBack" -QT_MOC_LITERAL(2, 20, 0) // "" - - }, - "DeclinePage\0getBack\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DeclinePage[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void DeclinePage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->getBack(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (DeclinePage::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DeclinePage::getBack)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject DeclinePage::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_DeclinePage.data, - qt_meta_data_DeclinePage, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DeclinePage::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DeclinePage::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DeclinePage.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int DeclinePage::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void DeclinePage::getBack() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_OnboardingWindow_t { - QByteArrayData data[3]; - char stringdata0[33]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_OnboardingWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_OnboardingWindow_t qt_meta_stringdata_OnboardingWindow = { - { -QT_MOC_LITERAL(0, 0, 16), // "OnboardingWindow" -QT_MOC_LITERAL(1, 17, 14), // "onboardingDone" -QT_MOC_LITERAL(2, 32, 0) // "" - - }, - "OnboardingWindow\0onboardingDone\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_OnboardingWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void OnboardingWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->onboardingDone(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (OnboardingWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&OnboardingWindow::onboardingDone)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject OnboardingWindow::staticMetaObject = { { - &QStackedWidget::staticMetaObject, - qt_meta_stringdata_OnboardingWindow.data, - qt_meta_data_OnboardingWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *OnboardingWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *OnboardingWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_OnboardingWindow.stringdata0)) - return static_cast(this); - return QStackedWidget::qt_metacast(_clname); -} - -int OnboardingWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QStackedWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void OnboardingWindow::onboardingDone() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/offroad/moc_settings.cc b/selfdrive/ui/qt/offroad/moc_settings.cc deleted file mode 100644 index a18d00ddc..000000000 --- a/selfdrive/ui/qt/offroad/moc_settings.cc +++ /dev/null @@ -1,756 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_SettingsWindow_t { - QByteArrayData data[16]; - char stringdata0[220]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_SettingsWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_SettingsWindow_t qt_meta_stringdata_SettingsWindow = { - { -QT_MOC_LITERAL(0, 0, 14), // "SettingsWindow" -QT_MOC_LITERAL(1, 15, 13), // "closeSettings" -QT_MOC_LITERAL(2, 29, 0), // "" -QT_MOC_LITERAL(3, 30, 19), // "reviewTrainingGuide" -QT_MOC_LITERAL(4, 50, 14), // "showDriverView" -QT_MOC_LITERAL(5, 65, 23), // "expandToggleDescription" -QT_MOC_LITERAL(6, 89, 5), // "param" -QT_MOC_LITERAL(7, 95, 14), // "scrollToToggle" -QT_MOC_LITERAL(8, 110, 10), // "closePanel" -QT_MOC_LITERAL(9, 121, 13), // "closeSubPanel" -QT_MOC_LITERAL(10, 135, 16), // "closeSubSubPanel" -QT_MOC_LITERAL(11, 152, 19), // "closeSubSubSubPanel" -QT_MOC_LITERAL(12, 172, 12), // "updateMetric" -QT_MOC_LITERAL(13, 185, 8), // "isMetric" -QT_MOC_LITERAL(14, 194, 7), // "bootRun" -QT_MOC_LITERAL(15, 202, 17) // "updateTuningLevel" - - }, - "SettingsWindow\0closeSettings\0\0" - "reviewTrainingGuide\0showDriverView\0" - "expandToggleDescription\0param\0" - "scrollToToggle\0closePanel\0closeSubPanel\0" - "closeSubSubPanel\0closeSubSubSubPanel\0" - "updateMetric\0isMetric\0bootRun\0" - "updateTuningLevel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_SettingsWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 12, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 12, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 74, 2, 0x06 /* Public */, - 3, 0, 75, 2, 0x06 /* Public */, - 4, 0, 76, 2, 0x06 /* Public */, - 5, 1, 77, 2, 0x06 /* Public */, - 7, 1, 80, 2, 0x06 /* Public */, - 8, 0, 83, 2, 0x06 /* Public */, - 9, 0, 84, 2, 0x06 /* Public */, - 10, 0, 85, 2, 0x06 /* Public */, - 11, 0, 86, 2, 0x06 /* Public */, - 12, 2, 87, 2, 0x06 /* Public */, - 12, 1, 92, 2, 0x26 /* Public | MethodCloned */, - 15, 0, 95, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, QMetaType::QString, 6, - QMetaType::Void, QMetaType::QString, 6, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, QMetaType::Bool, QMetaType::Bool, 13, 14, - QMetaType::Void, QMetaType::Bool, 13, - QMetaType::Void, - - 0 // eod -}; - -void SettingsWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->closeSettings(); break; - case 1: _t->reviewTrainingGuide(); break; - case 2: _t->showDriverView(); break; - case 3: _t->expandToggleDescription((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 4: _t->scrollToToggle((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 5: _t->closePanel(); break; - case 6: _t->closeSubPanel(); break; - case 7: _t->closeSubSubPanel(); break; - case 8: _t->closeSubSubSubPanel(); break; - case 9: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; - case 10: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 11: _t->updateTuningLevel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::closeSettings)) { - *result = 0; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::reviewTrainingGuide)) { - *result = 1; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::showDriverView)) { - *result = 2; - return; - } - } - { - using _t = void (SettingsWindow::*)(const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::expandToggleDescription)) { - *result = 3; - return; - } - } - { - using _t = void (SettingsWindow::*)(const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::scrollToToggle)) { - *result = 4; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::closePanel)) { - *result = 5; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::closeSubPanel)) { - *result = 6; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::closeSubSubPanel)) { - *result = 7; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::closeSubSubSubPanel)) { - *result = 8; - return; - } - } - { - using _t = void (SettingsWindow::*)(bool , bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::updateMetric)) { - *result = 9; - return; - } - } - { - using _t = void (SettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SettingsWindow::updateTuningLevel)) { - *result = 11; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject SettingsWindow::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_SettingsWindow.data, - qt_meta_data_SettingsWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *SettingsWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *SettingsWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_SettingsWindow.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int SettingsWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 12) - qt_static_metacall(this, _c, _id, _a); - _id -= 12; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 12) - *reinterpret_cast(_a[0]) = -1; - _id -= 12; - } - return _id; -} - -// SIGNAL 0 -void SettingsWindow::closeSettings() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void SettingsWindow::reviewTrainingGuide() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} - -// SIGNAL 2 -void SettingsWindow::showDriverView() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} - -// SIGNAL 3 -void SettingsWindow::expandToggleDescription(const QString & _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 3, _a); -} - -// SIGNAL 4 -void SettingsWindow::scrollToToggle(const QString & _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 4, _a); -} - -// SIGNAL 5 -void SettingsWindow::closePanel() -{ - QMetaObject::activate(this, &staticMetaObject, 5, nullptr); -} - -// SIGNAL 6 -void SettingsWindow::closeSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 6, nullptr); -} - -// SIGNAL 7 -void SettingsWindow::closeSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 7, nullptr); -} - -// SIGNAL 8 -void SettingsWindow::closeSubSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 8, nullptr); -} - -// SIGNAL 9 -void SettingsWindow::updateMetric(bool _t1, bool _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 9, _a); -} - -// SIGNAL 11 -void SettingsWindow::updateTuningLevel() -{ - QMetaObject::activate(this, &staticMetaObject, 11, nullptr); -} -struct qt_meta_stringdata_GalaxyQRPopup_t { - QByteArrayData data[1]; - char stringdata0[14]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_GalaxyQRPopup_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_GalaxyQRPopup_t qt_meta_stringdata_GalaxyQRPopup = { - { -QT_MOC_LITERAL(0, 0, 13) // "GalaxyQRPopup" - - }, - "GalaxyQRPopup" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_GalaxyQRPopup[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void GalaxyQRPopup::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject GalaxyQRPopup::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_GalaxyQRPopup.data, - qt_meta_data_GalaxyQRPopup, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *GalaxyQRPopup::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *GalaxyQRPopup::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_GalaxyQRPopup.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int GalaxyQRPopup::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_DevicePanel_t { - QByteArrayData data[7]; - char stringdata0[87]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DevicePanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DevicePanel_t qt_meta_stringdata_DevicePanel = { - { -QT_MOC_LITERAL(0, 0, 11), // "DevicePanel" -QT_MOC_LITERAL(1, 12, 19), // "reviewTrainingGuide" -QT_MOC_LITERAL(2, 32, 0), // "" -QT_MOC_LITERAL(3, 33, 14), // "showDriverView" -QT_MOC_LITERAL(4, 48, 8), // "poweroff" -QT_MOC_LITERAL(5, 57, 6), // "reboot" -QT_MOC_LITERAL(6, 64, 22) // "updateCalibDescription" - - }, - "DevicePanel\0reviewTrainingGuide\0\0" - "showDriverView\0poweroff\0reboot\0" - "updateCalibDescription" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DevicePanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 5, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 39, 2, 0x06 /* Public */, - 3, 0, 40, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 4, 0, 41, 2, 0x08 /* Private */, - 5, 0, 42, 2, 0x08 /* Private */, - 6, 0, 43, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void DevicePanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->reviewTrainingGuide(); break; - case 1: _t->showDriverView(); break; - case 2: _t->poweroff(); break; - case 3: _t->reboot(); break; - case 4: _t->updateCalibDescription(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (DevicePanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DevicePanel::reviewTrainingGuide)) { - *result = 0; - return; - } - } - { - using _t = void (DevicePanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DevicePanel::showDriverView)) { - *result = 1; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject DevicePanel::staticMetaObject = { { - &ListWidget::staticMetaObject, - qt_meta_stringdata_DevicePanel.data, - qt_meta_data_DevicePanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DevicePanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DevicePanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DevicePanel.stringdata0)) - return static_cast(this); - return ListWidget::qt_metacast(_clname); -} - -int DevicePanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 5) - qt_static_metacall(this, _c, _id, _a); - _id -= 5; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 5) - *reinterpret_cast(_a[0]) = -1; - _id -= 5; - } - return _id; -} - -// SIGNAL 0 -void DevicePanel::reviewTrainingGuide() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void DevicePanel::showDriverView() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -struct qt_meta_stringdata_TogglesPanel_t { - QByteArrayData data[13]; - char stringdata0[135]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_TogglesPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_TogglesPanel_t qt_meta_stringdata_TogglesPanel = { - { -QT_MOC_LITERAL(0, 0, 12), // "TogglesPanel" -QT_MOC_LITERAL(1, 13, 12), // "updateMetric" -QT_MOC_LITERAL(2, 26, 0), // "" -QT_MOC_LITERAL(3, 27, 6), // "metric" -QT_MOC_LITERAL(4, 34, 7), // "bootRun" -QT_MOC_LITERAL(5, 42, 17), // "simpleModeChanged" -QT_MOC_LITERAL(6, 60, 7), // "enabled" -QT_MOC_LITERAL(7, 68, 23), // "expandToggleDescription" -QT_MOC_LITERAL(8, 92, 5), // "param" -QT_MOC_LITERAL(9, 98, 14), // "scrollToToggle" -QT_MOC_LITERAL(10, 113, 11), // "updateState" -QT_MOC_LITERAL(11, 125, 7), // "UIState" -QT_MOC_LITERAL(12, 133, 1) // "s" - - }, - "TogglesPanel\0updateMetric\0\0metric\0" - "bootRun\0simpleModeChanged\0enabled\0" - "expandToggleDescription\0param\0" - "scrollToToggle\0updateState\0UIState\0s" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_TogglesPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 6, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 44, 2, 0x06 /* Public */, - 1, 1, 49, 2, 0x26 /* Public | MethodCloned */, - 5, 1, 52, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 7, 1, 55, 2, 0x0a /* Public */, - 9, 1, 58, 2, 0x0a /* Public */, - 10, 1, 61, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, QMetaType::Bool, QMetaType::Bool, 3, 4, - QMetaType::Void, QMetaType::Bool, 3, - QMetaType::Void, QMetaType::Bool, 6, - - // slots: parameters - QMetaType::Void, QMetaType::QString, 8, - QMetaType::Void, QMetaType::QString, 8, - QMetaType::Void, 0x80000000 | 11, 12, - - 0 // eod -}; - -void TogglesPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; - case 1: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 2: _t->simpleModeChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 3: _t->expandToggleDescription((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 4: _t->scrollToToggle((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 5: _t->updateState((*reinterpret_cast< const UIState(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (TogglesPanel::*)(bool , bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TogglesPanel::updateMetric)) { - *result = 0; - return; - } - } - { - using _t = void (TogglesPanel::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TogglesPanel::simpleModeChanged)) { - *result = 2; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject TogglesPanel::staticMetaObject = { { - &ListWidget::staticMetaObject, - qt_meta_stringdata_TogglesPanel.data, - qt_meta_data_TogglesPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *TogglesPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *TogglesPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_TogglesPanel.stringdata0)) - return static_cast(this); - return ListWidget::qt_metacast(_clname); -} - -int TogglesPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 6) - qt_static_metacall(this, _c, _id, _a); - _id -= 6; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 6) - *reinterpret_cast(_a[0]) = -1; - _id -= 6; - } - return _id; -} - -// SIGNAL 0 -void TogglesPanel::updateMetric(bool _t1, bool _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 2 -void TogglesPanel::simpleModeChanged(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 2, _a); -} -struct qt_meta_stringdata_SoftwarePanel_t { - QByteArrayData data[1]; - char stringdata0[14]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_SoftwarePanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_SoftwarePanel_t qt_meta_stringdata_SoftwarePanel = { - { -QT_MOC_LITERAL(0, 0, 13) // "SoftwarePanel" - - }, - "SoftwarePanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_SoftwarePanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void SoftwarePanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject SoftwarePanel::staticMetaObject = { { - &ListWidget::staticMetaObject, - qt_meta_stringdata_SoftwarePanel.data, - qt_meta_data_SoftwarePanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *SoftwarePanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *SoftwarePanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_SoftwarePanel.stringdata0)) - return static_cast(this); - return ListWidget::qt_metacast(_clname); -} - -int SoftwarePanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ListWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/offroad/onboarding.cc b/selfdrive/ui/qt/offroad/onboarding.cc deleted file mode 100644 index 139056667..000000000 --- a/selfdrive/ui/qt/offroad/onboarding.cc +++ /dev/null @@ -1,211 +0,0 @@ -#include "selfdrive/ui/qt/offroad/onboarding.h" - -#include - -#include -#include -#include -#include - -#include "common/util.h" -#include "common/params.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/input.h" - -TrainingGuide::TrainingGuide(QWidget *parent) : QFrame(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); -} - -void TrainingGuide::mouseReleaseEvent(QMouseEvent *e) { - if (click_timer.elapsed() < 250) { - return; - } - click_timer.restart(); - - auto contains = [this](QRect r, const QPoint &pt) { - if (image.size() != image_raw_size) { - QTransform transform; - transform.translate((width()- image.width()) / 2.0, (height()- image.height()) / 2.0); - transform.scale(image.width() / (float)image_raw_size.width(), image.height() / (float)image_raw_size.height()); - r= transform.mapRect(r); - } - return r.contains(pt); - }; - - if (contains(boundingRect[currentIndex], e->pos())) { - if (currentIndex == 9) { - const QRect yes = QRect(707, 804, 531, 164); - Params().putBool("RecordFront", contains(yes, e->pos())); - } - currentIndex += 1; - } else if (currentIndex == (boundingRect.size() - 2) && contains(boundingRect.last(), e->pos())) { - currentIndex = 0; - } - - if (currentIndex >= (boundingRect.size() - 1)) { - emit completedTraining(); - } else { - update(); - } -} - -void TrainingGuide::showEvent(QShowEvent *event) { - currentIndex = 0; - click_timer.start(); -} - -QImage TrainingGuide::loadImage(int id) { - QImage img(img_path + QString("step%1.png").arg(id)); - image_raw_size = img.size(); - if (image_raw_size != rect().size()) { - img = img.scaled(width(), height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - return img; -} - -void TrainingGuide::paintEvent(QPaintEvent *event) { - QPainter painter(this); - - QRect bg(0, 0, painter.device()->width(), painter.device()->height()); - painter.fillRect(bg, QColor("#000000")); - - image = loadImage(currentIndex); - QRect rect(image.rect()); - rect.moveCenter(bg.center()); - painter.drawImage(rect.topLeft(), image); - - // progress bar - if (currentIndex > 0 && currentIndex < (boundingRect.size() - 2)) { - const int h = 20; - const int w = (currentIndex / (float)(boundingRect.size() - 2)) * width(); - painter.fillRect(QRect(0, height() - h, w, h), QColor("#465BEA")); - } -} - -void TermsPage::showEvent(QShowEvent *event) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(45, 35, 45, 45); - main_layout->setSpacing(0); - - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(165, 165, 165, 0); - main_layout->addLayout(vlayout); - - QLabel *title = new QLabel(tr("Welcome to openpilot")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addSpacing(90); - QLabel *desc = new QLabel(tr("You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 80px; font-weight: 300;"); - vlayout->addWidget(desc, 0); - - vlayout->addStretch(); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setMargin(0); - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *decline_btn = new QPushButton(tr("Decline")); - buttons->addWidget(decline_btn); - QObject::connect(decline_btn, &QPushButton::clicked, this, &TermsPage::declinedTerms); - - accept_btn = new QPushButton(tr("Agree")); - accept_btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - buttons->addWidget(accept_btn); - QObject::connect(accept_btn, &QPushButton::clicked, this, &TermsPage::acceptedTerms); -} - -void DeclinePage::showEvent(QShowEvent *event) { - if (layout()) { - return; - } - - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(45); - main_layout->setSpacing(40); - - QLabel *text = new QLabel(this); - text->setText(tr("You must accept the Terms and Conditions in order to use openpilot.")); - text->setStyleSheet(R"(font-size: 80px; font-weight: 300; margin: 200px;)"); - text->setWordWrap(true); - main_layout->addWidget(text, 0, Qt::AlignCenter); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *back_btn = new QPushButton(tr("Back")); - buttons->addWidget(back_btn); - - QObject::connect(back_btn, &QPushButton::clicked, this, &DeclinePage::getBack); - - QPushButton *uninstall_btn = new QPushButton(tr("Decline, uninstall %1").arg(getBrand())); - uninstall_btn->setStyleSheet("background-color: #B73D3D"); - buttons->addWidget(uninstall_btn); - QObject::connect(uninstall_btn, &QPushButton::clicked, [=]() { - Params().putBool("DoUninstall", true); - }); -} - -void OnboardingWindow::updateActiveScreen() { - if (!accepted_terms) { - setCurrentIndex(0); - } else if (!training_done) { - setCurrentIndex(1); - } else { - emit onboardingDone(); - } -} - -OnboardingWindow::OnboardingWindow(QWidget *parent) : QStackedWidget(parent) { - std::string current_terms_version = params.get("TermsVersion"); - std::string current_training_version = params.get("TrainingVersion"); - accepted_terms = params.get("HasAcceptedTerms") == current_terms_version; - training_done = params.get("CompletedTrainingVersion") == current_training_version; - - TermsPage* terms = new TermsPage(this); - addWidget(terms); - connect(terms, &TermsPage::acceptedTerms, [=]() { - params.put("HasAcceptedTerms", current_terms_version); - accepted_terms = true; - updateActiveScreen(); - }); - connect(terms, &TermsPage::declinedTerms, [=]() { setCurrentIndex(2); }); - - TrainingGuide* tr = new TrainingGuide(this); - addWidget(tr); - connect(tr, &TrainingGuide::completedTraining, [=]() { - training_done = true; - params.put("CompletedTrainingVersion", current_training_version); - updateActiveScreen(); - }); - - DeclinePage* declinePage = new DeclinePage(this); - addWidget(declinePage); - connect(declinePage, &DeclinePage::getBack, [=]() { updateActiveScreen(); }); - - setStyleSheet(R"( - * { - color: white; - background-color: black; - } - QPushButton { - height: 160px; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #4F4F4F; - } - )"); - updateActiveScreen(); -} diff --git a/selfdrive/ui/qt/offroad/onboarding.h b/selfdrive/ui/qt/offroad/onboarding.h deleted file mode 100644 index db229c5fa..000000000 --- a/selfdrive/ui/qt/offroad/onboarding.h +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/qt_window.h" - -class TrainingGuide : public QFrame { - Q_OBJECT - -public: - explicit TrainingGuide(QWidget *parent = 0); - -private: - void showEvent(QShowEvent *event) override; - void paintEvent(QPaintEvent *event) override; - void mouseReleaseEvent(QMouseEvent* e) override; - QImage loadImage(int id); - - QImage image; - QSize image_raw_size; - int currentIndex = 0; - - // Bounding boxes for each training guide step - const QRect continueBtn = {1840, 0, 320, 1080}; - QVector boundingRect { - QRect(112, 804, 618, 164), - continueBtn, - continueBtn, - QRect(1641, 558, 210, 313), - QRect(1662, 528, 184, 108), - continueBtn, - QRect(1814, 621, 211, 170), - QRect(1350, 0, 497, 755), - QRect(1540, 386, 468, 238), - QRect(112, 804, 1126, 164), - QRect(1598, 199, 316, 333), - continueBtn, - QRect(1364, 90, 796, 990), - continueBtn, - QRect(1593, 114, 318, 853), - QRect(1379, 511, 391, 243), - continueBtn, - continueBtn, - QRect(630, 804, 626, 164), - QRect(108, 804, 426, 164), - }; - - const QString img_path = "../assets/training/"; - QElapsedTimer click_timer; - -signals: - void completedTraining(); -}; - - -class TermsPage : public QFrame { - Q_OBJECT - -public: - explicit TermsPage(QWidget *parent = 0) : QFrame(parent) {} - -private: - void showEvent(QShowEvent *event) override; - - QPushButton *accept_btn; - -signals: - void acceptedTerms(); - void declinedTerms(); -}; - -class DeclinePage : public QFrame { - Q_OBJECT - -public: - explicit DeclinePage(QWidget *parent = 0) : QFrame(parent) {} - -private: - void showEvent(QShowEvent *event) override; - -signals: - void getBack(); -}; - -class OnboardingWindow : public QStackedWidget { - Q_OBJECT - -public: - explicit OnboardingWindow(QWidget *parent = 0); - inline void showTrainingGuide() { setCurrentIndex(1); } - inline bool completed() const { return accepted_terms && training_done; } - -private: - void updateActiveScreen(); - - Params params; - bool accepted_terms = false, training_done = false; - -signals: - void onboardingDone(); -}; diff --git a/selfdrive/ui/qt/offroad/settings.cc b/selfdrive/ui/qt/offroad/settings.cc deleted file mode 100644 index 2816e3974..000000000 --- a/selfdrive/ui/qt/offroad/settings.cc +++ /dev/null @@ -1,897 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "common/watchdog.h" -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/network/networking.h" -#include "selfdrive/ui/qt/offroad/settings.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/prime.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" -#include "selfdrive/ui/qt/offroad/developer_panel.h" - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { - syncRhdToggle(); - - // param, title, desc, icon, restart needed - std::vector> toggle_defs{ - { - "OpenpilotEnabledToggle", - tr("Enable openpilot"), - tr("Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature."), - "../assets/icons/chffr_wheel.png", - true, - }, - { - "ExperimentalMode", - tr("Experimental Mode"), - "", - "../assets/icons/experimental_white.svg", - false, - }, - { - "SafeMode", - tr("Safe Mode"), - tr("Temporarily force driving-affecting StarPilot settings back to safe defaults, stock tuning, and the branch default model until disabled."), - "../assets/icons/warning.png", - true, - }, - { - "SimpleMode", - tr("Simple Mode"), - tr("Use a more stock-like Qt interface by hiding most branch-specific UI, theme, sound, and alert styling. This only changes presentation and does not change driving behavior."), - "../assets/icons/settings.png", - false, - }, - { - "DisengageOnAccelerator", - tr("Disengage on Accelerator Pedal"), - tr("When enabled, pressing the accelerator pedal will disengage openpilot."), - "../assets/icons/disengage_on_accelerator.svg", - false, - }, - { - "IsLdwEnabled", - tr("Enable Lane Departure Warnings"), - tr("Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)."), - "../assets/icons/warning.png", - false, - }, - { - "AlwaysOnDM", - tr("Always-On Driver Monitoring"), - tr("Enable driver monitoring even when openpilot is not engaged."), - "../assets/icons/monitoring.png", - false, - }, - { - "IsRHD", - tr("Right Hand Driving"), - tr("Use right-hand-drive driver monitoring. This follows the auto-detected side until changed manually."), - "../assets/icons/monitoring.png", - false, - }, - { - "RecordFront", - tr("Record and Upload Driver Camera"), - tr("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), - "../assets/icons/monitoring.png", - true, - }, - { - "RecordAudio", - tr("Record and Upload Microphone Audio"), - tr("Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect."), - "../assets/icons/microphone.png", - true, - }, - { - "IsMetric", - tr("Use Metric System"), - tr("Display speed in km/h instead of mph."), - "../assets/icons/metric.png", - false, - }, - }; - - - std::vector longi_button_texts{tr("Aggressive"), tr("Standard"), tr("Relaxed")}; - long_personality_setting = new ButtonParamControl("LongitudinalPersonality", tr("Driving Personality"), - tr("Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " - "In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " - "your steering wheel distance button."), - "../assets/icons/speed_limit.png", - longi_button_texts); - - // set up uiState update for personality setting - QObject::connect(uiState(), &UIState::uiUpdate, this, &TogglesPanel::updateState); - - for (auto &[param, title, desc, icon, needs_restart] : toggle_defs) { - auto toggle = new ParamControl(param, title, desc, icon, this); - - bool locked = params.getBool((param + "Lock").toStdString()); - toggle->setEnabled(!locked); - - if (needs_restart && !locked) { - toggle->setDescription(toggle->getDescription() + tr(" Changing this setting will restart openpilot if the car is powered on.")); - - QObject::connect(uiState(), &UIState::engagedChanged, [toggle](bool engaged) { - toggle->setEnabled(!engaged); - }); - - QObject::connect(toggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("OnroadCycleRequested", true); - }); - } - - if (param == "SimpleMode") { - QObject::connect(toggle, &ParamControl::toggleFlipped, this, [this](bool state) { - updateToggles(); - emit simpleModeChanged(state); - }); - } - - if (param == "IsRHD") { - QObject::connect(toggle, &ParamControl::toggleFlipped, this, [this](bool state) { - params.putBool("IsRHD", state); - params.putBool("IsRHDOverride", true); - }); - } - - addItem(toggle); - toggles[param.toStdString()] = toggle; - - // insert longitudinal personality after NDOG toggle - if (param == "DisengageOnAccelerator") { - addItem(long_personality_setting); - } - } - - // Toggles with confirmation dialogs - toggles["ExperimentalMode"]->setActiveIcon("../assets/icons/experimental.svg"); - toggles["ExperimentalMode"]->setConfirmation(true, true); - - connect(toggles["IsMetric"], &ToggleControl::toggleFlipped, [=](bool isMetric) { - updateMetric(isMetric); - }); -} - -void TogglesPanel::syncRhdToggle() { - if (!params.getBool("IsRHDOverride")) { - params.putBool("IsRHD", params.getBool("IsRhdDetected")); - } -} - -void TogglesPanel::updateState(const UIState &s) { - const SubMaster &sm = *(s.sm); - - if (sm.updated("selfdriveState")) { - auto personality = sm["selfdriveState"].getSelfdriveState().getPersonality(); - if (personality != s.scene.personality && s.scene.started && isVisible()) { - long_personality_setting->setCheckedButton(static_cast(personality)); - } - uiState()->scene.personality = personality; - } -} - -void TogglesPanel::expandToggleDescription(const QString ¶m) { - toggles[param.toStdString()]->showDescription(); -} - -void TogglesPanel::scrollToToggle(const QString ¶m) { - if (auto it = toggles.find(param.toStdString()); it != toggles.end()) { - auto scroll_area = qobject_cast(parent()->parent()); - if (scroll_area) { - scroll_area->ensureWidgetVisible(it->second); - } - } -} - -void TogglesPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void TogglesPanel::updateToggles() { - syncRhdToggle(); - - const bool showAllToggles = params.getBool("ShowAllToggles"); - const bool safe_mode = params.getBool("SafeMode"); - const bool simple_mode = params.getBool("SimpleMode"); - if (safe_mode) { - if (params.getBool("ExperimentalMode")) { - params.putBool("ExperimentalMode", false); - } - if (params.getInt("LongitudinalPersonality") != static_cast(cereal::LongitudinalPersonality::RELAXED)) { - params.putInt("LongitudinalPersonality", static_cast(cereal::LongitudinalPersonality::RELAXED)); - } - } - auto experimental_mode_toggle = toggles["ExperimentalMode"]; - const QString e2e_description = QString("%1
" - "

%2


" - "%3
" - "

%4


" - "%5
") - .arg(tr("openpilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. Experimental features are listed below:")) - .arg(tr("End-to-End Longitudinal Control")) - .arg(tr("Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " - "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " - "mistakes should be expected.")) - .arg(tr("New Driving Visualization")) - .arg(tr("The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner.")); - - const bool is_release = false; - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (hasLongitudinalControl(CP) || showAllToggles) { - // normal description and toggle - experimental_mode_toggle->setEnabled(!safe_mode); - experimental_mode_toggle->setDescription(e2e_description); - long_personality_setting->setEnabled(!safe_mode); - if (safe_mode) { - long_personality_setting->setCheckedButton(static_cast(cereal::LongitudinalPersonality::RELAXED)); - } - } else { - // no long for now - experimental_mode_toggle->setEnabled(false); - long_personality_setting->setEnabled(false); - params.remove("ExperimentalMode"); - - const QString unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control."); - - QString long_desc = unavailable + " " + \ - tr("openpilot longitudinal control may come in a future update."); - if (CP.getAlphaLongitudinalAvailable()) { - if (is_release) { - long_desc = unavailable + " " + tr("An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches."); - } else { - long_desc = tr("Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode."); - } - } - experimental_mode_toggle->setDescription("" + long_desc + "

" + e2e_description); - } - - experimental_mode_toggle->refresh(); - } else { - experimental_mode_toggle->setDescription(e2e_description); - } - - if (safe_mode) { - experimental_mode_toggle->setEnabled(false); - long_personality_setting->setEnabled(false); - long_personality_setting->setCheckedButton(static_cast(cereal::LongitudinalPersonality::RELAXED)); - } - - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - auto disengage_on_accelerator_toggle = toggles["DisengageOnAccelerator"]; - disengage_on_accelerator_toggle->setVisible(showAllToggles || !starpilot_toggles.value("always_on_lateral").toBool()); - auto driver_camera_toggle = toggles["RecordFront"]; - driver_camera_toggle->setVisible(showAllToggles || !starpilot_toggles.value("no_logging").toBool()); - experimental_mode_toggle->setVisible(showAllToggles || !starpilot_toggles.value("conditional_experimental_mode").toBool()); - auto record_audio_toggle = toggles["RecordAudio"]; - record_audio_toggle->setVisible(showAllToggles || !starpilot_toggles.value("no_logging").toBool()); - toggles["IsRHD"]->refresh(); - - auto safe_mode_toggle = toggles["SafeMode"]; - if (safe_mode_toggle != nullptr) { - safe_mode_toggle->setVisible(!simple_mode); - } -} - -GalaxyQRPopup::GalaxyQRPopup(const QString &url, QWidget *parent) : DialogBase(parent) { - setStyleSheet("GalaxyQRPopup { background-color: #1a1a30; }"); - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setAlignment(Qt::AlignCenter); - layout->setSpacing(30); - layout->setContentsMargins(60, 40, 60, 40); - - auto qr = qrcodegen::QrCode::encodeText(url.toUtf8().constData(), qrcodegen::QrCode::Ecc::LOW); - const int qr_size = qr.getSize(); - const int quiet_zone_modules = 4; - const int qr_display_size = 520; - const int image_size = qr_size + 2 * quiet_zone_modules; - QImage image(image_size, image_size, QImage::Format_RGB32); - image.fill(qRgb(255, 255, 255)); - for (int y = 0; y < qr_size; ++y) { - for (int x = 0; x < qr_size; ++x) { - image.setPixel(x + quiet_zone_modules, y + quiet_zone_modules, - qr.getModule(x, y) ? qRgb(0, 0, 0) : qRgb(255, 255, 255)); - } - } - - QLabel *title = new QLabel(tr("Scan to open Galaxy"), this); - title->setStyleSheet("font-size: 52px; font-weight: bold; color: white;"); - title->setAlignment(Qt::AlignCenter); - layout->addWidget(title); - - QLabel *qr_label = new QLabel(this); - qr_label->setPixmap(QPixmap::fromImage( - image.scaled(qr_display_size, qr_display_size, Qt::KeepAspectRatio), Qt::MonoOnly)); - qr_label->setAlignment(Qt::AlignCenter); - layout->addWidget(qr_label); - - QLabel *url_label = new QLabel(url, this); - url_label->setStyleSheet("font-size: 36px; color: #8b6cc5;"); - url_label->setAlignment(Qt::AlignCenter); - layout->addWidget(url_label); - - QLabel *hint = new QLabel(tr("Tap anywhere to dismiss"), this); - hint->setStyleSheet("font-size: 28px; color: #7e7e98;"); - hint->setAlignment(Qt::AlignCenter); - layout->addWidget(hint); -} - -DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { - setSpacing(50); - addItem(new LabelControl(tr("Dongle ID"), getDongleId().value_or(tr("N/A")))); - addItem(new LabelControl(tr("Serial"), params.get("HardwareSerial").c_str())); - - pair_device = new ButtonControl(tr("Pair Device"), tr("PAIR"), - useKonikServer() ? tr("Pair your device with Konik connect (stable.konik.ai).") : tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - connect(pair_device, &ButtonControl::clicked, [=]() { - PairingPopup popup(this); - popup.exec(); - }); - addItem(pair_device); - - const std::string galaxy_dir = Hardware::PC() ? (Path::comma_home() + "/starpilot/data/galaxy") : "/data/galaxy"; - const std::string galaxy_auth_path = galaxy_dir + "/glxyauth"; - const std::string galaxy_session_path = galaxy_dir + "/glxysession"; - const std::string galaxy_slug_path = galaxy_dir + "/glxyslug"; - - auto showGalaxyQR = [=]() { - std::string slug = util::read_file(galaxy_slug_path); - if (slug.empty()) { - ConfirmationDialog::alert(tr("Galaxy is not paired yet."), this); - return; - } - - GalaxyQRPopup popup("https://galaxy.firestar.link/" + QString::fromStdString(slug), this); - popup.exec(); - }; - - pair_galaxy = new ButtonControl(tr("Galaxy"), tr("PAIR"), tr("Pair your device with Galaxy for remote access to The Galaxy.")); - connect(pair_galaxy, &ButtonControl::clicked, [=]() { - const std::string current_password = util::read_file(galaxy_auth_path); - if (current_password.empty()) { - QString new_password = InputDialog::getText( - tr("Set Galaxy Password"), this, - tr("Set a password to secure your Galaxy access. (Min 6 characters)"), - false, 6); - if (new_password.isEmpty()) { - return; - } - - std::string hash = QCryptographicHash::hash(new_password.toUtf8(), QCryptographicHash::Sha256).toHex().toStdString(); - util::create_directories(galaxy_dir, 0775); - util::write_file(galaxy_auth_path.c_str(), hash.data(), hash.size(), O_WRONLY | O_CREAT | O_TRUNC); - - QByteArray session_bytes(32, 0); - QRandomGenerator::securelySeeded().fillRange(reinterpret_cast(session_bytes.data()), 8); - std::string session_token = session_bytes.toHex().toStdString(); - util::write_file(galaxy_session_path.c_str(), session_token.data(), session_token.size(), O_WRONLY | O_CREAT | O_TRUNC); - - static constexpr char charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - std::string slug(16, '\0'); - auto *rng = QRandomGenerator::global(); - for (int i = 0; i < 16; ++i) { - slug[i] = charset[rng->bounded(62)]; - } - util::write_file(galaxy_slug_path.c_str(), slug.data(), slug.size(), O_WRONLY | O_CREAT | O_TRUNC); - - pair_galaxy->setText(tr("UNPAIR")); - galaxy_qr_btn->setVisible(true); - showGalaxyQR(); - return; - } - - if (ConfirmationDialog::confirm(tr("Are you sure you want to unpair from Galaxy?"), tr("Unpair"), this)) { - std::remove(galaxy_auth_path.c_str()); - std::remove(galaxy_session_path.c_str()); - std::remove(galaxy_slug_path.c_str()); - pair_galaxy->setText(tr("PAIR")); - galaxy_qr_btn->setVisible(false); - } - }); - - galaxy_qr_btn = new QPushButton(tr("QR")); - galaxy_qr_btn->setFixedSize(250, 100); - galaxy_qr_btn->setStyleSheet(R"( - QPushButton { background-color: #393939; color: #E4E4E4; border-radius: 50px; font-size: 35px; font-weight: 500; } - QPushButton:pressed { background-color: #4a4a4a; } - )"); - galaxy_qr_btn->setVisible(false); - connect(galaxy_qr_btn, &QPushButton::clicked, showGalaxyQR); - if (QHBoxLayout *hlayout = pair_galaxy->findChild()) { - hlayout->insertWidget(3, galaxy_qr_btn); - } - - const bool galaxy_paired = !util::read_file(galaxy_auth_path).empty(); - pair_galaxy->setText(galaxy_paired ? tr("UNPAIR") : tr("PAIR")); - galaxy_qr_btn->setVisible(galaxy_paired); - addItem(pair_galaxy); - - // offroad-only buttons - - auto dcamBtn = new ButtonControl(tr("Driver Camera"), tr("PREVIEW"), - tr("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)")); - connect(dcamBtn, &ButtonControl::clicked, [=]() { emit showDriverView(); }); - addItem(dcamBtn); - - resetDmCalibBtn = new ButtonControl( - tr("Reset Driver Monitoring"), - tr("RESET"), - tr("Clears the saved driver monitoring wheel-side calibration and any manual right-hand-driving override if the device thinks you're seated on the wrong side. " - "Resetting will restart openpilot if the car is powered on.") - ); - connect(resetDmCalibBtn, &ButtonControl::clicked, [&]() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset driver monitoring calibration?"), tr("Reset"), this)) { - if (!uiState()->engaged()) { - params.remove("IsRhdDetected"); - params.remove("IsRHD"); - params.remove("IsRHDOverride"); - params.putBool("OnroadCycleRequested", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reset Driver Monitoring"), this); - } - }); - addItem(resetDmCalibBtn); - - resetCalibBtn = new ButtonControl(tr("Reset Calibration"), tr("RESET"), ""); - connect(resetCalibBtn, &ButtonControl::showDescriptionEvent, this, &DevicePanel::updateCalibDescription); - connect(resetCalibBtn, &ButtonControl::clicked, [&]() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset calibration?"), tr("Reset"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.remove("CalibrationParams"); - params.remove("LiveTorqueParameters"); - params.remove("LiveParameters"); - params.remove("LiveParametersV2"); - params.remove("LiveDelay"); - params.putBool("OnroadCycleRequested", true); - updateCalibDescription(); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reset Calibration"), this); - } - }); - addItem(resetCalibBtn); - - auto retrainingBtn = new ButtonControl(tr("Review Training Guide"), tr("REVIEW"), tr("Review the rules, features, and limitations of openpilot")); - connect(retrainingBtn, &ButtonControl::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { - emit reviewTrainingGuide(); - } - }); - addItem(retrainingBtn); - - if (Hardware::TICI()) { - auto regulatoryBtn = new ButtonControl(tr("Regulatory"), tr("VIEW"), ""); - connect(regulatoryBtn, &ButtonControl::clicked, [=]() { - const std::string txt = util::read_file("../assets/offroad/fcc.html"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - addItem(regulatoryBtn); - } - - auto translateBtn = new ButtonControl(tr("Change Language"), tr("CHANGE"), ""); - connect(translateBtn, &ButtonControl::clicked, [=]() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); - if (!selection.isEmpty()) { - // put language setting, exit Qt UI, and trigger fast restart - params.put("LanguageSetting", langs[selection].toStdString()); - qApp->exit(18); - watchdog_kick(0); - } - }); - addItem(translateBtn); - - QObject::connect(uiState()->prime_state, &PrimeState::changed, [this] (PrimeState::Type type) { - pair_device->setVisible(type == PrimeState::PRIME_TYPE_UNPAIRED); - }); - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - for (auto btn : findChildren()) { - if (btn != pair_device && btn != resetCalibBtn && btn != resetDmCalibBtn) { - btn->setEnabled(offroad); - } - } - }); - - // power buttons - QHBoxLayout *power_layout = new QHBoxLayout(); - power_layout->setSpacing(30); - - QPushButton *reboot_btn = new QPushButton(tr("Reboot")); - reboot_btn->setObjectName("reboot_btn"); - power_layout->addWidget(reboot_btn); - QObject::connect(reboot_btn, &QPushButton::clicked, this, &DevicePanel::reboot); - - QPushButton *poweroff_btn = new QPushButton(tr("Power Off")); - poweroff_btn->setObjectName("poweroff_btn"); - power_layout->addWidget(poweroff_btn); - QObject::connect(poweroff_btn, &QPushButton::clicked, this, &DevicePanel::poweroff); - - if (!Hardware::PC()) { - connect(uiState(), &UIState::offroadTransition, poweroff_btn, &QPushButton::setVisible); - } - - setStyleSheet(R"( - #reboot_btn { height: 120px; border-radius: 15px; background-color: #393939; } - #reboot_btn:pressed { background-color: #4a4a4a; } - #poweroff_btn { height: 120px; border-radius: 15px; background-color: #E22C2C; } - #poweroff_btn:pressed { background-color: #FF2424; } - )"); - addItem(power_layout); -} - -void DevicePanel::updateCalibDescription() { - QString desc = tr("openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."); - std::string calib_bytes = params.get("CalibrationParams"); - if (!calib_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(calib_bytes.data(), calib_bytes.size())); - auto calib = cmsg.getRoot().getLiveCalibration(); - if (calib.getCalStatus() != cereal::LiveCalibrationData::Status::UNCALIBRATED) { - double pitch = calib.getRpyCalib()[1] * (180 / M_PI); - double yaw = calib.getRpyCalib()[2] * (180 / M_PI); - desc += tr(" Your device is pointed %1° %2 and %3° %4.") - .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? tr("down") : tr("up"), - QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? tr("left") : tr("right")); - } - } catch (kj::Exception) { - qInfo() << "invalid CalibrationParams"; - } - } - - int lag_perc = 0; - std::string lag_bytes = params.get("LiveDelay"); - if (!lag_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(lag_bytes.data(), lag_bytes.size())); - lag_perc = cmsg.getRoot().getLiveDelay().getCalPerc(); - } catch (kj::Exception) { - qInfo() << "invalid LiveDelay"; - } - } - if (lag_perc < 100) { - desc += tr("\n\nSteering lag calibration is %1% complete.").arg(lag_perc); - } else { - desc += tr("\n\nSteering lag calibration is complete."); - } - - std::string torque_bytes = params.get("LiveTorqueParameters"); - if (!torque_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(torque_bytes.data(), torque_bytes.size())); - auto torque = cmsg.getRoot().getLiveTorqueParameters(); - // don't add for non-torque cars - if (torque.getUseParams()) { - int torque_perc = torque.getCalPerc(); - if (torque_perc < 100) { - desc += tr(" Steering torque response calibration is %1% complete.").arg(torque_perc); - } else { - desc += tr(" Steering torque response calibration is complete."); - } - } - } catch (kj::Exception) { - qInfo() << "invalid LiveTorqueParameters"; - } - } - - desc += "\n\n"; - desc += tr("openpilot is continuously calibrating, resetting is rarely required. " - "Resetting calibration will restart openpilot if the car is powered on."); - resetCalibBtn->setDescription(desc); -} - -void DevicePanel::reboot() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reboot?"), tr("Reboot"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoReboot", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reboot"), this); - } -} - -void DevicePanel::poweroff() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to power off?"), tr("Power Off"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoShutdown", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Power Off"), this); - } -} - -void SettingsWindow::showEvent(QShowEvent *event) { - setCurrentPanel(0); -} - -void SettingsWindow::hideEvent(QHideEvent *event) { - closePanel(); - closeSubPanel(); - - panelOpen = false; - subPanelOpen = false; - subSubPanelOpen = false; - subSubSubPanelOpen = false; - - updateStarPilotToggles(); -} - -void SettingsWindow::setCurrentPanel(int index, const QString ¶m) { - if (!param.isEmpty()) { - // Check if param ends with "Panel" to determine if it's a panel name - if (param.endsWith("Panel")) { - QString panelName = param; - panelName.chop(5); // Remove "Panel" suffix - - // Find the panel by name - for (int i = 0; i < nav_btns->buttons().size(); i++) { - if (nav_btns->buttons()[i]->text() == tr(panelName.toStdString().c_str())) { - index = i; - break; - } - } - } else { - emit expandToggleDescription(param); - emit scrollToToggle(param); - } - } - - panel_widget->setCurrentIndex(index); - nav_btns->buttons()[index]->setChecked(true); -} - -SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { - - // setup two main layouts - sidebar_widget = new QWidget; - QVBoxLayout *sidebar_layout = new QVBoxLayout(sidebar_widget); - panel_widget = new QStackedWidget(); - - // close button - QPushButton *close_btn = new QPushButton(tr("← Back")); - close_btn->setStyleSheet(R"( - QPushButton { - font-size: 50px; - border-radius: 25px; - background-color: #292929; - font-weight: 500; - } - QPushButton:pressed { - background-color: #ADADAD; - } - )"); - close_btn->setFixedSize(300, 125); - sidebar_layout->addSpacing(10); - sidebar_layout->addWidget(close_btn, 0, Qt::AlignRight); - QObject::connect(close_btn, &QPushButton::clicked, [this]() { - if (subSubSubPanelOpen) { - closeSubSubSubPanel(); - subSubSubPanelOpen = false; - } else if (subSubPanelOpen) { - closeSubSubPanel(); - subSubPanelOpen = false; - } else if (subPanelOpen) { - closeSubPanel(); - subPanelOpen = false; - } else if (panelOpen) { - closePanel(); - panelOpen = false; - } else { - closeSettings(); - } - }); - - // setup panels - DevicePanel *device = new DevicePanel(this); - QObject::connect(device, &DevicePanel::reviewTrainingGuide, this, &SettingsWindow::reviewTrainingGuide); - QObject::connect(device, &DevicePanel::showDriverView, this, &SettingsWindow::showDriverView); - - TogglesPanel *toggles = new TogglesPanel(this); - QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); - QObject::connect(this, &SettingsWindow::scrollToToggle, toggles, &TogglesPanel::scrollToToggle); - - auto networking = new Networking(this); - QObject::connect(uiState()->prime_state, &PrimeState::changed, networking, &Networking::setPrimeType); - - QObject::connect(toggles, &TogglesPanel::updateMetric, this, &SettingsWindow::updateMetric); - - StarPilotSettingsWindow *starpilotSettingsWindow = new StarPilotSettingsWindow(this); - QObject::connect(starpilotSettingsWindow, &StarPilotSettingsWindow::openPanel, [this]() {panelOpen=true;}); - QObject::connect(starpilotSettingsWindow, &StarPilotSettingsWindow::openSubPanel, [this]() {subPanelOpen=true;}); - QObject::connect(starpilotSettingsWindow, &StarPilotSettingsWindow::openSubSubPanel, [this]() {subSubPanelOpen=true;}); - QObject::connect(starpilotSettingsWindow, &StarPilotSettingsWindow::openSubSubSubPanel, [this]() {subSubSubPanelOpen=true;}); - QObject::connect(starpilotSettingsWindow, &StarPilotSettingsWindow::tuningLevelChanged, this, &SettingsWindow::updateDeveloperToggle); - - DeveloperPanel *developerPanel = new DeveloperPanel(this); - QObject::connect(developerPanel, &DeveloperPanel::openSubPanel, [this]() {subPanelOpen=true;}); - QObject::connect(developerPanel, &DeveloperPanel::openSubSubPanel, [this]() {subSubPanelOpen=true;}); - QObject::connect(developerPanel, &DeveloperPanel::showAllTogglesChanged, [this]() { - updateDeveloperToggle(params.getInt("TuningLevel")); - }); - QObject::connect(toggles, &TogglesPanel::simpleModeChanged, [this](bool enabled) { - updateDeveloperToggle(params.getInt("TuningLevel")); - if (enabled && panel_widget->currentIndex() < nav_btns->buttons().size() && - nav_btns->buttons()[panel_widget->currentIndex()]->text() == tr("StarPilot")) { - setCurrentPanel(2); - } - }); - - QList> panels = { - {tr("Device"), device}, - {tr("Network"), networking}, - {tr("Toggles"), toggles}, - {tr("Software"), new SoftwarePanel(this)}, - {tr("Developer"), developerPanel}, - {tr("StarPilot"), starpilotSettingsWindow}, - }; - - nav_btns = new QButtonGroup(this); - for (auto &[name, panel] : panels) { - QPushButton *btn = new QPushButton(name); - btn->setCheckable(true); - btn->setChecked(nav_btns->buttons().size() == 0); - btn->setStyleSheet(R"( - QPushButton { - color: grey; - border: none; - background: none; - font-size: 65px; - font-weight: 500; - } - QPushButton:checked { - color: white; - } - QPushButton:pressed { - color: #ADADAD; - } - )"); - btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - nav_btns->addButton(btn); - sidebar_layout->addWidget(btn, 0, Qt::AlignRight); - - const int lr_margin = name != tr("Network") ? 50 : 0; // Network panel handles its own margins - panel->setContentsMargins(lr_margin, 25, lr_margin, 25); - - ScrollView *panel_frame = new ScrollView(panel, this); - panel_widget->addWidget(panel_frame); - - QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { - if (w->widget() == starpilotSettingsWindow) { - bool tuningLevelConfirmed = params.getBool("TuningLevelConfirmed"); - - if (!tuningLevelConfirmed) { - int starpilotHours = QJsonDocument::fromJson(QString::fromStdString(params.get("StarPilotStats")).toUtf8()).object().value("StarPilotSeconds").toInt() / (60 * 60); - int openpilotHours = params.getInt("KonikMinutes") / 60 + params.getInt("openpilotMinutes") / 60; - - if (starpilotHours < 1 && openpilotHours < 100) { - if (openpilotHours < 10) { - if (ConfirmationDialog::alert(tr("Welcome to StarPilot! Since you're new to openpilot, the \"Minimal\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 0); - } - } else { - if (ConfirmationDialog::alert(tr("Welcome to StarPilot! Since you're new to StarPilot, the \"Minimal\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 0); - } - } - } else if (starpilotHours < 50 && openpilotHours < 100) { - if (ConfirmationDialog::alert(tr("Since you're fairly new to StarPilot, the \"Minimal\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 0); - } - } else if (starpilotHours < 100) { - if (openpilotHours >= 100) { - if (ConfirmationDialog::alert(tr("Since you're experienced with openpilot, the \"Standard\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 1); - } - } else { - if (ConfirmationDialog::alert(tr("Since you're experienced with StarPilot, the \"Standard\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 1); - } - } - } else if (starpilotHours >= 100) { - if (ConfirmationDialog::alert(tr("Since you're very experienced with StarPilot, the \"Advanced\" toggle preset has been applied, but you can change this at any time via the \"Tuning Level\" button!"), this, true)) { - params.putBool("TuningLevelConfirmed", true); - params.putInt("TuningLevel", 2); - } - } - updateTuningLevel(); - } - } - - if (subSubSubPanelOpen) { - closeSubSubSubPanel(); - subSubSubPanelOpen = false; - } - if (subSubPanelOpen) { - closeSubSubPanel(); - subSubPanelOpen = false; - } - if (subPanelOpen) { - closeSubPanel(); - subPanelOpen = false; - } - if (panelOpen) { - closePanel(); - panelOpen = false; - } - btn->setChecked(true); - panel_widget->setCurrentWidget(w); - }); - } - sidebar_layout->setContentsMargins(50, 50, 100, 50); - - // main settings layout, sidebar + main panel - QHBoxLayout *main_layout = new QHBoxLayout(this); - - sidebar_widget->setFixedWidth(500); - main_layout->addWidget(sidebar_widget); - main_layout->addWidget(panel_widget); - - setStyleSheet(R"( - * { - color: white; - font-size: 50px; - } - SettingsWindow { - background-color: black; - } - QStackedWidget, ScrollView { - background-color: #292929; - border-radius: 30px; - } - )"); - - updateDeveloperToggle(params.getInt("TuningLevel")); -} - -void SettingsWindow::updateDeveloperToggle(int tuningLevel) { - for (QAbstractButton *btn : nav_btns->buttons()) { - if (btn->text() == tr("Developer")) { - btn->setVisible(tuningLevel >= 3 || params.getBool("ShowAllToggles")); - } else if (btn->text() == tr("StarPilot")) { - btn->setVisible(!params.getBool("SimpleMode")); - } - } -} diff --git a/selfdrive/ui/qt/offroad/settings.h b/selfdrive/ui/qt/offroad/settings.h deleted file mode 100644 index 7630c296e..000000000 --- a/selfdrive/ui/qt/offroad/settings.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -// ********** settings window + top-level panels ********** -class SettingsWindow : public QFrame { - Q_OBJECT - -public: - explicit SettingsWindow(QWidget *parent = 0); - void setCurrentPanel(int index, const QString ¶m = ""); - -protected: - void showEvent(QShowEvent *event) override; - - void hideEvent(QHideEvent *event) override; - -signals: - void closeSettings(); - void reviewTrainingGuide(); - void showDriverView(); - void expandToggleDescription(const QString ¶m); - void scrollToToggle(const QString ¶m); - - void closePanel(); - void closeSubPanel(); - void closeSubSubPanel(); - void closeSubSubSubPanel(); - void updateMetric(bool isMetric, bool bootRun=false); - void updateTuningLevel(); - -private: - QPushButton *sidebar_alert_widget; - QWidget *sidebar_widget; - QButtonGroup *nav_btns; - QStackedWidget *panel_widget; - - void updateDeveloperToggle(int tuningLevel); - - bool panelOpen; - bool subPanelOpen; - bool subSubPanelOpen; - bool subSubSubPanelOpen; - - Params params; -}; - -class GalaxyQRPopup : public DialogBase { - Q_OBJECT - -public: - explicit GalaxyQRPopup(const QString &url, QWidget *parent = nullptr); - -protected: - void mousePressEvent(QMouseEvent *event) override { - reject(); - DialogBase::mousePressEvent(event); - } -}; - -class DevicePanel : public ListWidget { - Q_OBJECT -public: - explicit DevicePanel(SettingsWindow *parent); - -signals: - void reviewTrainingGuide(); - void showDriverView(); - -private slots: - void poweroff(); - void reboot(); - void updateCalibDescription(); - -private: - Params params; - ButtonControl *pair_device; - ButtonControl *pair_galaxy; - QPushButton *galaxy_qr_btn; - ButtonControl *resetCalibBtn; - ButtonControl *resetDmCalibBtn; -}; - -class TogglesPanel : public ListWidget { - Q_OBJECT -public: - explicit TogglesPanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -signals: - void updateMetric(bool metric, bool bootRun=false); - void simpleModeChanged(bool enabled); - -public slots: - void expandToggleDescription(const QString ¶m); - void scrollToToggle(const QString ¶m); - -private slots: - void updateState(const UIState &s); - -private: - Params params; - std::map toggles; - ButtonParamControl *long_personality_setting; - - void syncRhdToggle(); - void updateToggles(); -}; - -class SoftwarePanel : public ListWidget { - Q_OBJECT -public: - explicit SoftwarePanel(QWidget* parent = nullptr); - -private: - void showEvent(QShowEvent *event) override; - void updateLabels(); - void checkForUpdates(); - - bool is_onroad = false; - - QLabel *onroadLbl; - LabelControl *versionLbl; - ButtonControl *installBtn; - ButtonControl *downloadBtn; - ButtonControl *targetBranchBtn; - - Params params; - ParamWatcher *fs_watch; -}; diff --git a/selfdrive/ui/qt/offroad/software_settings.cc b/selfdrive/ui/qt/offroad/software_settings.cc deleted file mode 100644 index efb595286..000000000 --- a/selfdrive/ui/qt/offroad/software_settings.cc +++ /dev/null @@ -1,202 +0,0 @@ -#include "selfdrive/ui/qt/offroad/settings.h" - -#include -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/util.h" -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "system/hardware/hw.h" - - -void SoftwarePanel::checkForUpdates() { - std::system("pkill -SIGUSR1 -f system.updated.updated"); -} - -SoftwarePanel::SoftwarePanel(QWidget* parent) : ListWidget(parent) { - onroadLbl = new QLabel(tr("Updates are only downloaded while the car is off or in park.")); - onroadLbl->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; padding-top: 30px; padding-bottom: 30px;"); - addItem(onroadLbl); - - // current version - versionLbl = new LabelControl(tr("Current Version"), ""); - addItem(versionLbl); - - // automatic updates toggle - ParamControl *automaticUpdatesToggle = new ParamControl("AutomaticUpdates", tr("Automatically Update StarPilot"), - tr("Automatically update StarPilot when the vehicle is parked with an active internet connection."), ""); - automaticUpdatesToggle->setVisible(true); - addItem(automaticUpdatesToggle); - - // download update btn - downloadBtn = new ButtonControl(tr("Download"), tr("CHECK")); - connect(downloadBtn, &ButtonControl::clicked, [=]() { - downloadBtn->setEnabled(false); - if (downloadBtn->text() == tr("CHECK")) { - checkForUpdates(); - } else { - std::system("pkill -SIGHUP -f system.updated.updated"); - } - starpilotUIState()->params_memory.putBool("ManualUpdateInitiated", true); - }); - addItem(downloadBtn); - - // install update btn - installBtn = new ButtonControl(tr("Install Update"), tr("INSTALL")); - connect(installBtn, &ButtonControl::clicked, [=]() { - installBtn->setEnabled(false); - params.putBool("DoReboot", true); - }); - addItem(installBtn); - - // branch selecting - targetBranchBtn = new ButtonControl(tr("Target Branch"), tr("SELECT")); - connect(targetBranchBtn, &ButtonControl::clicked, [=]() { - auto current = params.get("GitBranch"); - QStringList branches = QString::fromStdString(params.get("UpdaterAvailableBranches")).split(","); - if (!isFrogsGoMoo()) { - branches.removeAll("StarPilot-Vetting"); - branches.removeAll("MAKE-PRS-HERE"); - } - for (QString b : {current.c_str(), "devel-staging", "devel", "nightly", "nightly-dev", "master"}) { - auto i = branches.indexOf(b); - if (i >= 0) { - branches.removeAt(i); - branches.insert(0, b); - } - } - - QString cur = QString::fromStdString(params.get("UpdaterTargetBranch")); - QString selection = MultiOptionDialog::getSelection(tr("Select a branch"), branches, cur, this); - if (!selection.isEmpty()) { - params.put("UpdaterTargetBranch", selection.toStdString()); - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - checkForUpdates(); - - if (selection != cur) { - if (StarPilotConfirmationDialog::yesorno(tr("This branch must be downloaded before switching. Would you like to download it now?"), this)) { - std::system("pkill -SIGHUP -f system.updated.updated"); - starpilotUIState()->params_memory.putBool("ManualUpdateInitiated", true); - } - } - } - }); - addItem(targetBranchBtn); - - // uninstall button - auto uninstallBtn = new ButtonControl(tr("Uninstall %1").arg(getBrand()), tr("UNINSTALL")); - connect(uninstallBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to uninstall?"), tr("Uninstall"), this)) { - if (StarPilotConfirmationDialog::yesorno(tr("Do you want to perform a full factory reset? All saved assets and settings will be permanently deleted!"), this)) { - if (StarPilotConfirmationDialog::yesorno(tr("This is a complete factory reset and cannot be undone. Are you absolutely sure you want to continue?"), this)) { - Params().clearAll(ParamKeyFlag::ALL); - } - } - params.putBool("DoUninstall", true); - } - }); - addItem(uninstallBtn); - - // error log button - auto errorLogBtn = new ButtonControl(tr("Error Log"), tr("VIEW"), tr("View the error log for openpilot crashes.")); - connect(errorLogBtn, &ButtonControl::clicked, [=]() { - std::string txt = util::read_file("/data/error_logs/error.txt"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - addItem(errorLogBtn); - - fs_watch = new ParamWatcher(this); - QObject::connect(fs_watch, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - updateLabels(); - }); - - connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - is_onroad = !offroad; - updateLabels(); - }); - - updateLabels(); -} - -void SoftwarePanel::showEvent(QShowEvent *event) { - // nice for testing on PC - installBtn->setEnabled(true); - - updateLabels(); - - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - if (starpilot_scene.online && params.get("UpdaterState") == "idle") { - checkForUpdates(); - } -} - -void SoftwarePanel::updateLabels() { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - bool parked = starpilot_scene.parked || isFrogsGoMoo(); - - // add these back in case the files got removed - fs_watch->addParam("LastUpdateTime"); - fs_watch->addParam("UpdateFailedCount"); - fs_watch->addParam("UpdaterState"); - fs_watch->addParam("UpdateAvailable"); - - if (!isVisible()) { - starpilot_scene.downloading_update = false; - return; - } - - // updater only runs offroad or when parked - onroadLbl->setVisible(is_onroad && !parked); - downloadBtn->setVisible(!is_onroad || parked); - - // download update - QString updater_state = QString::fromStdString(params.get("UpdaterState")); - bool failed = std::atoi(params.get("UpdateFailedCount").c_str()) > 0; - if (updater_state != "idle") { - downloadBtn->setEnabled(false); - downloadBtn->setValue(updater_state); - - starpilot_scene.downloading_update = true; - } else { - if (failed) { - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("failed to check for update")); - } else if (params.getBool("UpdaterFetchAvailable")) { - downloadBtn->setText(tr("DOWNLOAD")); - downloadBtn->setValue(tr("update available")); - } else { - QString lastUpdate = tr("never"); - auto tm = params.get("LastUpdateTime"); - if (!tm.empty()) { - lastUpdate = timeAgo(QDateTime::fromString(QString::fromStdString(tm + "Z"), Qt::ISODate)); - } - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("up to date, last checked %1").arg(lastUpdate)); - } - downloadBtn->setEnabled(true); - - starpilot_scene.downloading_update = false; - } - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - - // current + new versions - versionLbl->setText(formatStarPilotDisplayVersionDescription(QString::fromStdString(params.get("UpdaterCurrentDescription")))); - versionLbl->setDescription(QString::fromStdString(params.get("UpdaterCurrentReleaseNotes"))); - - installBtn->setVisible((!is_onroad || parked) && params.getBool("UpdateAvailable")); - installBtn->setValue(formatStarPilotDisplayVersionDescription(QString::fromStdString(params.get("UpdaterNewDescription")))); - installBtn->setDescription(QString::fromStdString(params.get("UpdaterNewReleaseNotes"))); - - update(); -} diff --git a/selfdrive/ui/qt/onroad/alerts.cc b/selfdrive/ui/qt/onroad/alerts.cc deleted file mode 100644 index d8244f34a..000000000 --- a/selfdrive/ui/qt/onroad/alerts.cc +++ /dev/null @@ -1,163 +0,0 @@ -#include "selfdrive/ui/qt/onroad/alerts.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -void OnroadAlerts::updateState(const UIState &s, const StarPilotUIState &fs) { - Alert a = getAlert(*(s.sm), *(fs.sm), s.scene.started_frame); - if (!alert.equal(a)) { - // Hide only incoming NORMAL alerts. Keep userPrompt/critical visible. - if (a.status == cereal::SelfdriveState::AlertStatus::NORMAL && starpilot_toggles.value("hide_alerts").toBool()) { - clear(); - } else { - alert = a; - update(); - } - } - - sidebarsOpen = fs.starpilot_scene.sidebars_open; -} - -void OnroadAlerts::clear() { - alert = {}; - update(); - - alertHeight = 0; -} - -OnroadAlerts::Alert OnroadAlerts::getAlert(const SubMaster &sm, const SubMaster &fpsm, uint64_t started_frame) { - const cereal::SelfdriveState::Reader &ss = sm["selfdriveState"].getSelfdriveState(); - const uint64_t selfdrive_frame = sm.rcv_frame("selfdriveState"); - - const cereal::StarPilotSelfdriveState::Reader &fpss = fpsm["starpilotSelfdriveState"].getStarpilotSelfdriveState(); - const bool starpilot_alert_received = fpsm.rcv_frame("starpilotSelfdriveState") > 0; - - Alert a = {}; - static QString crash_log_path = "/data/error_logs/error.txt"; - if (QFile::exists(crash_log_path)) { - if (starpilot_toggles.value("random_events").toBool()) { - a = {tr("openpilot crashed 💩"), - tr("Please post the \"Error Log\" in the StarPilot Discord!"), - "openpilotCrashedRandomEvent", - cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::CRITICAL}; - } else { - a = {tr("openpilot crashed"), - tr("Please post the \"Error Log\" in the StarPilot Discord!"), - "openpilotCrashed", - cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::CRITICAL}; - } - return a; - } else if (selfdrive_frame >= started_frame) { // Don't get old alert. - a = {ss.getAlertText1().cStr(), ss.getAlertText2().cStr(), - ss.getAlertType().cStr(), ss.getAlertSize(), ss.getAlertStatus()}; - - if (a.size == cereal::SelfdriveState::AlertSize::NONE && starpilot_alert_received) { - a = {fpss.getAlertText1().cStr(), fpss.getAlertText2().cStr(), - fpss.getAlertType().cStr(), static_cast(fpss.getAlertSize()), static_cast(fpss.getAlertStatus())}; - } - } - - if (!sm.updated("selfdriveState") && (sm.frame - started_frame) > 5 * UI_FREQ && !starpilot_toggles.value("force_onroad").toBool()) { - const int SELFDRIVE_STATE_TIMEOUT = 5; - const int ss_missing = (nanos_since_boot() - sm.rcv_time("selfdriveState")) / 1e9; - - // Handle selfdrive timeout - if (selfdrive_frame < started_frame) { - // car is started, but selfdriveState hasn't been seen at all - a = {tr("openpilot Unavailable"), tr("Waiting to start"), - "selfdriveWaiting", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } else if (ss_missing > SELFDRIVE_STATE_TIMEOUT && !Hardware::PC()) { - // car is started, but selfdrive is lagging or died - if (ss.getEnabled() && (ss_missing - SELFDRIVE_STATE_TIMEOUT) < 10) { - a = {tr("TAKE CONTROL IMMEDIATELY"), tr("System Unresponsive"), - "selfdriveUnresponsive", cereal::SelfdriveState::AlertSize::FULL, - cereal::SelfdriveState::AlertStatus::CRITICAL}; - } else { - a = {tr("System Unresponsive"), tr("Reboot Device"), - "selfdriveUnresponsivePermanent", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } - } - } - return a; -} - -void OnroadAlerts::paintEvent(QPaintEvent *event) { - if (alert.size == cereal::SelfdriveState::AlertSize::NONE) { - alertHeight = 0; - return; - } - static std::map alert_heights = { - {cereal::SelfdriveState::AlertSize::SMALL, 271}, - {cereal::SelfdriveState::AlertSize::MID, 420}, - {cereal::SelfdriveState::AlertSize::FULL, height()}, - }; - alertHeight = alert_heights[alert.size]; - int h = alertHeight; - - int margin = 40; - int radius = 30; - if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - margin = 0; - radius = 0; - } - alertHeight -= margin; - QRect r = QRect(0 + margin, height() - h + margin, width() - margin*2, h - margin*2); - - QPainter p(this); - const bool simple_mode = starpilot_toggles.value("simple_mode").toBool(); - QColor alert_color; - if (simple_mode) { - cereal::SelfdriveState::AlertStatus status = alert.status; - if (status == static_cast(cereal::StarPilotSelfdriveState::AlertStatus::STARPILOT)) { - status = cereal::SelfdriveState::AlertStatus::NORMAL; - } - alert_color = alert_colors.value(status, alert_colors.value(cereal::SelfdriveState::AlertStatus::NORMAL)); - } else { - alert_color = starpilot_alert_colors.value(static_cast(alert.status), - alert_colors.value(cereal::SelfdriveState::AlertStatus::NORMAL)); - } - - // draw background + gradient - p.setPen(Qt::NoPen); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - p.setBrush(QBrush(alert_color)); - p.drawRoundedRect(r, radius, radius); - - QLinearGradient g(0, r.y(), 0, r.bottom()); - g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.05)); - g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0.35)); - - p.setCompositionMode(QPainter::CompositionMode_DestinationOver); - p.setBrush(QBrush(g)); - p.drawRoundedRect(r, radius, radius); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - - // text - const QPoint c = r.center(); - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setRenderHint(QPainter::TextAntialiasing); - if (alert.size == cereal::SelfdriveState::AlertSize::SMALL) { - bool long_alert1 = alert.text1.length() > 40; - p.setFont(InterFont(long_alert1 && sidebarsOpen ? 64 : 74, QFont::DemiBold)); - p.drawText(r, Qt::AlignCenter, alert.text1); - } else if (alert.size == cereal::SelfdriveState::AlertSize::MID) { - bool long_alert1 = alert.text1.length() > 30; - p.setFont(InterFont(long_alert1 && sidebarsOpen ? 78 : 88, QFont::Bold)); - p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, alert.text1); - bool long_alert2 = alert.text2.length() > 40; - p.setFont(InterFont(long_alert2 && sidebarsOpen ? 56 : 66)); - p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, alert.text2); - } else if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - bool l = alert.text1.length() > 15; - p.setFont(InterFont(l ? 132 : 177, QFont::Bold)); - p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, alert.text1); - p.setFont(InterFont(88)); - p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, alert.text2); - } -} diff --git a/selfdrive/ui/qt/onroad/alerts.h b/selfdrive/ui/qt/onroad/alerts.h deleted file mode 100644 index 16a9234af..000000000 --- a/selfdrive/ui/qt/onroad/alerts.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/ui.h" - -class OnroadAlerts : public QWidget { - Q_OBJECT - -public: - OnroadAlerts(QWidget *parent = 0) : QWidget(parent) {} - void updateState(const UIState &s, const StarPilotUIState &fs); - void clear(); - - int alertHeight; - - QJsonObject starpilot_toggles; - -protected: - struct Alert { - QString text1; - QString text2; - QString type; - cereal::SelfdriveState::AlertSize size; - cereal::SelfdriveState::AlertStatus status; - - bool equal(const Alert &other) const { - return text1 == other.text1 && text2 == other.text2 && type == other.type && - size == other.size && status == other.status; - } - }; - - const QMap alert_colors = { - {cereal::SelfdriveState::AlertStatus::NORMAL, QColor(0x15, 0x15, 0x15, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::USER_PROMPT, QColor(0xDA, 0x6F, 0x25, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::CRITICAL, QColor(0xC9, 0x22, 0x31, 0xf1)}, - }; - - void paintEvent(QPaintEvent*) override; - OnroadAlerts::Alert getAlert(const SubMaster &sm, const SubMaster &fpsm, uint64_t started_frame); - - QColor bg; - Alert alert = {}; - - bool sidebarsOpen; - - const QMap starpilot_alert_colors = { - {cereal::StarPilotSelfdriveState::AlertStatus::NORMAL, QColor(0x15, 0x15, 0x15, 0xf1)}, - {cereal::StarPilotSelfdriveState::AlertStatus::USER_PROMPT, QColor(0xDA, 0x6F, 0x25, 0xf1)}, - {cereal::StarPilotSelfdriveState::AlertStatus::CRITICAL, QColor(0xC9, 0x22, 0x31, 0xf1)}, - {cereal::StarPilotSelfdriveState::AlertStatus::STARPILOT, QColor(0x17, 0x86, 0x44, 0xf1)}, - }; -}; diff --git a/selfdrive/ui/qt/onroad/annotated_camera.cc b/selfdrive/ui/qt/onroad/annotated_camera.cc deleted file mode 100644 index ad5ce5b6d..000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.cc +++ /dev/null @@ -1,281 +0,0 @@ - -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -constexpr int CAMERA_VIEW_NONE = 4; - -// Window that shows camera view and variety of info drawn on top -AnnotatedCameraWidget::AnnotatedCameraWidget(VisionStreamType type, QWidget *parent) - : fps_filter(UI_FREQ, 3, 1. / UI_FREQ), CameraWidget("camerad", type, parent) { - pm = std::make_unique(std::vector{"uiDebug"}); - - main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - main_layout->setSpacing(0); - - experimental_btn = new ExperimentalButton(this); - main_layout->addWidget(experimental_btn, 0, Qt::AlignTop | Qt::AlignRight); - - personality_btn = new DrivingPersonalityButton(this); - personality_btn->setVisible(false); - - for (int i = 0; i < static_cast(favorite_btns.size()); ++i) { - favorite_btns[i] = new FavoriteButton(i, this); - favorite_btns[i]->setVisible(false); - } - - screen_recorder = new ScreenRecorder(this); - screen_recorder->setVisible(false); -} - -bool AnnotatedCameraWidget::handleHudPress(const QPoint &pos) { - return hud.handleNavigationPress(pos); -} - -bool AnnotatedCameraWidget::handleHudRelease(const QPoint &pos) { - return hud.handleNavigationRelease(pos); -} - -void AnnotatedCameraWidget::updateState(const UIState &s, const StarPilotUIState &fs) { - // update engageability/experimental mode button - experimental_btn->updateState(s, fs); - dmon.updateState(s); - - const SubMaster &sm = *(s.sm); - - const cereal::CarState::Reader &carState = sm["carState"].getCarState(); - - static Params params; - const bool hide_steering_wheel = starpilot_toggles.value("hide_steering_wheel").toBool() || params.getBool("HideSteeringWheel"); - experimental_btn->setVisible(!hide_steering_wheel); - - const QPoint experimental_button_position = hide_steering_wheel - ? QPoint(width() - UI_BORDER_SIZE - btn_size, UI_BORDER_SIZE) - : QPoint(experimental_btn->x(), experimental_btn->y()); - starpilot_nvg->experimentalButtonPosition = experimental_button_position; - - std::vector visible_favorite_btns; - const bool favorites_anchor_ready = starpilot_nvg->dmIconPosition != QPoint(0, 0) && !starpilot_nvg->hideBottomIcons; - for (FavoriteButton *favorite_btn : favorite_btns) { - favorite_btn->updateState(); - if (favorites_anchor_ready && favorite_btn->shouldShow()) { - visible_favorite_btns.push_back(favorite_btn); - } else { - favorite_btn->setVisible(false); - } - } - - const bool onroad_distance_btn_enabled = favorites_anchor_ready && starpilot_toggles.value("onroad_distance_button").toBool(); - const int gap = UI_BORDER_SIZE / 2; - int controls_width = 0; - if (!visible_favorite_btns.empty()) { - controls_width = visible_favorite_btns.size() * btn_size + (visible_favorite_btns.size() - 1) * gap; - } - if (onroad_distance_btn_enabled) { - controls_width += (controls_width > 0 ? gap : 0) + personality_btn->width(); - } - dmon.onroad_controls_width = controls_width; - - const int controls_y = favorites_anchor_ready - ? std::clamp(starpilot_nvg->dmIconPosition.y() - (btn_size / 2), UI_BORDER_SIZE, height() - UI_BORDER_SIZE - btn_size) - : 0; - int cursor_x = starpilot_nvg->rightHandDM ? width() - UI_BORDER_SIZE : UI_BORDER_SIZE; - - personality_btn->setVisible(onroad_distance_btn_enabled); - if (onroad_distance_btn_enabled) { - const int personality_x = starpilot_nvg->rightHandDM ? cursor_x - personality_btn->width() : cursor_x; - personality_btn->move(personality_x, controls_y); - personality_btn->updateState(s, fs); - cursor_x += starpilot_nvg->rightHandDM ? -(personality_btn->width() + gap) : personality_btn->width() + gap; - } - - for (FavoriteButton *favorite_btn : visible_favorite_btns) { - const int favorite_x = starpilot_nvg->rightHandDM ? cursor_x - favorite_btn->width() : cursor_x; - favorite_btn->move(favorite_x, controls_y); - favorite_btn->setVisible(true); - cursor_x += starpilot_nvg->rightHandDM ? -(favorite_btn->width() + gap) : favorite_btn->width() + gap; - } - - const QPoint screen_recorder_position = hide_steering_wheel - ? experimental_button_position - : QPoint(experimental_button_position.x() - UI_BORDER_SIZE - btn_size, experimental_button_position.y()); - screen_recorder->move(screen_recorder_position); - screen_recorder->setVisible(starpilot_nvg->standstillDuration == 0 && !(starpilot_nvg->signalStyle == "static" && carState.getRightBlinker()) && starpilot_toggles.value("screen_recorder").toBool()); -} - -void AnnotatedCameraWidget::initializeGL() { - CameraWidget::initializeGL(); - qInfo() << "OpenGL version:" << QString((const char*)glGetString(GL_VERSION)); - qInfo() << "OpenGL vendor:" << QString((const char*)glGetString(GL_VENDOR)); - qInfo() << "OpenGL renderer:" << QString((const char*)glGetString(GL_RENDERER)); - qInfo() << "OpenGL language version:" << QString((const char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); - - prev_draw_t = millis_since_boot(); - setBackgroundColor(bg_colors[STATUS_DISENGAGED]); -} - -mat4 AnnotatedCameraWidget::calcFrameMatrix() { - // Project point at "infinity" to compute x and y offsets - // to ensure this ends up in the middle of the screen - // for narrow come and a little lower for wide cam. - // TODO: use proper perspective transform? - - // Select intrinsic matrix and calibration based on camera type - auto *s = uiState(); - bool wide_cam = active_stream_type == VISION_STREAM_WIDE_ROAD; - const auto &intrinsic_matrix = wide_cam ? ECAM_INTRINSIC_MATRIX : FCAM_INTRINSIC_MATRIX; - const auto &calibration = wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib; - - // Compute the calibration transformation matrix - const auto calib_transform = intrinsic_matrix * calibration; - - float zoom = wide_cam ? 2.0 : 1.1; - Eigen::Vector3f inf(1000., 0., 0.); - auto Kep = calib_transform * inf; - - int w = width(), h = height(); - float center_x = intrinsic_matrix(0, 2); - float center_y = intrinsic_matrix(1, 2); - - float max_x_offset = center_x * zoom - w / 2 - 5; - float max_y_offset = center_y * zoom - h / 2 - 5; - float x_offset = std::clamp((Kep.x() / Kep.z() - center_x) * zoom, -max_x_offset, max_x_offset); - float y_offset = std::clamp((Kep.y() / Kep.z() - center_y) * zoom, -max_y_offset, max_y_offset); - - // Apply transformation such that video pixel coordinates match video - // 1) Put (0, 0) in the middle of the video - // 2) Apply same scaling as video - // 3) Put (0, 0) in top left corner of video - Eigen::Matrix3f video_transform =(Eigen::Matrix3f() << - zoom, 0.0f, (w / 2 - x_offset) - (center_x * zoom), - 0.0f, zoom, (h / 2 - y_offset) - (center_y * zoom), - 0.0f, 0.0f, 1.0f).finished(); - - model.setTransform(video_transform * calib_transform); - - float zx = zoom * 2 * center_x / w; - float zy = zoom * 2 * center_y / h; - return mat4{{ - zx, 0.0, 0.0, -x_offset / w * 2, - 0.0, zy, 0.0, y_offset / h * 2, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} - -void AnnotatedCameraWidget::paintGL() { -} - -void AnnotatedCameraWidget::paintEvent(QPaintEvent *event) { - UIState *s = uiState(); - SubMaster &sm = *(s->sm); - const double start_draw_t = millis_since_boot(); - - QPainter painter(this); - static Params params; - const std::string camera_view_param = params.get("CameraView"); - int camera_view = starpilot_toggles.value("camera_view").toInt(); - if (!camera_view_param.empty()) { - try { - camera_view = std::stoi(camera_view_param); - } catch (const std::exception &) { - LOGW("invalid CameraView param: %s", camera_view_param.c_str()); - } - } - const bool camera_view_none = camera_view == CAMERA_VIEW_NONE; - - // draw camera frame - if (camera_view_none) { - painter.fillRect(rect(), Qt::black); - } else { - std::lock_guard lk(frame_lock); - - if (frames.empty()) { - if (skip_frame_count > 0) { - skip_frame_count--; - qDebug() << "skipping frame, not ready"; - return; - } - } else { - // skip drawing up to this many frames if we're - // missing camera frames. this smooths out the - // transitions from the narrow and wide cameras - skip_frame_count = 5; - } - - // Wide or narrow cam dependent on speed - bool has_wide_cam = available_streams.count(VISION_STREAM_WIDE_ROAD); - if (has_wide_cam) { - float v_ego = sm["carState"].getCarState().getVEgo(); - if ((v_ego < 10) || available_streams.size() == 1) { - wide_cam_requested = true; - } else if (v_ego > 15) { - wide_cam_requested = false; - } - wide_cam_requested = wide_cam_requested && sm["selfdriveState"].getSelfdriveState().getExperimentalMode() && camera_view == 0; - } - CameraWidget::setStreamType(camera_view == 1 ? VISION_STREAM_DRIVER : - ((camera_view == 3 && has_wide_cam) || wide_cam_requested) ? VISION_STREAM_WIDE_ROAD : - VISION_STREAM_ROAD); - CameraWidget::setFrameId(sm["modelV2"].getModelV2().getFrameId()); - - painter.beginNativePainting(); - CameraWidget::paintGL(); - painter.endNativePainting(); - } - - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(Qt::NoPen); - - dmon.starpilot_nvg = starpilot_nvg; - hud.starpilot_nvg = starpilot_nvg; - model.starpilot_nvg = starpilot_nvg; - - experimental_btn->starpilot_scene = starpilot_scene; - model.starpilot_scene = starpilot_scene; - - dmon.starpilot_toggles = starpilot_toggles; - experimental_btn->starpilot_toggles = starpilot_toggles; - hud.starpilot_toggles = starpilot_toggles; - model.starpilot_toggles = starpilot_toggles; - - if (!camera_view_none) { - model.draw(painter, rect()); - } - dmon.draw(painter, rect()); - hud.updateState(*s); - hud.draw(painter, rect()); - - starpilot_nvg->paintStarPilotWidgets(painter, *s, camera_view_none); - - double cur_draw_t = millis_since_boot(); - double dt = cur_draw_t - prev_draw_t; - fps = fps_filter.update(1. / dt * 1000); - if (fps < 15) { - LOGW("slow frame rate: %.2f fps", fps); - } - prev_draw_t = cur_draw_t; - - // publish debug msg - MessageBuilder msg; - auto m = msg.initEvent().initUiDebug(); - m.setDrawTimeMillis(cur_draw_t - start_draw_t); - pm->send("uiDebug", msg); -} - -void AnnotatedCameraWidget::showEvent(QShowEvent *event) { - CameraWidget::showEvent(event); - - ui_update_params(uiState()); - prev_draw_t = millis_since_boot(); -} diff --git a/selfdrive/ui/qt/onroad/annotated_camera.h b/selfdrive/ui/qt/onroad/annotated_camera.h deleted file mode 100644 index 9709ab82d..000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include -#include -#include -#include "selfdrive/ui/qt/onroad/hud.h" -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include "selfdrive/ui/qt/onroad/model.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -#include "starpilot/ui/qt/onroad/starpilot_buttons.h" -#include "starpilot/ui/screenrecorder/screenrecorder.h" - -class AnnotatedCameraWidget : public CameraWidget { - Q_OBJECT - -public: - explicit AnnotatedCameraWidget(VisionStreamType type, QWidget* parent = 0); - void updateState(const UIState &s, const StarPilotUIState &fs); - bool handleHudPress(const QPoint &pos); - bool handleHudRelease(const QPoint &pos); - - double fps; - - StarPilotAnnotatedCameraWidget *starpilot_nvg; - - StarPilotUIScene starpilot_scene; - - QJsonObject starpilot_toggles; - -private: - QVBoxLayout *main_layout; - ExperimentalButton *experimental_btn; - DriverMonitorRenderer dmon; - HudRenderer hud; - ModelRenderer model; - std::unique_ptr pm; - - int skip_frame_count = 0; - bool wide_cam_requested = false; - - void paintEvent(QPaintEvent *event) override; - - DrivingPersonalityButton *personality_btn; - std::array favorite_btns; - ScreenRecorder *screen_recorder; - -protected: - void paintGL() override; - void initializeGL() override; - void showEvent(QShowEvent *event) override; - mat4 calcFrameMatrix() override; - - double prev_draw_t = 0; - FirstOrderFilter fps_filter; -}; diff --git a/selfdrive/ui/qt/onroad/buttons.cc b/selfdrive/ui/qt/onroad/buttons.cc deleted file mode 100644 index da58f4d6c..000000000 --- a/selfdrive/ui/qt/onroad/buttons.cc +++ /dev/null @@ -1,143 +0,0 @@ -#include "selfdrive/ui/qt/onroad/buttons.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -namespace { -bool ccmManualOverride(int status) { - return status == 1 || status == 2; -} - -bool cemManualOverride(int status) { - return status == 1 || status == 2; -} -} // namespace - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity, const int &angle) { - p.setRenderHint(QPainter::Antialiasing); - p.setOpacity(1.0); // bg dictates opacity of ellipse - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, btn_size / 2, btn_size / 2); - p.save(); - p.translate(center); - p.rotate(angle); - p.setOpacity(opacity); - p.drawPixmap(-QPoint(img.width() / 2, img.height() / 2), img); - p.restore(); - p.setOpacity(1.0); -} - -// ExperimentalButton -ExperimentalButton::ExperimentalButton(QWidget *parent) : QPushButton(parent), experimental_mode(false), engageable(false), steering_angle_deg(0) { - setFixedSize(btn_size, btn_size); - - engage_img = loadPixmap("../assets/icons/chffr_wheel.png", {img_size, img_size}); - experimental_img = loadPixmap("../assets/icons/experimental.svg", {img_size, img_size}); - QObject::connect(this, &QPushButton::clicked, this, &ExperimentalButton::changeMode); - - QObject::connect(starpilotUIState(), &StarPilotUIState::themeUpdated, this, &ExperimentalButton::updateTheme); -} - -void ExperimentalButton::changeMode() { - const auto cp = (*uiState()->sm)["carParams"].getCarParams(); - if (params.getBool("SafeMode")) { - return; - } - bool can_change = hasLongitudinalControl(cp) && params.getBool("ExperimentalModeConfirmed"); - if (can_change) { - if (starpilot_toggles.value("conditional_experimental_mode").toBool()) { - int override_value = cemManualOverride(starpilot_scene.conditional_status) ? 0 : experimental_mode ? 1 : 2; - params_memory.putInt("CEStatus", override_value); - params.putInt("PersistedCEStatus", params.getBool("PersistExperimentalState") ? override_value : 0); - } else if (starpilot_toggles.value("conditional_chill_mode").toBool()) { - int override_value = ccmManualOverride(starpilot_scene.conditional_status) ? 0 : experimental_mode ? 2 : 1; - params_memory.putInt("CCStatus", override_value); - params.putInt("PersistedCCStatus", params.getBool("PersistChillState") ? override_value : 0); - } else { - params.putBool("ExperimentalMode", !experimental_mode); - } - } -} - -void ExperimentalButton::updateState(const UIState &s, const StarPilotUIState &fs) { - const auto cs = (*s.sm)["selfdriveState"].getSelfdriveState(); - bool eng = cs.getEngageable() || cs.getEnabled() || fs.starpilot_scene.always_on_lateral_active; - if ((cs.getExperimentalMode() != experimental_mode) || (eng != engageable)) { - engageable = eng; - experimental_mode = cs.getExperimentalMode(); - update(); - } - - const cereal::CarState::Reader &carState = (*s.sm)["carState"].getCarState(); - - updateBackgroundColor(); - - int current_steering_angle_deg = -carState.getSteeringAngleDeg(); - if (current_steering_angle_deg != steering_angle_deg && starpilot_toggles.value("rotating_wheel").toBool()) { - steering_angle_deg = current_steering_angle_deg; - update(); - } else if (!starpilot_toggles.value("rotating_wheel").toBool()) { - steering_angle_deg = 0; - } - - if (params_memory.getBool("UpdateWheelImage")) { - updateTheme(); - params_memory.remove("UpdateWheelImage"); - } -} - -void ExperimentalButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setClipRegion(QRegion(QRect(0, 0, btn_size, btn_size), QRegion::Ellipse)); - p.setRenderHint(QPainter::Antialiasing); - - if (starpilot_toggles.value("wheel_image").toString() == "stock") { - QPixmap img = experimental_mode ? experimental_img : engage_img; - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), img, background_color, (isDown() || !engageable) ? 0.6 : 1.0, steering_angle_deg); - } else if (wheel_gif) { - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), wheel_gif->currentPixmap(), background_color, (isDown() || !engageable) ? 0.6 : 1.0, steering_angle_deg); - } else if (!wheel_img.isNull()) { - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), wheel_img, background_color, (isDown() || !engageable) ? 0.6 : 1.0, steering_angle_deg); - } else { - QPixmap img = experimental_mode ? experimental_img : engage_img; - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), img, background_color, (isDown() || !engageable) ? 0.6 : 1.0, steering_angle_deg); - } -} - -void ExperimentalButton::showEvent(QShowEvent *event) { - updateTheme(); -} - -void ExperimentalButton::updateBackgroundColor() { - const bool conditional_experimental_mode = starpilot_toggles.value("conditional_experimental_mode").toBool(); - const bool conditional_chill_mode = starpilot_toggles.value("conditional_chill_mode").toBool(); - const bool highlight_override = - (conditional_experimental_mode && starpilot_scene.conditional_status == 1) || - (conditional_chill_mode && ccmManualOverride(starpilot_scene.conditional_status)); - if (starpilot_toggles.value("simple_mode").toBool()) { - background_color = QColor(0, 0, 0, 166); - } else if (isDown() || !engageable) { - background_color = QColor(0, 0, 0, 166); - } else if (starpilot_scene.switchback_mode_enabled) { - background_color = bg_colors[STATUS_SWITCHBACK_MODE_ENABLED]; - } else if (starpilot_scene.always_on_lateral_active) { - background_color = bg_colors[STATUS_ALWAYS_ON_LATERAL_ACTIVE]; - } else if (highlight_override) { - background_color = bg_colors[STATUS_CEM_DISABLED]; - } else if (experimental_mode) { - background_color = bg_colors[STATUS_EXPERIMENTAL_MODE_ENABLED]; - } else if (starpilot_scene.traffic_mode_enabled) { - background_color = bg_colors[STATUS_TRAFFIC_MODE_ENABLED]; - } else { - background_color = QColor(0, 0, 0, 166); - } -} - -void ExperimentalButton::updateTheme() { - loadImage("../../starpilot/assets/active_theme/steering_wheel/wheel", wheel_img, wheel_gif, QSize(img_size, img_size), this); - if (!wheel_gif && wheel_img.isNull()) { - loadImage("../../starpilot/assets/stock_theme/steering_wheel/wheel", wheel_img, wheel_gif, QSize(img_size, img_size), this); - } -} diff --git a/selfdrive/ui/qt/onroad/buttons.h b/selfdrive/ui/qt/onroad/buttons.h deleted file mode 100644 index 8e7a10d15..000000000 --- a/selfdrive/ui/qt/onroad/buttons.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/ui.h" - -const int btn_size = 192; -const int img_size = (btn_size / 4) * 3; - -class ExperimentalButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalButton(QWidget *parent = 0); - void updateState(const UIState &s, const StarPilotUIState &fs); - - StarPilotUIScene starpilot_scene; - - QJsonObject starpilot_toggles; - -private: - void paintEvent(QPaintEvent *event) override; - void changeMode(); - - Params params; - QPixmap engage_img; - QPixmap experimental_img; - bool experimental_mode; - bool engageable; - - void showEvent(QShowEvent *event) override; - void updateBackgroundColor(); - void updateTheme(); - - int steering_angle_deg; - - Params params_memory{"", true}; - - QColor background_color; - - QPixmap wheel_img; - - QSharedPointer wheel_gif; -}; - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity, const int &angle = 0); diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.cc b/selfdrive/ui/qt/onroad/driver_monitoring.cc deleted file mode 100644 index 330c70cec..000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.cc +++ /dev/null @@ -1,129 +0,0 @@ -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include -#include - -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/util.h" - -// Default 3D coordinates for face keypoints -static constexpr vec3 DEFAULT_FACE_KPTS_3D[] = { - {-5.98, -51.20, 8.00}, {-17.64, -49.14, 8.00}, {-23.81, -46.40, 8.00}, {-29.98, -40.91, 8.00}, {-32.04, -37.49, 8.00}, - {-34.10, -32.00, 8.00}, {-36.16, -21.03, 8.00}, {-36.16, 6.40, 8.00}, {-35.47, 10.51, 8.00}, {-32.73, 19.43, 8.00}, - {-29.30, 26.29, 8.00}, {-24.50, 33.83, 8.00}, {-19.01, 41.37, 8.00}, {-14.21, 46.17, 8.00}, {-12.16, 47.54, 8.00}, - {-4.61, 49.60, 8.00}, {4.99, 49.60, 8.00}, {12.53, 47.54, 8.00}, {14.59, 46.17, 8.00}, {19.39, 41.37, 8.00}, - {24.87, 33.83, 8.00}, {29.67, 26.29, 8.00}, {33.10, 19.43, 8.00}, {35.84, 10.51, 8.00}, {36.53, 6.40, 8.00}, - {36.53, -21.03, 8.00}, {34.47, -32.00, 8.00}, {32.42, -37.49, 8.00}, {30.36, -40.91, 8.00}, {24.19, -46.40, 8.00}, - {18.02, -49.14, 8.00}, {6.36, -51.20, 8.00}, {-5.98, -51.20, 8.00}, -}; - -// Colors used for drawing based on monitoring state -static const QColor DMON_ENGAGED_COLOR = QColor::fromRgbF(0.1, 0.945, 0.26); -static const QColor DMON_DISENGAGED_COLOR = QColor::fromRgbF(0.545, 0.545, 0.545); - -DriverMonitorRenderer::DriverMonitorRenderer() : face_kpts_draw(std::size(DEFAULT_FACE_KPTS_3D)) { - dm_img = loadPixmap("../assets/icons/driver_face.png", {img_size + 5, img_size + 5}); -} - -void DriverMonitorRenderer::updateState(const UIState &s) { - auto &sm = *(s.sm); - is_visible = sm["selfdriveState"].getSelfdriveState().getAlertSize() == cereal::SelfdriveState::AlertSize::NONE && - sm.rcv_frame("driverStateV2") > s.scene.started_frame; - if (!is_visible) return; - - auto dm_state = sm["driverMonitoringState"].getDriverMonitoringState(); - is_active = dm_state.getActivePolicy() == cereal::DriverMonitoringState::MonitoringPolicy::VISION; - is_rhd = dm_state.getIsRHD(); - dm_fade_state = std::clamp(dm_fade_state + 0.2f * (0.5f - is_active), 0.0f, 1.0f); - - const auto &driverstate = sm["driverStateV2"].getDriverStateV2(); - const auto driver_orient = is_rhd ? driverstate.getRightDriverData().getFaceOrientation() : driverstate.getLeftDriverData().getFaceOrientation(); - - for (int i = 0; i < 3; ++i) { - float v_this = (i == 0 ? (driver_orient[i] < 0 ? 0.7 : 0.9) : 0.4) * driver_orient[i]; - driver_pose_diff[i] = std::abs(driver_pose_vals[i] - v_this); - driver_pose_vals[i] = 0.8f * v_this + (1 - 0.8) * driver_pose_vals[i]; - driver_pose_sins[i] = std::sin(driver_pose_vals[i] * (1.0f - dm_fade_state)); - driver_pose_coss[i] = std::cos(driver_pose_vals[i] * (1.0f - dm_fade_state)); - } - - auto [sin_y, sin_x, sin_z] = driver_pose_sins; - auto [cos_y, cos_x, cos_z] = driver_pose_coss; - - // Rotation matrix for transforming face keypoints based on driver's head orientation - const mat3 r_xyz = {{ - cos_x * cos_z, cos_x * sin_z, -sin_x, - -sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x, - cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x, - }}; - - // Transform vertices - for (int i = 0; i < face_kpts_draw.size(); ++i) { - vec3 kpt = matvecmul3(r_xyz, DEFAULT_FACE_KPTS_3D[i]); - face_kpts_draw[i] = {{kpt.v[0], kpt.v[1], kpt.v[2] * (1.0f - dm_fade_state) + 8 * dm_fade_state}}; - } -} - -void DriverMonitorRenderer::draw(QPainter &painter, const QRect &surface_rect) { - if (!is_visible) return; - - int offset = UI_BORDER_SIZE + btn_size / 2; - float x = is_rhd ? surface_rect.width() - offset : offset; - float y = surface_rect.height() - offset; - - if (onroad_controls_width > 0) { - const int controls_offset = onroad_controls_width + (2 * UI_BORDER_SIZE); - if (is_rhd) { - x -= controls_offset; - } else { - x += controls_offset; - } - } - - if (starpilot_toggles.value("road_name_ui").toBool()) { - y -= UI_BORDER_SIZE; - } - - if (starpilot_nvg) { - starpilot_nvg->dmIconPosition.setX(x); - starpilot_nvg->dmIconPosition.setY(y); - starpilot_nvg->rightHandDM = is_rhd; - } - - if (starpilot_toggles.value("hide_dm_icon").toBool()) return; - - painter.save(); - - float opacity = is_active ? 0.65f : 0.2f; - - drawIcon(painter, QPoint(x, y), dm_img, QColor(0, 0, 0, 70), opacity); - - QPointF keypoints[std::size(DEFAULT_FACE_KPTS_3D)]; - for (int i = 0; i < std::size(keypoints); ++i) { - const auto &v = face_kpts_draw[i].v; - float kp = (v[2] - 8) / 120.0f + 1.0f; - keypoints[i] = QPointF(v[0] * kp + x, v[1] * kp + y); - } - - painter.setPen(QPen(QColor::fromRgbF(1.0, 1.0, 1.0, opacity), 5.2, Qt::SolidLine, Qt::RoundCap)); - painter.drawPolyline(keypoints, std::size(keypoints)); - - // tracking arcs - const int arc_l = 133; - const float arc_t_default = 6.7f; - const float arc_t_extend = 12.0f; - QColor arc_color = uiState()->engaged() ? DMON_ENGAGED_COLOR : DMON_DISENGAGED_COLOR; - arc_color.setAlphaF(0.4 * (1.0f - dm_fade_state)); - - float delta_x = -driver_pose_sins[1] * arc_l / 2.0f; - float delta_y = -driver_pose_sins[0] * arc_l / 2.0f; - - // Draw horizontal tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[1] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(std::min(x + delta_x, x), y - arc_l / 2, std::abs(delta_x), arc_l), (driver_pose_sins[1] > 0 ? 90 : -90) * 16, 180 * 16); - - // Draw vertical tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[0] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(x - arc_l / 2, std::min(y + delta_y, y), arc_l, std::abs(delta_y)), (driver_pose_sins[0] > 0 ? 0 : 180) * 16, 180 * 16); - - painter.restore(); -} diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.h b/selfdrive/ui/qt/onroad/driver_monitoring.h deleted file mode 100644 index 5c0e230cf..000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include "selfdrive/ui/ui.h" - -#include "starpilot/ui/qt/onroad/starpilot_annotated_camera.h" - -class DriverMonitorRenderer { -public: - DriverMonitorRenderer(); - void updateState(const UIState &s); - void draw(QPainter &painter, const QRect &surface_rect); - - StarPilotAnnotatedCameraWidget *starpilot_nvg; - - int onroad_controls_width = 0; - - QJsonObject starpilot_toggles; - -private: - float driver_pose_vals[3] = {}; - float driver_pose_diff[3] = {}; - float driver_pose_sins[3] = {}; - float driver_pose_coss[3] = {}; - bool is_visible = false; - bool is_active = false; - bool is_rhd = false; - float dm_fade_state = 1.0; - QPixmap dm_img; - std::vector face_kpts_draw; -}; diff --git a/selfdrive/ui/qt/onroad/hud.cc b/selfdrive/ui/qt/onroad/hud.cc deleted file mode 100644 index 6ebb87867..000000000 --- a/selfdrive/ui/qt/onroad/hud.cc +++ /dev/null @@ -1,427 +0,0 @@ -#include "selfdrive/ui/qt/onroad/hud.h" - -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/util.h" - -constexpr int SET_SPEED_NA = 255; -constexpr int NAV_CANCEL_HOLD_MS = 650; - -HudRenderer::HudRenderer() {} - -bool HudRenderer::handleNavigationPress(const QPoint &pos) { - if (!navigation_valid || !nav_hit_rect.contains(pos)) { - return false; - } - - nav_press_active = true; - nav_press_timer.restart(); - return true; -} - -bool HudRenderer::handleNavigationRelease(const QPoint &pos) { - if (!nav_press_active) { - return false; - } - - nav_press_active = false; - if (!nav_hit_rect.contains(pos)) { - return true; - } - - if (nav_press_timer.isValid() && nav_press_timer.elapsed() >= NAV_CANCEL_HOLD_MS) { - cancelNavigation(); - } else { - params_memory.putBool("NavInstructionCollapsed", !navigation_collapsed); - } - return true; -} - -void HudRenderer::cancelNavigation() { - params.remove("NavDestination"); - params_memory.remove("NavInstructionState"); - params_memory.remove("NavInstructionCollapsed"); - navigation_valid = false; - navigation_collapsed = false; - nav_hit_rect = QRect(); - nav_primary_text.clear(); - nav_secondary_text.clear(); - nav_distance.clear(); - nav_maneuver_type.clear(); - nav_modifier.clear(); - nav_next_maneuver_type.clear(); - nav_next_modifier.clear(); -} - -void HudRenderer::updateState(const UIState &s) { - is_metric = s.scene.is_metric; - status = s.status; - - const SubMaster &sm = *(s.sm); - if (sm.rcv_frame("carState") < s.scene.started_frame) { - is_cruise_set = false; - set_speed = SET_SPEED_NA; - speed = 0.0; - return; - } - - const auto &controls_state = sm["controlsState"].getControlsState(); - const auto &car_state = sm["carState"].getCarState(); - - // Handle older routes where vCruiseCluster is not set - set_speed = car_state.getVCruiseCluster() == 0.0 ? controls_state.getVCruiseDEPRECATED() : car_state.getVCruiseCluster(); - is_cruise_set = set_speed > 0 && set_speed != SET_SPEED_NA; - is_cruise_available = set_speed != -1; - - if (is_cruise_set && starpilot_toggles.value("set_speed_offset").toDouble() > 0) { - set_speed += starpilot_toggles.value("set_speed_offset").toDouble(); - } - - if (is_cruise_set && !is_metric) { - set_speed *= KM_TO_MILE; - } - - // Handle older routes where vEgoCluster is not set - v_ego_cluster_seen = v_ego_cluster_seen || car_state.getVEgoCluster() != 0.0; - float v_ego = v_ego_cluster_seen && !starpilot_toggles.value("use_wheel_speed").toBool() ? car_state.getVEgoCluster() : car_state.getVEgo(); - speed = std::max(0.0f, v_ego * (is_metric ? MS_TO_KPH : MS_TO_MPH)); - - navigation_enabled = params.getBool("NavigationUI"); - navigation_valid = false; - navigation_has_next = false; - navigation_collapsed = false; - nav_hit_rect = QRect(); - nav_primary_text.clear(); - nav_secondary_text.clear(); - nav_distance.clear(); - nav_maneuver_type.clear(); - nav_modifier.clear(); - nav_next_maneuver_type.clear(); - nav_next_modifier.clear(); - - if (!navigation_enabled) { - return; - } - - if (params.get("NavDestination").empty()) { - return; - } - - const std::string nav_state_raw = params_memory.get("NavInstructionState"); - if (nav_state_raw.empty()) { - return; - } - - const QJsonDocument nav_state_doc = QJsonDocument::fromJson(QByteArray::fromStdString(nav_state_raw)); - if (!nav_state_doc.isObject()) { - return; - } - - const QJsonObject nav = nav_state_doc.object(); - if (!nav.value("valid").toBool(false)) { - return; - } - - nav_primary_text = nav.value("maneuverPrimaryText").toString().trimmed(); - if (nav_primary_text.isEmpty()) { - return; - } - - navigation_valid = true; - nav_secondary_text = nav.value("maneuverSecondaryText").toString().trimmed(); - nav_distance = formatNavDistance(static_cast(nav.value("maneuverDistance").toDouble(0.0))); - nav_maneuver_type = nav.value("maneuverType").toString().trimmed(); - nav_modifier = nav.value("maneuverModifier").toString().trimmed(); - nav_next_maneuver_type = nav.value("nextManeuverType").toString().trimmed(); - nav_next_modifier = nav.value("nextManeuverModifier").toString().trimmed(); - navigation_has_next = !nav_next_maneuver_type.isEmpty() || !nav_next_modifier.isEmpty(); - navigation_collapsed = params_memory.getBool("NavInstructionCollapsed"); -} - -void HudRenderer::draw(QPainter &p, const QRect &surface_rect) { - p.save(); - - // Draw header gradient — constant stops, build once - static const QLinearGradient bg = []() { - QLinearGradient g(0, UI_HEADER_HEIGHT - (UI_HEADER_HEIGHT / 2.5), 0, UI_HEADER_HEIGHT); - g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.45)); - g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0)); - return g; - }(); - p.fillRect(0, 0, surface_rect.width(), UI_HEADER_HEIGHT, bg); - - - if (is_cruise_available) { - drawSetSpeed(p, surface_rect); - } - if (starpilot_nvg->standstillDuration == 0 && !starpilot_toggles.value("hide_speed").toBool()) { - drawCurrentSpeed(p, surface_rect); - } - if (navigation_valid) { - drawNavigationCard(p, surface_rect); - } - - p.restore(); -} - -void HudRenderer::drawSetSpeed(QPainter &p, const QRect &surface_rect) { - // Draw outer box + border to contain set speed - const QSize default_size = {172, 204}; - QSize set_speed_size = is_metric ? QSize(200, 204) : default_size; - - if (starpilot_nvg->speedLimitHeight != 0) { - set_speed_size.rheight() += starpilot_nvg->speedLimitHeight; - if (starpilot_toggles.value("speed_limit_vienna").toBool()) { - set_speed_size.rwidth() = 200; - } - } - - QRect set_speed_rect(QPoint(60 + (default_size.width() - set_speed_size.width()) / 2, 45), set_speed_size); - - if (!starpilot_toggles.value("hide_max_speed").toBool()) { - // Draw set speed box - p.setPen(QPen(QColor(255, 255, 255, 75), 6)); - p.setBrush(QColor(0, 0, 0, 166)); - p.drawRoundedRect(set_speed_rect, 32, 32); - - // Colors based on status - QColor max_color = QColor(0xa6, 0xa6, 0xa6, 0xff); - QColor set_speed_color = QColor(0x72, 0x72, 0x72, 0xff); - if (is_cruise_set) { - set_speed_color = QColor(255, 255, 255); - if (status == STATUS_DISENGAGED) { - max_color = QColor(255, 255, 255); - } else if (status == STATUS_OVERRIDE) { - max_color = QColor(0x91, 0x9b, 0x95, 0xff); - } else { - max_color = QColor(0x80, 0xd8, 0xa6, 0xff); - } - } - - // Draw "MAX" text - p.setFont(InterFont(40, QFont::DemiBold)); - p.setPen(max_color); - p.drawText(set_speed_rect.adjusted(0, 27, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("MAX")); - - // Draw set speed - QString setSpeedStr = is_cruise_set ? QString::number(std::nearbyint(set_speed)) : "–"; - p.setFont(InterFont(90, QFont::Bold)); - p.setPen(set_speed_color); - p.drawText(set_speed_rect.adjusted(0, 77, 0, 0), Qt::AlignTop | Qt::AlignHCenter, setSpeedStr); - } - - starpilot_nvg->defaultSize = default_size; - starpilot_nvg->isCruiseSet = is_cruise_set; - starpilot_nvg->setSpeedRect = set_speed_rect; - starpilot_nvg->speed = speed; -} - -void HudRenderer::drawCurrentSpeed(QPainter &p, const QRect &surface_rect) { - QString speedStr = QString::number(std::nearbyint(speed)); - - p.setFont(InterFont(176, QFont::Bold)); - drawText(p, surface_rect.center().x(), 210, speedStr); - - p.setFont(InterFont(66)); - drawText(p, surface_rect.center().x(), 290, is_metric ? tr("km/h") : tr("mph"), 200); -} - -void HudRenderer::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { - QRect real_rect = p.fontMetrics().boundingRect(text); - real_rect.moveCenter({x, y - real_rect.height() / 2}); - - p.setPen(QColor(0xff, 0xff, 0xff, alpha)); - p.drawText(real_rect.x(), real_rect.bottom(), text); -} - -QString HudRenderer::formatNavDistance(float distance_m) const { - if (is_metric) { - if (distance_m < 1000.0f) { - int step = distance_m < 500.0f ? 25 : 50; - return QString("%1 m").arg(qRound(distance_m / step) * step); - } - float km = distance_m / 1000.0f; - return km >= 10.0f ? QString("%1 km").arg(static_cast(std::floor(km))) : QString("%1 km").arg(km, 0, 'f', 1); - } - - float distance_ft = distance_m * METER_TO_FOOT; - if (distance_ft < 1000.0f) { - int step = distance_ft <= 100.0f ? 10 : 50; - return QString("%1 ft").arg(qRound(distance_ft / step) * step); - } - - float miles = distance_ft / 5280.0f; - return miles >= 10.0f ? QString("%1 mi").arg(static_cast(std::floor(miles))) : QString("%1 mi").arg(miles, 0, 'f', 1); -} - -QString HudRenderer::navigationIconFilename(const QString &maneuver_type, const QString &modifier) const { - QString normalized_type = maneuver_type.isEmpty() ? "turn" : maneuver_type; - if (normalized_type == "rotary") { - normalized_type = "roundabout"; - } else if (normalized_type == "new name" || normalized_type == "continue") { - normalized_type = "turn"; - } - - if (modifier == "uturn") { - return "direction_uturn.png"; - } - - static const QHash suffixes = { - {"left", "left"}, - {"right", "right"}, - {"straight", "straight"}, - {"slightLeft", "slight_left"}, - {"slightRight", "slight_right"}, - {"sharpLeft", "sharp_left"}, - {"sharpRight", "sharp_right"}, - }; - - normalized_type.replace(" ", "_"); - const QString suffix = suffixes.value(modifier, ""); - const QString candidate = suffix.isEmpty() ? QString("direction_%1.png").arg(normalized_type) - : QString("direction_%1_%2.png").arg(normalized_type, suffix); - const QString candidate_path = QString("../../starpilot/assets/navigation/%1").arg(candidate); - return QFileInfo::exists(candidate_path) ? candidate : "direction_turn_straight.png"; -} - -QPixmap HudRenderer::getNavigationIcon(const QString &maneuver_type, const QString &modifier, int size) { - const QString icon_name = navigationIconFilename(maneuver_type, modifier); - const QString cache_key = QString("%1|%2").arg(icon_name).arg(size); - if (!nav_icon_cache.contains(cache_key)) { - nav_icon_cache.insert(cache_key, loadPixmap(QString("../../starpilot/assets/navigation/%1").arg(icon_name), QSize(size, size))); - } - return nav_icon_cache.value(cache_key); -} - -QStringList HudRenderer::wrapNavigationText(int max_width, int font_size, const QString &text) const { - QStringList words = text.split(' ', QString::SkipEmptyParts); - QStringList lines; - QString current_line; - const QFontMetrics metrics(InterFont(font_size, QFont::Bold)); - - for (const QString &word : words) { - QString test_line = current_line.isEmpty() ? word : current_line + " " + word; - if (metrics.horizontalAdvance(test_line) <= max_width) { - current_line = test_line; - } else { - if (!current_line.isEmpty()) { - lines.append(current_line); - } - current_line = word; - if (lines.size() >= 2) { - break; - } - } - } - - if (!current_line.isEmpty() && lines.size() < 2) { - lines.append(current_line); - } - return lines; -} - -void HudRenderer::drawNavigationCard(QPainter &p, const QRect &surface_rect) { - if (navigation_collapsed) { - const int chip_size = 94; - const int chip_x = surface_rect.right() - chip_size - 32; - const int chip_y = surface_rect.width() >= 1200 ? 232 : 204; - nav_hit_rect = QRect(chip_x, chip_y, chip_size, chip_size); - - p.setPen(Qt::NoPen); - p.setBrush(QColor(7, 11, 18, 228)); - p.drawRoundedRect(nav_hit_rect, 28, 28); - p.setPen(QPen(QColor(255, 255, 255, 40), 2)); - p.setBrush(Qt::NoBrush); - p.drawRoundedRect(nav_hit_rect, 28, 28); - - const int icon_size = 58; - const QPixmap icon = getNavigationIcon(nav_maneuver_type, nav_modifier, icon_size); - const int icon_x = chip_x + (chip_size - icon_size) / 2; - const int icon_y = chip_y + (chip_size - icon_size) / 2; - p.drawPixmap(icon_x, icon_y, icon); - return; - } - - const int container_width = std::clamp(surface_rect.width() - 120, 760, 1080); - const int container_height = surface_rect.width() >= 1200 ? 238 : 206; - const int container_x = (surface_rect.width() - container_width) / 2; - const int container_y = surface_rect.width() >= 1200 ? 332 : 298; - const int border_radius = container_height == 238 ? 42 : 34; - const int icon_size = container_height == 238 ? 150 : 122; - const int icon_padding = container_height == 238 ? 30 : 24; - const int then_section_width = container_height == 238 ? 180 : 144; - const int then_icon_size = container_height == 238 ? 105 : 82; - const int title_font_size = container_height == 238 ? 75 : 58; - const int secondary_font_size = container_height == 238 ? 34 : 28; - const int distance_font_size = container_height == 238 ? 48 : 40; - const int title_top_padding = container_height == 238 ? 10 : 10; - const int title_line_spacing = container_height == 238 ? 68 : 56; - const int secondary_bottom_padding = container_height == 238 ? 24 : 20; - const int secondary_gap = container_height == 238 ? 10 : 8; - - QRect container(container_x, container_y, container_width, container_height); - nav_hit_rect = container; - p.setPen(Qt::NoPen); - p.setBrush(QColor(0, 0, 0, 180)); - p.drawRoundedRect(container, border_radius, border_radius); - - const int icon_x = container_x + icon_padding; - const int icon_y = container_y + title_top_padding + 4; - const QPixmap icon = getNavigationIcon(nav_maneuver_type, nav_modifier, icon_size); - p.drawPixmap(icon_x, icon_y, icon); - - p.setFont(InterFont(distance_font_size, QFont::Bold)); - p.setPen(Qt::white); - const int distance_width = p.fontMetrics().horizontalAdvance(nav_distance); - p.drawText(icon_x + (icon_size - distance_width) / 2, container_y + container_height - 18, nav_distance); - - const int text_x = icon_x + icon_size + 53; - const int right_gutter = icon_padding + (navigation_has_next ? then_section_width : 0); - const int text_width = container_width - (text_x - container_x) - right_gutter; - const QStringList title_lines = wrapNavigationText(text_width, title_font_size, nav_primary_text); - const QFont title_font = InterFont(title_font_size, QFont::Bold); - const QFontMetrics title_metrics(title_font); - const int title_baseline = container_y + title_top_padding + title_metrics.ascent(); - - p.setFont(title_font); - p.setPen(Qt::white); - for (int index = 0; index < title_lines.size() && index < 2; ++index) { - p.drawText(text_x, title_baseline + index * title_line_spacing, title_lines[index]); - } - - if (!nav_secondary_text.isEmpty()) { - const QFont secondary_font = InterFont(secondary_font_size, QFont::Medium); - const QFontMetrics secondary_metrics(secondary_font); - const int title_bottom = title_baseline + (std::max(title_lines.size(), 1) - 1) * title_line_spacing + title_metrics.descent(); - const int secondary_max_baseline = container_y + container_height - secondary_bottom_padding - secondary_metrics.descent(); - const int secondary_preferred_baseline = title_bottom + secondary_gap + secondary_metrics.ascent(); - const int secondary_baseline = std::min(secondary_preferred_baseline, secondary_max_baseline); - p.setFont(secondary_font); - p.setPen(QColor(255, 255, 255, 180)); - p.drawText(text_x, secondary_baseline, nav_secondary_text); - } - - if (!navigation_has_next) { - return; - } - - const int divider_x = container_x + container_width - then_section_width - 8; - p.setPen(QPen(QColor(255, 255, 255, 50), 2)); - p.drawLine(divider_x, container_y + 23, divider_x, container_y + container_height - 23); - - p.setFont(InterFont(container_height == 225 ? 53 : 40, QFont::Medium)); - p.setPen(Qt::white); - const QString then_label = tr("Then"); - const int then_x = divider_x + 15; - const int then_label_width = p.fontMetrics().horizontalAdvance(then_label); - p.drawText(then_x + (then_section_width - 23 - then_label_width) / 2, container_y + (container_height == 238 ? 66 : 60), then_label); - - const QPixmap next_icon = getNavigationIcon(nav_next_maneuver_type, nav_next_modifier, then_icon_size); - const int then_icon_x = then_x + (then_section_width - 23 - then_icon_size) / 2; - const int then_icon_y = container_y + (container_height == 238 ? 96 : 78); - p.drawPixmap(then_icon_x, then_icon_y, next_icon); -} diff --git a/selfdrive/ui/qt/onroad/hud.h b/selfdrive/ui/qt/onroad/hud.h deleted file mode 100644 index ddc7f0112..000000000 --- a/selfdrive/ui/qt/onroad/hud.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "selfdrive/ui/ui.h" - -#include "starpilot/ui/qt/onroad/starpilot_annotated_camera.h" - -class HudRenderer : public QObject { - Q_OBJECT - -public: - HudRenderer(); - void updateState(const UIState &s); - void draw(QPainter &p, const QRect &surface_rect); - bool handleNavigationPress(const QPoint &pos); - bool handleNavigationRelease(const QPoint &pos); - - StarPilotAnnotatedCameraWidget *starpilot_nvg; - - QJsonObject starpilot_toggles; - -private: - void drawSetSpeed(QPainter &p, const QRect &surface_rect); - void drawCurrentSpeed(QPainter &p, const QRect &surface_rect); - void drawNavigationCard(QPainter &p, const QRect &surface_rect); - void drawText(QPainter &p, int x, int y, const QString &text, int alpha = 255); - QStringList wrapNavigationText(int max_width, int font_size, const QString &text) const; - QString formatNavDistance(float distance_m) const; - QString navigationIconFilename(const QString &maneuver_type, const QString &modifier) const; - QPixmap getNavigationIcon(const QString &maneuver_type, const QString &modifier, int size); - void cancelNavigation(); - - float speed = 0; - float set_speed = 0; - bool is_cruise_set = false; - bool is_cruise_available = true; - bool is_metric = false; - bool v_ego_cluster_seen = false; - bool navigation_enabled = false; - bool navigation_valid = false; - bool navigation_has_next = false; - bool navigation_collapsed = false; - int status = STATUS_DISENGAGED; - QString nav_distance; - QString nav_primary_text; - QString nav_secondary_text; - QString nav_maneuver_type; - QString nav_modifier; - QString nav_next_maneuver_type; - QString nav_next_modifier; - QRect nav_hit_rect; - QHash nav_icon_cache; - QElapsedTimer nav_press_timer; - bool nav_press_active = false; - Params params; - Params params_memory{"", true}; -}; diff --git a/selfdrive/ui/qt/onroad/moc_alerts.cc b/selfdrive/ui/qt/onroad/moc_alerts.cc deleted file mode 100644 index 14c21dd77..000000000 --- a/selfdrive/ui/qt/onroad/moc_alerts.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'alerts.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "alerts.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'alerts.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_OnroadAlerts_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_OnroadAlerts_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_OnroadAlerts_t qt_meta_stringdata_OnroadAlerts = { - { -QT_MOC_LITERAL(0, 0, 12) // "OnroadAlerts" - - }, - "OnroadAlerts" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_OnroadAlerts[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void OnroadAlerts::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject OnroadAlerts::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_OnroadAlerts.data, - qt_meta_data_OnroadAlerts, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *OnroadAlerts::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *OnroadAlerts::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_OnroadAlerts.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int OnroadAlerts::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/onroad/moc_annotated_camera.cc b/selfdrive/ui/qt/onroad/moc_annotated_camera.cc deleted file mode 100644 index d0428c97b..000000000 --- a/selfdrive/ui/qt/onroad/moc_annotated_camera.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'annotated_camera.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "annotated_camera.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'annotated_camera.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_AnnotatedCameraWidget_t { - QByteArrayData data[1]; - char stringdata0[22]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_AnnotatedCameraWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_AnnotatedCameraWidget_t qt_meta_stringdata_AnnotatedCameraWidget = { - { -QT_MOC_LITERAL(0, 0, 21) // "AnnotatedCameraWidget" - - }, - "AnnotatedCameraWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_AnnotatedCameraWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void AnnotatedCameraWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject AnnotatedCameraWidget::staticMetaObject = { { - &CameraWidget::staticMetaObject, - qt_meta_stringdata_AnnotatedCameraWidget.data, - qt_meta_data_AnnotatedCameraWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *AnnotatedCameraWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *AnnotatedCameraWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_AnnotatedCameraWidget.stringdata0)) - return static_cast(this); - return CameraWidget::qt_metacast(_clname); -} - -int AnnotatedCameraWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = CameraWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/onroad/moc_buttons.cc b/selfdrive/ui/qt/onroad/moc_buttons.cc deleted file mode 100644 index b6f0f8560..000000000 --- a/selfdrive/ui/qt/onroad/moc_buttons.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'buttons.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "buttons.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'buttons.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ExperimentalButton_t { - QByteArrayData data[1]; - char stringdata0[19]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ExperimentalButton_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ExperimentalButton_t qt_meta_stringdata_ExperimentalButton = { - { -QT_MOC_LITERAL(0, 0, 18) // "ExperimentalButton" - - }, - "ExperimentalButton" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ExperimentalButton[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ExperimentalButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ExperimentalButton::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_ExperimentalButton.data, - qt_meta_data_ExperimentalButton, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ExperimentalButton::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ExperimentalButton::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ExperimentalButton.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int ExperimentalButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/onroad/moc_hud.cc b/selfdrive/ui/qt/onroad/moc_hud.cc deleted file mode 100644 index 1fe14e341..000000000 --- a/selfdrive/ui/qt/onroad/moc_hud.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'hud.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "hud.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'hud.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_HudRenderer_t { - QByteArrayData data[1]; - char stringdata0[12]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_HudRenderer_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_HudRenderer_t qt_meta_stringdata_HudRenderer = { - { -QT_MOC_LITERAL(0, 0, 11) // "HudRenderer" - - }, - "HudRenderer" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_HudRenderer[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void HudRenderer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject HudRenderer::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_HudRenderer.data, - qt_meta_data_HudRenderer, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *HudRenderer::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *HudRenderer::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_HudRenderer.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int HudRenderer::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/onroad/moc_onroad_home.cc b/selfdrive/ui/qt/onroad/moc_onroad_home.cc deleted file mode 100644 index 5fb75f45e..000000000 --- a/selfdrive/ui/qt/onroad/moc_onroad_home.cc +++ /dev/null @@ -1,128 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'onroad_home.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "onroad_home.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'onroad_home.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_OnroadWindow_t { - QByteArrayData data[9]; - char stringdata0[82]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_OnroadWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_OnroadWindow_t qt_meta_stringdata_OnroadWindow = { - { -QT_MOC_LITERAL(0, 0, 12), // "OnroadWindow" -QT_MOC_LITERAL(1, 13, 17), // "offroadTransition" -QT_MOC_LITERAL(2, 31, 0), // "" -QT_MOC_LITERAL(3, 32, 7), // "offroad" -QT_MOC_LITERAL(4, 40, 11), // "updateState" -QT_MOC_LITERAL(5, 52, 7), // "UIState" -QT_MOC_LITERAL(6, 60, 1), // "s" -QT_MOC_LITERAL(7, 62, 16), // "StarPilotUIState" -QT_MOC_LITERAL(8, 79, 2) // "fs" - - }, - "OnroadWindow\0offroadTransition\0\0offroad\0" - "updateState\0UIState\0s\0StarPilotUIState\0" - "fs" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_OnroadWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 1, 24, 2, 0x08 /* Private */, - 4, 2, 27, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, QMetaType::Bool, 3, - QMetaType::Void, 0x80000000 | 5, 0x80000000 | 7, 6, 8, - - 0 // eod -}; - -void OnroadWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->offroadTransition((*reinterpret_cast< bool(*)>(_a[1]))); break; - case 1: _t->updateState((*reinterpret_cast< const UIState(*)>(_a[1])),(*reinterpret_cast< const StarPilotUIState(*)>(_a[2]))); break; - default: ; - } - } -} - -QT_INIT_METAOBJECT const QMetaObject OnroadWindow::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_OnroadWindow.data, - qt_meta_data_OnroadWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *OnroadWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *OnroadWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_OnroadWindow.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int OnroadWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/onroad/model.cc b/selfdrive/ui/qt/onroad/model.cc deleted file mode 100644 index 7f0304b9c..000000000 --- a/selfdrive/ui/qt/onroad/model.cc +++ /dev/null @@ -1,401 +0,0 @@ -#include "selfdrive/ui/qt/onroad/model.h" - -constexpr int CLIP_MARGIN = 500; - -static int get_path_length_idx(const cereal::XYZTData::Reader &line, const float path_height) { - const auto &line_x = line.getX(); - int max_idx = 0; - for (int i = 1; i < line_x.size() && line_x[i] <= path_height; ++i) { - max_idx = i; - } - return max_idx; -} - -void ModelRenderer::draw(QPainter &painter, const QRect &surface_rect) { - auto *s = uiState(); - auto &sm = *(s->sm); - // Check if data is up-to-date - if (sm.rcv_frame("liveCalibration") < s->scene.started_frame || - sm.rcv_frame("modelV2") < s->scene.started_frame) { - return; - } - - clip_region = surface_rect.adjusted(-CLIP_MARGIN, -CLIP_MARGIN, CLIP_MARGIN, CLIP_MARGIN); - experimental_mode = sm["selfdriveState"].getSelfdriveState().getExperimentalMode(); - longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); - path_offset_z = sm["liveCalibration"].getLiveCalibration().getHeight()[0]; - - painter.save(); - - const auto &model = sm["modelV2"].getModelV2(); - const auto &radar_state = sm["radarState"].getRadarState(); - const auto &lead_one = radar_state.getLeadOne(); - - update_model(model, lead_one, surface_rect.height()); - drawLaneLines(painter); - drawPath(painter, model, surface_rect.height()); - - if ((longitudinal_control || starpilot_toggles.value("lead_info").toBool()) && sm.alive("radarState") && !starpilot_toggles.value("hide_lead_marker").toBool()) { - update_leads(radar_state, model.getPosition()); - const auto &lead_two = radar_state.getLeadTwo(); - if (lead_one.getStatus()) { - if (lead_one.getModelProb() >= starpilot_toggles.value("lead_detection_probability").toDouble()) { - drawLead(painter, lead_one, lead_vertices[0], surface_rect, QColor(starpilot_toggles.value("lead_marker_color").toString())); - } else { - drawLead(painter, lead_one, lead_vertices[0], surface_rect, starpilot_nvg->whiteColor()); - } - } else { - starpilot_nvg->leadTextRect = QRect(); - } - if (lead_two.getStatus() && (std::abs(lead_one.getDRel() - lead_two.getDRel()) > 3.0)) { - drawLead(painter, lead_two, lead_vertices[1], surface_rect, QColor(starpilot_toggles.value("lead_marker_color").toString())); - } - - // Adjacent leads may be published by radard for non-UI consumers (e.g. HumanLaneChanges), - // so gate drawing on the AdjacentLeadsUI toggle directly. - if (starpilot_toggles.value("adjacent_lead_tracking").toBool()) { - SubMaster &fpsm = *(starpilotUIState()->sm); - const cereal::StarPilotRadarState::Reader &starpilot_radar_state = fpsm["starpilotRadarState"].getStarpilotRadarState(); - - const cereal::StarPilotRadarState::LeadData::Reader &lead_left = starpilot_radar_state.getLeadLeft(); - const cereal::StarPilotRadarState::LeadData::Reader &lead_right = starpilot_radar_state.getLeadRight(); - - updateAdjacentLeads(starpilot_radar_state, model.getPosition()); - - starpilot_nvg->adjacentLeadTextRect = QRect(); - - if (lead_left.getStatus() && lead_right.getStatus() && (lead_left.getDRel() < lead_right.getDRel())) { - drawLead(painter, reinterpret_cast(lead_left), adjacent_lead_vertices[0], surface_rect, starpilot_nvg->blueColor(), true); - drawLead(painter, reinterpret_cast(lead_right), adjacent_lead_vertices[1], surface_rect, starpilot_nvg->purpleColor(), true); - } else { - if (lead_left.getStatus()) { - drawLead(painter, reinterpret_cast(lead_left), adjacent_lead_vertices[0], surface_rect, starpilot_nvg->blueColor(), true); - } - if (lead_right.getStatus()) { - drawLead(painter, reinterpret_cast(lead_right), adjacent_lead_vertices[1], surface_rect, starpilot_nvg->purpleColor(), true); - } - } - } - } - - if (starpilot_toggles.value("radar_tracks").toBool()) { - updateRadarTracks(model.getPosition()); - } - - painter.restore(); -} - -void ModelRenderer::update_leads(const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line) { - for (int i = 0; i < 2; ++i) { - const auto &lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo(); - if (lead_data.getStatus()) { - float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())]; - mapToScreen(lead_data.getDRel(), -lead_data.getYRel(), z + path_offset_z, &lead_vertices[i]); - } - } -} - -void ModelRenderer::update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead, float height) { - const auto &model_position = model.getPosition(); - float max_distance = *(model_position.getX().end() - 1); - - // update lane lines - const auto &lane_lines = model.getLaneLines(); - const auto &line_probs = model.getLaneLineProbs(); - int max_idx = get_path_length_idx(lane_lines[0], max_distance); - for (int i = 0; i < std::size(lane_line_vertices); i++) { - lane_line_probs[i] = line_probs[i]; - mapLineToPolygon(lane_lines[i], (starpilot_toggles.value("model_ui").toBool() ? starpilot_toggles.value("lane_line_width").toDouble() : 0.025) * lane_line_probs[i], 0, &lane_line_vertices[i], max_idx); - } - - // update road edges - const auto &road_edges = model.getRoadEdges(); - const auto &edge_stds = model.getRoadEdgeStds(); - for (int i = 0; i < std::size(road_edge_vertices); i++) { - road_edge_stds[i] = edge_stds[i]; - mapLineToPolygon(road_edges[i], starpilot_toggles.value("model_ui").toBool() ? starpilot_toggles.value("road_edge_width").toDouble() : 0.025, 0, &road_edge_vertices[i], max_idx); - } - - // update path - if (lead.getStatus()) { - const float lead_d = lead.getDRel() * 2.; - max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); - } - max_idx = get_path_length_idx(model_position, max_distance); - float path_width = starpilot_toggles.value("path_width").toDouble(); - if (starpilot_toggles.value("dynamic_path_width").toBool()) { - UIState *s = uiState(); - path_width *= s->status == STATUS_ENGAGED ? 1.0f : s->status == STATUS_ALWAYS_ON_LATERAL_ACTIVE ? 0.75f : 0.50f; - } - mapLineToPolygon(model_position, starpilot_toggles.value("model_ui").toBool() ? path_width * (1 - (starpilot_toggles.value("path_edge_width").toDouble() / 100.0f)) : 0.9, path_offset_z, &track_vertices, max_idx, false); - - StarPilotUIState *fs = starpilotUIState(); - SubMaster &fpsm = *(fs->sm); - - const cereal::StarPilotPlan::Reader &starpilotPlan = fpsm["starpilotPlan"].getStarpilotPlan(); - - starpilot_nvg->track_vertices = track_vertices; - - mapLineToPolygon(model_position, starpilot_toggles.value("model_ui").toBool() ? path_width : 0, path_offset_z, &starpilot_nvg->track_edge_vertices, max_idx, false); - - mapAveragedLineToPolygon(lane_lines[0], lane_lines[1], starpilotPlan.getLaneWidthLeft() / 2.0f, 0, &starpilot_nvg->track_adjacent_vertices[0], max_idx, height, false); - mapAveragedLineToPolygon(lane_lines[2], lane_lines[3], starpilotPlan.getLaneWidthRight() / 2.0f, 0, &starpilot_nvg->track_adjacent_vertices[1], max_idx, height, false); -} - -void ModelRenderer::drawLaneLines(QPainter &painter) { - // lanelines - for (int i = 0; i < std::size(lane_line_vertices); ++i) { - if (starpilot_toggles.value("color_scheme").toString() != "stock") { - painter.setBrush(QColor::fromRgbF(1.0, 1.0, 1.0, std::clamp(lane_line_probs[i], 0.0, 0.7))); - } else { - QColor lane_color = QColor(starpilot_toggles.value("lane_lines_color").toString()); - lane_color.setAlphaF(lane_color.alphaF() * std::clamp(lane_line_probs[i], 0.0, 0.7)); - painter.setBrush(lane_color); - } - painter.drawPolygon(lane_line_vertices[i]); - } - - // road edges - for (int i = 0; i < std::size(road_edge_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 0, 0, std::clamp(1.0 - road_edge_stds[i], 0.0, 1.0))); - painter.drawPolygon(road_edge_vertices[i]); - } -} - -void ModelRenderer::drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, int height) { - QLinearGradient bg(0, height, 0, 0); - if (experimental_mode || starpilot_toggles.value("acceleration_path").toBool() || starpilot_toggles.value("rainbow_path").toBool()) { - // The first half of track_vertices are the points for the right side of the path - const auto &acceleration = model.getAcceleration().getX(); - const int max_len = std::min(track_vertices.length() / 2, acceleration.size()); - - for (int i = 0; i < max_len; ++i) { - // Some points are out of frame - int track_idx = max_len - i - 1; // flip idx to start from bottom right - if (track_vertices[track_idx].y() < 0 || track_vertices[track_idx].y() > height) continue; - - // Flip so 0 is bottom of frame - float lin_grad_point = (height - track_vertices[track_idx].y()) / height; - - if ((fabs(acceleration[i]) < 0.25 || !starpilot_toggles.value("acceleration_path").toBool()) && starpilot_toggles.value("rainbow_path").toBool()) { - starpilot_nvg->paintRainbowPath(painter, bg, lin_grad_point); - } else if (fabs(acceleration[i]) < 0.25 && starpilot_toggles.value("color_scheme").toString() != "stock") { - QColor color = QColor(starpilot_toggles.value("path_color").toString()); - color.setAlphaF(util::map_val(lin_grad_point, 0.0f, 1.0f, 1.0f, 0.1f)); - bg.setColorAt(lin_grad_point, color); - } else { - // speed up: 120, slow down: 0 - float path_hue = fmax(fmin(60 + acceleration[i] * 35, 120), 0); - // FIXME: painter.drawPolygon can be slow if hue is not rounded - path_hue = int(path_hue * 100 + 0.5) / 100; - - float saturation = fmin(fabs(acceleration[i] * 1.5), 1); - float lightness = util::map_val(saturation, 0.0f, 1.0f, 0.95f, 0.62f); // lighter when grey - float alpha = util::map_val(lin_grad_point, 0.75f / 2.f, 0.75f, 0.4f, 0.0f); // matches previous alpha fade - bg.setColorAt(lin_grad_point, QColor::fromHslF(path_hue / 360., saturation, lightness, alpha)); - - // Skip a point, unless next is last - i += (i + 2) < max_len ? 1 : 0; - } - } - - } else { - updatePathGradient(bg); - } - - painter.setBrush(bg); - painter.drawPolygon(track_vertices); - - if (starpilot_toggles.value("adjacent_paths").toBool() || starpilot_toggles.value("adjacent_path_metrics").toBool()) { - starpilot_nvg->paintAdjacentPaths(painter); - } else if (starpilot_toggles.value("blind_spot_path").toBool()) { - starpilot_nvg->paintBlindSpotPath(painter); - } - - starpilot_nvg->paintPathEdges(painter, height); -} - -void ModelRenderer::updatePathGradient(QLinearGradient &bg) { - static const QColor throttle_colors[] = { - QColor::fromHslF(148. / 360., 0.94, 0.51, 0.4), - QColor::fromHslF(112. / 360., 1.0, 0.68, 0.35), - QColor::fromHslF(112. / 360., 1.0, 0.68, 0.0)}; - - static const QColor no_throttle_colors[] = { - QColor::fromHslF(148. / 360., 0.0, 0.95, 0.4), - QColor::fromHslF(112. / 360., 0.0, 0.95, 0.35), - QColor::fromHslF(112. / 360., 0.0, 0.95, 0.0), - }; - - // Transition speed; 0.1 corresponds to 0.5 seconds at UI_FREQ - constexpr float transition_speed = 0.1f; - - // Start transition if throttle state changes - bool allow_throttle = (*uiState()->sm)["longitudinalPlan"].getLongitudinalPlan().getAllowThrottle() || !longitudinal_control; - if (allow_throttle != prev_allow_throttle) { - prev_allow_throttle = allow_throttle; - // Invert blend factor for a smooth transition when the state changes mid-animation - blend_factor = std::max(1.0f - blend_factor, 0.0f); - } - - const QColor *begin_colors = allow_throttle ? no_throttle_colors : throttle_colors; - const QColor *end_colors = allow_throttle ? throttle_colors : no_throttle_colors; - if (blend_factor < 1.0f) { - blend_factor = std::min(blend_factor + transition_speed, 1.0f); - } - - // Set gradient colors by blending the start and end colors - bg.setColorAt(0.0f, blendColors(begin_colors[0], end_colors[0], blend_factor)); - bg.setColorAt(0.5f, blendColors(begin_colors[1], end_colors[1], blend_factor)); - bg.setColorAt(1.0f, blendColors(begin_colors[2], end_colors[2], blend_factor)); -} - -QColor ModelRenderer::blendColors(const QColor &start, const QColor &end, float t) { - if (t == 1.0f) return end; - return QColor::fromRgbF( - (1 - t) * start.redF() + t * end.redF(), - (1 - t) * start.greenF() + t * end.greenF(), - (1 - t) * start.blueF() + t * end.blueF(), - (1 - t) * start.alphaF() + t * end.alphaF()); -} - -void ModelRenderer::drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, - const QPointF &vd, const QRect &surface_rect, QColor marker_color, bool adjacent) { - const float speedBuff = 10.; - const float leadBuff = 40.; - const float d_rel = lead_data.getDRel() + (adjacent ? fabs(lead_data.getYRel()) : 0); - const float v_rel = lead_data.getVRel(); - - float fillAlpha = 0; - if (d_rel < leadBuff) { - fillAlpha = 255 * (1.0 - (d_rel / leadBuff)); - if (v_rel < 0) { - fillAlpha += 255 * (-1 * (v_rel / speedBuff)); - } - fillAlpha = (int)(fmin(fillAlpha, 255)); - } - - float sz = std::clamp((25 * 30) / (d_rel / 3 + 30), 15.0f, 30.0f) * 2.35; - float x = std::clamp(vd.x(), 0.f, surface_rect.width() - sz / 2); - float y = std::min(vd.y(), surface_rect.height() - sz * 0.6); - - float g_xo = sz / 5; - float g_yo = sz / 10; - - QPointF glow[] = {{x + (sz * 1.35) + g_xo, y + sz + g_yo}, {x, y - g_yo}, {x - (sz * 1.35) - g_xo, y + sz + g_yo}}; - painter.setBrush(QColor(218, 202, 37, 255)); - painter.drawPolygon(glow, std::size(glow)); - - // chevron - QPointF chevron[] = {{x + (sz * 1.25), y + sz}, {x, y}, {x - (sz * 1.25), y + sz}}; - painter.setBrush(QColor(marker_color.red(), marker_color.green(), marker_color.blue(), fillAlpha)); - painter.drawPolygon(chevron, std::size(chevron)); - - if (starpilot_toggles.value("lead_info").toBool()) { - starpilot_nvg->paintLeadMetrics(painter, adjacent, chevron, lead_data); - } -} - -// Projects a point in car to space to the corresponding point in full frame image space. -bool ModelRenderer::mapToScreen(float in_x, float in_y, float in_z, QPointF *out) { - Eigen::Vector3f input(in_x, in_y, in_z); - auto pt = car_space_transform * input; - *out = QPointF(pt.x() / pt.z(), pt.y() / pt.z()); - return clip_region.contains(*out); -} - -void ModelRenderer::mapLineToPolygon(const cereal::XYZTData::Reader &line, float y_off, float z_off, - QPolygonF *pvd, int max_idx, bool allow_invert) { - const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); - QPointF left, right; - pvd->clear(); - for (int i = 0; i <= max_idx; i++) { - // highly negative x positions are drawn above the frame and cause flickering, clip to zy plane of camera - if (line_x[i] < 0) continue; - - bool l = mapToScreen(line_x[i], line_y[i] - y_off, line_z[i] + z_off, &left); - bool r = mapToScreen(line_x[i], line_y[i] + y_off, line_z[i] + z_off, &right); - if (l && r) { - // For wider lines the drawn polygon will "invert" when going over a hill and cause artifacts - if (!allow_invert && pvd->size() && left.y() > pvd->back().y()) { - continue; - } - pvd->push_back(left); - pvd->push_front(right); - } - } -} - -void ModelRenderer::mapAveragedLineToPolygon(const cereal::XYZTData::Reader &line1, const cereal::XYZTData::Reader &line2, float y_off, float z_off, - QPolygonF *pvd, int max_idx, float height, bool allow_invert) { - const auto line_x1 = line1.getX(), line_y1 = line1.getY(), line_z1 = line1.getZ(); - const auto line_y2 = line2.getY(); - QPointF left, right; - pvd->clear(); - for (int i = 0; i <= max_idx; i++) { - // highly negative x positions are drawn above the frame and cause flickering, clip to zy plane of camera - if (line_x1[i] < 0) continue; - - bool l = mapToScreen(line_x1[i], ((line_y1[i] + line_y2[i]) / 2.0f) - y_off, line_z1[i] + z_off, &left); - bool r = mapToScreen(line_x1[i], ((line_y1[i] + line_y2[i]) / 2.0f) + y_off, line_z1[i] + z_off, &right); - if (l && r) { - // For wider lines the drawn polygon will "invert" when going over a hill and cause artifacts - if (!allow_invert && pvd->size() && left.y() > pvd->back().y()) { - continue; - } - pvd->push_back(left); - pvd->push_front(right); - } - } - - // Ground the path - if (pvd->size() >= 4) { - int mid = pvd->size() / 2; - - std::function extendToBottom = [&](int idx1, int idx2) { - QPointF &p0 = (*pvd)[idx1]; - QPointF &p1 = (*pvd)[idx2]; - - float dy = p0.y() - p1.y(); - if (std::abs(dy) > 0.1f) { - float slope = (p0.x() - p1.x()) / dy; - p0.setX(p0.x() + (height - p0.y()) * slope); - p0.setY(height); - } - }; - - extendToBottom(mid, mid + 1); - extendToBottom(mid - 1, mid - 2); - } -} - -void ModelRenderer::updateAdjacentLeads(const cereal::StarPilotRadarState::Reader &radar_state, const cereal::XYZTData::Reader &line) { - for (int i = 0; i < 2; ++i) { - const auto &lead_data = (i == 0) ? radar_state.getLeadLeft() : radar_state.getLeadRight(); - if (lead_data.getStatus()) { - float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())]; - mapToScreen(lead_data.getDRel(), -lead_data.getYRel(), z + path_offset_z, &adjacent_lead_vertices[i]); - } - } -} - -void ModelRenderer::updateRadarTracks(const cereal::XYZTData::Reader &line) { - std::vector &radar_tracks = starpilot_nvg->radar_tracks; - radar_tracks.clear(); - - SubMaster &fpsm = *(starpilotUIState()->sm); - capnp::List::Reader radar_points = fpsm["liveTracks"].getLiveTracks().getPoints(); - radar_tracks.reserve(radar_points.size()); - - capnp::List::Reader line_z = line.getZ(); - - for (cereal::RadarData::RadarPoint::Reader point : radar_points) { - float d_rel = point.getDRel(); - float z = line_z[get_path_length_idx(line, d_rel)]; - - QPointF calibrated_point; - if (mapToScreen(d_rel, -point.getYRel(), z + path_offset_z, &calibrated_point)) { - radar_tracks.push_back(calibrated_point); - } - } -} diff --git a/selfdrive/ui/qt/onroad/model.h b/selfdrive/ui/qt/onroad/model.h deleted file mode 100644 index fc9f846d3..000000000 --- a/selfdrive/ui/qt/onroad/model.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/ui.h" - -#include "starpilot/ui/qt/onroad/starpilot_annotated_camera.h" - -class ModelRenderer { -public: - ModelRenderer() {} - void setTransform(const Eigen::Matrix3f &transform) { car_space_transform = transform; } - void draw(QPainter &painter, const QRect &surface_rect); - - StarPilotAnnotatedCameraWidget *starpilot_nvg; - - StarPilotUIScene starpilot_scene; - - QJsonObject starpilot_toggles; - -private: - bool mapToScreen(float in_x, float in_y, float in_z, QPointF *out); - void mapLineToPolygon(const cereal::XYZTData::Reader &line, float y_off, float z_off, - QPolygonF *pvd, int max_idx, bool allow_invert = true); - void drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, const QPointF &vd, const QRect &surface_rect, QColor marker_color, bool adjacent=false); - void update_leads(const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line); - void update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead, float height); - void drawLaneLines(QPainter &painter); - void drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, int height); - void updatePathGradient(QLinearGradient &bg); - QColor blendColors(const QColor &start, const QColor &end, float t); - - bool longitudinal_control = false; - bool experimental_mode = false; - float blend_factor = 1.0f; - bool prev_allow_throttle = true; - float lane_line_probs[4] = {}; - float road_edge_stds[2] = {}; - float path_offset_z = 1.22f; - QPolygonF track_vertices; - QPolygonF lane_line_vertices[4] = {}; - QPolygonF road_edge_vertices[2] = {}; - QPointF lead_vertices[2] = {}; - Eigen::Matrix3f car_space_transform = Eigen::Matrix3f::Zero(); - QRectF clip_region; - - void mapAveragedLineToPolygon(const cereal::XYZTData::Reader &line1, const cereal::XYZTData::Reader &line2, float y_off, float z_off, - QPolygonF *pvd, int max_idx, float height, bool allow_invert = true); - void updateAdjacentLeads(const cereal::StarPilotRadarState::Reader &radar_state, const cereal::XYZTData::Reader &line); - void updateRadarTracks(const cereal::XYZTData::Reader &line); - - QPointF adjacent_lead_vertices[2] = {}; -}; diff --git a/selfdrive/ui/qt/onroad/onroad_home.cc b/selfdrive/ui/qt/onroad/onroad_home.cc deleted file mode 100644 index 6fd83821f..000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.cc +++ /dev/null @@ -1,149 +0,0 @@ -#include "selfdrive/ui/qt/onroad/onroad_home.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - QStackedLayout *stacked_layout = new QStackedLayout; - stacked_layout->setStackingMode(QStackedLayout::StackAll); - main_layout->addLayout(stacked_layout); - - nvg = new AnnotatedCameraWidget(VISION_STREAM_ROAD, this); - - QWidget * split_wrapper = new QWidget; - split = new QHBoxLayout(split_wrapper); - split->setContentsMargins(0, 0, 0, 0); - split->setSpacing(0); - split->addWidget(nvg); - - if (getenv("DUAL_CAMERA_VIEW")) { - CameraWidget *arCam = new CameraWidget("camerad", VISION_STREAM_ROAD, this); - split->insertWidget(0, arCam); - } - - stacked_layout->addWidget(split_wrapper); - - alerts = new OnroadAlerts(this); - alerts->setAttribute(Qt::WA_TransparentForMouseEvents, true); - stacked_layout->addWidget(alerts); - - // setup stacking order - alerts->raise(); - - setAttribute(Qt::WA_OpaquePaintEvent); - QObject::connect(uiState(), &UIState::uiUpdate, this, &OnroadWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &OnroadWindow::offroadTransition); - - starpilot_nvg = new StarPilotAnnotatedCameraWidget(this); - starpilot_onroad = new StarPilotOnroadWindow(this); - starpilot_onroad->setAttribute(Qt::WA_TransparentForMouseEvents, true); - - stacked_layout->addWidget(starpilot_nvg); - stacked_layout->addWidget(starpilot_onroad); - - starpilot_onroad->raise(); - alerts->raise(); - - nvg->starpilot_nvg = starpilot_nvg; -} - -void OnroadWindow::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!s.scene.started) { - return; - } - - alerts->updateState(s, fs); - nvg->updateState(s, fs); - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const auto selfdriveState = (*s.sm)["selfdriveState"].getSelfdriveState(); - const bool enabled = selfdriveState.getEnabled(); - QColor bgColor = bg_colors[s.status]; - const bool conditional_experimental_mode = starpilot_toggles.value("conditional_experimental_mode").toBool(); - const bool conditional_chill_mode = starpilot_toggles.value("conditional_chill_mode").toBool(); - const bool highlight_override = - enabled && ((conditional_experimental_mode && starpilot_scene.conditional_status == 1) || - (conditional_chill_mode && (starpilot_scene.conditional_status == 1 || starpilot_scene.conditional_status == 2))); - if (starpilot_scene.switchback_mode_enabled && (enabled || starpilot_scene.always_on_lateral_active)) { - bgColor = bg_colors[STATUS_SWITCHBACK_MODE_ENABLED]; - } else if (starpilot_scene.always_on_lateral_active) { - bgColor = bg_colors[STATUS_ALWAYS_ON_LATERAL_ACTIVE]; - } else if (highlight_override) { - bgColor = bg_colors[STATUS_CEM_DISABLED]; - } else if (enabled && selfdriveState.getExperimentalMode()) { - bgColor = bg_colors[STATUS_EXPERIMENTAL_MODE_ENABLED]; - } else if (starpilot_scene.traffic_mode_enabled && enabled) { - bgColor = bg_colors[STATUS_TRAFFIC_MODE_ENABLED]; - } - - if (bg != bgColor) { - // repaint border - bg = bgColor; - update(); - } - starpilot_nvg->alertHeight = alerts->alertHeight; - - starpilot_onroad->bg = bg; - starpilot_onroad->fps = nvg->fps; - - nvg->starpilot_nvg = starpilot_nvg; - - nvg->starpilot_scene = starpilot_scene; - starpilot_nvg->starpilot_scene = starpilot_scene; - starpilot_onroad->starpilot_scene = starpilot_scene; - - alerts->starpilot_toggles = starpilot_toggles; - starpilot_nvg->starpilot_toggles = starpilot_toggles; - starpilot_onroad->starpilot_toggles = starpilot_toggles; - nvg->starpilot_toggles = starpilot_toggles; - - starpilot_onroad->setGeometry(rect()); - - starpilot_nvg->updateState(s, fs); - starpilot_onroad->updateState(s, fs); -} - -void OnroadWindow::offroadTransition(bool offroad) { - alerts->clear(); -} - -void OnroadWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.fillRect(rect(), QColor(bg.red(), bg.green(), bg.blue(), 255)); -} - -void OnroadWindow::mousePressEvent(QMouseEvent* mouseEvent) { - if (nvg->handleHudPress(mouseEvent->pos())) { - grabMouse(); - mouseEvent->accept(); - return; - } - - starpilot_nvg->mousePressEvent(mouseEvent); - - if (mouseEvent->isAccepted()) { - return; - } - - // propagation event to parent(HomeWindow) - QWidget::mousePressEvent(mouseEvent); -} - -void OnroadWindow::mouseReleaseEvent(QMouseEvent* mouseEvent) { - const bool handled = nvg->handleHudRelease(mouseEvent->pos()); - if (QWidget::mouseGrabber() == this) { - releaseMouse(); - } - - if (handled) { - mouseEvent->accept(); - return; - } - - QWidget::mouseReleaseEvent(mouseEvent); -} diff --git a/selfdrive/ui/qt/onroad/onroad_home.h b/selfdrive/ui/qt/onroad/onroad_home.h deleted file mode 100644 index d6b6d68a1..000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/onroad/alerts.h" -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -#include "starpilot/ui/qt/onroad/starpilot_onroad.h" - -class OnroadWindow : public QWidget { - Q_OBJECT - -public: - OnroadWindow(QWidget* parent = 0); - -private: - void paintEvent(QPaintEvent *event); - OnroadAlerts *alerts; - AnnotatedCameraWidget *nvg; - QColor bg = bg_colors[STATUS_DISENGAGED]; - QHBoxLayout* split; - - void mousePressEvent(QMouseEvent* mouseEvent); - void mouseReleaseEvent(QMouseEvent* mouseEvent); - - StarPilotAnnotatedCameraWidget *starpilot_nvg; - StarPilotOnroadWindow *starpilot_onroad; - -private slots: - void offroadTransition(bool offroad); - void updateState(const UIState &s, const StarPilotUIState &fs); -}; diff --git a/selfdrive/ui/qt/prime_state.cc b/selfdrive/ui/qt/prime_state.cc deleted file mode 100644 index 4dc17d757..000000000 --- a/selfdrive/ui/qt/prime_state.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "selfdrive/ui/qt/prime_state.h" - -#include - -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" - -PrimeState::PrimeState(QObject* parent) : QObject(parent) { - const char *env_prime_type = std::getenv("PRIME_TYPE"); - auto type = env_prime_type ? env_prime_type : Params().get("PrimeType"); - - if (!type.empty()) { - prime_type = static_cast(std::atoi(type.c_str())); - } - - if (auto dongleId = getDongleId()) { - QString url = CommaApi::BASE_URL + "/v1.1/devices/" + *dongleId + "/"; - RequestRepeater* repeater = new RequestRepeater(this, url, "ApiCache_Device", 60); - QObject::connect(repeater, &RequestRepeater::requestDone, this, &PrimeState::handleReply); - } - - // Emit the initial state change - QTimer::singleShot(1, [this]() { emit changed(prime_type); }); -} - -void PrimeState::handleReply(const QString& response, bool success) { - if (!success) return; - - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - if (doc.isNull()) { - qDebug() << "JSON Parse failed on getting pairing and PrimeState status"; - return; - } - - QJsonObject json = doc.object(); - bool is_paired = json["is_paired"].toBool(); - auto type = static_cast(json["prime_type"].toInt()); - setType(is_paired ? type : PrimeState::PRIME_TYPE_UNPAIRED); -} - -void PrimeState::setType(PrimeState::Type type) { - if (type != prime_type) { - prime_type = type; - Params().put("PrimeType", std::to_string(prime_type)); - emit changed(prime_type); - } -} diff --git a/selfdrive/ui/qt/prime_state.h b/selfdrive/ui/qt/prime_state.h deleted file mode 100644 index 0e2e3bb04..000000000 --- a/selfdrive/ui/qt/prime_state.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include - -class PrimeState : public QObject { - Q_OBJECT - -public: - - enum Type { - PRIME_TYPE_UNKNOWN = -2, - PRIME_TYPE_UNPAIRED = -1, - PRIME_TYPE_NONE = 0, - PRIME_TYPE_MAGENTA = 1, - PRIME_TYPE_LITE = 2, - PRIME_TYPE_BLUE = 3, - PRIME_TYPE_MAGENTA_NEW = 4, - PRIME_TYPE_PURPLE = 5, - }; - - PrimeState(QObject *parent); - void setType(PrimeState::Type type); - inline PrimeState::Type currentType() const { return prime_type; } - inline bool isSubscribed() const { return prime_type > PrimeState::PRIME_TYPE_NONE; } - -signals: - void changed(PrimeState::Type prime_type); - -private: - void handleReply(const QString &response, bool success); - - PrimeState::Type prime_type = PrimeState::PRIME_TYPE_UNKNOWN; -}; diff --git a/selfdrive/ui/qt/qt_window.cc b/selfdrive/ui/qt/qt_window.cc deleted file mode 100644 index 8d3d7cf72..000000000 --- a/selfdrive/ui/qt/qt_window.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include "selfdrive/ui/qt/qt_window.h" - -void setMainWindow(QWidget *w) { - const float scale = util::getenv("SCALE", 1.0f); - const QSize sz = QGuiApplication::primaryScreen()->size(); - - if (Hardware::PC() && scale == 1.0 && !(sz - DEVICE_SCREEN_SIZE).isValid()) { - w->setMinimumSize(QSize(640, 480)); // allow resize smaller than fullscreen - w->setMaximumSize(DEVICE_SCREEN_SIZE); - w->resize(sz); - } else { - w->setFixedSize(DEVICE_SCREEN_SIZE * scale); - } - w->show(); - -#ifdef QCOM2 - QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); - wl_surface *s = reinterpret_cast(native->nativeResourceForWindow("surface", w->windowHandle())); - wl_surface_set_buffer_transform(s, WL_OUTPUT_TRANSFORM_270); - wl_surface_commit(s); - - w->setWindowState(Qt::WindowFullScreen); - w->setVisible(true); - - // ensure we have a valid eglDisplay, otherwise the ui will silently fail - void *egl = native->nativeResourceForWindow("egldisplay", w->windowHandle()); - assert(egl != nullptr); -#endif -} - - -extern "C" { - void set_main_window(void *w) { - setMainWindow((QWidget*)w); - } -} diff --git a/selfdrive/ui/qt/qt_window.h b/selfdrive/ui/qt/qt_window.h deleted file mode 100644 index 6f16e0095..000000000 --- a/selfdrive/ui/qt/qt_window.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -#ifdef QCOM2 -#include -#include -#include -#endif - -#include "system/hardware/hw.h" - -const QString ASSET_PATH = ":/"; -const QSize DEVICE_SCREEN_SIZE = {2160, 1080}; - -void setMainWindow(QWidget *w); diff --git a/selfdrive/ui/qt/request_repeater.cc b/selfdrive/ui/qt/request_repeater.cc deleted file mode 100644 index 7aa731898..000000000 --- a/selfdrive/ui/qt/request_repeater.cc +++ /dev/null @@ -1,27 +0,0 @@ -#include "selfdrive/ui/qt/request_repeater.h" - -RequestRepeater::RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey, - int period, bool while_onroad) : HttpRequest(parent) { - timer = new QTimer(this); - timer->setTimerType(Qt::VeryCoarseTimer); - QObject::connect(timer, &QTimer::timeout, [=]() { - if ((!uiState()->scene.started || while_onroad) && device()->isAwake() && !active()) { - sendRequest(requestURL); - } - }); - - timer->start(period * 1000); - - if (!cacheKey.isEmpty()) { - prevResp = QString::fromStdString(params.get(cacheKey.toStdString())); - if (!prevResp.isEmpty()) { - QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true, QNetworkReply::NoError); }); - } - QObject::connect(this, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success && resp != prevResp) { - params.put(cacheKey.toStdString(), resp.toStdString()); - prevResp = resp; - } - }); - } -} diff --git a/selfdrive/ui/qt/request_repeater.h b/selfdrive/ui/qt/request_repeater.h deleted file mode 100644 index c0e275827..000000000 --- a/selfdrive/ui/qt/request_repeater.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "common/util.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/ui.h" - -class RequestRepeater : public HttpRequest { -public: - RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey = "", int period = 0, bool while_onroad=false); - -private: - Params params; - QTimer *timer; - QString prevResp; -}; diff --git a/selfdrive/ui/qt/sidebar.cc b/selfdrive/ui/qt/sidebar.cc deleted file mode 100644 index ae5d24045..000000000 --- a/selfdrive/ui/qt/sidebar.cc +++ /dev/null @@ -1,336 +0,0 @@ -#include "selfdrive/ui/qt/sidebar.h" - -#include -#include - -#include - -#include "selfdrive/ui/qt/util.h" - -void Sidebar::drawMetric(QPainter &p, const QPair &label, QColor c, int y) { - const QRect rect = {30, y, 240, 126}; - - p.setPen(Qt::NoPen); - p.setBrush(QBrush(c)); - p.setClipRect(rect.x() + 4, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); - p.drawRoundedRect(QRect(rect.x() + 4, rect.y() + 4, 100, 118), 18, 18); - p.setClipping(false); - - QPen pen = QPen(QColor(0xff, 0xff, 0xff, 0x55)); - pen.setWidth(2); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRoundedRect(rect, 20, 20); - - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setFont(InterFont(35, QFont::DemiBold)); - p.drawText(rect.adjusted(22, 0, 0, 0), Qt::AlignCenter, label.first + "\n" + label.second); -} - -Sidebar::Sidebar(QWidget *parent) : QFrame(parent), onroad(false), flag_pressed(false), settings_pressed(false), mic_indicator_pressed(false) { - home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); - flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); - settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); - mic_img = loadPixmap("../assets/icons/microphone.png", QSize(30, 30)); - link_img = loadPixmap("../assets/icons/link.png", QSize(60, 60)); - - connect(this, &Sidebar::valueChanged, [=] { update(); }); - - setAttribute(Qt::WA_OpaquePaintEvent); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - setFixedWidth(300); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &Sidebar::updateState); - - pm = std::make_unique(std::vector{"bookmarkButton"}); - - QObject::connect(starpilotUIState(), &StarPilotUIState::themeUpdated, this, &Sidebar::updateTheme); -} - -void Sidebar::mousePressEvent(QMouseEvent *event) { - QPoint pos = event->pos(); - - static constexpr QRect cpuRect = {30, 496, 240, 126}; - static constexpr QRect memoryRect = {30, 654, 240, 126}; - static constexpr QRect tempRect = {30, 338, 240, 126}; - - static int showChip = 0; - static int showMemory = 0; - static int showTemp = 0; - - StarPilotUIState *fs = starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool simple_mode = starpilot_toggles.value("simple_mode").toBool(); - - if (!simple_mode && cpuRect.contains(pos) && starpilot_toggles.value("developer_ui").toBool()) { - showChip = (showChip + 1) % 3; - - params.putBool("ShowCPU", showChip == 1); - params.putBool("ShowGPU", showChip == 2); - } else if (!simple_mode && memoryRect.contains(pos) && starpilot_toggles.value("developer_ui").toBool()) { - showMemory = (showMemory + 1) % 4; - - params.putBool("ShowMemoryUsage", showMemory == 1); - params.putBool("ShowStorageLeft", showMemory == 2); - params.putBool("ShowStorageUsed", showMemory == 3); - } else if (!simple_mode && tempRect.contains(pos) && starpilot_toggles.value("developer_ui").toBool()) { - showTemp = (showTemp + 1) % 3; - - params.putBool("Fahrenheit", showTemp == 2); - params.putBool("NumericalTemp", showTemp != 0); - } else if (onroad && home_btn.contains(pos)) { - flag_pressed = true; - } else if (settings_btn.contains(pos)) { - settings_pressed = true; - } else if (recording_audio && mic_indicator_btn.contains(event->pos())) { - mic_indicator_pressed = true; - } - - if (!(flag_pressed || mic_indicator_pressed || settings_pressed)) { - update(); - updateStarPilotToggles(); - } -} - -void Sidebar::mouseReleaseEvent(QMouseEvent *event) { - if (flag_pressed || settings_pressed || mic_indicator_pressed) { - flag_pressed = settings_pressed = mic_indicator_pressed = false; - update(); - } - if (onroad && home_btn.contains(event->pos())) { - MessageBuilder msg; - msg.initEvent().initBookmarkButton(); - pm->send("bookmarkButton", msg); - } else if (settings_btn.contains(event->pos())) { - emit openSettings(); - } else if (recording_audio && mic_indicator_btn.contains(event->pos())) { - emit openSettings(2, "RecordAudio"); - } -} - -void Sidebar::offroadTransition(bool offroad) { - onroad = !offroad; - update(); -} - -void Sidebar::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible()) return; - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool simple_mode = starpilot_toggles.value("simple_mode").toBool(); - static bool previous_simple_mode = simple_mode; - if (previous_simple_mode != simple_mode) { - updateTheme(); - previous_simple_mode = simple_mode; - } - - const SubMaster &fpsm = *(fs.sm); - - const cereal::StarPilotDeviceState::Reader &starpilotDeviceState = fpsm["starpilotDeviceState"].getStarpilotDeviceState(); - - auto &sm = *(s.sm); - - networking = networking ? networking : window()->findChild(""); - bool tethering_on = networking && networking->wifi->tethering_on; - auto deviceState = sm["deviceState"].getDeviceState(); - - const char *desktop_fake_wifi_env = std::getenv("SP_ALLOW_DESKTOP_FAKE_WIFI"); - const bool desktop_force_online = Hardware::PC() && desktop_fake_wifi_env != nullptr && std::string(desktop_fake_wifi_env) != "0"; - - auto net_type_value = desktop_force_online ? cereal::DeviceState::NetworkType::WIFI : deviceState.getNetworkType(); - setProperty("netType", tethering_on ? "Hotspot" : network_type[net_type_value]); - int strength = tethering_on ? 4 : (desktop_force_online ? 4 : (int)deviceState.getNetworkStrength()); - setProperty("netStrength", strength > 0 ? strength + 1 : 0); - - ItemStatus connectStatus; - auto last_ping = deviceState.getLastAthenaPingTime(); - if (desktop_force_online) { - connectStatus = ItemStatus{{tr("CONNECT"), tr("ONLINE")}, simple_mode ? good_color : QColor(starpilot_toggles.value("sidebar_color3").toString())}; - } else if (last_ping == 0) { - connectStatus = ItemStatus{{tr("CONNECT"), tr("OFFLINE")}, warning_color}; - } else { - connectStatus = nanos_since_boot() - last_ping < 80e9 - ? ItemStatus{{tr("CONNECT"), tr("ONLINE")}, simple_mode ? good_color : QColor(starpilot_toggles.value("sidebar_color3").toString())} - : ItemStatus{{tr("CONNECT"), tr("ERROR")}, danger_color}; - } - setProperty("connectStatus", QVariant::fromValue(connectStatus)); - - int maxTempC = deviceState.getMaxTempC(); - QString max_temp = starpilot_toggles.value("fahrenheit").toBool() ? QString::number(maxTempC * 9 / 5 + 32) + "°F" : QString::number(maxTempC) + "°C"; - ItemStatus tempStatus = {{tr("TEMP"), simple_mode ? tr("HIGH") : (starpilot_toggles.value("numerical_temp").toBool() ? max_temp : tr("HIGH"))}, danger_color}; - auto ts = deviceState.getThermalStatus(); - if (ts == cereal::DeviceState::ThermalStatus::GREEN) { - tempStatus = {{tr("TEMP"), simple_mode ? tr("GOOD") : (starpilot_toggles.value("numerical_temp").toBool() ? max_temp : tr("GOOD"))}, - simple_mode ? good_color : QColor(starpilot_toggles.value("sidebar_color1").toString())}; - } else if (ts == cereal::DeviceState::ThermalStatus::YELLOW) { - tempStatus = {{tr("TEMP"), simple_mode ? tr("OK") : (starpilot_toggles.value("numerical_temp").toBool() ? max_temp : tr("OK"))}, warning_color}; - } - setProperty("tempStatus", QVariant::fromValue(tempStatus)); - - ItemStatus pandaStatus = {{tr("VEHICLE"), tr("ONLINE")}, simple_mode ? good_color : QColor(starpilot_toggles.value("sidebar_color2").toString())}; - if (s.scene.pandaType == cereal::PandaState::PandaType::UNKNOWN) { - pandaStatus = {{tr("NO"), tr("PANDA")}, danger_color}; - } - setProperty("pandaStatus", QVariant::fromValue(pandaStatus)); - - setProperty("recordingAudio", s.scene.recording_audio); - - if (!simple_mode && (starpilot_toggles.value("cpu_metrics").toBool() || starpilot_toggles.value("gpu_metrics").toBool())) { - capnp::List::Reader cpu_loads = deviceState.getCpuUsagePercent(); - int cpu_usage = cpu_loads.size() != 0 ? std::accumulate(cpu_loads.begin(), cpu_loads.end(), 0) / cpu_loads.size() : 0; - int gpu_usage = deviceState.getGpuUsagePercent(); - int usage = starpilot_toggles.value("cpu_metrics").toBool() ? cpu_usage : gpu_usage; - - QString chip_usage = QString::number(usage) + "%"; - - ItemStatus chipStatus = {{starpilot_toggles.value("gpu_metrics").toBool() ? tr("GPU") : tr("CPU"), chip_usage}, QColor(starpilot_toggles.value("sidebar_color2").toString())}; - if (usage >= 85) { - chipStatus = {{starpilot_toggles.value("gpu_metrics").toBool() ? tr("GPU") : tr("CPU"), chip_usage}, danger_color}; - } else if (usage >= 70) { - chipStatus = {{starpilot_toggles.value("gpu_metrics").toBool() ? tr("GPU") : tr("CPU"), chip_usage}, warning_color}; - } - setProperty("chipStatus", QVariant::fromValue(chipStatus)); - } - - if (!simple_mode && (starpilot_toggles.value("memory_metrics").toBool() || starpilot_toggles.value("storage_left_metrics").toBool() || starpilot_toggles.value("storage_used_metrics").toBool())) { - int free_space = deviceState.getFreeSpacePercent(); - int memory_usage = deviceState.getMemoryUsagePercent(); - int storage_left = starpilotDeviceState.getFreeSpace(); - int storage_used = starpilotDeviceState.getUsedSpace(); - - QString memory = QString::number(memory_usage) + "%"; - QString storage = QString::number(starpilot_toggles.value("storage_left_metrics").toBool() ? storage_left : storage_used) + tr(" GB"); - - if (starpilot_toggles.value("memory_metrics").toBool()) { - ItemStatus memoryStatus = {{tr("MEMORY"), memory}, QColor(starpilot_toggles.value("sidebar_color3").toString())}; - if (memory_usage >= 85) { - memoryStatus = {{tr("MEMORY"), memory}, danger_color}; - } else if (memory_usage >= 70) { - memoryStatus = {{tr("MEMORY"), memory}, warning_color}; - } - setProperty("memoryStatus", QVariant::fromValue(memoryStatus)); - } else { - ItemStatus storageStatus = {{starpilot_toggles.value("storage_left_metrics").toBool() ? tr("LEFT") : tr("USED"), storage}, QColor(starpilot_toggles.value("sidebar_color3").toString())}; - if (free_space < 25 && free_space >= 10) { - storageStatus = {{starpilot_toggles.value("storage_left_metrics").toBool() ? tr("LEFT") : tr("USED"), storage}, warning_color}; - } else if (10 > free_space) { - storageStatus = {{starpilot_toggles.value("storage_left_metrics").toBool() ? tr("LEFT") : tr("USED"), storage}, danger_color}; - } - setProperty("storageStatus", QVariant::fromValue(storageStatus)); - } - } -} - -void Sidebar::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(57, 57, 57)); - - // buttons - p.setOpacity(settings_pressed ? 0.65 : 1.0); - p.drawPixmap(settings_btn.x(), settings_btn.y(), settings_gif ? settings_gif->currentPixmap() : settings_img); - p.setOpacity(onroad && flag_pressed ? 0.65 : 1.0); - p.drawPixmap(home_btn.x(), home_btn.y(), onroad ? flag_gif ? flag_gif->currentPixmap() : flag_img : home_gif ? home_gif->currentPixmap() : home_img); - if (recording_audio) { - p.setBrush(danger_color); - p.setOpacity(mic_indicator_pressed ? 0.65 : 1.0); - p.drawRoundedRect(mic_indicator_btn, mic_indicator_btn.height() / 2, mic_indicator_btn.height() / 2); - int icon_x = mic_indicator_btn.x() + (mic_indicator_btn.width() - mic_img.width()) / 2; - int icon_y = mic_indicator_btn.y() + (mic_indicator_btn.height() - mic_img.height()) / 2; - p.drawPixmap(icon_x, icon_y, mic_img); - } - p.setOpacity(1.0); - - StarPilotUIState *fs = starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool simple_mode = starpilot_toggles.value("simple_mode").toBool(); - - // network - if (!simple_mode && starpilot_toggles.value("ip_metrics").toBool()) { - p.setPen(QColor(0xff, 0xff, 0xff)); - p.save(); - p.setFont(InterFont(30)); - p.drawText(QRect(50, 196, 225, 27), Qt::AlignLeft | Qt::AlignVCenter, starpilotUIState()->wifi->getIp4Address()); - p.restore(); - } else { - int x = 58; - const QColor gray(0x54, 0x54, 0x54); - for (int i = 0; i < 5; ++i) { - p.setBrush(i < net_strength ? Qt::white : gray); - p.drawEllipse(x, 196, 27, 27); - x += 37; - } - } - - p.setFont(InterFont(35)); - p.setPen(QColor(0xff, 0xff, 0xff)); - const QRect r = QRect(58, 247, width() - 100, 50); - - if (net_type == "Hotspot") { - p.drawPixmap(r.x(), r.y() + (r.height() - link_img.height()) / 2, link_img); - } else { - p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, net_type); - } - - // metrics - drawMetric(p, temp_status.first, temp_status.second, 338); - if (simple_mode) { - drawMetric(p, panda_status.first, panda_status.second, 496); - drawMetric(p, connect_status.first, connect_status.second, 654); - } else if (starpilot_toggles.value("cpu_metrics").toBool() || starpilot_toggles.value("gpu_metrics").toBool()) { - drawMetric(p, chip_status.first, chip_status.second, 496); - } else { - drawMetric(p, panda_status.first, panda_status.second, 496); - } - if (starpilot_toggles.value("memory_metrics").toBool()) { - drawMetric(p, memory_status.first, memory_status.second, 654); - } else if (starpilot_toggles.value("storage_left_metrics").toBool() || starpilot_toggles.value("storage_used_metrics").toBool()) { - drawMetric(p, storage_status.first, storage_status.second, 654); - } else { - drawMetric(p, connect_status.first, connect_status.second, 654); - } -} - -void Sidebar::showEvent(QShowEvent *event) { - updateTheme(); -} - -void Sidebar::updateTheme() { - auto clearMovie = [](QSharedPointer &movie) { - if (!movie.isNull()) { - movie->stop(); - movie.reset(); - } - }; - - if (starpilotUIState()->starpilot_scene.starpilot_toggles.value("simple_mode").toBool()) { - clearMovie(home_gif); - clearMovie(flag_gif); - clearMovie(settings_gif); - - home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); - flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); - settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); - return; - } - - loadImage("../../starpilot/assets/active_theme/icons/button_home", home_img, home_gif, home_btn.size(), this); - loadImage("../../starpilot/assets/active_theme/icons/button_flag", flag_img, flag_gif, home_btn.size(), this); - loadImage("../../starpilot/assets/active_theme/icons/button_settings", settings_img, settings_gif, settings_btn.size(), this); - - // Keep stock icons visible when a theme is partial or missing an icon. - if (!home_gif && home_img.isNull()) { - home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); - } - if (!flag_gif && flag_img.isNull()) { - flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); - } - if (!settings_gif && settings_img.isNull()) { - settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); - } -} diff --git a/selfdrive/ui/qt/sidebar.h b/selfdrive/ui/qt/sidebar.h deleted file mode 100644 index d999da4f8..000000000 --- a/selfdrive/ui/qt/sidebar.h +++ /dev/null @@ -1,82 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/network/networking.h" - -typedef QPair, QColor> ItemStatus; -Q_DECLARE_METATYPE(ItemStatus); - -class Sidebar : public QFrame { - Q_OBJECT - Q_PROPERTY(ItemStatus connectStatus MEMBER connect_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus pandaStatus MEMBER panda_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus tempStatus MEMBER temp_status NOTIFY valueChanged); - Q_PROPERTY(QString netType MEMBER net_type NOTIFY valueChanged); - Q_PROPERTY(int netStrength MEMBER net_strength NOTIFY valueChanged); - Q_PROPERTY(bool recordingAudio MEMBER recording_audio NOTIFY valueChanged); - - // Additional properties - Q_PROPERTY(ItemStatus chipStatus MEMBER chip_status NOTIFY valueChanged) - Q_PROPERTY(ItemStatus memoryStatus MEMBER memory_status NOTIFY valueChanged) - Q_PROPERTY(ItemStatus storageStatus MEMBER storage_status NOTIFY valueChanged) - -public: - explicit Sidebar(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void valueChanged(); - -public slots: - void offroadTransition(bool offroad); - void updateState(const UIState &s, const StarPilotUIState &fs); - -protected: - void paintEvent(QPaintEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void drawMetric(QPainter &p, const QPair &label, QColor c, int y); - - QPixmap home_img, flag_img, settings_img, mic_img, link_img; - bool onroad, recording_audio, flag_pressed, settings_pressed, mic_indicator_pressed; - const QMap network_type = { - {cereal::DeviceState::NetworkType::NONE, tr("--")}, - {cereal::DeviceState::NetworkType::WIFI, tr("Wi-Fi")}, - {cereal::DeviceState::NetworkType::ETHERNET, tr("ETH")}, - {cereal::DeviceState::NetworkType::CELL2_G, tr("2G")}, - {cereal::DeviceState::NetworkType::CELL3_G, tr("3G")}, - {cereal::DeviceState::NetworkType::CELL4_G, tr("LTE")}, - {cereal::DeviceState::NetworkType::CELL5_G, tr("5G")} - }; - - const QRect home_btn = QRect(60, 860, 180, 180); - const QRect settings_btn = QRect(50, 35, 200, 117); - const QRect mic_indicator_btn = QRect(158, 252, 75, 40); - const QColor good_color = QColor(255, 255, 255); - const QColor warning_color = QColor(218, 202, 37); - const QColor danger_color = QColor(201, 34, 49); - - ItemStatus connect_status, panda_status, temp_status; - QString net_type; - int net_strength = 0; - - ItemStatus chip_status, memory_status, storage_status; - -private: - std::unique_ptr pm; - Networking *networking = nullptr; - - void showEvent(QShowEvent *event); - void updateTheme(); - - Params params; - - QSharedPointer flag_gif; - QSharedPointer home_gif; - QSharedPointer settings_gif; -}; diff --git a/selfdrive/ui/qt/spinner_larch64 b/selfdrive/ui/qt/spinner_larch64 deleted file mode 100755 index 645bc4430..000000000 Binary files a/selfdrive/ui/qt/spinner_larch64 and /dev/null differ diff --git a/selfdrive/ui/qt/text_larch64 b/selfdrive/ui/qt/text_larch64 deleted file mode 100755 index eb0f535bf..000000000 Binary files a/selfdrive/ui/qt/text_larch64 and /dev/null differ diff --git a/selfdrive/ui/qt/util.cc b/selfdrive/ui/qt/util.cc deleted file mode 100644 index afc1c03bb..000000000 --- a/selfdrive/ui/qt/util.cc +++ /dev/null @@ -1,248 +0,0 @@ -#include "selfdrive/ui/qt/util.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" -#include "system/hardware/hw.h" - -QString getVersion() { - static QString version = QString::fromStdString(Params().get("Version")); - return version; -} - -QString getBrand() { - return QObject::tr("StarPilot"); -} - -QString getStarPilotDisplayVersion() { - return "6.7"; -} - -QString formatStarPilotDisplayVersionDescription(const QString &description) { - if (description.isEmpty()) { - return ""; - } - - QStringList parts = description.split(" / "); - if (parts.isEmpty()) { - return getStarPilotDisplayVersion(); - } - - parts[0] = getStarPilotDisplayVersion(); - return parts.join(" / "); -} - -QString getUserAgent() { - return "openpilot-" + getVersion(); -} - -std::optional getDongleId() { - std::string id = Params().get("DongleId"); - - if (!id.empty() && (id != "UnregisteredDevice")) { - return QString::fromStdString(id); - } else { - return {}; - } -} - -QMap getSupportedLanguages() { - QFile f(":/languages.json"); - f.open(QIODevice::ReadOnly | QIODevice::Text); - QString val = f.readAll(); - - QJsonObject obj = QJsonDocument::fromJson(val.toUtf8()).object(); - QMap map; - for (auto key : obj.keys()) { - map[key] = obj[key].toString(); - } - return map; -} - -QString timeAgo(const QDateTime &date) { - if (!util::system_time_valid()) { - return date.date().toString(); - } - - int diff = date.secsTo(QDateTime::currentDateTimeUtc()); - - QString s; - if (diff < 60) { - s = QObject::tr("now"); - } else if (diff < 60 * 60) { - int minutes = diff / 60; - s = QObject::tr("%n minute(s) ago", "", minutes); - } else if (diff < 60 * 60 * 24) { - int hours = diff / (60 * 60); - s = QObject::tr("%n hour(s) ago", "", hours); - } else if (diff < 3600 * 24 * 7) { - int days = diff / (60 * 60 * 24); - s = QObject::tr("%n day(s) ago", "", days); - } else { - s = date.date().toString(); - } - - return s; -} - -void setQtSurfaceFormat() { - QSurfaceFormat fmt; -#ifdef __APPLE__ - fmt.setVersion(3, 2); - fmt.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile); - fmt.setRenderableType(QSurfaceFormat::OpenGL); -#else - fmt.setRenderableType(QSurfaceFormat::OpenGLES); -#endif - fmt.setSamples(16); - fmt.setStencilBufferSize(1); - QSurfaceFormat::setDefaultFormat(fmt); -} - -void sigTermHandler(int s) { - std::signal(s, SIG_DFL); - qApp->quit(); -} - -void initApp(int argc, char *argv[], bool disable_hidpi) { - Hardware::set_display_power(true); - Hardware::set_brightness(65); - - // setup signal handlers to exit gracefully - std::signal(SIGINT, sigTermHandler); - std::signal(SIGTERM, sigTermHandler); - - QString app_dir; -#ifdef __APPLE__ - // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering - QApplication tmp(argc, argv); - app_dir = QCoreApplication::applicationDirPath(); - if (disable_hidpi) { - qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio()).toLocal8Bit()); - } -#else - app_dir = QFileInfo(util::readlink("/proc/self/exe").c_str()).path(); -#endif - - qputenv("QT_DBL_CLICK_DIST", QByteArray::number(150)); - // ensure the current dir matches the exectuable's directory - QDir::setCurrent(app_dir); - - setQtSurfaceFormat(); -} - -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - static std::map levels = { - {QtMsgType::QtDebugMsg, CLOUDLOG_DEBUG}, - {QtMsgType::QtInfoMsg, CLOUDLOG_INFO}, - {QtMsgType::QtWarningMsg, CLOUDLOG_WARNING}, - {QtMsgType::QtCriticalMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtSystemMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtFatalMsg, CLOUDLOG_CRITICAL}, - }; - - std::string file, function; - if (context.file != nullptr) file = context.file; - if (context.function != nullptr) function = context.function; - - auto bts = msg.toUtf8(); - cloudlog_e(levels[type], file.c_str(), context.line, function.c_str(), "%s", bts.constData()); -} - - -QWidget* topWidget(QWidget* widget) { - while (widget->parentWidget() != nullptr) widget=widget->parentWidget(); - return widget; -} - -QPixmap loadPixmap(const QString &fileName, const QSize &size, Qt::AspectRatioMode aspectRatioMode) { - if (size.isEmpty()) { - return QPixmap(fileName); - } else { - return QPixmap(fileName).scaled(size, aspectRatioMode, Qt::SmoothTransformation); - } -} - -static QHash load_bootstrap_icons() { - QHash icons; - - QFile f(":/bootstrap-icons.svg"); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { - QDomDocument xml; - xml.setContent(&f); - QDomNode n = xml.documentElement().firstChild(); - while (!n.isNull()) { - QDomElement e = n.toElement(); - if (!e.isNull() && e.hasAttribute("id")) { - QString svg_str; - QTextStream stream(&svg_str); - n.save(stream, 0); - svg_str.replace("", ""); - icons[e.attribute("id")] = svg_str.toUtf8(); - } - n = n.nextSibling(); - } - } - return icons; -} - -QPixmap bootstrapPixmap(const QString &id) { - static QHash icons = load_bootstrap_icons(); - - QPixmap pixmap; - if (auto it = icons.find(id); it != icons.end()) { - pixmap.loadFromData(it.value(), "svg"); - } - return pixmap; -} - -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params) { - // Using the experimental longitudinal toggle, returns whether longitudinal control - // will be active without needing a restart of openpilot - Params params = Params(); - return (car_params.getAlphaLongitudinalAvailable() - ? params.getBool("AlphaLongitudinalEnabled") - : car_params.getOpenpilotLongitudinalControl()) && !params.getBool("DisableOpenpilotLongitudinal"); -} - -// ParamWatcher - -ParamWatcher::ParamWatcher(QObject *parent) : QObject(parent) { - watcher = new QFileSystemWatcher(this); - QObject::connect(watcher, &QFileSystemWatcher::fileChanged, this, &ParamWatcher::fileChanged); -} - -void ParamWatcher::fileChanged(const QString &path) { - auto param_name = QFileInfo(path).fileName(); - auto param_value = QString::fromStdString(params.get(param_name.toStdString())); - - auto it = params_hash.find(param_name); - bool content_changed = (it == params_hash.end()) || (it.value() != param_value); - params_hash[param_name] = param_value; - // emit signal when the content changes. - if (content_changed) { - emit paramChanged(param_name, param_value); - } -} - -void ParamWatcher::addParam(const QString ¶m_name) { - watcher->addPath(QString::fromStdString(params.getParamPath(param_name.toStdString()))); -} diff --git a/selfdrive/ui/qt/util.h b/selfdrive/ui/qt/util.h deleted file mode 100644 index 9d62b34cc..000000000 --- a/selfdrive/ui/qt/util.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "cereal/gen/cpp/car.capnp.h" -#include "common/params.h" - -QString getVersion(); -QString getBrand(); -QString getStarPilotDisplayVersion(); -QString formatStarPilotDisplayVersionDescription(const QString &description); -QString getUserAgent(); -std::optional getDongleId(); -QMap getSupportedLanguages(); -void setQtSurfaceFormat(); -void sigTermHandler(int s); -QString timeAgo(const QDateTime &date); -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); -void initApp(int argc, char *argv[], bool disable_hidpi = true); -QWidget* topWidget(QWidget* widget); -QPixmap loadPixmap(const QString &fileName, const QSize &size = {}, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio); -QPixmap bootstrapPixmap(const QString &id); -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params); - -struct InterFont : public QFont { - InterFont(int pixel_size, QFont::Weight weight = QFont::Normal) : QFont("Inter") { - setPixelSize(pixel_size); - setWeight(weight); - } -}; - -class ParamWatcher : public QObject { - Q_OBJECT - -public: - ParamWatcher(QObject *parent); - void addParam(const QString ¶m_name); - -signals: - void paramChanged(const QString ¶m_name, const QString ¶m_value); - -private: - void fileChanged(const QString &path); - - QFileSystemWatcher *watcher; - QHash params_hash; - Params params; -}; diff --git a/selfdrive/ui/qt/widgets/cameraview.cc b/selfdrive/ui/qt/widgets/cameraview.cc deleted file mode 100644 index 81ef61339..000000000 --- a/selfdrive/ui/qt/widgets/cameraview.cc +++ /dev/null @@ -1,365 +0,0 @@ -#include "selfdrive/ui/qt/widgets/cameraview.h" - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include -#include - -namespace { - -const char frame_vertex_shader[] = -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" -#endif - "layout(location = 0) in vec4 aPosition;\n" - "layout(location = 1) in vec2 aTexCoord;\n" - "uniform mat4 uTransform;\n" - "out vec2 vTexCoord;\n" - "void main() {\n" - " gl_Position = uTransform * aPosition;\n" - " vTexCoord = aTexCoord;\n" - "}\n"; - -const char frame_fragment_shader[] = -#ifdef QCOM2 - "#version 300 es\n" - "#extension GL_OES_EGL_image_external_essl3 : enable\n" - "precision mediump float;\n" - "uniform samplerExternalOES uTexture;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " colorOut = texture(uTexture, vTexCoord);\n" - // gamma to improve worst case visibility when dark - " colorOut.rgb = pow(colorOut.rgb, vec3(1.0/1.28));\n" - "}\n"; -#else -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" - "precision mediump float;\n" -#endif - "uniform sampler2D uTextureY;\n" - "uniform sampler2D uTextureUV;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " float y = texture(uTextureY, vTexCoord).r;\n" - " vec2 uv = texture(uTextureUV, vTexCoord).rg - 0.5;\n" - " float r = y + 1.402 * uv.y;\n" - " float g = y - 0.344 * uv.x - 0.714 * uv.y;\n" - " float b = y + 1.772 * uv.x;\n" - " colorOut = vec4(r, g, b, 1.0);\n" - "}\n"; -#endif - -} // namespace - -CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, QWidget* parent) : - stream_name(stream_name), active_stream_type(type), requested_stream_type(type), QOpenGLWidget(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); - qRegisterMetaType>("availableStreams"); - QObject::connect(this, &CameraWidget::vipcThreadConnected, this, &CameraWidget::vipcConnected, Qt::BlockingQueuedConnection); - QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); - QObject::connect(this, &CameraWidget::vipcAvailableStreamsUpdated, this, &CameraWidget::availableStreamsUpdated, Qt::QueuedConnection); - QObject::connect(QApplication::instance(), &QCoreApplication::aboutToQuit, this, &CameraWidget::stopVipcThread); -} - -CameraWidget::~CameraWidget() { - makeCurrent(); - stopVipcThread(); - if (isValid()) { - glDeleteVertexArrays(1, &frame_vao); - glDeleteBuffers(1, &frame_vbo); - glDeleteBuffers(1, &frame_ibo); -#ifndef QCOM2 - glDeleteTextures(2, textures); -#endif - } - doneCurrent(); -} - -// Qt uses device-independent pixels, depending on platform this may be -// different to what OpenGL uses -int CameraWidget::glWidth() { - return width() * devicePixelRatio(); -} - -int CameraWidget::glHeight() { - return height() * devicePixelRatio(); -} - -void CameraWidget::initializeGL() { - initializeOpenGLFunctions(); - - program = std::make_unique(context()); - bool ret = program->addShaderFromSourceCode(QOpenGLShader::Vertex, frame_vertex_shader); - assert(ret); - ret = program->addShaderFromSourceCode(QOpenGLShader::Fragment, frame_fragment_shader); - assert(ret); - - program->link(); - GLint frame_pos_loc = program->attributeLocation("aPosition"); - GLint frame_texcoord_loc = program->attributeLocation("aTexCoord"); - - auto [x1, x2, y1, y2] = requested_stream_type == VISION_STREAM_DRIVER ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); - const uint8_t frame_indicies[] = {0, 1, 2, 0, 2, 3}; - const float frame_coords[4][4] = { - {-1.0, -1.0, x2, y1}, // bl - {-1.0, 1.0, x2, y2}, // tl - { 1.0, 1.0, x1, y2}, // tr - { 1.0, -1.0, x1, y1}, // br - }; - - glGenVertexArrays(1, &frame_vao); - glBindVertexArray(frame_vao); - glGenBuffers(1, &frame_vbo); - glBindBuffer(GL_ARRAY_BUFFER, frame_vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(frame_coords), frame_coords, GL_STATIC_DRAW); - glEnableVertexAttribArray(frame_pos_loc); - glVertexAttribPointer(frame_pos_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)0); - glEnableVertexAttribArray(frame_texcoord_loc); - glVertexAttribPointer(frame_texcoord_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)(sizeof(float) * 2)); - glGenBuffers(1, &frame_ibo); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, frame_ibo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(frame_indicies), frame_indicies, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - glUseProgram(program->programId()); - -#ifdef QCOM2 - glUniform1i(program->uniformLocation("uTexture"), 0); -#else - glGenTextures(2, textures); - glUniform1i(program->uniformLocation("uTextureY"), 0); - glUniform1i(program->uniformLocation("uTextureUV"), 1); -#endif -} - -void CameraWidget::showEvent(QShowEvent *event) { - if (!vipc_thread) { - clearFrames(); - vipc_thread = new QThread(); - connect(vipc_thread, &QThread::started, [=]() { vipcThread(); }); - connect(vipc_thread, &QThread::finished, vipc_thread, &QObject::deleteLater); - vipc_thread->start(); - } -} - -void CameraWidget::stopVipcThread() { - makeCurrent(); - if (vipc_thread) { - vipc_thread->requestInterruption(); - vipc_thread->quit(); - vipc_thread->wait(); - vipc_thread = nullptr; - } - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - assert(eglGetError() == EGL_SUCCESS); - } - egl_images.clear(); -#endif -} - -void CameraWidget::availableStreamsUpdated(std::set streams) { - available_streams = streams; -} - -mat4 CameraWidget::calcFrameMatrix() { - // Scale the frame to fit the widget while maintaining the aspect ratio. - float widget_aspect_ratio = (float)width() / height(); - float frame_aspect_ratio = (float)stream_width / stream_height; - float zx = std::min(frame_aspect_ratio / widget_aspect_ratio, 1.0f); - float zy = std::min(widget_aspect_ratio / frame_aspect_ratio, 1.0f); - - return mat4{{ - zx, 0.0, 0.0, 0.0, - 0.0, zy, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} - -void CameraWidget::paintGL() { - glClearColor(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF()); - glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - - std::lock_guard lk(frame_lock); - if (frames.empty()) return; - - int frame_idx = frames.size() - 1; - - // Always draw latest frame until sync logic is more stable - // for (frame_idx = 0; frame_idx < frames.size() - 1; frame_idx++) { - // if (frames[frame_idx].first == draw_frame_id) break; - // } - - // Log duplicate/dropped frames - if (frames[frame_idx].first == prev_frame_id) { - qDebug() << "Drawing same frame twice" << frames[frame_idx].first; - } else if (frames[frame_idx].first != prev_frame_id + 1) { - qDebug() << "Skipped frame" << frames[frame_idx].first; - } - prev_frame_id = frames[frame_idx].first; - VisionBuf *frame = frames[frame_idx].second; - assert(frame != nullptr); - - auto frame_mat = calcFrameMatrix(); - - glViewport(0, 0, glWidth(), glHeight()); - glBindVertexArray(frame_vao); - glUseProgram(program->programId()); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - -#ifdef QCOM2 - // no frame copy - glActiveTexture(GL_TEXTURE0); - glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, egl_images[frame->idx]); - assert(glGetError() == GL_NO_ERROR); -#else - // fallback to copy - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width, stream_height, GL_RED, GL_UNSIGNED_BYTE, frame->y); - assert(glGetError() == GL_NO_ERROR); - - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride/2); - glActiveTexture(GL_TEXTURE0 + 1); - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width/2, stream_height/2, GL_RG, GL_UNSIGNED_BYTE, frame->uv); - assert(glGetError() == GL_NO_ERROR); -#endif - - glUniformMatrix4fv(program->uniformLocation("uTransform"), 1, GL_TRUE, frame_mat.v); - glEnableVertexAttribArray(0); - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, (const void *)0); - glDisableVertexAttribArray(0); - glBindVertexArray(0); - glBindTexture(GL_TEXTURE_2D, 0); - glActiveTexture(GL_TEXTURE0); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); -} - -void CameraWidget::vipcConnected(VisionIpcClient *vipc_client) { - makeCurrent(); - stream_width = vipc_client->buffers[0].width; - stream_height = vipc_client->buffers[0].height; - stream_stride = vipc_client->buffers[0].stride; - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - } - egl_images.clear(); - - for (int i = 0; i < vipc_client->num_buffers; i++) { // import buffers into OpenGL - int fd = dup(vipc_client->buffers[i].fd); // eglDestroyImageKHR will close, so duplicate - EGLint img_attrs[] = { - EGL_WIDTH, (int)vipc_client->buffers[i].width, - EGL_HEIGHT, (int)vipc_client->buffers[i].height, - EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, - EGL_DMA_BUF_PLANE0_FD_EXT, fd, - EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, - EGL_DMA_BUF_PLANE0_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_DMA_BUF_PLANE1_FD_EXT, fd, - EGL_DMA_BUF_PLANE1_OFFSET_EXT, (int)vipc_client->buffers[i].uv_offset, - EGL_DMA_BUF_PLANE1_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_NONE - }; - egl_images[i] = eglCreateImageKHR(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, img_attrs); - assert(eglGetError() == EGL_SUCCESS); - } -#else - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, stream_width, stream_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); - - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, stream_width/2, stream_height/2, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); -#endif -} - -void CameraWidget::vipcFrameReceived() { - update(); -} - -void CameraWidget::vipcThread() { - VisionStreamType cur_stream = requested_stream_type; - std::unique_ptr vipc_client; - VisionIpcBufExtra meta_main = {0}; - - while (!QThread::currentThread()->isInterruptionRequested()) { - if (!vipc_client || cur_stream != requested_stream_type) { - clearFrames(); - qDebug().nospace() << "connecting to stream " << requested_stream_type << ", was connected to " << cur_stream; - cur_stream = requested_stream_type; - vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); - } - active_stream_type = cur_stream; - - if (!vipc_client->connected) { - clearFrames(); - auto streams = VisionIpcClient::getAvailableStreams(stream_name, false); - if (streams.empty()) { - QThread::msleep(100); - continue; - } - emit vipcAvailableStreamsUpdated(streams); - - if (!vipc_client->connect(false)) { - QThread::msleep(100); - continue; - } - emit vipcThreadConnected(vipc_client.get()); - } - - if (VisionBuf *buf = vipc_client->recv(&meta_main, 1000)) { - { - std::lock_guard lk(frame_lock); - frames.push_back(std::make_pair(meta_main.frame_id, buf)); - while (frames.size() > FRAME_BUFFER_SIZE) { - frames.pop_front(); - } - } - emit vipcThreadFrameReceived(); - } else { - if (!isVisible()) { - vipc_client->connected = false; - } - } - } -} - -void CameraWidget::clearFrames() { - std::lock_guard lk(frame_lock); - frames.clear(); - available_streams.clear(); -} diff --git a/selfdrive/ui/qt/widgets/cameraview.h b/selfdrive/ui/qt/widgets/cameraview.h deleted file mode 100644 index 29aa8493c..000000000 --- a/selfdrive/ui/qt/widgets/cameraview.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#ifdef QCOM2 -#define EGL_EGLEXT_PROTOTYPES -#define EGL_NO_X11 -#define GL_TEXTURE_EXTERNAL_OES 0x8D65 -#include -#include -#include -#endif - -#include "msgq/visionipc/visionipc_client.h" -#include "selfdrive/ui/ui.h" - -const int FRAME_BUFFER_SIZE = 5; - -class CameraWidget : public QOpenGLWidget, protected QOpenGLFunctions { - Q_OBJECT - -public: - using QOpenGLWidget::QOpenGLWidget; - explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, QWidget* parent = nullptr); - ~CameraWidget(); - void setBackgroundColor(const QColor &color) { bg = color; } - void setFrameId(int frame_id) { draw_frame_id = frame_id; } - void setStreamType(VisionStreamType type) { requested_stream_type = type; } - VisionStreamType getStreamType() { return active_stream_type; } - void stopVipcThread(); - -signals: - void clicked(); - void vipcThreadConnected(VisionIpcClient *); - void vipcThreadFrameReceived(); - void vipcAvailableStreamsUpdated(std::set); - -protected: - void paintGL() override; - void initializeGL() override; - void showEvent(QShowEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } - virtual mat4 calcFrameMatrix(); - void vipcThread(); - void clearFrames(); - - int glWidth(); - int glHeight(); - - GLuint frame_vao, frame_vbo, frame_ibo; - GLuint textures[2]; - std::unique_ptr program; - QColor bg = QColor("#000000"); - -#ifdef QCOM2 - std::map egl_images; -#endif - - std::string stream_name; - int stream_width = 0; - int stream_height = 0; - int stream_stride = 0; - std::atomic active_stream_type; - std::atomic requested_stream_type; - std::set available_streams; - QThread *vipc_thread = nullptr; - std::recursive_mutex frame_lock; - std::deque> frames; - uint32_t draw_frame_id = 0; - uint32_t prev_frame_id = 0; - -protected slots: - void vipcConnected(VisionIpcClient *vipc_client); - void vipcFrameReceived(); - void availableStreamsUpdated(std::set streams); -}; - -Q_DECLARE_METATYPE(std::set); diff --git a/selfdrive/ui/qt/widgets/controls.cc b/selfdrive/ui/qt/widgets/controls.cc deleted file mode 100644 index b74272d0c..000000000 --- a/selfdrive/ui/qt/widgets/controls.cc +++ /dev/null @@ -1,168 +0,0 @@ -#include "selfdrive/ui/qt/widgets/controls.h" - -#include -#include - -AbstractControl::AbstractControl(const QString &title, const QString &desc, const QString &icon, QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - - hlayout = new QHBoxLayout; - hlayout->setMargin(0); - hlayout->setSpacing(20); - - // left icon - icon_label = new QLabel(this); - hlayout->addWidget(icon_label); - if (!icon.isEmpty()) { - icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - icon_label->setPixmap(icon_pixmap); - icon_label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - } - icon_label->setVisible(!icon.isEmpty()); - - // title - title_label = new QPushButton(title); - title_label->setFixedHeight(120); - title_label->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; border: none;"); - hlayout->addWidget(title_label, 1); - - // value next to control button - value = new ElidedLabel(); - value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - value->setStyleSheet("color: #aaaaaa"); - hlayout->addWidget(value); - - main_layout->addLayout(hlayout); - - // description - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescriptionEvent(); - } - - if (!description->text().isEmpty()) { - if (description->isVisible()) { - emit hideDescriptionEvent(); - description->setVisible(false); - } else { - description->setVisible(true); - } - } - }); - - main_layout->addStretch(); -} - -void AbstractControl::hideEvent(QHideEvent *e) { - if (description != nullptr) { - description->hide(); - } -} - -// controls - -ButtonControl::ButtonControl(const QString &title, const QString &text, const QString &desc, QWidget *parent) : AbstractControl(title, desc, "", parent) { - btn.setText(text); - btn.setStyleSheet(R"( - QPushButton { - padding: 0; - border-radius: 50px; - font-size: 35px; - font-weight: 500; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"); - btn.setFixedSize(250, 100); - QObject::connect(&btn, &QPushButton::clicked, this, &ButtonControl::clicked); - hlayout->addWidget(&btn); -} - -// ElidedLabel - -ElidedLabel::ElidedLabel(QWidget *parent) : ElidedLabel({}, parent) {} - -ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - setMinimumWidth(1); -} - -void ElidedLabel::resizeEvent(QResizeEvent* event) { - QLabel::resizeEvent(event); - lastText_ = elidedText_ = ""; -} - -void ElidedLabel::paintEvent(QPaintEvent *event) { - const QString curText = text(); - if (curText != lastText_) { - elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); - lastText_ = curText; - } - - QPainter painter(this); - drawFrame(&painter); - QStyleOption opt; - opt.initFrom(this); - style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); -} - -// ParamControl - -ParamControl::ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ToggleControl(title, desc, icon, false, parent) { - key = param.toStdString(); - QObject::connect(this, &ParamControl::toggleFlipped, this, &ParamControl::toggleClicked); -} - -void ParamControl::toggleClicked(bool state) { - auto do_confirm = [this]() { - QString content("

" + title_label->text() + "


" - "

" + getDescription() + "

"); - return ConfirmationDialog(content, tr("Enable"), tr("Cancel"), true, this).exec(); - }; - - bool confirmed = store_confirm && params.getBool(key + "Confirmed"); - if (!confirm || confirmed || !state || do_confirm()) { - if (store_confirm && state) params.putBool(key + "Confirmed", true); - params.putBool(key, state); - if (state && key == "ConditionalExperimental") { - params.putBool("ConditionalChill", false); - } else if (state && key == "ConditionalChill") { - params.putBool("ConditionalExperimental", false); - } - if (key == "PersistExperimentalState") { - static Params params_memory{"", true}; - int persisted_status = 0; - if (state) { - int current_status = params_memory.getInt("CEStatus"); - persisted_status = (current_status == 1 || current_status == 2) ? current_status : 0; - } - params.putInt("PersistedCEStatus", persisted_status); - } else if (key == "PersistChillState") { - static Params params_memory{"", true}; - int persisted_status = 0; - if (state) { - int current_status = params_memory.getInt("CCStatus"); - persisted_status = (current_status == 1 || current_status == 2) ? current_status : 0; - } - params.putInt("PersistedCCStatus", persisted_status); - } - setIcon(state); - } else { - toggle.togglePosition(); - } -} diff --git a/selfdrive/ui/qt/widgets/controls.h b/selfdrive/ui/qt/widgets/controls.h deleted file mode 100644 index 137b3ef8d..000000000 --- a/selfdrive/ui/qt/widgets/controls.h +++ /dev/null @@ -1,328 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/toggle.h" - -class ElidedLabel : public QLabel { - Q_OBJECT - -public: - explicit ElidedLabel(QWidget *parent = 0); - explicit ElidedLabel(const QString &text, QWidget *parent = 0); - -signals: - void clicked(); - -protected: - void paintEvent(QPaintEvent *event) override; - void resizeEvent(QResizeEvent* event) override; - void mouseReleaseEvent(QMouseEvent *event) override { - if (rect().contains(event->pos())) { - emit clicked(); - } - } - QString lastText_, elidedText_; -}; - - -class AbstractControl : public QFrame { - Q_OBJECT - -public: - void setDescription(const QString &desc) { - if (description) description->setText(desc); - } - - void setTitle(const QString &title) { - title_label->setText(title); - } - - void setValue(const QString &val) { - value->setText(val); - } - - const QString getDescription() { - return description->text(); - } - - QLabel *icon_label; - QPixmap icon_pixmap; - -public slots: - void showDescription() { - description->setVisible(true); - } - -signals: - void showDescriptionEvent(); - - void hideDescriptionEvent(); - -protected: - AbstractControl(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); - void hideEvent(QHideEvent *e) override; - - QHBoxLayout *hlayout; - QPushButton *title_label; - -private: - ElidedLabel *value; - QLabel *description = nullptr; -}; - -// widget to display a value -class LabelControl : public AbstractControl { - Q_OBJECT - -public: - LabelControl(const QString &title, const QString &text = "", const QString &desc = "", QWidget *parent = nullptr) : AbstractControl(title, desc, "", parent) { - label.setText(text); - label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hlayout->addWidget(&label); - } - void setText(const QString &text) { label.setText(text); } - -private: - ElidedLabel label; -}; - -// widget for a button with a label -class ButtonControl : public AbstractControl { - Q_OBJECT - -public: - ButtonControl(const QString &title, const QString &text, const QString &desc = "", QWidget *parent = nullptr); - inline void setText(const QString &text) { btn.setText(text); } - inline QString text() const { return btn.text(); } - -signals: - void clicked(); - -public slots: - void setEnabled(bool enabled) { btn.setEnabled(enabled); } - -private: - QPushButton btn; -}; - -class ToggleControl : public AbstractControl { - Q_OBJECT - -public: - ToggleControl(const QString &title, const QString &desc = "", const QString &icon = "", const bool state = false, QWidget *parent = nullptr) : AbstractControl(title, desc, icon, parent) { - toggle.setFixedSize(150, 100); - if (state) { - toggle.togglePosition(); - } - hlayout->addWidget(&toggle); - QObject::connect(&toggle, &Toggle::stateChanged, this, &ToggleControl::toggleFlipped); - } - - void setEnabled(bool enabled) { - toggle.setEnabled(enabled); - toggle.update(); - } - - void forceOn(bool force) { - toggle.setEnabled(!force); - if (force && !toggle.on) { - toggle.togglePosition(); - } - } - -signals: - void toggleFlipped(bool state); - -protected: - Toggle toggle; -}; - -// widget to toggle params -class ParamControl : public ToggleControl { - Q_OBJECT - -public: - ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - void setConfirmation(bool _confirm, bool _store_confirm) { - confirm = _confirm; - store_confirm = _store_confirm; - } - - void setActiveIcon(const QString &icon) { - active_icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - } - - void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - setIcon(state); - } - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - void toggleClicked(bool state); - void setIcon(bool state) { - if (state && !active_icon_pixmap.isNull()) { - icon_label->setPixmap(active_icon_pixmap); - } else if (!icon_pixmap.isNull()) { - icon_label->setPixmap(icon_pixmap); - } - } - - std::string key; - Params params; - QPixmap active_icon_pixmap; - bool confirm = false; - bool store_confirm = false; -}; - -class MultiButtonControl : public AbstractControl { - Q_OBJECT -public: - MultiButtonControl(const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225) : AbstractControl(title, desc, icon) { - const QString style = R"( - QPushButton { - border-radius: 50px; - font-size: 40px; - font-weight: 500; - height:100px; - padding: 0 25 0 25; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:checked:enabled { - background-color: #33Ab4C; - } - QPushButton:checked:disabled { - background-color: #9933Ab4C; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"; - - button_group = new QButtonGroup(this); - button_group->setExclusive(true); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(true); - button->setChecked(i == 0); - button->setStyleSheet(style); - button->setMinimumWidth(minimum_button_width); - hlayout->addWidget(button); - button_group->addButton(button, i); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), this, &MultiButtonControl::buttonClicked); - } - - void setEnabled(bool enable) { - for (auto btn : button_group->buttons()) { - btn->setEnabled(enable); - } - } - - void setCheckedButton(int id) { - button_group->button(id)->setChecked(true); - } - -signals: - void buttonClicked(int id); - -protected: - QButtonGroup *button_group; -}; - -class ButtonParamControl : public MultiButtonControl { - Q_OBJECT -public: - ButtonParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225) : MultiButtonControl(title, desc, icon, - button_texts, minimum_button_width) { - key = param.toStdString(); - int value = atoi(params.get(key).c_str()); - - if (value > 0 && value < button_group->buttons().size()) { - button_group->button(value)->setChecked(true); - } - - QObject::connect(this, QOverload::of(&MultiButtonControl::buttonClicked), [=](int id) { - params.put(key, std::to_string(id)); - }); - } - - void refresh() { - int value = atoi(params.get(key).c_str()); - button_group->button(value)->setChecked(true); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - std::string key; - Params params; -}; - -class ListWidget : public QWidget { - Q_OBJECT - public: - explicit ListWidget(QWidget *parent = 0) : QWidget(parent), outer_layout(this) { - outer_layout.setMargin(0); - outer_layout.setSpacing(0); - outer_layout.addLayout(&inner_layout); - inner_layout.setMargin(0); - inner_layout.setSpacing(25); // default spacing is 25 - outer_layout.addStretch(1); - } - inline void addItem(QWidget *w) { inner_layout.addWidget(w); } - inline void addItem(QLayout *layout) { inner_layout.addLayout(layout); } - inline void setSpacing(int spacing) { inner_layout.setSpacing(spacing); } - -private: - void paintEvent(QPaintEvent *) override { - QPainter p(this); - p.setPen(Qt::gray); - for (int i = 0; i < inner_layout.count() - 1; ++i) { - QWidget *widget = inner_layout.itemAt(i)->widget(); - if (widget == nullptr || widget->isVisible()) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); - } - } - } - QVBoxLayout outer_layout; - QVBoxLayout inner_layout; -}; - -// convenience class for wrapping layouts -class LayoutWidget : public QWidget { - Q_OBJECT - -public: - LayoutWidget(QLayout *l, QWidget *parent = nullptr) : QWidget(parent) { - setLayout(l); - } -}; diff --git a/selfdrive/ui/qt/widgets/input.cc b/selfdrive/ui/qt/widgets/input.cc deleted file mode 100644 index ae36123f7..000000000 --- a/selfdrive/ui/qt/widgets/input.cc +++ /dev/null @@ -1,355 +0,0 @@ -#include "selfdrive/ui/qt/widgets/input.h" - -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - - -DialogBase::DialogBase(QWidget *parent) : QDialog(parent) { - Q_ASSERT(parent != nullptr); - parent->installEventFilter(this); - - setStyleSheet(R"( - * { - outline: none; - color: white; - font-family: Inter; - } - DialogBase { - background-color: black; - } - QPushButton { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - color: white; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); -} - -bool DialogBase::eventFilter(QObject *o, QEvent *e) { - if (o == parent() && e->type() == QEvent::Hide) { - reject(); - } - return QDialog::eventFilter(o, e); -} - -int DialogBase::exec() { - setMainWindow(this); - return QDialog::exec(); -} - -InputDialog::InputDialog(const QString &title, QWidget *parent, const QString &subtitle, bool secret) : DialogBase(parent) { - main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 55, 50, 50); - main_layout->setSpacing(0); - - // build header - QHBoxLayout *header_layout = new QHBoxLayout(); - - QVBoxLayout *vlayout = new QVBoxLayout; - header_layout->addLayout(vlayout); - label = new QLabel(title, this); - label->setStyleSheet("font-size: 90px; font-weight: bold;"); - vlayout->addWidget(label, 1, Qt::AlignTop | Qt::AlignLeft); - - if (!subtitle.isEmpty()) { - sublabel = new QLabel(subtitle, this); - sublabel->setStyleSheet("font-size: 55px; font-weight: light; color: #BDBDBD;"); - vlayout->addWidget(sublabel, 1, Qt::AlignTop | Qt::AlignLeft); - } - - QPushButton* cancel_btn = new QPushButton(tr("Cancel")); - cancel_btn->setFixedSize(386, 125); - cancel_btn->setStyleSheet(R"( - QPushButton { - font-size: 48px; - border-radius: 10px; - color: #E4E4E4; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - header_layout->addWidget(cancel_btn, 0, Qt::AlignRight); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::reject); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::cancel); - - main_layout->addLayout(header_layout); - - // text box - main_layout->addStretch(2); - - QWidget *textbox_widget = new QWidget; - textbox_widget->setObjectName("textbox"); - QHBoxLayout *textbox_layout = new QHBoxLayout(textbox_widget); - textbox_layout->setContentsMargins(50, 0, 50, 0); - - textbox_widget->setStyleSheet(R"( - #textbox { - margin-left: 50px; - margin-right: 50px; - border-radius: 0; - border-bottom: 3px solid #BDBDBD; - } - * { - border: none; - font-size: 80px; - font-weight: light; - background-color: transparent; - } - )"); - - line = new QLineEdit(); - line->setStyleSheet("lineedit-password-character: 8226; lineedit-password-mask-delay: 1500;"); - textbox_layout->addWidget(line, 1); - - if (secret) { - eye_btn = new QPushButton(); - eye_btn->setCheckable(true); - eye_btn->setFixedSize(150, 120); - QObject::connect(eye_btn, &QPushButton::toggled, [=](bool checked) { - if (checked) { - eye_btn->setIcon(QIcon(ASSET_PATH + "icons/eye_closed.svg")); - eye_btn->setIconSize(QSize(81, 54)); - line->setEchoMode(QLineEdit::Password); - } else { - eye_btn->setIcon(QIcon(ASSET_PATH + "icons/eye_open.svg")); - eye_btn->setIconSize(QSize(81, 44)); - line->setEchoMode(QLineEdit::Normal); - } - }); - eye_btn->toggle(); - eye_btn->setChecked(false); - textbox_layout->addWidget(eye_btn); - } - - main_layout->addWidget(textbox_widget, 0, Qt::AlignBottom); - main_layout->addSpacing(25); - - k = new Keyboard(this); - QObject::connect(k, &Keyboard::emitEnter, this, &InputDialog::handleEnter); - QObject::connect(k, &Keyboard::emitBackspace, this, [=]() { - line->backspace(); - - updateMaxLengthSublabel(line->text()); - }); - QObject::connect(k, &Keyboard::emitKey, this, [=](const QString &key) { - if (line->text().length() < maxLength || maxLength == DEFAULT_MAX_LENGTH) { - line->insert(key.left(1)); - updateMaxLengthSublabel(line->text()); - } - }); - - main_layout->addWidget(k, 2, Qt::AlignBottom); -} - -QString InputDialog::getText(const QString &prompt, QWidget *parent, const QString &subtitle, - bool secret, int minLength, const QString &defaultText, int maxLength) { - InputDialog d(prompt, parent, subtitle, secret); - d.line->setText(defaultText); - d.setMinLength(minLength); - - d.setMaxLength(maxLength); - d.updateMaxLengthSublabel(defaultText); - - const int ret = d.exec(); - return ret ? d.text() : QString(); -} - -QString InputDialog::text() { - return line->text(); -} - -void InputDialog::show() { - setMainWindow(this); -} - -void InputDialog::handleEnter() { - if (line->text().length() >= minLength) { - done(QDialog::Accepted); - emitText(line->text()); - } else { - setMessage(tr("Need at least %n character(s)!", "", minLength), false); - } -} - -void InputDialog::setMessage(const QString &message, bool clearInputField) { - label->setText(message); - if (clearInputField) { - line->setText(""); - } -} - -void InputDialog::setMinLength(int length) { - minLength = length; -} - -void InputDialog::setMaxLength(int length) { - maxLength = length; -} - -void InputDialog::updateMaxLengthSublabel(const QString &text) { - if (maxLength != DEFAULT_MAX_LENGTH) { - sublabel->setText(tr("Characters: %1/%2").arg(text.length()).arg(maxLength)); - } -} - -// ConfirmationDialog - -ConfirmationDialog::ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, const QString &cancel_text, - const bool rich, QWidget *parent, const bool is_long) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; color: #C9C9C9; } - #confirm_btn { background-color: #465BEA; } - #confirm_btn:pressed { background-color: #3049F4; } - )"); - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(32, rich || is_long ? 32 : 120, 32, 32); - - QLabel *prompt = new QLabel(prompt_text, this); - prompt->setWordWrap(true); - prompt->setAlignment(rich ? Qt::AlignLeft : Qt::AlignHCenter); - prompt->setStyleSheet((rich ? "font-size: 42px; font-weight: light;" : "font-size: 70px; font-weight: bold;") + QString(" margin: 45px;")); - main_layout->addWidget(rich ? (QWidget*)new ScrollView(prompt, this) : (QWidget*)prompt, 1, Qt::AlignTop); - - // cancel + confirm buttons - QHBoxLayout *btn_layout = new QHBoxLayout(); - btn_layout->setSpacing(30); - main_layout->addLayout(btn_layout); - - if (cancel_text.length()) { - QPushButton* cancel_btn = new QPushButton(cancel_text); - btn_layout->addWidget(cancel_btn); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - } - - if (confirm_text.length()) { - QPushButton* confirm_btn = new QPushButton(confirm_text); - confirm_btn->setObjectName("confirm_btn"); - btn_layout->addWidget(confirm_btn); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - } - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - int margin = rich ? 100 : 200; - outer_layout->setContentsMargins(margin, margin, margin, margin); - outer_layout->addWidget(container); -} - -bool ConfirmationDialog::alert(const QString &prompt_text, QWidget *parent, bool is_long) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", false, parent, is_long); - return d.exec(); -} - -bool ConfirmationDialog::confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, confirm_text, tr("Cancel"), false, parent); - return d.exec(); -} - -bool ConfirmationDialog::rich(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", true, parent); - return d.exec(); -} - -// MultiOptionDialog - -MultiOptionDialog::MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; } - #confirm_btn[enabled="false"] { background-color: #2B2B2B; } - #confirm_btn:enabled { background-color: #465BEA; } - #confirm_btn:enabled:pressed { background-color: #3049F4; } - )"); - - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(55, 50, 55, 50); - - QLabel *title = new QLabel(prompt_text, this); - title->setStyleSheet("font-size: 70px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - main_layout->addSpacing(25); - - QWidget *listWidget = new QWidget(this); - QVBoxLayout *listLayout = new QVBoxLayout(listWidget); - listLayout->setSpacing(20); - listWidget->setStyleSheet(R"( - QPushButton { - height: 135; - padding: 0px 50px; - text-align: left; - font-size: 55px; - font-weight: 300; - border-radius: 10px; - background-color: #4F4F4F; - } - QPushButton:checked { background-color: #465BEA; } - )"); - - QButtonGroup *group = new QButtonGroup(listWidget); - group->setExclusive(true); - - QPushButton *confirm_btn = new QPushButton(tr("Select")); - confirm_btn->setObjectName("confirm_btn"); - confirm_btn->setEnabled(false); - - for (const QString &s : l) { - QPushButton *selectionLabel = new QPushButton(s); - selectionLabel->setCheckable(true); - selectionLabel->setChecked(s == current); - QObject::connect(selectionLabel, &QPushButton::toggled, [=](bool checked) { - if (checked) selection = s; - if (selection != current) { - confirm_btn->setEnabled(true); - } else { - confirm_btn->setEnabled(false); - } - }); - - group->addButton(selectionLabel); - listLayout->addWidget(selectionLabel); - } - // add stretch to keep buttons spaced correctly - listLayout->addStretch(1); - - ScrollView *scroll_view = new ScrollView(listWidget, this); - scroll_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - - main_layout->addWidget(scroll_view); - main_layout->addSpacing(35); - - // cancel + confirm buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *cancel_btn = new QPushButton(tr("Cancel")); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - blayout->addWidget(cancel_btn); - blayout->addWidget(confirm_btn); - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(50, 50, 50, 50); - outer_layout->addWidget(container); -} - -QString MultiOptionDialog::getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) { - MultiOptionDialog d(prompt_text, l, current, parent); - if (d.exec()) { - return d.selection; - } - return ""; -} diff --git a/selfdrive/ui/qt/widgets/input.h b/selfdrive/ui/qt/widgets/input.h deleted file mode 100644 index f1c1f7f8f..000000000 --- a/selfdrive/ui/qt/widgets/input.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/keyboard.h" - -const int DEFAULT_MAX_LENGTH = 512; - -class DialogBase : public QDialog { - Q_OBJECT - -protected: - DialogBase(QWidget *parent); - bool eventFilter(QObject *o, QEvent *e) override; - -public slots: - int exec() override; -}; - -class InputDialog : public DialogBase { - Q_OBJECT - -public: - explicit InputDialog(const QString &title, QWidget *parent, const QString &subtitle = "", bool secret = false); - static QString getText(const QString &title, QWidget *parent, const QString &subtitle = "", - bool secret = false, int minLength = -1, const QString &defaultText = "", int maxLength = DEFAULT_MAX_LENGTH); - QString text(); - void setMessage(const QString &message, bool clearInputField = true); - void setMinLength(int length); - void show(); - - void setMaxLength(int length); - -private: - int minLength; - QLineEdit *line; - Keyboard *k; - QLabel *label; - QLabel *sublabel; - QVBoxLayout *main_layout; - QPushButton *eye_btn; - - void updateMaxLengthSublabel(const QString &text); - - int maxLength; - -private slots: - void handleEnter(); - -signals: - void cancel(); - void emitText(const QString &text); -}; - -class ConfirmationDialog : public DialogBase { - Q_OBJECT - -public: - explicit ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, - const QString &cancel_text, const bool rich, QWidget* parent, const bool is_long=false); - static bool alert(const QString &prompt_text, QWidget *parent, bool isLong=false); - static bool confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent); - static bool rich(const QString &prompt_text, QWidget *parent); -}; - -class MultiOptionDialog : public DialogBase { - Q_OBJECT - -public: - explicit MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - static QString getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - QString selection; -}; diff --git a/selfdrive/ui/qt/widgets/keyboard.cc b/selfdrive/ui/qt/widgets/keyboard.cc deleted file mode 100644 index 9ead27b8d..000000000 --- a/selfdrive/ui/qt/widgets/keyboard.cc +++ /dev/null @@ -1,182 +0,0 @@ -#include "selfdrive/ui/qt/widgets/keyboard.h" - -#include - -#include -#include -#include -#include -#include - -const QString BACKSPACE_KEY = "⌫"; -const QString ENTER_KEY = "→"; -const QString SHIFT_KEY = "⇧"; -const QString CAPS_LOCK_KEY = "⇪"; - -const QMap KEY_STRETCH = {{" ", 3}, {ENTER_KEY, 2}}; - -const QStringList CONTROL_BUTTONS = {SHIFT_KEY, CAPS_LOCK_KEY, "ABC", "#+=", "123", BACKSPACE_KEY, ENTER_KEY}; - -const float key_spacing_vertical = 20; -const float key_spacing_horizontal = 15; - -KeyButton::KeyButton(const QString &text, QWidget *parent) : QPushButton(text, parent) { - setAttribute(Qt::WA_AcceptTouchEvents); - setFocusPolicy(Qt::NoFocus); -} - -bool KeyButton::event(QEvent *event) { - if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchEnd) { - QTouchEvent *touchEvent = static_cast(event); - if (!touchEvent->touchPoints().empty()) { - const QEvent::Type mouseType = event->type() == QEvent::TouchBegin ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease; - QMouseEvent mouseEvent(mouseType, touchEvent->touchPoints().front().pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); - QPushButton::event(&mouseEvent); - event->accept(); - parentWidget()->update(); - return true; - } - } - return QPushButton::event(event); -} - -KeyboardLayout::KeyboardLayout(QWidget* parent, const std::vector>& layout) : QWidget(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - QButtonGroup* btn_group = new QButtonGroup(this); - QObject::connect(btn_group, SIGNAL(buttonClicked(QAbstractButton*)), parent, SLOT(handleButton(QAbstractButton*))); - - for (const auto &s : layout) { - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setSpacing(0); - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - for (const QString &p : s) { - KeyButton* btn = new KeyButton(p); - if (p == BACKSPACE_KEY) { - btn->setAutoRepeat(true); - } else if (p == ENTER_KEY) { - btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - } - btn->setFixedHeight(135 + key_spacing_vertical); - btn_group->addButton(btn); - hlayout->addWidget(btn, KEY_STRETCH.value(p, 1)); - } - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - main_layout->addLayout(hlayout); - } - - setStyleSheet(QString(R"( - QPushButton { - font-size: 75px; - margin-left: %1px; - margin-right: %1px; - margin-top: %2px; - margin-bottom: %2px; - padding: 0px; - border-radius: 10px; - color: #dddddd; - background-color: #444444; - } - QPushButton:pressed { - background-color: #333333; - } - )").arg(key_spacing_vertical / 2).arg(key_spacing_horizontal / 2)); -} - -Keyboard::Keyboard(QWidget *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - // lowercase - std::vector> lowercase = { - {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, - {"a", "s", "d", "f", "g", "h", "j", "k", "l"}, - {SHIFT_KEY, "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY}, - {"123", "/", "-", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, lowercase)); - - // uppercase - std::vector> uppercase = { - {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"}, - {"A", "S", "D", "F", "G", "H", "J", "K", "L"}, - {SHIFT_KEY, "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY}, - {"123", "/", "-", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, uppercase)); - - // numbers + specials - std::vector> numbers = { - {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}, - {"-", "/", ":", ";", "(", ")", "$", "&&", "@", "\""}, - {"#+=", ".", ",", "?", "!", "`", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, numbers)); - - // extra specials - std::vector> specials = { - {"[", "]", "{", "}", "#", "%", "^", "*", "+", "="}, - {"_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"}, - {"123", ".", ",", "?", "!", "'", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, specials)); - - main_layout->setCurrentIndex(0); -} - -void Keyboard::handleCapsPress() { - shift_state = (shift_state + 1) % 3; - bool is_uppercase = shift_state > 0; - main_layout->setCurrentIndex(is_uppercase); - - for (KeyButton* btn : main_layout->currentWidget()->findChildren()) { - if (btn->text() == SHIFT_KEY || btn->text() == CAPS_LOCK_KEY) { - btn->setText(shift_state == 2 ? CAPS_LOCK_KEY : SHIFT_KEY); - btn->setStyleSheet(is_uppercase ? "background-color: #465BEA;" : ""); - } - } -} - -void Keyboard::handleButton(QAbstractButton* btn) { - const QString &key = btn->text(); - if (CONTROL_BUTTONS.contains(key)) { - if (key == "ABC" || key == "123" || key == "#+=") { - int index = (key == "ABC") ? 0 : (key == "123" ? 2 : 3); - main_layout->setCurrentIndex(index); - shift_state = 0; - } else if (key == SHIFT_KEY || key == CAPS_LOCK_KEY) { - handleCapsPress(); - } else if (key == ENTER_KEY) { - main_layout->setCurrentIndex(0); - shift_state = 0; - emit emitEnter(); - } else if (key == BACKSPACE_KEY) { - emit emitBackspace(); - } - } else { - if (shift_state == 1 && "A" <= key && key <= "Z") { - main_layout->setCurrentIndex(0); - shift_state = 0; - } - emit emitKey(key); - } -} diff --git a/selfdrive/ui/qt/widgets/keyboard.h b/selfdrive/ui/qt/widgets/keyboard.h deleted file mode 100644 index e61617283..000000000 --- a/selfdrive/ui/qt/widgets/keyboard.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -class KeyButton : public QPushButton { - Q_OBJECT - -public: - KeyButton(const QString &text, QWidget *parent = 0); - bool event(QEvent *event) override; -}; - -class KeyboardLayout : public QWidget { - Q_OBJECT - -public: - explicit KeyboardLayout(QWidget* parent, const std::vector>& layout); -}; - -class Keyboard : public QFrame { - Q_OBJECT - -public: - explicit Keyboard(QWidget *parent = 0); - -private: - QStackedLayout* main_layout; - int shift_state = 0; - -private slots: - void handleButton(QAbstractButton* m_button); - void handleCapsPress(); - -signals: - void emitKey(const QString &s); - void emitBackspace(); - void emitEnter(); -}; diff --git a/selfdrive/ui/qt/widgets/moc_cameraview.cc b/selfdrive/ui/qt/widgets/moc_cameraview.cc deleted file mode 100644 index 8410583bb..000000000 --- a/selfdrive/ui/qt/widgets/moc_cameraview.cc +++ /dev/null @@ -1,230 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'cameraview.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "cameraview.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'cameraview.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_CameraWidget_t { - QByteArrayData data[13]; - char stringdata0[214]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_CameraWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_CameraWidget_t qt_meta_stringdata_CameraWidget = { - { -QT_MOC_LITERAL(0, 0, 12), // "CameraWidget" -QT_MOC_LITERAL(1, 13, 7), // "clicked" -QT_MOC_LITERAL(2, 21, 0), // "" -QT_MOC_LITERAL(3, 22, 19), // "vipcThreadConnected" -QT_MOC_LITERAL(4, 42, 16), // "VisionIpcClient*" -QT_MOC_LITERAL(5, 59, 23), // "vipcThreadFrameReceived" -QT_MOC_LITERAL(6, 83, 27), // "vipcAvailableStreamsUpdated" -QT_MOC_LITERAL(7, 111, 26), // "std::set" -QT_MOC_LITERAL(8, 138, 13), // "vipcConnected" -QT_MOC_LITERAL(9, 152, 11), // "vipc_client" -QT_MOC_LITERAL(10, 164, 17), // "vipcFrameReceived" -QT_MOC_LITERAL(11, 182, 23), // "availableStreamsUpdated" -QT_MOC_LITERAL(12, 206, 7) // "streams" - - }, - "CameraWidget\0clicked\0\0vipcThreadConnected\0" - "VisionIpcClient*\0vipcThreadFrameReceived\0" - "vipcAvailableStreamsUpdated\0" - "std::set\0vipcConnected\0" - "vipc_client\0vipcFrameReceived\0" - "availableStreamsUpdated\0streams" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_CameraWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 7, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 4, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 49, 2, 0x06 /* Public */, - 3, 1, 50, 2, 0x06 /* Public */, - 5, 0, 53, 2, 0x06 /* Public */, - 6, 1, 54, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 8, 1, 57, 2, 0x09 /* Protected */, - 10, 0, 60, 2, 0x09 /* Protected */, - 11, 1, 61, 2, 0x09 /* Protected */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, 0x80000000 | 4, 2, - QMetaType::Void, - QMetaType::Void, 0x80000000 | 7, 2, - - // slots: parameters - QMetaType::Void, 0x80000000 | 4, 9, - QMetaType::Void, - QMetaType::Void, 0x80000000 | 7, 12, - - 0 // eod -}; - -void CameraWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->clicked(); break; - case 1: _t->vipcThreadConnected((*reinterpret_cast< VisionIpcClient*(*)>(_a[1]))); break; - case 2: _t->vipcThreadFrameReceived(); break; - case 3: _t->vipcAvailableStreamsUpdated((*reinterpret_cast< std::set(*)>(_a[1]))); break; - case 4: _t->vipcConnected((*reinterpret_cast< VisionIpcClient*(*)>(_a[1]))); break; - case 5: _t->vipcFrameReceived(); break; - case 6: _t->availableStreamsUpdated((*reinterpret_cast< std::set(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - switch (_id) { - default: *reinterpret_cast(_a[0]) = -1; break; - case 3: - switch (*reinterpret_cast(_a[1])) { - default: *reinterpret_cast(_a[0]) = -1; break; - case 0: - *reinterpret_cast(_a[0]) = qRegisterMetaType< std::set >(); break; - } - break; - case 6: - switch (*reinterpret_cast(_a[1])) { - default: *reinterpret_cast(_a[0]) = -1; break; - case 0: - *reinterpret_cast(_a[0]) = qRegisterMetaType< std::set >(); break; - } - break; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (CameraWidget::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraWidget::clicked)) { - *result = 0; - return; - } - } - { - using _t = void (CameraWidget::*)(VisionIpcClient * ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraWidget::vipcThreadConnected)) { - *result = 1; - return; - } - } - { - using _t = void (CameraWidget::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraWidget::vipcThreadFrameReceived)) { - *result = 2; - return; - } - } - { - using _t = void (CameraWidget::*)(std::set ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraWidget::vipcAvailableStreamsUpdated)) { - *result = 3; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject CameraWidget::staticMetaObject = { { - &QOpenGLWidget::staticMetaObject, - qt_meta_stringdata_CameraWidget.data, - qt_meta_data_CameraWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *CameraWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *CameraWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_CameraWidget.stringdata0)) - return static_cast(this); - if (!strcmp(_clname, "QOpenGLFunctions")) - return static_cast< QOpenGLFunctions*>(this); - return QOpenGLWidget::qt_metacast(_clname); -} - -int CameraWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QOpenGLWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 7) - qt_static_metacall(this, _c, _id, _a); - _id -= 7; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 7) - qt_static_metacall(this, _c, _id, _a); - _id -= 7; - } - return _id; -} - -// SIGNAL 0 -void CameraWidget::clicked() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void CameraWidget::vipcThreadConnected(VisionIpcClient * _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 1, _a); -} - -// SIGNAL 2 -void CameraWidget::vipcThreadFrameReceived() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} - -// SIGNAL 3 -void CameraWidget::vipcAvailableStreamsUpdated(std::set _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 3, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_controls.cc b/selfdrive/ui/qt/widgets/moc_controls.cc deleted file mode 100644 index d4d33cd2b..000000000 --- a/selfdrive/ui/qt/widgets/moc_controls.cc +++ /dev/null @@ -1,956 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'controls.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "controls.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'controls.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ElidedLabel_t { - QByteArrayData data[3]; - char stringdata0[21]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ElidedLabel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ElidedLabel_t qt_meta_stringdata_ElidedLabel = { - { -QT_MOC_LITERAL(0, 0, 11), // "ElidedLabel" -QT_MOC_LITERAL(1, 12, 7), // "clicked" -QT_MOC_LITERAL(2, 20, 0) // "" - - }, - "ElidedLabel\0clicked\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ElidedLabel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void ElidedLabel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->clicked(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (ElidedLabel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ElidedLabel::clicked)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ElidedLabel::staticMetaObject = { { - &QLabel::staticMetaObject, - qt_meta_stringdata_ElidedLabel.data, - qt_meta_data_ElidedLabel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ElidedLabel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ElidedLabel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ElidedLabel.stringdata0)) - return static_cast(this); - return QLabel::qt_metacast(_clname); -} - -int ElidedLabel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QLabel::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void ElidedLabel::clicked() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_AbstractControl_t { - QByteArrayData data[5]; - char stringdata0[75]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_AbstractControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_AbstractControl_t qt_meta_stringdata_AbstractControl = { - { -QT_MOC_LITERAL(0, 0, 15), // "AbstractControl" -QT_MOC_LITERAL(1, 16, 20), // "showDescriptionEvent" -QT_MOC_LITERAL(2, 37, 0), // "" -QT_MOC_LITERAL(3, 38, 20), // "hideDescriptionEvent" -QT_MOC_LITERAL(4, 59, 15) // "showDescription" - - }, - "AbstractControl\0showDescriptionEvent\0" - "\0hideDescriptionEvent\0showDescription" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_AbstractControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 29, 2, 0x06 /* Public */, - 3, 0, 30, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 4, 0, 31, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void AbstractControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->showDescriptionEvent(); break; - case 1: _t->hideDescriptionEvent(); break; - case 2: _t->showDescription(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (AbstractControl::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AbstractControl::showDescriptionEvent)) { - *result = 0; - return; - } - } - { - using _t = void (AbstractControl::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AbstractControl::hideDescriptionEvent)) { - *result = 1; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject AbstractControl::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_AbstractControl.data, - qt_meta_data_AbstractControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *AbstractControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *AbstractControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_AbstractControl.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int AbstractControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void AbstractControl::showDescriptionEvent() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void AbstractControl::hideDescriptionEvent() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -struct qt_meta_stringdata_LabelControl_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_LabelControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_LabelControl_t qt_meta_stringdata_LabelControl = { - { -QT_MOC_LITERAL(0, 0, 12) // "LabelControl" - - }, - "LabelControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_LabelControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void LabelControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject LabelControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_LabelControl.data, - qt_meta_data_LabelControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *LabelControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *LabelControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_LabelControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int LabelControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_ButtonControl_t { - QByteArrayData data[5]; - char stringdata0[42]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ButtonControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ButtonControl_t qt_meta_stringdata_ButtonControl = { - { -QT_MOC_LITERAL(0, 0, 13), // "ButtonControl" -QT_MOC_LITERAL(1, 14, 7), // "clicked" -QT_MOC_LITERAL(2, 22, 0), // "" -QT_MOC_LITERAL(3, 23, 10), // "setEnabled" -QT_MOC_LITERAL(4, 34, 7) // "enabled" - - }, - "ButtonControl\0clicked\0\0setEnabled\0" - "enabled" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ButtonControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 24, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 3, 1, 25, 2, 0x0a /* Public */, - - // signals: parameters - QMetaType::Void, - - // slots: parameters - QMetaType::Void, QMetaType::Bool, 4, - - 0 // eod -}; - -void ButtonControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->clicked(); break; - case 1: _t->setEnabled((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (ButtonControl::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ButtonControl::clicked)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject ButtonControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_ButtonControl.data, - qt_meta_data_ButtonControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ButtonControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ButtonControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ButtonControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int ButtonControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void ButtonControl::clicked() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_ToggleControl_t { - QByteArrayData data[4]; - char stringdata0[35]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ToggleControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ToggleControl_t qt_meta_stringdata_ToggleControl = { - { -QT_MOC_LITERAL(0, 0, 13), // "ToggleControl" -QT_MOC_LITERAL(1, 14, 13), // "toggleFlipped" -QT_MOC_LITERAL(2, 28, 0), // "" -QT_MOC_LITERAL(3, 29, 5) // "state" - - }, - "ToggleControl\0toggleFlipped\0\0state" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ToggleControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Bool, 3, - - 0 // eod -}; - -void ToggleControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->toggleFlipped((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (ToggleControl::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ToggleControl::toggleFlipped)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject ToggleControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_ToggleControl.data, - qt_meta_data_ToggleControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ToggleControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ToggleControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ToggleControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int ToggleControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void ToggleControl::toggleFlipped(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_ParamControl_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ParamControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ParamControl_t qt_meta_stringdata_ParamControl = { - { -QT_MOC_LITERAL(0, 0, 12) // "ParamControl" - - }, - "ParamControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ParamControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ParamControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ParamControl::staticMetaObject = { { - &ToggleControl::staticMetaObject, - qt_meta_stringdata_ParamControl.data, - qt_meta_data_ParamControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ParamControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ParamControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ParamControl.stringdata0)) - return static_cast(this); - return ToggleControl::qt_metacast(_clname); -} - -int ParamControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ToggleControl::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_MultiButtonControl_t { - QByteArrayData data[4]; - char stringdata0[37]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_MultiButtonControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_MultiButtonControl_t qt_meta_stringdata_MultiButtonControl = { - { -QT_MOC_LITERAL(0, 0, 18), // "MultiButtonControl" -QT_MOC_LITERAL(1, 19, 13), // "buttonClicked" -QT_MOC_LITERAL(2, 33, 0), // "" -QT_MOC_LITERAL(3, 34, 2) // "id" - - }, - "MultiButtonControl\0buttonClicked\0\0id" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_MultiButtonControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, 3, - - 0 // eod -}; - -void MultiButtonControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->buttonClicked((*reinterpret_cast< int(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (MultiButtonControl::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MultiButtonControl::buttonClicked)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject MultiButtonControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_MultiButtonControl.data, - qt_meta_data_MultiButtonControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *MultiButtonControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *MultiButtonControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_MultiButtonControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int MultiButtonControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void MultiButtonControl::buttonClicked(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_ButtonParamControl_t { - QByteArrayData data[1]; - char stringdata0[19]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ButtonParamControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ButtonParamControl_t qt_meta_stringdata_ButtonParamControl = { - { -QT_MOC_LITERAL(0, 0, 18) // "ButtonParamControl" - - }, - "ButtonParamControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ButtonParamControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ButtonParamControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ButtonParamControl::staticMetaObject = { { - &MultiButtonControl::staticMetaObject, - qt_meta_stringdata_ButtonParamControl.data, - qt_meta_data_ButtonParamControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ButtonParamControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ButtonParamControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ButtonParamControl.stringdata0)) - return static_cast(this); - return MultiButtonControl::qt_metacast(_clname); -} - -int ButtonParamControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = MultiButtonControl::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_ListWidget_t { - QByteArrayData data[1]; - char stringdata0[11]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ListWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ListWidget_t qt_meta_stringdata_ListWidget = { - { -QT_MOC_LITERAL(0, 0, 10) // "ListWidget" - - }, - "ListWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ListWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ListWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ListWidget::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_ListWidget.data, - qt_meta_data_ListWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ListWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ListWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ListWidget.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int ListWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_LayoutWidget_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_LayoutWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_LayoutWidget_t qt_meta_stringdata_LayoutWidget = { - { -QT_MOC_LITERAL(0, 0, 12) // "LayoutWidget" - - }, - "LayoutWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_LayoutWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void LayoutWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject LayoutWidget::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_LayoutWidget.data, - qt_meta_data_LayoutWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *LayoutWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *LayoutWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_LayoutWidget.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int LayoutWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_input.cc b/selfdrive/ui/qt/widgets/moc_input.cc deleted file mode 100644 index e1881853e..000000000 --- a/selfdrive/ui/qt/widgets/moc_input.cc +++ /dev/null @@ -1,394 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'input.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "input.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'input.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DialogBase_t { - QByteArrayData data[3]; - char stringdata0[17]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DialogBase_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DialogBase_t qt_meta_stringdata_DialogBase = { - { -QT_MOC_LITERAL(0, 0, 10), // "DialogBase" -QT_MOC_LITERAL(1, 11, 4), // "exec" -QT_MOC_LITERAL(2, 16, 0) // "" - - }, - "DialogBase\0exec\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DialogBase[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x0a /* Public */, - - // slots: parameters - QMetaType::Int, - - 0 // eod -}; - -void DialogBase::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: { int _r = _t->exec(); - if (_a[0]) *reinterpret_cast< int*>(_a[0]) = std::move(_r); } break; - default: ; - } - } -} - -QT_INIT_METAOBJECT const QMetaObject DialogBase::staticMetaObject = { { - &QDialog::staticMetaObject, - qt_meta_stringdata_DialogBase.data, - qt_meta_data_DialogBase, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DialogBase::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DialogBase::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DialogBase.stringdata0)) - return static_cast(this); - return QDialog::qt_metacast(_clname); -} - -int DialogBase::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QDialog::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} -struct qt_meta_stringdata_InputDialog_t { - QByteArrayData data[6]; - char stringdata0[46]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_InputDialog_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_InputDialog_t qt_meta_stringdata_InputDialog = { - { -QT_MOC_LITERAL(0, 0, 11), // "InputDialog" -QT_MOC_LITERAL(1, 12, 6), // "cancel" -QT_MOC_LITERAL(2, 19, 0), // "" -QT_MOC_LITERAL(3, 20, 8), // "emitText" -QT_MOC_LITERAL(4, 29, 4), // "text" -QT_MOC_LITERAL(5, 34, 11) // "handleEnter" - - }, - "InputDialog\0cancel\0\0emitText\0text\0" - "handleEnter" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_InputDialog[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 29, 2, 0x06 /* Public */, - 3, 1, 30, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 5, 0, 33, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, QMetaType::QString, 4, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void InputDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->cancel(); break; - case 1: _t->emitText((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 2: _t->handleEnter(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (InputDialog::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&InputDialog::cancel)) { - *result = 0; - return; - } - } - { - using _t = void (InputDialog::*)(const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&InputDialog::emitText)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject InputDialog::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_InputDialog.data, - qt_meta_data_InputDialog, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *InputDialog::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *InputDialog::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_InputDialog.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int InputDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void InputDialog::cancel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void InputDialog::emitText(const QString & _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 1, _a); -} -struct qt_meta_stringdata_ConfirmationDialog_t { - QByteArrayData data[1]; - char stringdata0[19]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ConfirmationDialog_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ConfirmationDialog_t qt_meta_stringdata_ConfirmationDialog = { - { -QT_MOC_LITERAL(0, 0, 18) // "ConfirmationDialog" - - }, - "ConfirmationDialog" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ConfirmationDialog[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ConfirmationDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ConfirmationDialog::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_ConfirmationDialog.data, - qt_meta_data_ConfirmationDialog, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ConfirmationDialog::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ConfirmationDialog::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ConfirmationDialog.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int ConfirmationDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_MultiOptionDialog_t { - QByteArrayData data[1]; - char stringdata0[18]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_MultiOptionDialog_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_MultiOptionDialog_t qt_meta_stringdata_MultiOptionDialog = { - { -QT_MOC_LITERAL(0, 0, 17) // "MultiOptionDialog" - - }, - "MultiOptionDialog" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_MultiOptionDialog[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void MultiOptionDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject MultiOptionDialog::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_MultiOptionDialog.data, - qt_meta_data_MultiOptionDialog, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *MultiOptionDialog::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *MultiOptionDialog::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_MultiOptionDialog.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int MultiOptionDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_keyboard.cc b/selfdrive/ui/qt/widgets/moc_keyboard.cc deleted file mode 100644 index b3542dc2c..000000000 --- a/selfdrive/ui/qt/widgets/moc_keyboard.cc +++ /dev/null @@ -1,324 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'keyboard.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "keyboard.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'keyboard.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_KeyButton_t { - QByteArrayData data[1]; - char stringdata0[10]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_KeyButton_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_KeyButton_t qt_meta_stringdata_KeyButton = { - { -QT_MOC_LITERAL(0, 0, 9) // "KeyButton" - - }, - "KeyButton" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_KeyButton[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void KeyButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject KeyButton::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_KeyButton.data, - qt_meta_data_KeyButton, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *KeyButton::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *KeyButton::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_KeyButton.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int KeyButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_KeyboardLayout_t { - QByteArrayData data[1]; - char stringdata0[15]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_KeyboardLayout_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_KeyboardLayout_t qt_meta_stringdata_KeyboardLayout = { - { -QT_MOC_LITERAL(0, 0, 14) // "KeyboardLayout" - - }, - "KeyboardLayout" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_KeyboardLayout[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void KeyboardLayout::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject KeyboardLayout::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_KeyboardLayout.data, - qt_meta_data_KeyboardLayout, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *KeyboardLayout::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *KeyboardLayout::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_KeyboardLayout.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int KeyboardLayout::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_Keyboard_t { - QByteArrayData data[10]; - char stringdata0[99]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_Keyboard_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_Keyboard_t qt_meta_stringdata_Keyboard = { - { -QT_MOC_LITERAL(0, 0, 8), // "Keyboard" -QT_MOC_LITERAL(1, 9, 7), // "emitKey" -QT_MOC_LITERAL(2, 17, 0), // "" -QT_MOC_LITERAL(3, 18, 1), // "s" -QT_MOC_LITERAL(4, 20, 13), // "emitBackspace" -QT_MOC_LITERAL(5, 34, 9), // "emitEnter" -QT_MOC_LITERAL(6, 44, 12), // "handleButton" -QT_MOC_LITERAL(7, 57, 16), // "QAbstractButton*" -QT_MOC_LITERAL(8, 74, 8), // "m_button" -QT_MOC_LITERAL(9, 83, 15) // "handleCapsPress" - - }, - "Keyboard\0emitKey\0\0s\0emitBackspace\0" - "emitEnter\0handleButton\0QAbstractButton*\0" - "m_button\0handleCapsPress" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_Keyboard[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 5, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 39, 2, 0x06 /* Public */, - 4, 0, 42, 2, 0x06 /* Public */, - 5, 0, 43, 2, 0x06 /* Public */, - - // slots: name, argc, parameters, tag, flags - 6, 1, 44, 2, 0x08 /* Private */, - 9, 0, 47, 2, 0x08 /* Private */, - - // signals: parameters - QMetaType::Void, QMetaType::QString, 3, - QMetaType::Void, - QMetaType::Void, - - // slots: parameters - QMetaType::Void, 0x80000000 | 7, 8, - QMetaType::Void, - - 0 // eod -}; - -void Keyboard::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->emitKey((*reinterpret_cast< const QString(*)>(_a[1]))); break; - case 1: _t->emitBackspace(); break; - case 2: _t->emitEnter(); break; - case 3: _t->handleButton((*reinterpret_cast< QAbstractButton*(*)>(_a[1]))); break; - case 4: _t->handleCapsPress(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (Keyboard::*)(const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Keyboard::emitKey)) { - *result = 0; - return; - } - } - { - using _t = void (Keyboard::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Keyboard::emitBackspace)) { - *result = 1; - return; - } - } - { - using _t = void (Keyboard::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Keyboard::emitEnter)) { - *result = 2; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject Keyboard::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_Keyboard.data, - qt_meta_data_Keyboard, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *Keyboard::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *Keyboard::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_Keyboard.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int Keyboard::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 5) - qt_static_metacall(this, _c, _id, _a); - _id -= 5; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 5) - *reinterpret_cast(_a[0]) = -1; - _id -= 5; - } - return _id; -} - -// SIGNAL 0 -void Keyboard::emitKey(const QString & _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void Keyboard::emitBackspace() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} - -// SIGNAL 2 -void Keyboard::emitEnter() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_offroad_alerts.cc b/selfdrive/ui/qt/widgets/moc_offroad_alerts.cc deleted file mode 100644 index e667313d5..000000000 --- a/selfdrive/ui/qt/widgets/moc_offroad_alerts.cc +++ /dev/null @@ -1,273 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'offroad_alerts.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "offroad_alerts.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'offroad_alerts.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_AbstractAlert_t { - QByteArrayData data[3]; - char stringdata0[23]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_AbstractAlert_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_AbstractAlert_t qt_meta_stringdata_AbstractAlert = { - { -QT_MOC_LITERAL(0, 0, 13), // "AbstractAlert" -QT_MOC_LITERAL(1, 14, 7), // "dismiss" -QT_MOC_LITERAL(2, 22, 0) // "" - - }, - "AbstractAlert\0dismiss\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_AbstractAlert[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void AbstractAlert::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->dismiss(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (AbstractAlert::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AbstractAlert::dismiss)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject AbstractAlert::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_AbstractAlert.data, - qt_meta_data_AbstractAlert, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *AbstractAlert::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *AbstractAlert::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_AbstractAlert.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int AbstractAlert::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void AbstractAlert::dismiss() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_UpdateAlert_t { - QByteArrayData data[1]; - char stringdata0[12]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_UpdateAlert_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_UpdateAlert_t qt_meta_stringdata_UpdateAlert = { - { -QT_MOC_LITERAL(0, 0, 11) // "UpdateAlert" - - }, - "UpdateAlert" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_UpdateAlert[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void UpdateAlert::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject UpdateAlert::staticMetaObject = { { - &AbstractAlert::staticMetaObject, - qt_meta_stringdata_UpdateAlert.data, - qt_meta_data_UpdateAlert, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *UpdateAlert::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *UpdateAlert::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_UpdateAlert.stringdata0)) - return static_cast(this); - return AbstractAlert::qt_metacast(_clname); -} - -int UpdateAlert::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractAlert::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_OffroadAlert_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_OffroadAlert_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_OffroadAlert_t qt_meta_stringdata_OffroadAlert = { - { -QT_MOC_LITERAL(0, 0, 12) // "OffroadAlert" - - }, - "OffroadAlert" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_OffroadAlert[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void OffroadAlert::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject OffroadAlert::staticMetaObject = { { - &AbstractAlert::staticMetaObject, - qt_meta_stringdata_OffroadAlert.data, - qt_meta_data_OffroadAlert, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *OffroadAlert::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *OffroadAlert::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_OffroadAlert.stringdata0)) - return static_cast(this); - return AbstractAlert::qt_metacast(_clname); -} - -int OffroadAlert::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractAlert::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_prime.cc b/selfdrive/ui/qt/widgets/moc_prime.cc deleted file mode 100644 index d75c5771e..000000000 --- a/selfdrive/ui/qt/widgets/moc_prime.cc +++ /dev/null @@ -1,445 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'prime.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "prime.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'prime.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_PairingQRWidget_t { - QByteArrayData data[3]; - char stringdata0[25]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_PairingQRWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_PairingQRWidget_t qt_meta_stringdata_PairingQRWidget = { - { -QT_MOC_LITERAL(0, 0, 15), // "PairingQRWidget" -QT_MOC_LITERAL(1, 16, 7), // "refresh" -QT_MOC_LITERAL(2, 24, 0) // "" - - }, - "PairingQRWidget\0refresh\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_PairingQRWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void PairingQRWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->refresh(); break; - default: ; - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject PairingQRWidget::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_PairingQRWidget.data, - qt_meta_data_PairingQRWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *PairingQRWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *PairingQRWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_PairingQRWidget.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int PairingQRWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} -struct qt_meta_stringdata_PairingPopup_t { - QByteArrayData data[1]; - char stringdata0[13]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_PairingPopup_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_PairingPopup_t qt_meta_stringdata_PairingPopup = { - { -QT_MOC_LITERAL(0, 0, 12) // "PairingPopup" - - }, - "PairingPopup" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_PairingPopup[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void PairingPopup::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject PairingPopup::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_PairingPopup.data, - qt_meta_data_PairingPopup, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *PairingPopup::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *PairingPopup::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_PairingPopup.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int PairingPopup::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_PrimeUserWidget_t { - QByteArrayData data[1]; - char stringdata0[16]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_PrimeUserWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_PrimeUserWidget_t qt_meta_stringdata_PrimeUserWidget = { - { -QT_MOC_LITERAL(0, 0, 15) // "PrimeUserWidget" - - }, - "PrimeUserWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_PrimeUserWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void PrimeUserWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject PrimeUserWidget::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_PrimeUserWidget.data, - qt_meta_data_PrimeUserWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *PrimeUserWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *PrimeUserWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_PrimeUserWidget.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int PrimeUserWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_PrimeAdWidget_t { - QByteArrayData data[1]; - char stringdata0[14]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_PrimeAdWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_PrimeAdWidget_t qt_meta_stringdata_PrimeAdWidget = { - { -QT_MOC_LITERAL(0, 0, 13) // "PrimeAdWidget" - - }, - "PrimeAdWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_PrimeAdWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void PrimeAdWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject PrimeAdWidget::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_PrimeAdWidget.data, - qt_meta_data_PrimeAdWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *PrimeAdWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *PrimeAdWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_PrimeAdWidget.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int PrimeAdWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_SetupWidget_t { - QByteArrayData data[5]; - char stringdata0[38]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_SetupWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_SetupWidget_t qt_meta_stringdata_SetupWidget = { - { -QT_MOC_LITERAL(0, 0, 11), // "SetupWidget" -QT_MOC_LITERAL(1, 12, 12), // "openSettings" -QT_MOC_LITERAL(2, 25, 0), // "" -QT_MOC_LITERAL(3, 26, 5), // "index" -QT_MOC_LITERAL(4, 32, 5) // "param" - - }, - "SetupWidget\0openSettings\0\0index\0param" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_SetupWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 2, 29, 2, 0x06 /* Public */, - 1, 1, 34, 2, 0x26 /* Public | MethodCloned */, - 1, 0, 37, 2, 0x26 /* Public | MethodCloned */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, QMetaType::QString, 3, 4, - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, - - 0 // eod -}; - -void SetupWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSettings((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; - case 1: _t->openSettings((*reinterpret_cast< int(*)>(_a[1]))); break; - case 2: _t->openSettings(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (SetupWidget::*)(int , const QString & ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SetupWidget::openSettings)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject SetupWidget::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_SetupWidget.data, - qt_meta_data_SetupWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *SetupWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *SetupWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_SetupWidget.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int SetupWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void SetupWidget::openSettings(int _t1, const QString & _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_scrollview.cc b/selfdrive/ui/qt/widgets/moc_scrollview.cc deleted file mode 100644 index f5fd143eb..000000000 --- a/selfdrive/ui/qt/widgets/moc_scrollview.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'scrollview.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "scrollview.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'scrollview.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ScrollView_t { - QByteArrayData data[1]; - char stringdata0[11]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ScrollView_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ScrollView_t qt_meta_stringdata_ScrollView = { - { -QT_MOC_LITERAL(0, 0, 10) // "ScrollView" - - }, - "ScrollView" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ScrollView[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ScrollView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ScrollView::staticMetaObject = { { - &QScrollArea::staticMetaObject, - qt_meta_stringdata_ScrollView.data, - qt_meta_data_ScrollView, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ScrollView::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ScrollView::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ScrollView.stringdata0)) - return static_cast(this); - return QScrollArea::qt_metacast(_clname); -} - -int ScrollView::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QScrollArea::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_ssh_keys.cc b/selfdrive/ui/qt/widgets/moc_ssh_keys.cc deleted file mode 100644 index be700f923..000000000 --- a/selfdrive/ui/qt/widgets/moc_ssh_keys.cc +++ /dev/null @@ -1,164 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'ssh_keys.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "ssh_keys.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'ssh_keys.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_SshToggle_t { - QByteArrayData data[1]; - char stringdata0[10]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_SshToggle_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_SshToggle_t qt_meta_stringdata_SshToggle = { - { -QT_MOC_LITERAL(0, 0, 9) // "SshToggle" - - }, - "SshToggle" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_SshToggle[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void SshToggle::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject SshToggle::staticMetaObject = { { - &ToggleControl::staticMetaObject, - qt_meta_stringdata_SshToggle.data, - qt_meta_data_SshToggle, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *SshToggle::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *SshToggle::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_SshToggle.stringdata0)) - return static_cast(this); - return ToggleControl::qt_metacast(_clname); -} - -int SshToggle::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ToggleControl::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_SshControl_t { - QByteArrayData data[1]; - char stringdata0[11]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_SshControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_SshControl_t qt_meta_stringdata_SshControl = { - { -QT_MOC_LITERAL(0, 0, 10) // "SshControl" - - }, - "SshControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_SshControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void SshControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject SshControl::staticMetaObject = { { - &ButtonControl::staticMetaObject, - qt_meta_stringdata_SshControl.data, - qt_meta_data_SshControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *SshControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *SshControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_SshControl.stringdata0)) - return static_cast(this); - return ButtonControl::qt_metacast(_clname); -} - -int SshControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ButtonControl::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/moc_toggle.cc b/selfdrive/ui/qt/widgets/moc_toggle.cc deleted file mode 100644 index 8817cbaeb..000000000 --- a/selfdrive/ui/qt/widgets/moc_toggle.cc +++ /dev/null @@ -1,176 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'toggle.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "toggle.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'toggle.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_Toggle_t { - QByteArrayData data[5]; - char stringdata0[45]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_Toggle_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_Toggle_t qt_meta_stringdata_Toggle = { - { -QT_MOC_LITERAL(0, 0, 6), // "Toggle" -QT_MOC_LITERAL(1, 7, 12), // "stateChanged" -QT_MOC_LITERAL(2, 20, 0), // "" -QT_MOC_LITERAL(3, 21, 9), // "new_state" -QT_MOC_LITERAL(4, 31, 13) // "offset_circle" - - }, - "Toggle\0stateChanged\0\0new_state\0" - "offset_circle" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_Toggle[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 1, 22, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Bool, 3, - - // properties: name, type, flags - 4, QMetaType::Int, 0x00095003, - - 0 // eod -}; - -void Toggle::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->stateChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (Toggle::*)(bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Toggle::stateChanged)) { - *result = 0; - return; - } - } - } -#ifndef QT_NO_PROPERTIES - else if (_c == QMetaObject::ReadProperty) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - void *_v = _a[0]; - switch (_id) { - case 0: *reinterpret_cast< int*>(_v) = _t->offset_circle(); break; - default: break; - } - } else if (_c == QMetaObject::WriteProperty) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - void *_v = _a[0]; - switch (_id) { - case 0: _t->set_offset_circle(*reinterpret_cast< int*>(_v)); break; - default: break; - } - } else if (_c == QMetaObject::ResetProperty) { - } -#endif // QT_NO_PROPERTIES -} - -QT_INIT_METAOBJECT const QMetaObject Toggle::staticMetaObject = { { - &QAbstractButton::staticMetaObject, - qt_meta_stringdata_Toggle.data, - qt_meta_data_Toggle, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *Toggle::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *Toggle::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_Toggle.stringdata0)) - return static_cast(this); - return QAbstractButton::qt_metacast(_clname); -} - -int Toggle::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QAbstractButton::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } -#ifndef QT_NO_PROPERTIES - else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty - || _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) { - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::QueryPropertyDesignable) { - _id -= 1; - } else if (_c == QMetaObject::QueryPropertyScriptable) { - _id -= 1; - } else if (_c == QMetaObject::QueryPropertyStored) { - _id -= 1; - } else if (_c == QMetaObject::QueryPropertyEditable) { - _id -= 1; - } else if (_c == QMetaObject::QueryPropertyUser) { - _id -= 1; - } -#endif // QT_NO_PROPERTIES - return _id; -} - -// SIGNAL 0 -void Toggle::stateChanged(bool _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.cc b/selfdrive/ui/qt/widgets/offroad_alerts.cc deleted file mode 100644 index 3a4828a2a..000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.cc +++ /dev/null @@ -1,138 +0,0 @@ -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(50); - main_layout->setSpacing(30); - - QWidget *widget = new QWidget; - scrollable_layout = new QVBoxLayout(widget); - widget->setStyleSheet("background-color: transparent;"); - main_layout->addWidget(new ScrollView(widget)); - - // bottom footer, dismiss + reboot buttons - QHBoxLayout *footer_layout = new QHBoxLayout(); - main_layout->addLayout(footer_layout); - - QPushButton *dismiss_btn = new QPushButton(tr("Close")); - dismiss_btn->setFixedSize(400, 125); - footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); - QObject::connect(dismiss_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - - action_btn = new QPushButton(); - action_btn->setVisible(false); - action_btn->setFixedHeight(125); - footer_layout->addWidget(action_btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(action_btn, &QPushButton::clicked, [=]() { - if (!alerts["Offroad_ExcessiveActuation"]->text().isEmpty()) { - params.remove("Offroad_ExcessiveActuation"); - } else { - params.putBool("SnoozeUpdate", true); - } - }); - QObject::connect(action_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - action_btn->setStyleSheet("color: white; background-color: #4F4F4F; padding-left: 60px; padding-right: 60px;"); - - if (hasRebootBtn) { - QPushButton *rebootBtn = new QPushButton(tr("Reboot and Update")); - rebootBtn->setFixedSize(600, 125); - footer_layout->addWidget(rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(rebootBtn, &QPushButton::clicked, [=]() { Hardware::reboot(); }); - } - - setStyleSheet(R"( - * { - font-size: 48px; - color: white; - } - QFrame { - border-radius: 30px; - background-color: #393939; - } - QPushButton { - color: black; - font-weight: 500; - border-radius: 30px; - background-color: white; - } - )"); -} - -int OffroadAlert::refresh() { - // build widgets for each offroad alert on first refresh - if (alerts.empty()) { - QString json = util::read_file("../selfdrived/alerts_offroad.json").c_str(); - QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); - - // descending sort labels by severity - std::vector> sorted; - for (auto it = obj.constBegin(); it != obj.constEnd(); ++it) { - sorted.push_back({it.key().toStdString(), it.value()["severity"].toInt()}); - } - std::sort(sorted.begin(), sorted.end(), [=](auto &l, auto &r) { return l.second > r.second; }); - - for (auto &[key, severity] : sorted) { - QLabel *l = new QLabel(this); - alerts[key] = l; - l->setMargin(60); - l->setWordWrap(true); - l->setStyleSheet(QString("background-color: %1").arg(severity ? "#E22C2C" : "#292929")); - scrollable_layout->addWidget(l); - } - scrollable_layout->addStretch(1); - } - - int alertCount = 0; - for (const auto &[key, label] : alerts) { - QString text; - std::string bytes = params.get(key); - if (bytes.size()) { - auto doc_par = QJsonDocument::fromJson(bytes.c_str()); - text = tr(doc_par["text"].toString().toUtf8().data()); - auto extra = doc_par["extra"].toString(); - if (!extra.isEmpty()) { - text = text.arg(extra); - } - } - label->setText(text); - label->setVisible(!text.isEmpty()); - alertCount += !text.isEmpty(); - } - - action_btn->setVisible(!alerts["Offroad_ExcessiveActuation"]->text().isEmpty() || !alerts["Offroad_ConnectivityNeeded"]->text().isEmpty()); - if (!alerts["Offroad_ExcessiveActuation"]->text().isEmpty()) { - action_btn->setText(tr("Acknowledge Excessive Actuation")); - } else { - action_btn->setText(tr("Snooze Update")); - } - - return alertCount; -} - -UpdateAlert::UpdateAlert(QWidget *parent) : AbstractAlert(true, parent) { - releaseNotes = new QLabel(this); - releaseNotes->setWordWrap(true); - releaseNotes->setAlignment(Qt::AlignTop); - scrollable_layout->addWidget(releaseNotes); -} - -bool UpdateAlert::refresh() { - bool updateAvailable = params.getBool("UpdateAvailable"); - if (updateAvailable) { - releaseNotes->setText(params.get("UpdaterNewReleaseNotes").c_str()); - } - return updateAvailable; -} diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.h b/selfdrive/ui/qt/widgets/offroad_alerts.h deleted file mode 100644 index 2dcf4f9d8..000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include - -#include "common/params.h" - -class AbstractAlert : public QFrame { - Q_OBJECT - -protected: - AbstractAlert(bool hasRebootBtn, QWidget *parent = nullptr); - - QPushButton *action_btn; - QVBoxLayout *scrollable_layout; - Params params; - std::map alerts; - -signals: - void dismiss(); -}; - -class UpdateAlert : public AbstractAlert { - Q_OBJECT - -public: - UpdateAlert(QWidget *parent = 0); - bool refresh(); - -private: - QLabel *releaseNotes = nullptr; -}; - -class OffroadAlert : public AbstractAlert { - Q_OBJECT - -public: - explicit OffroadAlert(QWidget *parent = 0) : AbstractAlert(false, parent) {} - int refresh(); -}; diff --git a/selfdrive/ui/qt/widgets/prime.cc b/selfdrive/ui/qt/widgets/prime.cc deleted file mode 100644 index d04cc9118..000000000 --- a/selfdrive/ui/qt/widgets/prime.cc +++ /dev/null @@ -1,266 +0,0 @@ -#include "selfdrive/ui/qt/widgets/prime.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" - -using qrcodegen::QrCode; - -PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { - timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, &PairingQRWidget::refresh); -} - -void PairingQRWidget::showEvent(QShowEvent *event) { - refresh(); - timer->start(5 * 60 * 1000); - device()->setOffroadBrightness(100); -} - -void PairingQRWidget::hideEvent(QHideEvent *event) { - timer->stop(); - device()->setOffroadBrightness(BACKLIGHT_OFFROAD); -} - -void PairingQRWidget::refresh() { - QString pairToken = CommaApi::create_jwt({{"pair", true}}); - QString qrString = (useKonikServer() ? "https://stable.konik.ai/?pair=" : "https://connect.comma.ai/?pair=") + pairToken; - this->updateQrCode(qrString); - update(); -} - -void PairingQRWidget::updateQrCode(const QString &text) { - QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); - qint32 sz = qr.getSize(); - QImage im(sz, sz, QImage::Format_RGB32); - - QRgb black = qRgb(0, 0, 0); - QRgb white = qRgb(255, 255, 255); - for (int y = 0; y < sz; y++) { - for (int x = 0; x < sz; x++) { - im.setPixel(x, y, qr.getModule(x, y) ? black : white); - } - } - - // Integer division to prevent anti-aliasing - int final_sz = ((width() / sz) - 1) * sz; - img = QPixmap::fromImage(im.scaled(final_sz, final_sz, Qt::KeepAspectRatio), Qt::MonoOnly); -} - -void PairingQRWidget::paintEvent(QPaintEvent *e) { - QPainter p(this); - p.fillRect(rect(), Qt::white); - - QSize s = (size() - img.size()) / 2; - p.drawPixmap(s.width(), s.height(), img); -} - - -PairingPopup::PairingPopup(QWidget *parent) : DialogBase(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(0, 0, 0, 0); - hlayout->setSpacing(0); - - setStyleSheet("PairingPopup { background-color: #E0E0E0; }"); - - // text - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(85, 70, 50, 70); - vlayout->setSpacing(50); - hlayout->addLayout(vlayout, 1); - { - QPushButton *close = new QPushButton(QIcon(":/icons/close.svg"), "", this); - close->setIconSize(QSize(80, 80)); - close->setStyleSheet("border: none;"); - vlayout->addWidget(close, 0, Qt::AlignLeft); - QObject::connect(close, &QPushButton::clicked, this, &QDialog::reject); - - vlayout->addSpacing(30); - - QLabel *title = new QLabel(tr("Pair your device to your %1 account").arg(useKonikServer() ? "Konik" : "comma"), this); - title->setStyleSheet("font-size: 75px; color: black;"); - title->setWordWrap(true); - vlayout->addWidget(title); - - QLabel *instructions = new QLabel(QString(R"( -
    -
  1. %1
  2. -
  3. %2
  4. -
  5. %3
  6. -
- )").arg(tr("Go to https://%1 on your phone").arg(useKonikServer() ? "stable.konik.ai" : "connect.comma.ai")) - .arg(tr("Click \"add new device\" and scan the QR code on the right")) - .arg(tr("Bookmark %1 to your home screen to use it like an app").arg(useKonikServer() ? "stable.konik.ai" : "connect.comma.ai")), this); - - instructions->setStyleSheet("font-size: 47px; font-weight: bold; color: black;"); - instructions->setWordWrap(true); - vlayout->addWidget(instructions); - - vlayout->addStretch(); - } - - // QR code - PairingQRWidget *qr = new PairingQRWidget(this); - hlayout->addWidget(qr, 1); -} - -int PairingPopup::exec() { - if (!util::system_time_valid()) { - ConfirmationDialog::alert(tr("Please connect to Wi-Fi to complete initial pairing"), parentWidget()); - return QDialog::Rejected; - } - return DialogBase::exec(); -} - - -PrimeUserWidget::PrimeUserWidget(QWidget *parent) : QFrame(parent) { - setObjectName("primeWidget"); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setContentsMargins(56, 40, 56, 40); - mainLayout->setSpacing(20); - - QLabel *subscribed = new QLabel(tr("✓ SUBSCRIBED")); - subscribed->setStyleSheet("font-size: 41px; font-weight: bold; color: #86FF4E;"); - mainLayout->addWidget(subscribed); - - QLabel *commaPrime = new QLabel(tr("comma prime")); - commaPrime->setStyleSheet("font-size: 75px; font-weight: bold;"); - mainLayout->addWidget(commaPrime); -} - - -PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(80, 90, 80, 60); - main_layout->setSpacing(0); - - QLabel *upgrade = new QLabel(tr("Upgrade Now")); - upgrade->setStyleSheet("font-size: 75px; font-weight: bold;"); - main_layout->addWidget(upgrade, 0, Qt::AlignTop); - main_layout->addSpacing(50); - - QLabel *description = new QLabel(tr("Become a comma prime member at connect.comma.ai")); - description->setStyleSheet("font-size: 56px; font-weight: light; color: white;"); - description->setWordWrap(true); - main_layout->addWidget(description, 0, Qt::AlignTop); - - main_layout->addStretch(); - - QLabel *features = new QLabel(tr("PRIME FEATURES:")); - features->setStyleSheet("font-size: 41px; font-weight: bold; color: #E5E5E5;"); - main_layout->addWidget(features, 0, Qt::AlignBottom); - main_layout->addSpacing(30); - - QVector bullets = {tr("Remote access"), tr("24/7 LTE connectivity"), tr("1 year of drive storage"), tr("Remote snapshots")}; - for (auto &b : bullets) { - const QString check = " "; - QLabel *l = new QLabel(check + b); - l->setAlignment(Qt::AlignLeft); - l->setStyleSheet("font-size: 50px; margin-bottom: 15px;"); - main_layout->addWidget(l, 0, Qt::AlignBottom); - } - - setStyleSheet(R"( - PrimeAdWidget { - border-radius: 10px; - background-color: #333333; - } - )"); -} - - -SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { - mainLayout = new QStackedWidget; - - // Unpaired, registration prompt layout - - QFrame* finishRegistration = new QFrame; - finishRegistration->setObjectName("primeWidget"); - QVBoxLayout* finishRegistrationLayout = new QVBoxLayout(finishRegistration); - finishRegistrationLayout->setSpacing(38); - finishRegistrationLayout->setContentsMargins(64, 48, 64, 48); - - QLabel* registrationTitle = new QLabel(tr("Finish Setup")); - registrationTitle->setStyleSheet("font-size: 75px; font-weight: bold;"); - finishRegistrationLayout->addWidget(registrationTitle); - - QLabel* registrationDescription = new QLabel(useKonikServer() ? tr("Pair your device with Konik connect (stable.konik.ai).") : tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - registrationDescription->setWordWrap(true); - registrationDescription->setStyleSheet("font-size: 50px; font-weight: light;"); - finishRegistrationLayout->addWidget(registrationDescription); - - finishRegistrationLayout->addStretch(); - - QPushButton* pair = new QPushButton(tr("Pair device")); - pair->setStyleSheet(R"( - QPushButton { - font-size: 55px; - font-weight: 500; - border-radius: 10px; - background-color: #465BEA; - padding: 64px; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - finishRegistrationLayout->addWidget(pair); - - popup = new PairingPopup(this); - QObject::connect(pair, &QPushButton::clicked, popup, &PairingPopup::exec); - - mainLayout->addWidget(finishRegistration); - - // build stacked layout - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(0, 0, 0, 0); - outer_layout->addWidget(mainLayout); - - QWidget *content = new QWidget; - QVBoxLayout *content_layout = new QVBoxLayout(content); - content_layout->setContentsMargins(0, 0, 0, 0); - content_layout->setSpacing(30); - - QLabel *logo = new QLabel; - QPixmap logo_pix("../assets/images/StarPilotLogo.png"); - logo->setPixmap(logo_pix.scaled(750, 770, Qt::KeepAspectRatio, Qt::SmoothTransformation)); - logo->setAlignment(Qt::AlignCenter); - content_layout->addWidget(logo, 0, Qt::AlignCenter); - content_layout->addStretch(); - - mainLayout->addWidget(content); - - mainLayout->setCurrentIndex(1); - - setStyleSheet(R"( - #primeWidget { - border-radius: 10px; - background-color: #333333; - } - )"); - - // Retain size while hidden - QSizePolicy sp_retain = sizePolicy(); - sp_retain.setRetainSizeWhenHidden(true); - setSizePolicy(sp_retain); - - QObject::connect(uiState()->prime_state, &PrimeState::changed, [this](PrimeState::Type type) { - if (type == PrimeState::PRIME_TYPE_UNPAIRED) { - mainLayout->setCurrentIndex(0); // Display "Pair your device" widget - } else { - popup->reject(); - mainLayout->setCurrentIndex(1); // Display Wi-Fi prompt widget - } - }); -} diff --git a/selfdrive/ui/qt/widgets/prime.h b/selfdrive/ui/qt/widgets/prime.h deleted file mode 100644 index 266a90a92..000000000 --- a/selfdrive/ui/qt/widgets/prime.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/input.h" - -// pairing QR code -class PairingQRWidget : public QWidget { - Q_OBJECT - -public: - explicit PairingQRWidget(QWidget* parent = 0); - void paintEvent(QPaintEvent*) override; - -private: - QPixmap img; - QTimer *timer; - void updateQrCode(const QString &text); - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - -private slots: - void refresh(); -}; - - -// pairing popup widget -class PairingPopup : public DialogBase { - Q_OBJECT - -public: - explicit PairingPopup(QWidget* parent); - int exec() override; -}; - - -// widget for paired users with prime -class PrimeUserWidget : public QFrame { - Q_OBJECT - -public: - explicit PrimeUserWidget(QWidget* parent = 0); -}; - - -// widget for paired users without prime -class PrimeAdWidget : public QFrame { - Q_OBJECT -public: - explicit PrimeAdWidget(QWidget* parent = 0); -}; - - -// container widget -class SetupWidget : public QFrame { - Q_OBJECT - -public: - explicit SetupWidget(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -private: - PairingPopup *popup; - QStackedWidget *mainLayout; -}; diff --git a/selfdrive/ui/qt/widgets/scrollview.cc b/selfdrive/ui/qt/widgets/scrollview.cc deleted file mode 100644 index 978bf83a6..000000000 --- a/selfdrive/ui/qt/widgets/scrollview.cc +++ /dev/null @@ -1,49 +0,0 @@ -#include "selfdrive/ui/qt/widgets/scrollview.h" - -#include -#include - -// TODO: disable horizontal scrolling and resize - -ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { - setWidget(w); - setWidgetResizable(true); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setStyleSheet("background-color: transparent; border:none"); - - QString style = R"( - QScrollBar:vertical { - border: none; - background: transparent; - width: 10px; - margin: 0; - } - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 5px; - background-color: white; - } - QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { - height: 0px; - } - QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; - } - )"; - verticalScrollBar()->setStyleSheet(style); - horizontalScrollBar()->setStyleSheet(style); - - QScroller *scroller = QScroller::scroller(this->viewport()); - QScrollerProperties sp = scroller->scrollerProperties(); - - sp.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::MousePressEventDelay, 0.01); - scroller->grabGesture(this->viewport(), QScroller::LeftMouseButtonGesture); - scroller->setScrollerProperties(sp); -} - -void ScrollView::hideEvent(QHideEvent *e) { - verticalScrollBar()->setValue(0); -} diff --git a/selfdrive/ui/qt/widgets/scrollview.h b/selfdrive/ui/qt/widgets/scrollview.h deleted file mode 100644 index 024331aa3..000000000 --- a/selfdrive/ui/qt/widgets/scrollview.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class ScrollView : public QScrollArea { - Q_OBJECT - -public: - explicit ScrollView(QWidget *w = nullptr, QWidget *parent = nullptr); -protected: - void hideEvent(QHideEvent *e) override; -}; diff --git a/selfdrive/ui/qt/widgets/ssh_keys.cc b/selfdrive/ui/qt/widgets/ssh_keys.cc deleted file mode 100644 index 83213d596..000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.cc +++ /dev/null @@ -1,65 +0,0 @@ -#include "selfdrive/ui/qt/widgets/ssh_keys.h" - -#include "common/params.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/widgets/input.h" - -SshControl::SshControl() : - ButtonControl(tr("SSH Keys"), "", tr("Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " - "other than your own. A comma employee will NEVER ask you to add their GitHub username.")) { - - QObject::connect(this, &ButtonControl::clicked, [=]() { - if (text() == tr("ADD")) { - QString username = InputDialog::getText(tr("Enter your GitHub username"), this); - if (username.length() > 0) { - setText(tr("LOADING")); - setEnabled(false); - getUserKeys(username); - } - } else { - params.remove("GithubUsername"); - params.remove("GithubSshKeys"); - - refresh(); - } - }); - - refresh(); -} - -void SshControl::refresh() { - QString param = QString::fromStdString(params.get("GithubSshKeys")); - if (param.length()) { - setValue(QString::fromStdString(params.get("GithubUsername"))); - setText(tr("REMOVE")); - } else { - setValue(""); - setText(tr("ADD")); - } - setEnabled(true); -} - -void SshControl::getUserKeys(const QString &username) { - HttpRequest *request = new HttpRequest(this, false); - QObject::connect(request, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success) { - if (!resp.isEmpty()) { - params.put("GithubUsername", username.toStdString()); - params.put("GithubSshKeys", resp.toStdString()); - } else { - ConfirmationDialog::alert(tr("Username '%1' has no keys on GitHub").arg(username), this); - } - } else { - if (request->timeout()) { - ConfirmationDialog::alert(tr("Request timed out"), this); - } else { - ConfirmationDialog::alert(tr("Username '%1' doesn't exist on GitHub").arg(username), this); - } - } - - refresh(); - request->deleteLater(); - }); - - request->sendRequest("https://github.com/" + username + ".keys"); -} diff --git a/selfdrive/ui/qt/widgets/ssh_keys.h b/selfdrive/ui/qt/widgets/ssh_keys.h deleted file mode 100644 index 920bd651e..000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -// SSH enable toggle -class SshToggle : public ToggleControl { - Q_OBJECT - -public: - SshToggle() : ToggleControl(tr("Enable SSH"), "", "", Hardware::get_ssh_enabled()) { - QObject::connect(this, &SshToggle::toggleFlipped, [=](bool state) { - Hardware::set_ssh_enabled(state); - }); - } -}; - -// SSH key management widget -class SshControl : public ButtonControl { - Q_OBJECT - -public: - SshControl(); - -private: - Params params; - - void refresh(); - void getUserKeys(const QString &username); -}; diff --git a/selfdrive/ui/qt/widgets/toggle.cc b/selfdrive/ui/qt/widgets/toggle.cc deleted file mode 100644 index 1236d25dd..000000000 --- a/selfdrive/ui/qt/widgets/toggle.cc +++ /dev/null @@ -1,83 +0,0 @@ -#include "selfdrive/ui/qt/widgets/toggle.h" - -#include - -Toggle::Toggle(QWidget *parent) : QAbstractButton(parent), -_height(80), -_height_rect(60), -on(false), -_anim(new QPropertyAnimation(this, "offset_circle", this)) -{ - _radius = _height / 2; - _x_circle = _radius; - _y_circle = _radius; - _y_rect = (_height - _height_rect)/2; - circleColor = QColor(0xffffff); // placeholder - green = QColor(0xffffff); // placeholder - setEnabled(true); -} - -void Toggle::paintEvent(QPaintEvent *e) { - this->setFixedHeight(_height); - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing, true); - - // Draw toggle background left - p.setBrush(green); - p.drawRoundedRect(QRect(0, _y_rect, _x_circle + _radius, _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle background right - p.setBrush(QColor(0x393939)); - p.drawRoundedRect(QRect(_x_circle - _radius, _y_rect, width() - (_x_circle - _radius), _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle circle - p.setBrush(circleColor); - p.drawEllipse(QRectF(_x_circle - _radius, _y_circle - _radius, 2 * _radius, 2 * _radius)); -} - -void Toggle::mouseReleaseEvent(QMouseEvent *e) { - if (!enabled) { - return; - } - const int left = _radius; - const int right = width() - _radius; - if ((_x_circle != left && _x_circle != right) || !this->rect().contains(e->localPos().toPoint())) { - // If mouse release isn't in rect or animation is running, don't parse touch events - return; - } - if (e->button() & Qt::LeftButton) { - togglePosition(); - emit stateChanged(on); - } -} - -void Toggle::togglePosition() { - on = !on; - const int left = _radius; - const int right = width() - _radius; - _anim->setStartValue(on ? left + immediateOffset : right - immediateOffset); - _anim->setEndValue(on ? right : left); - _anim->setDuration(animation_duration); - _anim->start(); - repaint(); -} - -void Toggle::enterEvent(QEvent *e) { - QAbstractButton::enterEvent(e); -} - -bool Toggle::getEnabled() { - return enabled; -} - -void Toggle::setEnabled(bool value) { - enabled = value; - if (value) { - circleColor.setRgb(0xfafafa); - green.setRgb(0x178644); - } else { - circleColor.setRgb(0x888888); - green.setRgb(0x227722); - } -} diff --git a/selfdrive/ui/qt/widgets/toggle.h b/selfdrive/ui/qt/widgets/toggle.h deleted file mode 100644 index e7263a008..000000000 --- a/selfdrive/ui/qt/widgets/toggle.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -#include - -class Toggle : public QAbstractButton { - Q_OBJECT - Q_PROPERTY(int offset_circle READ offset_circle WRITE set_offset_circle CONSTANT) - -public: - Toggle(QWidget* parent = nullptr); - void togglePosition(); - bool on; - int animation_duration = 150; - int immediateOffset = 0; - int offset_circle() const { - return _x_circle; - } - - void set_offset_circle(int o) { - _x_circle = o; - update(); - } - bool getEnabled(); - void setEnabled(bool value); - -protected: - void paintEvent(QPaintEvent*) override; - void mouseReleaseEvent(QMouseEvent*) override; - void enterEvent(QEvent*) override; - -private: - QColor circleColor; - QColor green; - bool enabled = true; - int _x_circle, _y_circle; - int _height, _radius; - int _height_rect, _y_rect; - QPropertyAnimation *_anim = nullptr; - -signals: - void stateChanged(bool new_state); -}; diff --git a/selfdrive/ui/qt/window.cc b/selfdrive/ui/qt/window.cc deleted file mode 100644 index ccc63d546..000000000 --- a/selfdrive/ui/qt/window.cc +++ /dev/null @@ -1,102 +0,0 @@ -#include "selfdrive/ui/qt/window.h" - -#include - -#include "system/hardware/hw.h" - -MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - homeWindow = new HomeWindow(this); - main_layout->addWidget(homeWindow); - QObject::connect(homeWindow, &HomeWindow::openSettings, this, &MainWindow::openSettings); - QObject::connect(homeWindow, &HomeWindow::closeSettings, this, &MainWindow::closeSettings); - - settingsWindow = new SettingsWindow(this); - main_layout->addWidget(settingsWindow); - QObject::connect(settingsWindow, &SettingsWindow::closeSettings, this, &MainWindow::closeSettings); - QObject::connect(settingsWindow, &SettingsWindow::reviewTrainingGuide, [=]() { - onboardingWindow->showTrainingGuide(); - main_layout->setCurrentWidget(onboardingWindow); - }); - QObject::connect(settingsWindow, &SettingsWindow::showDriverView, [=] { - homeWindow->showDriverView(true); - }); - - onboardingWindow = new OnboardingWindow(this); - main_layout->addWidget(onboardingWindow); - QObject::connect(onboardingWindow, &OnboardingWindow::onboardingDone, [=]() { - main_layout->setCurrentWidget(homeWindow); - }); - if (!onboardingWindow->completed()) { - main_layout->setCurrentWidget(onboardingWindow); - } - - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - if (!offroad) { - closeSettings(); - } - }); - QObject::connect(device(), &Device::interactiveTimeout, [=]() { - if (main_layout->currentWidget() == settingsWindow) { - closeSettings(); - } - }); - - // load fonts - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Black.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Bold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraLight.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Medium.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Regular.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-SemiBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Thin.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/JetBrainsMono-Medium.ttf"); - - // no outline to prevent the focus rectangle - setStyleSheet(R"( - * { - font-family: Inter; - outline: none; - } - )"); - setAttribute(Qt::WA_NoSystemBackground); -} - -void MainWindow::openSettings(int index, const QString ¶m) { - main_layout->setCurrentWidget(settingsWindow); - settingsWindow->setCurrentPanel(index, param); -} - -void MainWindow::closeSettings() { - main_layout->setCurrentWidget(homeWindow); - - if (uiState()->scene.started) { - homeWindow->showSidebar(params.getBool("SidebarOpen") || starpilotUIState()->starpilot_scene.starpilot_toggles.value("debug_mode").toBool()); - } -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *event) { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - bool ignore = false; - switch (event->type()) { - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::MouseButtonPress: - case QEvent::MouseMove: { - // ignore events when device is awakened by resetInteractiveTimeout - ignore = !device()->isAwake() || starpilot_scene.driver_camera_timer >= UI_FREQ / 2; - device()->resetInteractiveTimeout(starpilot_toggles.value("screen_timeout").toInt(), starpilot_toggles.value("screen_timeout_onroad").toInt()); - break; - } - default: - break; - } - return ignore; -} diff --git a/selfdrive/ui/qt/window.h b/selfdrive/ui/qt/window.h deleted file mode 100644 index 88f4b2410..000000000 --- a/selfdrive/ui/qt/window.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/home.h" -#include "selfdrive/ui/qt/offroad/onboarding.h" -#include "selfdrive/ui/qt/offroad/settings.h" - -class MainWindow : public QWidget { - Q_OBJECT - -public: - explicit MainWindow(QWidget *parent = 0); - -private: - bool eventFilter(QObject *obj, QEvent *event) override; - void openSettings(int index = 0, const QString ¶m = ""); - void closeSettings(); - - QStackedLayout *main_layout; - HomeWindow *homeWindow; - SettingsWindow *settingsWindow; - OnboardingWindow *onboardingWindow; - - Params params; -}; diff --git a/selfdrive/ui/spinner b/selfdrive/ui/spinner deleted file mode 100755 index 379d322e2..000000000 --- a/selfdrive/ui/spinner +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh - -DIR="$(cd "$(dirname "$0")" && pwd)" -ROOT_DIR="$(cd "${DIR}/../.." && pwd)" - -device_type() { - if [ -f /sys/firmware/devicetree/base/model ]; then - tr -d '\000'
/dev/null | sed 's/.*comma //' - fi -} - -if [ -f /TICI ]; then - DT="$(device_type)" - if [ "${DT}" != "tici" ] && [ "${DT}" != "tizi" ]; then - PYTHON="${ROOT_DIR}/.venv/bin/python" - if [ ! -x "${PYTHON}" ]; then - PYTHON="python3" - fi - exec "${PYTHON}" "${ROOT_DIR}/system/ui/spinner.py" "$1" - fi - - if [ ! -f "${DIR}/_spinner" ]; then - cp "${DIR}/qt/spinner_larch64" "${DIR}/_spinner" - fi -fi - -exec "${DIR}/_spinner" "$1" diff --git a/selfdrive/ui/tests/test_stopped_timer_widget.py b/selfdrive/ui/tests/test_stopped_timer_widget.py index 5bcd6271b..794703848 100644 --- a/selfdrive/ui/tests/test_stopped_timer_widget.py +++ b/selfdrive/ui/tests/test_stopped_timer_widget.py @@ -83,14 +83,14 @@ def test_stopped_timer_visibility_waits_for_onroad_grace_period(monkeypatch): assert widget.is_visible -def test_stopped_timer_uses_qt_text_contract(monkeypatch): +def test_stopped_timer_uses_text_contract(monkeypatch): stopped_timer = _load_stopped_timer(monkeypatch) assert stopped_timer.StoppedTimerWidget._format_duration_text(61) == ("1 minute", "1 second") assert stopped_timer.StoppedTimerWidget._format_duration_text(121) == ("2 minutes", "1 second") -def test_stopped_timer_draws_qt_positions_and_opaque_seconds(monkeypatch): +def test_stopped_timer_draws_positions_and_opaque_seconds(monkeypatch): stopped_timer = _load_stopped_timer(monkeypatch) widget = stopped_timer.StoppedTimerWidget() widget._duration = 61 diff --git a/selfdrive/ui/text b/selfdrive/ui/text deleted file mode 100755 index ecfdad4ab..000000000 --- a/selfdrive/ui/text +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh - -DIR="$(cd "$(dirname "$0")" && pwd)" -ROOT_DIR="$(cd "${DIR}/../.." && pwd)" - -device_type() { - if [ -f /sys/firmware/devicetree/base/model ]; then - tr -d '\000' /dev/null | sed 's/.*comma //' - fi -} - -if [ -f /TICI ]; then - DT="$(device_type)" - if [ "${DT}" != "tici" ] && [ "${DT}" != "tizi" ]; then - PYTHON="${ROOT_DIR}/.venv/bin/python" - if [ ! -x "${PYTHON}" ]; then - PYTHON="python3" - fi - exec "${PYTHON}" "${ROOT_DIR}/system/ui/text.py" "$1" - fi - - if [ ! -f "${DIR}/_text" ]; then - cp "${DIR}/qt/text_larch64" "${DIR}/_text" - fi -fi - -exec "${DIR}/_text" "$1" diff --git a/selfdrive/ui/ui b/selfdrive/ui/ui deleted file mode 100755 index 4ef73fbd8..000000000 Binary files a/selfdrive/ui/ui and /dev/null differ diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc deleted file mode 100644 index ec0896d3d..000000000 --- a/selfdrive/ui/ui.cc +++ /dev/null @@ -1,522 +0,0 @@ -#include "selfdrive/ui/ui.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "common/transformations/orientation.hpp" -#include "common/swaglog.h" -#include "common/util.h" -#include "common/watchdog.h" -#include "system/hardware/hw.h" - -#define BACKLIGHT_DT 0.05 -#define BACKLIGHT_TS 10.00 - -namespace { - -enum class UIStallPhase { - INIT = 0, - UPDATE_START, - AFTER_SOCKETS, - AFTER_STATE, - AFTER_STATUS, - AFTER_WATCHDOG, - AFTER_EMIT, - AFTER_FS_UPDATE, - IDLE, -}; - -std::atomic ui_stall_last_progress_ns{0}; -std::atomic ui_stall_phase{static_cast(UIStallPhase::INIT)}; -std::atomic ui_stall_frame{0}; -std::atomic ui_stall_reported{false}; -std::atomic ui_stall_reported_ns{0}; -std::atomic ui_stall_reported_phase{static_cast(UIStallPhase::INIT)}; -std::atomic ui_main_tid{0}; - -double read_env_double(const char *name, double default_value) { - const char *value = std::getenv(name); - if (value == nullptr || *value == '\0') { - return default_value; - } - - char *end = nullptr; - double parsed = std::strtod(value, &end); - if (end == value || (end != nullptr && *end != '\0') || parsed <= 0.0) { - return default_value; - } - return parsed; -} - -const char *ui_stall_phase_name(UIStallPhase phase) { - switch (phase) { - case UIStallPhase::INIT: return "init"; - case UIStallPhase::UPDATE_START: return "update_start"; - case UIStallPhase::AFTER_SOCKETS: return "after_sockets"; - case UIStallPhase::AFTER_STATE: return "after_state"; - case UIStallPhase::AFTER_STATUS: return "after_status"; - case UIStallPhase::AFTER_WATCHDOG: return "after_watchdog"; - case UIStallPhase::AFTER_EMIT: return "after_emit"; - case UIStallPhase::AFTER_FS_UPDATE: return "after_fs_update"; - case UIStallPhase::IDLE: return "idle"; - } - return "unknown"; -} - -std::string ui_stall_dump_dir() { - return access("/data/log", W_OK) == 0 ? "/data/log" : "/tmp"; -} - -void write_stall_dump_section(int fd, const std::string &title, const std::string &body) { - std::string output = "== " + title + " ==\n"; - output += body.empty() ? "\n" : body; - if (!output.empty() && output.back() != '\n') { - output += '\n'; - } - HANDLE_EINTR(write(fd, output.data(), output.size())); -} - -void write_ui_thread_snapshot(int fd) { - const pid_t tid = ui_main_tid.load(std::memory_order_relaxed); - if (tid <= 0) { - write_stall_dump_section(fd, "main_thread", ""); - return; - } - - write_stall_dump_section(fd, "main_thread", util::string_format("pid=%d tid=%d", getpid(), tid)); - - const std::string task_dir = "/proc/self/task/" + std::to_string(tid); - write_stall_dump_section(fd, "main_thread status", util::read_file(task_dir + "/status")); - write_stall_dump_section(fd, "main_thread wchan", util::read_file(task_dir + "/wchan")); - write_stall_dump_section(fd, "main_thread syscall", util::read_file(task_dir + "/syscall")); - write_stall_dump_section(fd, "main_thread kernel_stack", util::read_file(task_dir + "/stack")); -} - -double ui_elapsed_s(uint64_t now, uint64_t then) { - if (then == 0 || now < then) { - return 0.0; - } - return static_cast(now - then) / 1e9; -} - -bool ui_timestamp_anomaly(uint64_t now, uint64_t then, const char *context, UIStallPhase phase, uint64_t frame) { - if (then == 0 || now >= then) { - return false; - } - - LOGW("UI stall monitor timestamp anomaly (%s now_ns=%llu then_ns=%llu phase=%s frame=%llu)", - context, - static_cast(now), - static_cast(then), - ui_stall_phase_name(phase), - static_cast(frame)); - return true; -} - -void ui_stall_progress(UIStallPhase phase, uint64_t frame = 0) { - const uint64_t now = nanos_since_boot(); - ui_stall_phase.store(static_cast(phase), std::memory_order_relaxed); - ui_stall_frame.store(frame, std::memory_order_relaxed); - ui_stall_last_progress_ns.store(now, std::memory_order_relaxed); - - if (ui_stall_reported.exchange(false, std::memory_order_relaxed)) { - const uint64_t stall_started = ui_stall_reported_ns.load(std::memory_order_relaxed); - const UIStallPhase stalled_phase = static_cast(ui_stall_reported_phase.load(std::memory_order_relaxed)); - const double stalled_for_s = ui_elapsed_s(now, stall_started); - if (ui_timestamp_anomaly(now, stall_started, "recover", stalled_phase, frame)) { - ui_stall_reported_ns.store(0, std::memory_order_relaxed); - } - LOGW("UI stall recovered after %.1fs (stalled_phase=%s current_phase=%s frame=%llu)", - stalled_for_s, - ui_stall_phase_name(stalled_phase), - ui_stall_phase_name(phase), - static_cast(frame)); - } -} - -void start_ui_stall_monitor() { - static std::once_flag once; - std::call_once(once, [] { - ui_main_tid.store(static_cast(syscall(SYS_gettid)), std::memory_order_relaxed); - ui_stall_progress(UIStallPhase::INIT, 0); - - const double stall_probe_dt = read_env_double("UI_STALL_PROBE_MAX_DT", 5.0); - if (stall_probe_dt <= 0.0) { - return; - } - - std::thread([stall_probe_dt]() { - using namespace std::chrono_literals; - constexpr auto poll_interval = 250ms; - - while (true) { - std::this_thread::sleep_for(poll_interval); - - const uint64_t now = nanos_since_boot(); - const uint64_t last_progress = ui_stall_last_progress_ns.load(std::memory_order_relaxed); - if (last_progress == 0) { - continue; - } - - const UIStallPhase phase = static_cast(ui_stall_phase.load(std::memory_order_relaxed)); - const uint64_t frame = ui_stall_frame.load(std::memory_order_relaxed); - if (ui_timestamp_anomaly(now, last_progress, "probe", phase, frame)) { - ui_stall_last_progress_ns.store(now, std::memory_order_relaxed); - ui_stall_reported.store(false, std::memory_order_relaxed); - continue; - } - - const double stalled_for_s = ui_elapsed_s(now, last_progress); - if (stalled_for_s < stall_probe_dt) { - continue; - } - - bool expected = false; - if (!ui_stall_reported.compare_exchange_strong(expected, true, std::memory_order_relaxed)) { - continue; - } - - ui_stall_reported_ns.store(now, std::memory_order_relaxed); - ui_stall_reported_phase.store(static_cast(phase), std::memory_order_relaxed); - - const std::string path = ui_stall_dump_dir() + "/qt_ui_stall_" + std::to_string(getpid()) + "_" + std::to_string(now) + ".log"; - int fd = open(path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0644); - if (fd >= 0) { - char header[384]; - const int header_len = std::snprintf(header, sizeof(header), - "phase=%s frame=%llu stalled_for_s=%.3f now_ns=%llu last_progress_ns=%llu\n", - ui_stall_phase_name(phase), - static_cast(frame), - stalled_for_s, - static_cast(now), - static_cast(last_progress)); - if (header_len > 0) { - write(fd, header, header_len); - } - - write_ui_thread_snapshot(fd); - close(fd); - LOGE("UI main thread stalled for %.1fs (phase=%s frame=%llu now_ns=%llu last_progress_ns=%llu dump=%s)", - stalled_for_s, - ui_stall_phase_name(phase), - static_cast(frame), - static_cast(now), - static_cast(last_progress), - path.c_str()); - } else { - LOGE("UI main thread stalled for %.1fs (phase=%s frame=%llu now_ns=%llu last_progress_ns=%llu dump_open_failed errno=%d)", - stalled_for_s, - ui_stall_phase_name(phase), - static_cast(frame), - static_cast(now), - static_cast(last_progress), - errno); - } - } - }).detach(); - }); -} - -} // namespace - -static void update_sockets(UIState *s) { - s->sm->update(0); -} - -static void update_state(UIState *s, StarPilotUIState *fs) { - SubMaster &sm = *(s->sm); - UIScene &scene = s->scene; - - if (sm.updated("liveCalibration")) { - auto list2rot = [](const capnp::List::Reader &rpy_list) ->Eigen::Matrix3f { - return euler2rot({rpy_list[0], rpy_list[1], rpy_list[2]}).cast(); - }; - - auto live_calib = sm["liveCalibration"].getLiveCalibration(); - if (live_calib.getCalStatus() == cereal::LiveCalibrationData::Status::CALIBRATED) { - auto device_from_calib = list2rot(live_calib.getRpyCalib()); - auto wide_from_device = list2rot(live_calib.getWideFromDeviceEuler()); - s->scene.view_from_calib = VIEW_FROM_DEVICE * device_from_calib; - s->scene.view_from_wide_calib = VIEW_FROM_DEVICE * wide_from_device * device_from_calib; - } else { - s->scene.view_from_calib = s->scene.view_from_wide_calib = VIEW_FROM_DEVICE; - } - } - if (sm.updated("pandaStates")) { - auto pandaStates = sm["pandaStates"].getPandaStates(); - if (pandaStates.size() > 0) { - scene.pandaType = pandaStates[0].getPandaType(); - - if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) { - scene.ignition = false; - for (const auto& pandaState : pandaStates) { - scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan(); - } - } - } - } else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) { - scene.pandaType = cereal::PandaState::PandaType::UNKNOWN; - } - if (sm.updated("wideRoadCameraState")) { - auto cam_state = sm["wideRoadCameraState"].getWideRoadCameraState(); - float scale = (cam_state.getSensor() == cereal::FrameData::ImageSensor::AR0231) ? 6.0f : 1.0f; - scene.light_sensor = std::max(100.0f - scale * cam_state.getExposureValPercent(), 0.0f); - } else if (!sm.allAliveAndValid({"wideRoadCameraState"})) { - scene.light_sensor = -1; - } - scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; - - auto params = Params(); - scene.recording_audio = params.getBool("RecordAudio") && scene.started; - - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - - if (sm.updated("carState")) { - const cereal::CarState::Reader &carState = sm["carState"].getCarState(); - starpilot_scene.parked = carState.getGearShifter() == cereal::CarState::GearShifter::PARK; - starpilot_scene.reverse = carState.getGearShifter() == cereal::CarState::GearShifter::REVERSE; - starpilot_scene.standstill = carState.getStandstill() && !starpilot_scene.reverse; - } - - if (scene.started) { - starpilot_scene.started_timer += 1; - } - scene.started |= starpilot_scene.starpilot_toggles.value("force_onroad").toBool(); - scene.started &= !starpilot_scene.starpilot_toggles.value("force_offroad").toBool(); -} - -void ui_update_params(UIState *s) { - auto params = Params(); - s->scene.is_metric = params.getBool("IsMetric"); -} - -void UIState::updateStatus(StarPilotUIState *fs) { - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - if (scene.started && sm->updated("selfdriveState")) { - auto ss = (*sm)["selfdriveState"].getSelfdriveState(); - auto state = ss.getState(); - - const UIStatus previous_status = status; - - if (state == cereal::SelfdriveState::OpenpilotState::PRE_ENABLED || state == cereal::SelfdriveState::OpenpilotState::OVERRIDING) { - status = STATUS_OVERRIDE; - } else if (starpilot_scene.switchback_mode_enabled && (ss.getEnabled() || starpilot_scene.always_on_lateral_active)) { - status = STATUS_SWITCHBACK_MODE_ENABLED; - } else if (starpilot_scene.always_on_lateral_active) { - status = STATUS_ALWAYS_ON_LATERAL_ACTIVE; - } else if (starpilot_scene.traffic_mode_enabled && ss.getEnabled()) { - status = STATUS_TRAFFIC_MODE_ENABLED; - } else { - status = ss.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; - } - - const bool selfdrive_visible_alert = ss.getAlertSize() != cereal::SelfdriveState::AlertSize::NONE; - bool starpilot_visible_alert = false; - if (fs->sm->rcv_frame("starpilotSelfdriveState") > 0) { - const auto fpss = (*fs->sm)["starpilotSelfdriveState"].getStarpilotSelfdriveState(); - starpilot_visible_alert = fpss.getAlertSize() != cereal::StarPilotSelfdriveState::AlertSize::NONE; - } - - // Standby mode should wake for any visible onroad alert, not just elevated - // alert statuses. Calibration uses NORMAL status but still needs to wake. - starpilot_scene.wake_up_screen = - selfdrive_visible_alert || - starpilot_visible_alert || - ss.getAlertStatus() != cereal::SelfdriveState::AlertStatus::NORMAL || - (status != previous_status && status != STATUS_OVERRIDE); - } - - if (engaged() != engaged_prev) { - engaged_prev = engaged(); - emit engagedChanged(engaged()); - } - - // Handle onroad/offroad transition - if (scene.started != started_prev || sm->frame == 1) { - if (scene.started) { - status = STATUS_DISENGAGED; - scene.started_frame = sm->frame; - } - started_prev = scene.started; - emit offroadTransition(!scene.started); - - if (starpilot_toggles.value("tethering_config").toInt() == 2) { - fs->wifi->setTetheringEnabled(scene.started); - } - } -} - -UIState::UIState(QObject *parent) : QObject(parent) { - start_ui_stall_monitor(); - sm = std::make_unique(std::vector{ - "modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", - "pandaStates", "carParams", "driverMonitoringState", "carState", "driverStateV2", - "wideRoadCameraState", "managerState", "selfdriveState", "longitudinalPlan", - }); - prime_state = new PrimeState(this); - language = QString::fromStdString(Params().get("LanguageSetting")); - - // update timer - timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, this, &UIState::update); - timer->start(1000 / UI_FREQ); - ui_stall_progress(UIStallPhase::IDLE, sm->frame); -} - -void UIState::update() { - ui_stall_progress(UIStallPhase::UPDATE_START, sm->frame); - update_sockets(this); - ui_stall_progress(UIStallPhase::AFTER_SOCKETS, sm->frame); - update_state(this, starpilotUIState()); - ui_stall_progress(UIStallPhase::AFTER_STATE, sm->frame); - updateStatus(starpilotUIState()); - ui_stall_progress(UIStallPhase::AFTER_STATUS, sm->frame); - - if (sm->frame % UI_FREQ == 0) { - if (!watchdog_kick(nanos_since_boot())) { - LOGE("UI watchdog kick failed at frame %llu", static_cast(sm->frame)); - } - // Re-pin to the little cores: power-save can offline our core and the - // kernel may rebalance us onto core 4 (the realtime control loop). - if (!Hardware::PC()) { - util::set_core_affinity({0, 1, 2, 3}); - } - } - ui_stall_progress(UIStallPhase::AFTER_WATCHDOG, sm->frame); - emit uiUpdate(*this, *starpilotUIState()); - ui_stall_progress(UIStallPhase::AFTER_EMIT, sm->frame); - - StarPilotUIState *fs = starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - if (starpilot_scene.downloading_update || starpilot_scene.starpilot_panel_active) { - device()->resetInteractiveTimeout(starpilot_toggles.value("screen_timeout").toInt(), starpilot_toggles.value("screen_timeout_onroad").toInt()); - } - - fs->update(); - ui_stall_progress(UIStallPhase::AFTER_FS_UPDATE, sm->frame); - ui_stall_progress(UIStallPhase::IDLE, sm->frame); -} - -Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) { - setAwake(true); - resetInteractiveTimeout(); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &Device::update); -} - -void Device::update(const UIState &s, const StarPilotUIState &fs) { - updateBrightness(s, fs); - updateWakefulness(s, fs); -} - -void Device::setAwake(bool on) { - if (on != awake) { - awake = on; - Hardware::set_display_power(awake); - LOGD("setting display power %d", awake); - emit displayPowerChanged(awake); - } -} - -void Device::resetInteractiveTimeout(int timeout, int timeout_onroad) { - if (timeout == -1) { - timeout = (ignition_on ? 10 : 30); - } else { - timeout = (ignition_on ? timeout_onroad : timeout); - } - interactive_timeout = timeout * UI_FREQ; -} - -void Device::updateBrightness(const UIState &s, const StarPilotUIState &fs) { - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const int screen_brightness_onroad = starpilot_toggles.value("screen_brightness_onroad").toInt(); - const int clamped_onroad_brightness = std::clamp(screen_brightness_onroad, 0, 100); - - float clipped_brightness = offroad_brightness; - if (s.scene.started && s.scene.light_sensor >= 0) { - clipped_brightness = s.scene.light_sensor; - - // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm - if (clipped_brightness <= 8) { - clipped_brightness = (clipped_brightness / 903.3); - } else { - clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0); - } - - // Scale back to 10% to 100% - clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f); - } - - int brightness = brightness_filter.update(clipped_brightness); - if (!awake) { - brightness = 0; - } else if (s.scene.started && !starpilot_scene.wake_up_screen && interactive_timeout == 0 && starpilot_toggles.value("standby_mode").toBool()) { - brightness = 0; - } else if (s.scene.started && screen_brightness_onroad != 101) { - brightness = interactive_timeout > 0 ? std::max(5, clamped_onroad_brightness) : clamped_onroad_brightness; - } else if (starpilot_toggles.value("screen_brightness").toInt() != 101) { - brightness = starpilot_toggles.value("screen_brightness").toInt(); - } - - if (brightness != last_brightness) { - if (!brightness_future.isRunning()) { - brightness_future = QtConcurrent::run(Hardware::set_brightness, brightness); - last_brightness = brightness; - } - } -} - -void Device::updateWakefulness(const UIState &s, const StarPilotUIState &fs) { - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool standby_mode = starpilot_toggles.value("standby_mode").toBool(); - const int screen_brightness_onroad = starpilot_toggles.value("screen_brightness_onroad").toInt(); - const int screen_timeout = starpilot_toggles.value("screen_timeout").toInt(); - const int screen_timeout_onroad = starpilot_toggles.value("screen_timeout_onroad").toInt(); - - bool ignition_state_changed = s.scene.ignition != ignition_on; - ignition_on = s.scene.ignition; - - // Standby mode should extend the current wake window for alerts and status - // changes, but it must not clear the timer every frame or manual wakes will - // collapse immediately. - if (ignition_on && standby_mode && screen_brightness_onroad != 0 && starpilot_scene.wake_up_screen) { - resetInteractiveTimeout(screen_timeout, screen_timeout_onroad); - } - - if (ignition_state_changed) { - resetInteractiveTimeout(screen_timeout, screen_timeout_onroad); - } else if (interactive_timeout > 0 && --interactive_timeout == 0) { - emit interactiveTimeout(); - } - - setAwake(s.scene.ignition || interactive_timeout > 0); -} - -UIState *uiState() { - static UIState ui_state; - return &ui_state; -} - -Device *device() { - static Device _device; - return &_device; -} diff --git a/selfdrive/ui/ui.h b/selfdrive/ui/ui.h deleted file mode 100644 index cf02c466e..000000000 --- a/selfdrive/ui/ui.h +++ /dev/null @@ -1,146 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/mat.h" -#include "common/params.h" -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/prime_state.h" - -#include "starpilot/ui/starpilot_ui.h" - -const int UI_BORDER_SIZE = 30; -const int UI_HEADER_HEIGHT = 420; - -const int UI_FREQ = 20; // Hz -const int BACKLIGHT_OFFROAD = 50; - -const Eigen::Matrix3f VIEW_FROM_DEVICE = (Eigen::Matrix3f() << - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0, - 1.0, 0.0, 0.0).finished(); - -const Eigen::Matrix3f FCAM_INTRINSIC_MATRIX = (Eigen::Matrix3f() << - 2648.0, 0.0, 1928.0 / 2, - 0.0, 2648.0, 1208.0 / 2, - 0.0, 0.0, 1.0).finished(); - -// tici ecam focal probably wrong? magnification is not consistent across frame -// Need to retrain model before this can be changed -const Eigen::Matrix3f ECAM_INTRINSIC_MATRIX = (Eigen::Matrix3f() << - 567.0, 0.0, 1928.0 / 2, - 0.0, 567.0, 1208.0 / 2, - 0.0, 0.0, 1.0).finished(); - -typedef enum UIStatus { - STATUS_DISENGAGED, - STATUS_OVERRIDE, - STATUS_ENGAGED, - - STATUS_ALWAYS_ON_LATERAL_ACTIVE, - STATUS_CEM_DISABLED, - STATUS_EXPERIMENTAL_MODE_ENABLED, - STATUS_SWITCHBACK_MODE_ENABLED, - STATUS_TRAFFIC_MODE_ENABLED, -} UIStatus; - -const QColor bg_colors [] = { - [STATUS_DISENGAGED] = QColor(0x17, 0x33, 0x49, 0xc8), - [STATUS_OVERRIDE] = QColor(0x91, 0x9b, 0x95, 0xf1), - [STATUS_ENGAGED] = QColor(0x17, 0x86, 0x44, 0xf1), - - [STATUS_ALWAYS_ON_LATERAL_ACTIVE] = QColor(0x0a, 0xba, 0xb5, 0xf1), - [STATUS_CEM_DISABLED] = QColor(0xff, 0xff, 0x00, 0xf1), - [STATUS_EXPERIMENTAL_MODE_ENABLED] = QColor(0xda, 0x6f, 0x25, 0xf1), - [STATUS_SWITCHBACK_MODE_ENABLED] = QColor(0x8b, 0x6c, 0xc5, 0xf1), - [STATUS_TRAFFIC_MODE_ENABLED] = QColor(0xc9, 0x22, 0x31, 0xf1), -}; - -typedef struct UIScene { - Eigen::Matrix3f view_from_calib = VIEW_FROM_DEVICE; - Eigen::Matrix3f view_from_wide_calib = VIEW_FROM_DEVICE; - cereal::PandaState::PandaType pandaType; - - cereal::LongitudinalPersonality personality; - - float light_sensor = -1; - bool started, ignition, is_metric, recording_audio; - uint64_t started_frame; -} UIScene; - -class UIState : public QObject { - Q_OBJECT - -public: - UIState(QObject* parent = 0); - void updateStatus(StarPilotUIState *fs); - inline bool engaged() const { - return scene.started && (*sm)["selfdriveState"].getSelfdriveState().getEnabled(); - } - - std::unique_ptr sm; - UIStatus status; - UIScene scene = {}; - QString language; - PrimeState *prime_state; - -signals: - void uiUpdate(const UIState &s, const StarPilotUIState &fs); - void offroadTransition(bool offroad); - void engagedChanged(bool engaged); - -private slots: - void update(); - -private: - QTimer *timer; - bool started_prev = false; - bool engaged_prev = false; -}; - -UIState *uiState(); - -// device management class -class Device : public QObject { - Q_OBJECT - -public: - Device(QObject *parent = 0); - bool isAwake() { return awake; } - void setOffroadBrightness(int brightness) { - offroad_brightness = std::clamp(brightness, 0, 100); - } - -private: - bool awake = false; - int interactive_timeout = 0; - bool ignition_on = false; - - int offroad_brightness = BACKLIGHT_OFFROAD; - int last_brightness = 0; - FirstOrderFilter brightness_filter; - QFuture brightness_future; - - void updateBrightness(const UIState &s, const StarPilotUIState &fs); - void updateWakefulness(const UIState &s, const StarPilotUIState &fs); - void setAwake(bool on); - -signals: - void displayPowerChanged(bool on); - void interactiveTimeout(); - -public slots: - void resetInteractiveTimeout(int timeout = -1, int timeout_onroad = -1); - void update(const UIState &s, const StarPilotUIState &fs); -}; - -Device *device(); -void ui_update_params(UIState *s); diff --git a/selfdrive/ui/widgets/drive_stats.py b/selfdrive/ui/widgets/drive_stats.py index 12e51c5ec..6b2fcbe85 100644 --- a/selfdrive/ui/widgets/drive_stats.py +++ b/selfdrive/ui/widgets/drive_stats.py @@ -526,7 +526,7 @@ class DriveStatsDashboard: self.refresh() def refresh(self) -> None: - demo_enabled = os.getenv("SP_RAYBIG_FAKE_DRIVE_STATS", "0").lower() in ("1", "true", "yes", "on") + demo_enabled = os.getenv("SP_C3_FAKE_DRIVE_STATS", "0").lower() in ("1", "true", "yes", "on") self._data = demo_drive_stats_data(self._params.get_bool("IsMetric")) if demo_enabled else load_drive_stats_data(self._params) @staticmethod diff --git a/selfdrive/ui/widgets/offroad_alerts.py b/selfdrive/ui/widgets/offroad_alerts.py index 802243ff3..8d218e24d 100644 --- a/selfdrive/ui/widgets/offroad_alerts.py +++ b/selfdrive/ui/widgets/offroad_alerts.py @@ -33,7 +33,7 @@ class AlertConstants: MARGIN = 50 SPACING = 30 FONT_SIZE = 48 - BORDER_RADIUS = 30 * 2 # matches Qt's 30px + BORDER_RADIUS = 30 * 2 ALERT_HEIGHT = 120 ALERT_SPACING = 10 ALERT_INSET = 60 diff --git a/starpilot/common/maps_selection.py b/starpilot/common/maps_selection.py index 73dd13382..9ad6d34b6 100644 --- a/starpilot/common/maps_selection.py +++ b/starpilot/common/maps_selection.py @@ -5,7 +5,7 @@ COUNTRY_PREFIX = "nation." STATE_PREFIX = "us_state." # Legacy C3 map selection stored bare region codes instead of the prefixed -# keys consumed by mapd and the Qt settings path. +# Keys consumed by mapd and the settings UIs. US_STATE_CODES = frozenset({ "AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", diff --git a/starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json b/starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json index 9d47c5bcb..561ee7fc0 100644 --- a/starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json +++ b/starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json @@ -4134,14 +4134,6 @@ "parent_key": "GalaxyDeveloperMode", "settings_tier": "advanced" }, - { - "key": "UseOldUI", - "label": "Use Old UI", - "description": "Use the old Qt UI instead of the default raylib UI on tici/tizi devices. This setting has no effect on C4/mici devices.", - "data_type": "bool", - "ui_type": "toggle", - "settings_tier": "simple" - }, { "key": "CameraOffset", "label": "Camera Offset", diff --git a/starpilot/system/the_galaxy/assets/components/tools/galaxy.css b/starpilot/system/the_galaxy/assets/components/tools/galaxy.css index 2363d7d2c..a468f5ba5 100644 --- a/starpilot/system/the_galaxy/assets/components/tools/galaxy.css +++ b/starpilot/system/the_galaxy/assets/components/tools/galaxy.css @@ -129,6 +129,80 @@ background-color: rgba(224, 85, 119, 0.35); } +/* ――― Sentry event viewer ――― */ +.sentry-event-widget { + background-color: var(--secondary-bg); + border-radius: var(--border-radius-lg); + box-shadow: var(--shadow-sm); + display: flex; + flex-direction: column; + gap: var(--gap-sm); + margin-top: var(--margin-lg); + max-width: var(--width-xxxl); + padding: var(--padding-lg); +} + +.sentry-event-heading { + align-items: flex-start; + display: flex; + gap: var(--gap-base); + justify-content: space-between; +} + +.sentry-event-heading h3 { + padding-top: 0; +} + +.sentry-event-state, +.sentry-event-kind { + background-color: var(--input-bg); + border-radius: 999px; + color: var(--main-fg); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-bold); + padding: 0.25rem 0.55rem; + white-space: nowrap; +} + +.sentry-event-meta { + align-items: center; + color: var(--text-muted); + display: flex; + flex-wrap: wrap; + font-size: var(--font-size-xs); + gap: var(--gap-sm); +} + +.sentry-event-message { + color: var(--text-color); + margin: 0; +} + +.sentry-image-grid { + display: grid; + gap: var(--gap-sm); + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); +} + +.sentry-image-grid a { + display: block; +} + +.sentry-image-grid img { + border: var(--border-style-main); + border-radius: var(--border-radius-base); + display: block; + height: auto; + max-width: 100%; + width: 100%; +} + +.sentry-empty { + color: var(--text-muted); + font-style: italic; + margin: 0; +} + /* ――― Mobile ――― */ @media only screen and (max-width: 768px) and (orientation: portrait) { .galaxy-wrapper { diff --git a/starpilot/system/the_galaxy/assets/components/tools/galaxy.js b/starpilot/system/the_galaxy/assets/components/tools/galaxy.js index 674d49fcf..dc2b4ecfa 100644 --- a/starpilot/system/the_galaxy/assets/components/tools/galaxy.js +++ b/starpilot/system/the_galaxy/assets/components/tools/galaxy.js @@ -11,8 +11,14 @@ const state = reactive({ submitting: false, showUnpairModal: false, fetched: false, + sentryLoading: true, + sentryStatus: {}, + sentryEvent: {}, + sentryTestBusy: false, }) +let sentryPollTimer = null + async function fetchStatus() { state.loading = true try { @@ -26,6 +32,91 @@ async function fetchStatus() { state.loading = false } +async function fetchSentryStatus() { + try { + const res = await fetch("/api/sentry/status", { cache: "no-store" }) + if (!res.ok) return + const data = await res.json() + state.sentryStatus = data.status || {} + state.sentryEvent = data.lastEvent || {} + } catch (e) { + console.error("Failed to fetch Sentry status:", e) + } finally { + state.sentryLoading = false + } +} + +function ensureSentryPolling() { + if (sentryPollTimer !== null) return + fetchSentryStatus() + sentryPollTimer = window.setInterval(fetchSentryStatus, 5000) +} + +async function sendSentryTest() { + if (state.sentryTestBusy) return + state.sentryTestBusy = true + try { + const res = await fetch("/api/sentry/test", { method: "POST" }) + const data = await res.json() + if (!res.ok) { + showSnackbar(data.error || "Sentry test failed.") + return + } + showSnackbar("Sentry test started. Galaxy will show the captured images when ready.") + } catch (e) { + showSnackbar("Network error — is the device reachable?") + } finally { + state.sentryTestBusy = false + } +} + +function SentryEventPanel(showTestButton = true) { + return html` +
+
+
+

Sentry Mode

+

View the latest movement event and captured images directly in Galaxy.

+
+ ${() => state.sentryStatus.state || "unknown"} +
+ + ${() => { + if (state.sentryLoading) return html`
Checking Sentry status…
` + const event = state.sentryEvent || {} + if (!event.eventId) return html`

No Sentry events recorded yet.

` + + return html` +
+ ${String(event.kind || "event").toUpperCase()} + ${event.detectedAt || ""} +
+

${event.message || "Movement detected while parked."}

+ ${Array.isArray(event.imageUrls) && event.imageUrls.length > 0 ? html` +
+ ${event.imageUrls.map((url, index) => html` + + Sentry capture ${index + 1} + + `)} +
+ ` : html`

No camera images were available for this event.

`} + ` + }} + + ${showTestButton ? html` + + ` : ""} +
+ ` +} + async function pair() { if (state.submitting) return const pw = state.password.trim() @@ -79,12 +170,17 @@ async function unpair() { } export function GalaxyPairing() { + ensureSentryPolling() + if (isGalaxyTunnel()) { return html` -
-
🛰️
-

Galaxy Pairing Unavailable via Galaxy

-

Galaxy pairing requires a direct connection.
Connect to your device's local network to use this feature.

+
+
+
🛰️
+

Galaxy Pairing Unavailable via Galaxy

+

Galaxy pairing requires a direct connection.
Connect to your device's local network to use this feature.

+
+ ${SentryEventPanel(false)}
`; } @@ -171,6 +267,7 @@ export function GalaxyPairing() { ` }} + ${SentryEventPanel()}
` } diff --git a/starpilot/system/the_galaxy/tests/test_device_settings_layout.py b/starpilot/system/the_galaxy/tests/test_device_settings_layout.py index 3ea99252e..9ec8c06f0 100644 --- a/starpilot/system/the_galaxy/tests/test_device_settings_layout.py +++ b/starpilot/system/the_galaxy/tests/test_device_settings_layout.py @@ -1,5 +1,4 @@ import json -import importlib.util import re from pathlib import Path @@ -7,7 +6,6 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[4] LAYOUT_PATH = REPO_ROOT / "starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json" PARAM_KEYS_PATH = REPO_ROOT / "common/params_keys.h" -GENERATOR_PATH = REPO_ROOT / "tools/StarPilot/generate_galaxy_layout.py" def _layout(): @@ -31,14 +29,6 @@ def _declared_default(key): return match.group(1) -def _generator_module(): - spec = importlib.util.spec_from_file_location("generate_galaxy_layout", GENERATOR_PATH) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - def test_galaxy_layout_removes_obsolete_and_duplicate_controls(): layout = _layout() sections = _params_by_section(layout) @@ -68,7 +58,7 @@ def test_galaxy_layout_contains_basic_mode_controls(): } <= sections["Longitudinal (Speed & Following)"].keys() assert "RedneckCruise" not in sections["Longitudinal (Speed & Following)"].keys() assert sections["Developer"]["RedneckCruise"]["parent_key"] == "GalaxyDeveloperMode" - assert {"AlphaLongitudinalEnabled", "ForceOffroad", "GalaxyDeveloperMode", "UseOldUI"} <= sections["Developer"].keys() + assert {"AlphaLongitudinalEnabled", "ForceOffroad", "GalaxyDeveloperMode"} <= sections["Developer"].keys() def test_device_shutdown_uses_literal_hours(): @@ -100,11 +90,6 @@ def test_every_galaxy_setting_has_a_shared_settings_tier(): assert None not in tiers -def test_galaxy_layout_generator_is_semantically_idempotent(): - layout = _layout() - assert _generator_module().generate_layout(layout) == layout - - def test_requested_simple_and_advanced_settings_tiers(): sections = _params_by_section(_layout()) lateral = sections["Lateral (Steering)"] @@ -161,7 +146,6 @@ def test_requested_simple_and_advanced_settings_tiers(): assert developer["ForceOffroad"]["parent_key"] == "GalaxyDeveloperMode" assert developer["ForceOffroad"]["requires_parked"] is True assert developer["ForceOffroad"]["settings_tier"] == "advanced" - assert developer["UseOldUI"]["settings_tier"] == "simple" assert developer["DeveloperUI"]["settings_tier"] == "advanced" assert developer["RedneckCruise"]["settings_tier"] == "advanced" assert sections["Visual (Display & UI)"]["DisableWideRoad"]["settings_tier"] == "advanced" diff --git a/starpilot/system/the_galaxy/tests/test_navigation_params.py b/starpilot/system/the_galaxy/tests/test_navigation_params.py index ef5148741..1919a603f 100644 --- a/starpilot/system/the_galaxy/tests/test_navigation_params.py +++ b/starpilot/system/the_galaxy/tests/test_navigation_params.py @@ -86,12 +86,10 @@ def _params_client(monkeypatch, values, device_type): the_galaxy, "_get_param_type_info", lambda: ( - {"AlphaLongitudinalEnabled", "ForceOffroad", "UseOldUI", "TryRaylibUI"}, + {"AlphaLongitudinalEnabled", "ForceOffroad"}, { "AlphaLongitudinalEnabled": bool, "ForceOffroad": bool, - "UseOldUI": bool, - "TryRaylibUI": bool, }, ), ) @@ -226,18 +224,18 @@ def test_configured_favorite_slot_values_only_reads_selected_keys(monkeypatch): def test_favorite_values_endpoint_returns_current_selected_value(monkeypatch): - client, _ = _params_client(monkeypatch, {"UseOldUI": False}, "tici") - monkeypatch.setattr(the_galaxy, "_get_favorite_slot_options", lambda: [{"key": "UseOldUI"}]) + client, _ = _params_client(monkeypatch, {"ForceOffroad": False}, "tici") + monkeypatch.setattr(the_galaxy, "_get_favorite_slot_options", lambda: [{"key": "ForceOffroad"}]) monkeypatch.setattr( the_galaxy, "normalize_favorite_slots", - lambda *args, **kwargs: [{"enabled": True, "key": "UseOldUI"}], + lambda *args, **kwargs: [{"enabled": True, "key": "ForceOffroad"}], ) response = client.get("/api/favorites/values") assert response.status_code == 200 - assert response.get_json() == {"values": {"UseOldUI": False}} + assert response.get_json() == {"values": {"ForceOffroad": False}} def test_favorite_slot_options_include_virtual_cruise_actions(monkeypatch): @@ -262,56 +260,6 @@ def test_favorite_action_endpoint_increments_virtual_button_counter(monkeypatch) assert fake_memory.get_int("FavoriteVirtualAccelCruiseCounter") == 1 -def test_use_old_ui_is_noop_on_c4_mici(monkeypatch): - client, fake_params = _params_client(monkeypatch, {"UseOldUI": False, "IsOnroad": False}, "mici") - - response = client.put("/api/params", json={"key": "UseOldUI", "value": True}) - payload = response.get_json() - - assert response.status_code == 200 - assert payload["updated"] == {"UseOldUI": False, "TryRaylibUI": False} - assert fake_params.values["UseOldUI"] is False - assert fake_params.writes == [] - - -def test_use_old_ui_writes_on_big_device_offroad(monkeypatch): - client, fake_params = _params_client(monkeypatch, {"UseOldUI": False, "TryRaylibUI": True, "IsOnroad": False}, "tici") - - response = client.put("/api/params", json={"key": "UseOldUI", "value": True}) - payload = response.get_json() - - assert response.status_code == 200 - assert payload["updated"] == {"UseOldUI": True, "TryRaylibUI": False} - assert fake_params.values["UseOldUI"] is True - assert fake_params.values["TryRaylibUI"] is False - assert fake_params.writes == [("UseOldUI", True), ("TryRaylibUI", False)] - - -def test_use_old_ui_rejects_big_device_onroad_change(monkeypatch): - client, fake_params = _params_client(monkeypatch, {"UseOldUI": False, "TryRaylibUI": True, "IsOnroad": True}, "tici") - - response = client.put("/api/params", json={"key": "UseOldUI", "value": True}) - - assert response.status_code == 403 - assert response.get_json()["error"] == "Cannot change Use Old UI while driving." - assert fake_params.values["UseOldUI"] is False - assert fake_params.values["TryRaylibUI"] is True - assert fake_params.writes == [] - - -def test_legacy_try_raylib_ui_payload_updates_use_old_ui(monkeypatch): - client, fake_params = _params_client(monkeypatch, {"UseOldUI": True, "TryRaylibUI": False, "IsOnroad": False}, "tici") - - response = client.put("/api/params", json={"key": "TryRaylibUI", "value": True}) - payload = response.get_json() - - assert response.status_code == 200 - assert payload["updated"] == {"UseOldUI": False, "TryRaylibUI": True} - assert fake_params.values["UseOldUI"] is False - assert fake_params.values["TryRaylibUI"] is True - assert fake_params.writes == [("UseOldUI", False), ("TryRaylibUI", True)] - - def test_alpha_longitudinal_toggle_writes_and_requests_offroad_cycle(monkeypatch): client, fake_params = _params_client(monkeypatch, { "AlphaLongitudinalEnabled": False, diff --git a/starpilot/system/the_galaxy/the_galaxy.py b/starpilot/system/the_galaxy/the_galaxy.py index 285d91063..0d18fb5ca 100644 --- a/starpilot/system/the_galaxy/the_galaxy.py +++ b/starpilot/system/the_galaxy/the_galaxy.py @@ -163,13 +163,6 @@ def _is_comma_device_runtime() -> bool: return False -def _raylib_ui_toggle_affects_device() -> bool: - try: - return HARDWARE.get_device_type() in ("tici", "tizi") - except Exception: - return False - - def _get_param_key_type(params_obj, key): getter = getattr(params_obj, "get_key_type", None) if getter is None: @@ -544,6 +537,64 @@ def _normalize_sentry_event(payload) -> dict | None: } +def _sentry_image_path(event_id: str, filename: str) -> Path | None: + if not event_id or Path(event_id).name != event_id: + return None + if filename not in {"wide.jpg", "driver.jpg"} or Path(filename).name != filename: + return None + + for root in _sentry_event_roots(): + path = (root / event_id / filename).resolve() + if root in path.parents and path.is_file(): + return path + return None + + +def _public_sentry_event(event: dict) -> dict: + public_event = dict(event) + public_event.pop("imagePaths", None) + public_event["imageUrls"] = [] + event_id = str(public_event.get("eventId") or "") + for raw_path in event.get("imagePaths", []): + path = Path(str(raw_path)).resolve() + if path.parent.name != event_id: + continue + if _sentry_image_path(event_id, path.name) == path: + public_event["imageUrls"].append( + f"/api/sentry/images/{quote(event_id, safe='')}/{quote(path.name, safe='')}" + ) + return public_event + + +def _capture_sentry_test_images(event_id: str) -> list[str]: + from openpilot.system.camerad.snapshot import jpeg_write, snapshot + + params.put_bool("SentryModeCapture", True) + try: + rear, front = snapshot(allow_existing=True) + except Exception: + cloudlog.exception("Galaxy: sentry test snapshot failed") + return [] + finally: + params.put_bool("SentryModeCapture", False) + + if rear is None and front is None: + return [] + + directory = _sentry_event_roots()[0] / event_id + directory.mkdir(parents=True, exist_ok=True) + paths = [] + if rear is not None: + path = directory / "wide.jpg" + jpeg_write(str(path), rear) + paths.append(str(path)) + if front is not None: + path = directory / "driver.jpg" + jpeg_write(str(path), front) + paths.append(str(path)) + return paths + + def _dispatch_sentry_event(event: dict) -> None: message = f"🚨 StarPilot Sentry Mode: {event['message']}" webhook = (params.get("SentryModeWebhook", encoding="utf-8") or "").strip() @@ -2756,18 +2807,6 @@ def _is_blank_param_raw(raw_value): return len(raw_value.strip()) == 0 return False -def _get_use_old_ui_enabled(): - if not _raylib_ui_toggle_affects_device(): - return False - - raw_value = _safe_params_get_live_raw("UseOldUI") - if _is_blank_param_raw(raw_value): - legacy_raw_value = _safe_params_get_live_raw("TryRaylibUI") - if not _is_blank_param_raw(legacy_raw_value): - return not _coerce_param_value(legacy_raw_value, bool) - - return _coerce_param_value(raw_value, bool) - def _has_runtime_default_value(key, raw_value): if _is_blank_param_raw(raw_value): return False @@ -2846,11 +2885,6 @@ def _get_runtime_default_param_overrides(): return overrides def _get_current_param_value(key, value_type, defaults_lookup=None): - if key == "UseOldUI": - return _get_use_old_ui_enabled() - if key == "TryRaylibUI": - return _raylib_ui_toggle_affects_device() and not _get_use_old_ui_enabled() - if key == CUSTOM_ACCEL_PROFILE_INITIALIZED_KEY: return _get_custom_accel_profile_initialized() @@ -4147,6 +4181,7 @@ def setup(app): "/assets/components/tools/device_settings.css", "/assets/components/tools/device_settings_layout.json", "/assets/components/tools/galaxy.js", + "/assets/components/tools/galaxy.css", "/assets/components/tools/v_asm.js", "/assets/components/tools/v_asm.css", "/assets/components/tools/pip_sidecam.js", @@ -4582,26 +4617,6 @@ def setup(app): if key not in allowed_keys: return jsonify({"error": f"Parameter '{key}' is not editable."}), 403 - if key in {"UseOldUI", "TryRaylibUI"}: - enabled = str_val.strip() in ("1", "true", "True") - use_old_ui = enabled if key == "UseOldUI" else not enabled - updated = {"UseOldUI": use_old_ui, "TryRaylibUI": not use_old_ui} - if not _raylib_ui_toggle_affects_device(): - return jsonify({ - "message": "Use Old UI is only available on tici/tizi devices.", - "updated": {"UseOldUI": False, "TryRaylibUI": False}, - }), 200 - - if params.get_bool("IsOnroad"): - return jsonify({"error": "Cannot change Use Old UI while driving."}), 403 - - params.put_bool("UseOldUI", use_old_ui) - params.put_bool("TryRaylibUI", not use_old_ui) - return jsonify({ - "message": f"{'Old' if use_old_ui else 'Raylib'} UI selected. UI will restart shortly.", - "updated": updated, - }), 200 - if key == "AlphaLongitudinalEnabled": if not _get_alpha_longitudinal_available(): return jsonify({"error": "Alpha Longitudinal is not available for the detected vehicle."}), 403 @@ -4954,10 +4969,6 @@ def setup(app): return _serialize_param_write_value(_get_custom_accel_profile_initialized()), 200 if request_key == "LeadIndicator": return _serialize_param_write_value(_get_lead_indicator_enabled()), 200 - if request_key == "UseOldUI": - return ("1" if _get_use_old_ui_enabled() else "0"), 200 - if request_key == "TryRaylibUI": - return ("1" if _raylib_ui_toggle_affects_device() and not _get_use_old_ui_enabled() else "0"), 200 if request_key == "IsRHD" and not params.get_bool("IsRHDOverride"): return ("1" if params.get_bool("IsRhdDetected") else "0"), 200 value = params.get(request_key) or "" @@ -5015,11 +5026,7 @@ def setup(app): default_val = defaults_lookup.get(key) try: - if key == "UseOldUI": - result[key] = False - elif key == "TryRaylibUI": - result[key] = _raylib_ui_toggle_affects_device() - elif t == bool: + if t == bool: if isinstance(default_val, bytes): default_str = default_val.decode("utf-8", errors="replace") else: @@ -6714,9 +6721,40 @@ def setup(app): return jsonify({ "enabled": params.get_bool("SentryModeEnabled"), "status": status if isinstance(status, dict) else {}, - "lastEvent": last_event if isinstance(last_event, dict) else {}, + "lastEvent": _public_sentry_event(last_event) if isinstance(last_event, dict) else {}, }) + @app.route("/api/sentry/images//", methods=["GET"]) + def sentry_image(event_id, filename): + image_path = _sentry_image_path(event_id, filename) + if image_path is None: + return jsonify({"error": "Sentry image not found."}), 404 + return send_file(image_path, mimetype="image/jpeg", max_age=0) + + @app.route("/api/sentry/test", methods=["POST"]) + def sentry_test(): + if request.remote_addr not in {None, "127.0.0.1", "::1"}: + return jsonify({"error": "Sentry tests must originate on the device."}), 403 + if not params.get_bool("IsOffroad"): + return jsonify({"error": "Sentry tests are only available while parked."}), 409 + + event_id = f"test-{int(time.time())}-{secrets.token_hex(4)}" + event = { + "eventId": event_id, + "kind": "alarm", + "detectedAt": datetime.now(timezone.utc).isoformat(), + "imagePaths": [], + "message": "Test sentry event.", + } + + def capture_and_publish(): + event["imagePaths"] = _capture_sentry_test_images(event_id) + params.put("SentryModeLastEvent", json.dumps(event, separators=(",", ":"))) + threading.Thread(target=_dispatch_sentry_event, args=(event,), name="galaxy-sentry-test-notify", daemon=True).start() + + threading.Thread(target=capture_and_publish, name="galaxy-sentry-test-capture", daemon=True).start() + return jsonify({"accepted": True, "eventId": event_id}), 202 + @app.route("/api/sentry/events", methods=["POST"]) def sentry_event(): if request.remote_addr not in {None, "127.0.0.1", "::1"}: diff --git a/starpilot/ui/moc_starpilot_ui.cc b/starpilot/ui/moc_starpilot_ui.cc deleted file mode 100644 index 53bf78456..000000000 --- a/starpilot/ui/moc_starpilot_ui.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_ui.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_ui.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_ui.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotUIState_t { - QByteArrayData data[3]; - char stringdata0[31]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotUIState_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotUIState_t qt_meta_stringdata_StarPilotUIState = { - { -QT_MOC_LITERAL(0, 0, 16), // "StarPilotUIState" -QT_MOC_LITERAL(1, 17, 12), // "themeUpdated" -QT_MOC_LITERAL(2, 30, 0) // "" - - }, - "StarPilotUIState\0themeUpdated\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotUIState[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotUIState::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->themeUpdated(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotUIState::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotUIState::themeUpdated)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotUIState::staticMetaObject = { { - &QObject::staticMetaObject, - qt_meta_stringdata_StarPilotUIState.data, - qt_meta_data_StarPilotUIState, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotUIState::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotUIState::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotUIState.stringdata0)) - return static_cast(this); - return QObject::qt_metacast(_clname); -} - -int StarPilotUIState::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotUIState::themeUpdated() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/data_settings.cc b/starpilot/ui/qt/offroad/data_settings.cc deleted file mode 100644 index 3774a9286..000000000 --- a/starpilot/ui/qt/offroad/data_settings.cc +++ /dev/null @@ -1,872 +0,0 @@ -#include - -#include "starpilot/ui/qt/offroad/data_settings.h" - -namespace { -bool isPathPreserved(const char *path) { - char preserveValue[10] = {0}; -#ifdef __APPLE__ - const ssize_t attr_size = getxattr(path, "user.preserve", preserveValue, sizeof(preserveValue), 0, 0); -#else - const ssize_t attr_size = getxattr(path, "user.preserve", preserveValue, sizeof(preserveValue)); -#endif - return attr_size > 0 && strcmp(preserveValue, "1") == 0; -} -} // namespace - -StarPilotDataPanel::StarPilotDataPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *dataLayout = new QStackedLayout(); - addItem(dataLayout); - - StarPilotListWidget *dataMainList = new StarPilotListWidget(this); - ScrollView *dataMainPanel = new ScrollView(dataMainList, this); - dataLayout->addWidget(dataMainPanel); - - StarPilotListWidget *statsLabelsList = new StarPilotListWidget(this); - ScrollView *statsLabelsPanel = new ScrollView(statsLabelsList, this); - dataLayout->addWidget(statsLabelsPanel); - - ButtonControl *deleteDrivingDataButton = new ButtonControl(tr("Delete Driving Data"), tr("DELETE"), tr("Delete all stored driving footage and data to free up storage space or to simply just erase driving data.")); - QObject::connect(deleteDrivingDataButton, &ButtonControl::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Delete all driving data and footage?"), tr("Delete"), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - deleteDrivingDataButton->setEnabled(false); - deleteDrivingDataButton->setValue(tr("Deleting...")); - - std::vector drivePaths = {"/data/media/0/realdata/", "/data/media/0/realdata_HD/", "/data/media/0/realdata_konik/"}; - for (const QString &path : drivePaths) { - QDir dir(path); - if (!dir.exists()) { - continue; - } - - for (const QFileInfo &entry : dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) { - if (!isPathPreserved(entry.absoluteFilePath().toUtf8().constData())) { - QDir(entry.absoluteFilePath()).removeRecursively(); - } - } - } - - deleteDrivingDataButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - deleteDrivingDataButton->setEnabled(true); - deleteDrivingDataButton->setValue(""); - - parent->keepScreenOn = false; - }).detach(); - } - }); - if (forceOpenDescriptions) { - deleteDrivingDataButton->showDescription(); - } - dataMainList->addItem(deleteDrivingDataButton); - - ButtonControl *deleteErrorLogsButton = new ButtonControl(tr("Delete Error Logs"), tr("DELETE"), tr("Delete collected error logs to free up space and clear old crash records.")); - QObject::connect(deleteErrorLogsButton, &ButtonControl::clicked, [=]() { - QDir errorLogsDir("/data/error_logs"); - - if (ConfirmationDialog::confirm(tr("Delete all error logs?"), tr("Delete"), this)) { - std::thread([=]() mutable { - parent->keepScreenOn = true; - - deleteErrorLogsButton->setEnabled(false); - deleteErrorLogsButton->setValue(tr("Deleting...")); - - errorLogsDir.removeRecursively(); - errorLogsDir.mkpath("."); - - deleteErrorLogsButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - deleteErrorLogsButton->setEnabled(true); - deleteErrorLogsButton->setValue(""); - - parent->keepScreenOn = false; - }).detach(); - } - }); - if (forceOpenDescriptions) { - deleteErrorLogsButton->showDescription(); - } - dataMainList->addItem(deleteErrorLogsButton); - - StarPilotButtonsControl *screenRecordingsButton = new StarPilotButtonsControl(tr("Screen Recordings"), tr("Delete or rename screen recordings."), "", {tr("DELETE"), tr("DELETE ALL"), tr("RENAME")}); - QObject::connect(screenRecordingsButton, &StarPilotButtonsControl::buttonClicked, [=](int id) { - QDir recordingsDir("/data/media/screen_recordings"); - QStringList recordingsNames = recordingsDir.entryList(QDir::Files | QDir::NoDotAndDotDot); - std::sort(recordingsNames.begin(), recordingsNames.end(), std::greater()); - - QStringList friendlyNames; - QMap recordingMap; - - for (const QString &name : recordingsNames) { - if (!name.endsWith(".mp4", Qt::CaseInsensitive)) { - continue; - } - - QString friendlyName = name; - QString cleanName = QString(name).remove(".mp4"); - - QStringList parts = cleanName.split(cleanName.contains("--") ? "--" : "_"); - - if (parts.size() >= 2) { - QDate date = QDate::fromString(parts[0], "yyyy-MM-dd"); - QTime time = QTime::fromString(parts[1], "HH-mm-ss"); - - if (date.isValid() && time.isValid()) { - int day = date.day(); - QString suffix = (day >= 11 && day <= 13) ? "th" : - (day % 10 == 1) ? "st" : - (day % 10 == 2) ? "nd" : - (day % 10 == 3) ? "rd" : "th"; - - friendlyName = QString("%1 %2%3, %4 (%5)") - .arg(date.toString("MMMM")) - .arg(day) - .arg(suffix) - .arg(date.year()) - .arg(time.toString("h:mm AP")); - } - } - - if (friendlyName == name) { - friendlyName = cleanName; - friendlyName.replace("_", " "); - } - - friendlyNames.append(friendlyName); - recordingMap[friendlyName] = name; - } - - if (id == 0) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a screen recording to delete"), friendlyNames, "", this); - if (!selection.isEmpty()) { - if (ConfirmationDialog::confirm(tr("Delete this screen recording?"), tr("Delete"), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - screenRecordingsButton->setEnabled(false); - screenRecordingsButton->setValue(tr("Deleting...")); - - screenRecordingsButton->setVisibleButton(1, false); - screenRecordingsButton->setVisibleButton(2, false); - - QFile::remove(recordingsDir.absoluteFilePath(recordingMap[selection])); - - screenRecordingsButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - screenRecordingsButton->setEnabled(true); - screenRecordingsButton->setValue(""); - - screenRecordingsButton->setVisibleButton(1, true); - screenRecordingsButton->setVisibleButton(2, true); - - parent->keepScreenOn = false; - }).detach(); - } - } - - } else if (id == 1) { - if (ConfirmationDialog::confirm(tr("Delete all screen recordings?"), tr("Delete All"), this)) { - std::thread([=]() mutable { - parent->keepScreenOn = true; - - screenRecordingsButton->setEnabled(false); - screenRecordingsButton->setValue(tr("Deleting...")); - - screenRecordingsButton->setVisibleButton(0, false); - screenRecordingsButton->setVisibleButton(2, false); - - recordingsDir.removeRecursively(); - recordingsDir.mkpath("."); - - screenRecordingsButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - screenRecordingsButton->setEnabled(true); - screenRecordingsButton->setValue(""); - - screenRecordingsButton->setVisibleButton(0, true); - screenRecordingsButton->setVisibleButton(2, true); - - parent->keepScreenOn = false; - }).detach(); - } - - } else if (id == 2) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a screen recording to rename"), friendlyNames, "", this); - if (!selection.isEmpty()) { - QString newBase = InputDialog::getText(tr("Enter a new name"), this, tr("Rename Screen Recording")).trimmed().replace(" ", "_"); - if (!newBase.isEmpty()) { - QString newName = newBase + ".mp4"; - if (recordingsNames.contains(newName)) { - ConfirmationDialog::alert(tr("Name already in use. Please choose a different name!"), this); - return; - } - std::thread([=]() { - parent->keepScreenOn = true; - - screenRecordingsButton->setEnabled(false); - screenRecordingsButton->setValue(tr("Renaming...")); - - screenRecordingsButton->setVisibleButton(0, false); - screenRecordingsButton->setVisibleButton(1, false); - - QString newPath = recordingsDir.absoluteFilePath(newName); - QString oldPath = recordingsDir.absoluteFilePath(recordingMap[selection]); - QFile::rename(oldPath, newPath); - - screenRecordingsButton->setValue(tr("Renamed!")); - - util::sleep_for(2500); - - screenRecordingsButton->setEnabled(true); - screenRecordingsButton->setValue(""); - - screenRecordingsButton->setVisibleButton(0, true); - screenRecordingsButton->setVisibleButton(1, true); - - parent->keepScreenOn = false; - }).detach(); - } - } - } - }); - if (forceOpenDescriptions) { - screenRecordingsButton->showDescription(); - } - dataMainList->addItem(screenRecordingsButton); - - StarPilotButtonsControl *starpilotBackupButton = new StarPilotButtonsControl(tr("StarPilot Backups"), tr("Create, delete, or restore StarPilot backups."), "", {tr("BACKUP"), tr("DELETE"), tr("DELETE ALL"), tr("RESTORE")}); - QObject::connect(starpilotBackupButton, &StarPilotButtonsControl::buttonClicked, [=](int id) { - QDir backupDir("/data/backups"); - - QFileInfoList backupList = backupDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot); - std::sort(backupList.begin(), backupList.end(), [](const QFileInfo &a, const QFileInfo &b) { - return a.lastModified() > b.lastModified(); - }); - - QStringList friendlyNames; - QMap backupMap; - - for (const QFileInfo &fileInfo : backupList) { - QString fileName = fileInfo.fileName(); - - if (fileName.contains("in_progress")) { - continue; - } - - QString friendlyName = fileName; - - if (fileName.endsWith("_auto.tar.zst")) { - QStringList parts = QString(fileName).remove(".tar.zst").split("_"); - - if (parts.size() >= 3) { - QDate date = fileInfo.lastModified().date(); - - if (date.isValid()) { - int day = date.day(); - QString suffix = (day >= 11 && day <= 13) ? "th" : - (day % 10 == 1) ? "st" : - (day % 10 == 2) ? "nd" : - (day % 10 == 3) ? "rd" : "th"; - - friendlyName = QString("%1 %2%3, %4 (%5)") - .arg(date.toString("MMMM")) - .arg(day) - .arg(suffix) - .arg(date.year()) - .arg(parts[1]); - } - } - } - - if (friendlyName == fileName) { - friendlyName.remove(".tar.zst"); - friendlyName.replace("_", " "); - } - - friendlyNames.append(friendlyName); - backupMap[friendlyName] = fileName; - } - - if (id == 0) { - QString name = InputDialog::getText(tr("Name your backup"), this, tr("Backup Name")).trimmed().replace(" ", "_"); - if (!name.isEmpty()) { - QStringList distinctFileNames = backupDir.entryList(QDir::Files | QDir::NoDotAndDotDot); - if (distinctFileNames.contains(name + ".tar.zst")) { - ConfirmationDialog::alert(tr("Name already in use. Please choose a different name!"), this); - return; - } - - std::thread([=]() { - parent->keepScreenOn = true; - - starpilotBackupButton->setEnabled(false); - starpilotBackupButton->setValue(tr("Backing up...")); - - starpilotBackupButton->setVisibleButton(1, false); - starpilotBackupButton->setVisibleButton(2, false); - starpilotBackupButton->setVisibleButton(3, false); - - std::system(QString("tar --use-compress-program=zstd -cf %1 %2").arg(backupDir.absoluteFilePath(name + ".tar.zst"), "/data/openpilot").toStdString().c_str()); - - starpilotBackupButton->setValue(tr("Backup created!")); - - util::sleep_for(2500); - - starpilotBackupButton->setEnabled(true); - starpilotBackupButton->setValue(""); - - starpilotBackupButton->setVisibleButton(1, true); - starpilotBackupButton->setVisibleButton(2, true); - starpilotBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - - } else if (id == 1) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a backup to delete"), friendlyNames, "", this); - if (!selection.isEmpty()) { - if (ConfirmationDialog::confirm(tr("Delete this backup?"), tr("Delete"), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - starpilotBackupButton->setEnabled(false); - starpilotBackupButton->setValue(tr("Deleting...")); - - starpilotBackupButton->setVisibleButton(0, false); - starpilotBackupButton->setVisibleButton(2, false); - starpilotBackupButton->setVisibleButton(3, false); - - QFile::remove(backupDir.absoluteFilePath(backupMap[selection])); - - starpilotBackupButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - starpilotBackupButton->setEnabled(true); - starpilotBackupButton->setValue(""); - - starpilotBackupButton->setVisibleButton(0, true); - starpilotBackupButton->setVisibleButton(2, true); - starpilotBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - } - - } else if (id == 2) { - if (ConfirmationDialog::confirm(tr("Delete all StarPilot backups?"), tr("Delete All"), this)) { - std::thread([=]() mutable { - parent->keepScreenOn = true; - - starpilotBackupButton->setEnabled(false); - starpilotBackupButton->setValue(tr("Deleting...")); - - starpilotBackupButton->setVisibleButton(0, false); - starpilotBackupButton->setVisibleButton(1, false); - starpilotBackupButton->setVisibleButton(3, false); - - backupDir.removeRecursively(); - backupDir.mkpath("."); - - starpilotBackupButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - starpilotBackupButton->setEnabled(true); - starpilotBackupButton->setValue(""); - - starpilotBackupButton->setVisibleButton(0, true); - starpilotBackupButton->setVisibleButton(1, true); - starpilotBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - - } else if (id == 3) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a backup to restore"), friendlyNames, "", this); - if (!selection.isEmpty()) { - if (StarPilotConfirmationDialog::yesorno(tr("Restore this backup? This will overwrite your current installation and reboot the device."), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - starpilotBackupButton->setEnabled(false); - starpilotBackupButton->setValue(tr("Restoring...")); - - starpilotBackupButton->setVisibleButton(0, false); - starpilotBackupButton->setVisibleButton(1, false); - starpilotBackupButton->setVisibleButton(2, false); - - std::system(QString("rm -rf /data/openpilot/* && tar --use-compress-program=zstd -xf %1 -C /").arg(backupDir.absoluteFilePath(backupMap[selection])).toStdString().c_str()); - QFile("/cache/on_backup").open(QIODevice::WriteOnly); - - starpilotBackupButton->setValue(tr("Restored!")); - - util::sleep_for(2500); - - starpilotBackupButton->setValue(tr("Rebooting...")); - - util::sleep_for(2500); - - Hardware::reboot(); - }).detach(); - } - } - } - }); - if (forceOpenDescriptions) { - starpilotBackupButton->showDescription(); - } - dataMainList->addItem(starpilotBackupButton); - - StarPilotButtonsControl *toggleBackupButton = new StarPilotButtonsControl(tr("Toggle Backups"), tr("Create, delete, or restore toggle backups."), "", {tr("BACKUP"), tr("DELETE"), tr("DELETE ALL"), tr("RESTORE")}); - QObject::connect(toggleBackupButton, &StarPilotButtonsControl::buttonClicked, [=](int id) { - QDir backupDir("/data/toggle_backups"); - - QStringList backupNames = backupDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); - std::sort(backupNames.begin(), backupNames.end(), std::greater()); - - QMap backupMap; - for (const QString &dirName : backupNames) { - if (dirName.contains("in_progress")) { - continue; - } - - QString friendlyName = dirName; - - if (dirName.endsWith("_auto")) { - QStringList parts = QString(dirName).remove("_auto").split("_"); - - if (parts.size() >= 2) { - QDate date = QDate::fromString(parts[0], "yyyy-MM-dd"); - QTime time = QTime::fromString(parts[1], "HH-mm-ss"); - - if (date.isValid() && time.isValid()) { - int day = date.day(); - QString suffix = (day >= 11 && day <= 13) ? "th" : - (day % 10 == 1) ? "st" : - (day % 10 == 2) ? "nd" : - (day % 10 == 3) ? "rd" : "th"; - - friendlyName = QString("%1 %2%3, %4 (%5)") - .arg(date.toString("MMMM")) - .arg(day) - .arg(suffix) - .arg(date.year()) - .arg(time.toString("h:mm AP")); - } - } - } - - if (friendlyName == dirName) { - friendlyName.replace("_", " "); - } - - backupMap[friendlyName] = dirName; - } - - if (id == 0) { - QString name = InputDialog::getText(tr("Name your backup"), this, tr("Backup Name")).trimmed().replace(" ", "_"); - if (!name.isEmpty()) { - if (backupNames.contains(name)) { - ConfirmationDialog::alert(tr("Name already in use. Please choose a different name!"), this); - return; - } - - std::thread([=]() { - parent->keepScreenOn = true; - - toggleBackupButton->setEnabled(false); - toggleBackupButton->setValue(tr("Backing up...")); - - toggleBackupButton->setVisibleButton(1, false); - toggleBackupButton->setVisibleButton(2, false); - toggleBackupButton->setVisibleButton(3, false); - - std::system(QString("cp -r /data/params/d/ %1").arg(backupDir.absoluteFilePath(name)).toStdString().c_str()); - - toggleBackupButton->setValue(tr("Backup created!")); - - util::sleep_for(2500); - - toggleBackupButton->setEnabled(true); - toggleBackupButton->setValue(""); - - toggleBackupButton->setVisibleButton(1, true); - toggleBackupButton->setVisibleButton(2, true); - toggleBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - - } else if (id == 1) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a backup to delete"), backupMap.keys(), "", this); - if (!selection.isEmpty()) { - if (ConfirmationDialog::confirm(tr("Delete this backup?"), tr("Delete"), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - toggleBackupButton->setEnabled(false); - toggleBackupButton->setValue(tr("Deleting...")); - - toggleBackupButton->setVisibleButton(0, false); - toggleBackupButton->setVisibleButton(2, false); - toggleBackupButton->setVisibleButton(3, false); - - QDir(backupDir.absoluteFilePath(backupMap[selection])).removeRecursively(); - - toggleBackupButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - toggleBackupButton->setEnabled(true); - toggleBackupButton->setValue(""); - - toggleBackupButton->setVisibleButton(0, true); - toggleBackupButton->setVisibleButton(2, true); - toggleBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - } - - } else if (id == 2) { - if (ConfirmationDialog::confirm(tr("Delete all toggle backups?"), tr("Delete All"), this)) { - std::thread([=]() mutable { - parent->keepScreenOn = true; - - toggleBackupButton->setEnabled(false); - toggleBackupButton->setValue(tr("Deleting...")); - - toggleBackupButton->setVisibleButton(0, false); - toggleBackupButton->setVisibleButton(1, false); - toggleBackupButton->setVisibleButton(3, false); - - backupDir.removeRecursively(); - backupDir.mkpath("."); - - toggleBackupButton->setValue(tr("Deleted!")); - - util::sleep_for(2500); - - toggleBackupButton->setEnabled(true); - toggleBackupButton->setValue(""); - - toggleBackupButton->setVisibleButton(0, true); - toggleBackupButton->setVisibleButton(1, true); - toggleBackupButton->setVisibleButton(3, true); - - parent->keepScreenOn = false; - }).detach(); - } - - } else if (id == 3) { - QString selection = MultiOptionDialog::getSelection(tr("Choose a backup to restore"), backupMap.keys(), "", this); - if (!selection.isEmpty()) { - if (StarPilotConfirmationDialog::yesorno(tr("Restore this backup? This will overwrite your current settings!"), this)) { - std::thread([=]() { - parent->keepScreenOn = true; - - toggleBackupButton->setEnabled(false); - toggleBackupButton->setValue(tr("Restoring...")); - - toggleBackupButton->setVisibleButton(0, false); - toggleBackupButton->setVisibleButton(1, false); - toggleBackupButton->setVisibleButton(2, false); - - std::system(QString("cp -r %1/* /data/params/d/").arg(backupDir.absoluteFilePath(backupMap[selection])).toStdString().c_str()); - - updateStarPilotToggles(); - - toggleBackupButton->setValue(tr("Restored!")); - - util::sleep_for(2500); - - toggleBackupButton->setEnabled(true); - toggleBackupButton->setValue(""); - - toggleBackupButton->setVisibleButton(0, true); - toggleBackupButton->setVisibleButton(1, true); - toggleBackupButton->setVisibleButton(2, true); - - parent->keepScreenOn = false; - }).detach(); - } - } - } - }); - if (forceOpenDescriptions) { - toggleBackupButton->showDescription(); - } - dataMainList->addItem(toggleBackupButton); - - StarPilotButtonsControl *viewStatsButton = new StarPilotButtonsControl(tr("StarPilot Stats"), tr("View your collected StarPilot stats."), "", {tr("RESET"), tr("VIEW")}); - QObject::connect(viewStatsButton, &StarPilotButtonsControl::buttonClicked, [dataLayout, statsLabelsPanel, this](int id) { - if (id == 0) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset all of your StarPilot stats?"), tr("Reset"), this)) { - params.remove("StarPilotStats"); - } - } else if (id == 1) { - emit openSubPanel(); - dataLayout->setCurrentWidget(statsLabelsPanel); - } - }); - if (forceOpenDescriptions) { - viewStatsButton->showDescription(); - } - dataMainList->addItem(viewStatsButton); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [dataLayout, dataMainPanel] { - dataLayout->setCurrentWidget(dataMainPanel); - }); - QObject::connect(parent, &StarPilotSettingsWindow::updateMetric, [this](bool metric){isMetric = metric;}); - QObject::connect(uiState(), &UIState::offroadTransition, [statsLabelsList, this](bool offroad) { - if (offroad) { - updateStatsLabels(statsLabelsList); - } - }); - - updateStatsLabels(statsLabelsList); -} - -void StarPilotDataPanel::updateStatsLabels(StarPilotListWidget *labelsList) { - labelsList->clear(); - - QJsonObject stats = QJsonDocument::fromJson(QByteArray::fromStdString(params.get("StarPilotStats"))).object(); - - static QMap> keyMap = { - {"AEBEvents", {tr("Total Emergency Brake Alerts"), "count"}}, - {"AOLTime", {tr("Time Using \"Always On Lateral\""), "timePercent"}}, - {"CruiseSpeedTimes", {tr("Favorite Set Speed"), "speed"}}, - {"CurrentMonthsMeters", {tr("Distance Driven This Month"), "distance"}}, - {"DayTime", {tr("Time Driving (Daytime)"), "timePercent"}}, - {"Disengages", {tr("Total Disengagements"), "count"}}, - {"Engages", {tr("Total Engagements"), "count"}}, - {"ExperimentalModeTime", {tr("Time Using \"Experimental Mode\""), "timePercent"}}, - {"FrogChirps", {tr("Total Frog Chirps"), "count"}}, - {"FrogHops", {tr("Total Frog Hops"), "count"}}, - {"StarPilotDrives", {tr("Total Drives"), "count"}}, - {"StarPilotMeters", {tr("Total Distance Driven"), "distance"}}, - {"StarPilotSeconds", {tr("Total Driving Time"), "time"}}, - {"FrogSqueaks", {tr("Total Frog Squeaks"), "count"}}, - {"GoatScreams", {tr("Total Goat Screams"), "count"}}, - {"LateralTime", {tr("Time Using Lateral Control"), "timePercent"}}, - {"LongestDistanceWithoutOverride", {tr("Longest Distance Without an Override"), "distance"}}, - {"LongitudinalTime", {tr("Time Using Longitudinal Control"), "timePercent"}}, - {"MaxAcceleration", {tr("Highest Acceleration Rate"), "accel"}}, - {"ModelTimes", {tr("Driving Models:"), "parent"}}, - {"Month", {tr("Month"), "other"}}, - {"NightTime", {tr("Time Driving (Nighttime)"), "timePercent"}}, - {"Overrides", {tr("Total Overrides"), "count"}}, - {"OverrideTime", {tr("Time Overriding openpilot"), "timePercent"}}, - {"PersonalityTimes", {tr("Driving Personalities:"), "parent"}}, - {"RandomEvents", {tr("Random Events:"), "parent"}}, - {"StandstillTime", {tr("Time Stopped"), "timePercent"}}, - {"StopLightTime", {tr("Time Spent at Stoplights"), "timePercent"}}, - {"TrackedTime", {tr("Total Time Tracked"), "time"}}, - {"WeatherTimes", {tr("Time Driven (Weather):"), "parent"}} - }; - - static QMap randomEventsMap = { - {"accel30", tr("UwUs")}, - {"accel35", tr("Loch Ness Encounters")}, - {"accel40", tr("Visits to 1955")}, - {"dejaVuCurve", tr("Deja Vu Moments")}, - {"firefoxSteerSaturated", tr("Internet Explorer Weeeeeeees")}, - {"hal9000", tr("HAL 9000 Denials")}, - {"openpilotCrashedRandomEvent", tr("openpilot Crashes")}, - {"thisIsFineSteerSaturated", tr("This Is Fine Moments")}, - {"toBeContinued", tr("To Be Continued Moments")}, - {"vCruise69", tr("Noices")}, - {"yourFrogTriedToKillMe", tr("Attempted Frog Murders")}, - {"youveGotMail", tr("Total Mail Received")} - }; - - static QSet ignoredKeys = { - "Month" - }; - - QStringList keys = keyMap.keys(); - std::sort(keys.begin(), keys.end(), [&](const QString &a, const QString &b) { - return keyMap.value(a).first.toLower() < keyMap.value(b).first.toLower(); - }); - - std::function format_number = [&](double number) { - return QLocale().toString(number); - }; - - std::function format_distance = [&](double meters) { - double value; - QString unit; - if (isMetric) { - value = meters / 1000.0; - unit = (value == 1.0) ? tr(" kilometer") : tr(" kilometers"); - } else { - value = meters * METER_TO_MILE; - unit = (value == 1.0) ? tr(" mile") : tr(" miles"); - } - return format_number(qRound(value)) + unit; - }; - - std::function format_time = [&](int seconds) { - static int secondsInDay = 60 * 60 * 24; - static int secondsInHour = 60 * 60; - - int days = seconds / secondsInDay; - int hours = (seconds % secondsInDay) / secondsInHour; - int minutes = (seconds % secondsInHour) / 60; - - QString result; - if (days > 0) { - result += format_number(days) + (days == 1 ? tr(" day ") : tr(" days ")); - } - if (hours > 0 || days > 0) { - result += format_number(hours) + (hours == 1 ? tr(" hour ") : tr(" hours ")); - } - result += format_number(minutes) + (minutes == 1 ? tr(" minute") : tr(" minutes")); - return result.trimmed(); - }; - - double trackedTime = stats.contains("TrackedTime") ? stats.value("TrackedTime").toDouble() : 0.0; - - for (const QString &key : keys) { - if (ignoredKeys.contains(key)) { - continue; - } - - QJsonValue value = stats.contains(key) ? stats.value(key) : QJsonValue(0); - QString labelText = keyMap.value(key).first; - QString type = keyMap.value(key).second; - - if (key == "AEBEvents") { - QJsonObject totalEvents = stats.value("TotalEvents").toObject(); - - QString trimmedLabel = labelText; - QString prefix = tr("Total "); - if (trimmedLabel.startsWith(prefix)) { - trimmedLabel = trimmedLabel.mid(prefix.length()); - } - QString displayValue = format_number(totalEvents.value("stockAeb").toInt(0) + totalEvents.value("fcw").toInt(0)) + " " + trimmedLabel; - - labelsList->addItem(new LabelControl(labelText, displayValue, "", this)); - - } else if (key == "CruiseSpeedTimes" && value.isObject()) { - QJsonObject speeds = value.toObject(); - - double maxTime = -1.0; - QString bestSpeed; - for (const QString &speedKey : speeds.keys()) { - double time = speeds.value(speedKey).toDouble(); - if (time > maxTime) { - bestSpeed = speedKey; - maxTime = time; - } - } - - QString displaySpeed; - if (isMetric) { - displaySpeed = QString::number(qRound(bestSpeed.toDouble() * MS_TO_KPH)) + " " + tr("km/h"); - } else { - displaySpeed = QString::number(qRound(bestSpeed.toDouble() * MS_TO_MPH)) + " " + tr("mph"); - } - - labelsList->addItem(new LabelControl(labelText, displaySpeed + " (" + format_time(maxTime) + ")", "", this)); - } else if (type == "parent" && value.isObject()) { - labelsList->addItem(new LabelControl(labelText, "", "", this)); - - QJsonObject subObject = value.toObject(); - QStringList subKeys; - - if (key == "RandomEvents") { - subKeys = randomEventsMap.keys(); - } else { - subKeys = subObject.keys(); - } - - std::sort(subKeys.begin(), subKeys.end(), [&](const QString &a, const QString &b) { - QString displayA, displayB; - if (key == "RandomEvents") { - displayA = randomEventsMap.value(a, a); - displayB = randomEventsMap.value(b, b); - } else { - displayA = a; - displayB = b; - } - return displayA.toLower() < displayB.toLower(); - }); - - for (const QString &subkey : subKeys) { - if (subkey == "Unknown") { - continue; - } - - QString displaySubKey; - if (key == "ModelTimes") { - displaySubKey = cleanModelName(subkey); - } else if (key == "RandomEvents") { - displaySubKey = randomEventsMap.value(subkey, subkey); - } else if (key == "WeatherTimes") { - displaySubKey = subkey.left(1).toUpper() + subkey.mid(1); - } else { - displaySubKey = subkey; - } - - QString subvalue; - if (key.endsWith("Times")) { - subvalue = format_time(subObject.value(subkey).toDouble()); - } else { - subvalue = format_number(subObject.value(subkey).toInt(0)); - } - - labelsList->addItem(new LabelControl(" " + displaySubKey, subvalue, "", this)); - } - } else { - QString displayValue; - if (type == "accel") { - displayValue = QString::number(value.toDouble(), 'f', 2) + " " + tr("m/s²"); - } else if (type == "count") { - QString trimmedLabel = labelText; - QString prefix = tr("Total "); - if (trimmedLabel.startsWith(prefix)) { - trimmedLabel = trimmedLabel.mid(prefix.length()); - } - displayValue = format_number(value.toInt()) + " " + trimmedLabel; - } else if (type == "distance") { - displayValue = format_distance(value.toDouble()); - } else if (type == "time" || type == "timePercent") { - displayValue = format_time(value.toDouble()); - } else { - QString stringValue = value.toVariant().toString(); - displayValue = stringValue.isEmpty() ? "0" : stringValue; - } - - labelsList->addItem(new LabelControl(labelText, displayValue, "", this)); - - if (type == "timePercent") { - int percent = 0; - if (trackedTime > 0.0) { - percent = (value.toDouble() * 100.0) / trackedTime; - } - - labelsList->addItem(new LabelControl(tr("% of ") + labelText, format_number(percent) + "%", "", this)); - } - } - } -} diff --git a/starpilot/ui/qt/offroad/data_settings.h b/starpilot/ui/qt/offroad/data_settings.h deleted file mode 100644 index dc01c17c9..000000000 --- a/starpilot/ui/qt/offroad/data_settings.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotDataPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotDataPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -private: - void updateStatsLabels(StarPilotListWidget *labelsList); - - bool forceOpenDescriptions; - bool isMetric; - - StarPilotSettingsWindow *parent; - - Params params; -}; diff --git a/starpilot/ui/qt/offroad/device_settings.cc b/starpilot/ui/qt/offroad/device_settings.cc deleted file mode 100644 index 1265a5d08..000000000 --- a/starpilot/ui/qt/offroad/device_settings.cc +++ /dev/null @@ -1,272 +0,0 @@ -#include "starpilot/ui/screenrecorder/screenrecorder.h" -#include "starpilot/ui/qt/offroad/device_settings.h" - -namespace { - -std::string cacheParamsPath() { - return Path::params_cache(); -} - -void prepareKonikServerSwitch(bool use_konik) { - Params params; - Params params_cache(cacheParamsPath()); - - if (use_konik) { - params.remove("KonikDongleId"); - params_cache.remove("KonikDongleId"); - } else { - params.remove("DongleId"); - params_cache.remove("DongleId"); - } -} - -} // namespace - -StarPilotDevicePanel::StarPilotDevicePanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - ScreenRecorder *screenRecorder = new ScreenRecorder(this); - screenRecorder->setVisible(false); - - QStackedLayout *deviceLayout = new QStackedLayout(); - addItem(deviceLayout); - - StarPilotListWidget *deviceList = new StarPilotListWidget(this); - - ScrollView *devicePanel = new ScrollView(deviceList, this); - - deviceLayout->addWidget(devicePanel); - - StarPilotListWidget *deviceManagementList = new StarPilotListWidget(this); - StarPilotListWidget *screenList = new StarPilotListWidget(this); - - ScrollView *deviceManagementPanel = new ScrollView(deviceManagementList, this); - ScrollView *screenPanel = new ScrollView(screenList, this); - - deviceLayout->addWidget(deviceManagementPanel); - deviceLayout->addWidget(screenPanel); - - const std::vector> deviceToggles { - {"DeviceManagement", tr("Device Settings"), tr("Settings that control how the device runs, powers off, and manages driving data."), "../../starpilot/assets/toggle_icons/icon_device.png"}, - {"DeviceShutdown", tr("Device Shutdown Timer"), tr("Keep the device on for the set amount of time after a drive before it shuts down automatically."), ""}, - {"DisableWideRoad", tr("Disable Wide Road Camera"), QString("%1

%2").arg(tr("WARNING: Only use this if the wide camera is malfunctioning or for development purposes. This may cause instability!")).arg(tr("Requires a reboot to take effect.")), ""}, - {"NoLogging", tr("Disable Logging"), QString("%1

%2").arg(tr("WARNING: This will prevent your drives from being recorded and all data will be unobtainable!")).arg(tr("Prevent the device from saving driving data.")), ""}, - {"NoUploads", tr("Disable Uploads"), QString("%1

%2").arg(tr("WARNING: This will prevent your drives from being uploaded to comma connect which will impact debugging and official support from comma!")).arg(tr("Prevent the device from uploading driving data.")), ""}, - {"HigherBitrate", tr("High-Quality Recording"), tr("Save drive footage in higher video quality."), ""}, - {"LowVoltageShutdown", tr("Low-Voltage Cutoff"), tr("While parked, if the battery voltage falls below the set level, the device shuts down to prevent excessive battery drain."), ""}, - {"IncreaseThermalLimits", tr("Raise Temperature Limits"), QString("%1

%2").arg(tr("WARNING: Running at higher temperatures may damage your device!")).arg(tr("Allow the device to run at higher temperatures before throttling or shutting down. Use only if you understand the risks!")), ""}, - {"UseKonikServer", tr("Use Konik Server"), tr("Upload driving data to \"stable.konik.ai\" instead of \"connect.comma.ai\"."), ""}, - - {"ScreenManagement", tr("Screen Settings"), tr("Settings that control screen brightness, screen recording, and timeout duration."), "../../starpilot/assets/toggle_icons/icon_light.png"}, - {"ScreenBrightness", tr("Screen Brightness (Offroad)"), tr("The screen brightness while not driving."), ""}, - {"ScreenBrightnessOnroad", tr("Screen Brightness (Onroad)"), tr("The screen brightness while driving."), ""}, - {"ScreenRecorder", tr("Screen Recorder"), tr("Add a button to the driving screen to record the display."), ""}, - {"ScreenTimeout", tr("Screen Timeout (Offroad)"), tr("How long the screen stays on after being tapped while not driving."), ""}, - {"ScreenTimeoutOnroad", tr("Screen Timeout (Onroad)"), tr("How long the screen stays on after being tapped while driving."), ""}, - {"StandbyMode", tr("Standby Mode"), tr("Turn the screen off while driving and automatically wake it up for alerts or engagement state changes."), ""} - }; - - for (const auto &[param, title, desc, icon] : deviceToggles) { - AbstractControl *deviceToggle; - - if (param == "DeviceManagement") { - StarPilotManageControl *deviceManagementToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(deviceManagementToggle, &StarPilotManageControl::manageButtonClicked, [deviceLayout, deviceManagementPanel]() { - deviceLayout->setCurrentWidget(deviceManagementPanel); - }); - deviceToggle = deviceManagementToggle; - } else if (param == "DeviceShutdown") { - std::map shutdownLabels; - for (int i = 0; i <= 33; ++i) { - shutdownLabels[i] = i == 0 ? tr("5 mins") : i <= 3 ? QString::number(i * 15) + tr(" mins") : QString::number(i - 3) + (i == 4 ? tr(" hour") : tr(" hours")); - } - deviceToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 33, QString(), shutdownLabels); - } else if (param == "NoUploads") { - std::vector uploadsToggles{"DisableOnroadUploads"}; - std::vector uploadsToggleNames{tr("Disable Onroad Only")}; - deviceToggle = new StarPilotButtonToggleControl(param, title, desc, icon, uploadsToggles, uploadsToggleNames); - } else if (param == "LowVoltageShutdown") { - deviceToggle = new StarPilotParamValueControl(param, title, desc, icon, 11.8, 12.5, tr(" volts"), std::map(), 0.1); - - } else if (param == "ScreenManagement") { - StarPilotManageControl *screenToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(screenToggle, &StarPilotManageControl::manageButtonClicked, [deviceLayout, screenPanel]() { - deviceLayout->setCurrentWidget(screenPanel); - }); - deviceToggle = screenToggle; - } else if (param == "ScreenBrightness" || param == "ScreenBrightnessOnroad") { - std::map brightnessLabels; - const int minBrightness = 1; - for (int i = minBrightness; i <= 101; ++i) { - brightnessLabels[i] = i == 101 ? tr("Auto") : QString::number(i) + "%"; - } - deviceToggle = new StarPilotParamValueControl(param, title, desc, icon, minBrightness, 101, QString(), brightnessLabels, 1, true); - } else if (param == "ScreenRecorder") { - std::vector recorderButtonNames{tr("Start Recording"), tr("Stop Recording")}; - StarPilotButtonControl *recorderToggle = new StarPilotButtonControl(param, title, desc, icon, recorderButtonNames, true); - QObject::connect(recorderToggle, &StarPilotButtonControl::buttonClicked, [recorderToggle, screenRecorder](int id) { - if (id == 0) { - recorderToggle->setCheckedButton(1); - - recorderToggle->setVisibleButton(0, false); - recorderToggle->setVisibleButton(1, true); - - screenRecorder->startRecording(); - } else if (id == 1) { - recorderToggle->clearCheckedButtons(); - - recorderToggle->setVisibleButton(0, true); - recorderToggle->setVisibleButton(1, false); - - screenRecorder->stopRecording(); - } - }); - recorderToggle->setVisibleButton(1, false); - deviceToggle = recorderToggle; - } else if (param == "ScreenTimeout" || param == "ScreenTimeoutOnroad") { - deviceToggle = new StarPilotParamValueControl(param, title, desc, icon, 5, 60, tr(" seconds"), {}, 5); - - } else { - deviceToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = deviceToggle; - - if (deviceManagementKeys.contains(param)) { - deviceManagementList->addItem(deviceToggle); - } else if (screenKeys.contains(param)) { - screenList->addItem(deviceToggle); - } else { - deviceList->addItem(deviceToggle); - - parentKeys.insert(param); - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(deviceToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(deviceToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(deviceToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - static_cast(toggles["IncreaseThermalLimits"])->setConfirmation(true, false); - static_cast(toggles["NoLogging"])->setConfirmation(true, false); - static_cast(toggles["NoUploads"])->setConfirmation(true, false); - - QSet brightnessKeys = {"ScreenBrightness", "ScreenBrightnessOnroad"}; - for (const QString &key : brightnessKeys) { - StarPilotParamValueControl *paramControl = static_cast(toggles[key]); - QObject::connect(paramControl, &StarPilotParamValueControl::valueChanged, [key, this](int value) { - if (!started && key == "ScreenBrightness") { - Hardware::set_brightness(value); - } else if (started && key == "ScreenBrightnessOnroad") { - Hardware::set_brightness(value); - } - }); - } - - QSet forceUpdateKeys = {"NoUploads"}; - for (const QString &key : forceUpdateKeys) { - QObject::connect(static_cast(toggles[key]), &StarPilotButtonToggleControl::buttonClicked, this, &StarPilotDevicePanel::updateToggles); - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, this, &StarPilotDevicePanel::updateToggles); - } - - QSet rebootKeys = {"DisableWideRoad", "HigherBitrate", "UseKonikServer"}; - for (const QString &key : rebootKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, [key, this](bool state) { - QString filePath; - if (key == "HigherBitrate") { - filePath = "/cache/use_HD"; - } else if (key == "UseKonikServer") { - filePath = "/cache/use_konik"; - prepareKonikServerSwitch(state); - } - - if (!filePath.isEmpty()) { - QFile toggleFile(filePath); - if (state) { - if (!toggleFile.exists()) { - toggleFile.open(QIODevice::WriteOnly); - toggleFile.close(); - } - } else { - if (toggleFile.exists()) { - toggleFile.remove(); - } - } - } - - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - }); - } - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [deviceLayout, devicePanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - deviceLayout->setCurrentWidget(devicePanel); - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotDevicePanel::updateState); -} - -void StarPilotDevicePanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void StarPilotDevicePanel::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - started = s.scene.started; -} - -void StarPilotDevicePanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles && key == "HigherBitrate") { - setVisible &= params.getBool("DeviceManagement") && params.getBool("NoUploads") && !params.getBool("DisableOnroadUploads"); - } - - else if (key == "UseKonikServer" && QFile("/data/not_vetted").exists()) { - static_cast(toggle)->forceOn(true); - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (deviceManagementKeys.contains(key)) { - toggles["DeviceManagement"]->setVisible(true); - } else if (screenKeys.contains(key)) { - toggles["ScreenManagement"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/device_settings.h b/starpilot/ui/qt/offroad/device_settings.h deleted file mode 100644 index 8d152741a..000000000 --- a/starpilot/ui/qt/offroad/device_settings.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotDevicePanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotDevicePanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateState(const UIState &s); - void updateToggles(); - - bool forceOpenDescriptions; - bool started; - - std::map toggles; - - QSet deviceManagementKeys = {"DeviceShutdown", "DisableWideRoad", "HigherBitrate", "IncreaseThermalLimits", "LowVoltageShutdown", "NoLogging", "NoUploads", "UseKonikServer"}; - QSet screenKeys = {"ScreenBrightness", "ScreenBrightnessOnroad", "ScreenRecorder", "ScreenTimeout", "ScreenTimeoutOnroad", "StandbyMode"}; - - QSet parentKeys; - - StarPilotSettingsWindow *parent; - - Params params; -}; diff --git a/starpilot/ui/qt/offroad/expandable_multi_option_dialog.cc b/starpilot/ui/qt/offroad/expandable_multi_option_dialog.cc deleted file mode 100644 index 573c578ce..000000000 --- a/starpilot/ui/qt/offroad/expandable_multi_option_dialog.cc +++ /dev/null @@ -1,769 +0,0 @@ -#include "starpilot/ui/qt/offroad/expandable_multi_option_dialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "selfdrive/ui/qt/widgets/scrollview.h" - -ExpandableMultiOptionDialog::ExpandableMultiOptionDialog(const QString &prompt_text, - const QMap &seriesToModels, - const QString ¤t, QWidget *parent, - const QStringList &userFavorites, - const QStringList &communityFavorites, - const QMap &modelReleasedDates, - const QMap &modelFileToNameMap, - const QString &initialSortMode) - : DialogBase(parent), seriesToModels(seriesToModels), currentSortMode(initialSortMode.isEmpty() ? QString("alphabetical") : initialSortMode), - userFavorites(userFavorites), communityFavorites(communityFavorites), modelReleasedDates(modelReleasedDates), - modelFileToNameMap(modelFileToNameMap), currentSelection(current) { - - baseSeriesToModels = seriesToModels; - - for (auto it = this->modelFileToNameMap.constBegin(); it != this->modelFileToNameMap.constEnd(); ++it) { - modelNameToFileMap.insert(it.value(), it.key()); - } - - for (auto it = seriesToModels.constBegin(); it != seriesToModels.constEnd(); ++it) { - const QStringList &models = it.value(); - for (const QString &modelName : models) { - if (modelName.isEmpty() || modelNameToFileMap.contains(modelName)) { - continue; - } - this->modelFileToNameMap.insert(modelName, modelName); - modelNameToFileMap.insert(modelName, modelName); - } - } - - currentSelectionKey = modelNameToFileMap.value(currentSelection); - if (!currentSelectionKey.isEmpty()) { - selectionKey = currentSelectionKey; - selection = this->modelFileToNameMap.value(currentSelectionKey, currentSelection); - currentSelection = selection; - } else { - selectionKey.clear(); - selection.clear(); - currentSelection.clear(); - } - - if (currentSortMode != "alphabetical" && currentSortMode != "date" && - currentSortMode != "favorites" && currentSortMode != "date_oldest") { - currentSortMode = "alphabetical"; - } - - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; } - QPushButton { - height: 135; - padding: 0px 50px; - text-align: left; - font-size: 55px; - font-weight: 300; - border-radius: 10px; - background-color: #4F4F4F; - border: 2px solid transparent; - } - QPushButton.model-option:checked { - background-color: #465BEA !important; - border: 3px solid #FFFFFF !important; - color: white !important; - font-weight: 500 !important; - } - QPushButton:hover { background-color: #5A5A5A; } - QPushButton.model-option:checked:hover { background-color: #5A6BEA; } - QPushButton:pressed { - background-color: #3049F4; - } - QPushButton.model-option:checked:pressed { - background-color: #3049F4; - border: 3px solid #CCCCCC; - } - QPushButton.series-header { - background-color: #333333; - font-weight: 500; - text-align: left; - padding-left: 80px; - } - QPushButton.series-header:hover { background-color: #404040; } - QPushButton.favorite-button { - background-color: transparent; - border: none; - font-size: 60px; - padding: 0px; - margin: 0px; - min-width: 80px; - max-width: 80px; - } - QPushButton.favorite-button:hover { background-color: #404040; } - QComboBox { - background-color: #4F4F4F; - border: 2px solid transparent; - border-radius: 10px; - padding: 10px; - font-size: 50px; - color: white; - min-width: 200px; - } - QComboBox:hover { background-color: #5A5A5A; } - QComboBox::drop-down { - border: none; - width: 50px; - } - QComboBox::down-arrow { - image: url("../../starpilot/assets/toggle_icons/icon_dropdown.png"); - width: 30px; - height: 30px; - } - QComboBox QAbstractItemView { - background-color: #4F4F4F; - border: 2px solid #FFFFFF; - border-radius: 10px; - color: white; - selection-background-color: #465BEA; - font-size: 50px; - } - )"); - - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(55, 50, 55, 50); - - QLabel *title = new QLabel(prompt_text, this); - title->setStyleSheet("font-size: 70px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - main_layout->addSpacing(25); - - // Sort controls - simple cycling button - QHBoxLayout *sortLayout = new QHBoxLayout(); - sortLayout->setContentsMargins(0, 0, 0, 0); - sortLayout->setSpacing(20); - sortLayout->addStretch(); // Push to the right - - QLabel *sortLabel = new QLabel(tr("Sort by:"), this); - sortLabel->setStyleSheet("font-size: 50px; color: white;"); - sortLayout->addWidget(sortLabel); - - QPushButton *sortButton = new QPushButton(tr("Alphabetical"), this); - sortButton->setFocusPolicy(Qt::NoFocus); - sortButton->setAutoDefault(false); - sortButton->setDefault(false); - sortButton->setFixedWidth(420); - sortButton->setStyleSheet(R"( - QPushButton { - background-color: #4F4F4F; - border: 2px solid transparent; - border-radius: 10px; - padding: 10px 20px; - font-size: 50px; - color: white; - text-align: center; - } - QPushButton:hover { background-color: #5A5A5A; } - )"); - - // Set initial button text based on sort mode - if (currentSortMode == "date") { - sortButton->setText(tr("Date (Newest)")); - } else if (currentSortMode == "date_oldest") { - sortButton->setText(tr("Date (Oldest)")); - } else if (currentSortMode == "favorites") { - sortButton->setText(tr("Favorites First")); - } else { - sortButton->setText(tr("Alphabetical")); - } - - QWidget *sortWidget = new QWidget(container); - sortWidget->setLayout(sortLayout); - sortWidget->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); - sortLayout->setSizeConstraint(QLayout::SetFixedSize); - sortWidget->setStyleSheet("background: transparent;"); - - sortLayout->addWidget(sortButton); - - auto updateSortOverlayGeometry = [sortWidget, sortLayout]() { - if (!sortWidget) return; - const QSize hint = sortLayout->sizeHint(); - sortWidget->setFixedSize(hint); - }; - updateSortOverlayGeometry(); - - QObject::connect(sortButton, &QPushButton::clicked, [this, sortButton, updateSortOverlayGeometry]() { - if (currentSortMode == "alphabetical") { - currentSortMode = "date"; - sortButton->setText(tr("Date (Newest)")); - } else if (currentSortMode == "date") { - currentSortMode = "date_oldest"; - sortButton->setText(tr("Date (Oldest)")); - } else if (currentSortMode == "date_oldest") { - currentSortMode = "favorites"; - sortButton->setText(tr("Favorites First")); - } else { - currentSortMode = "alphabetical"; - sortButton->setText(tr("Alphabetical")); - } - updateSortOverlayGeometry(); - updateSorting(); - }); - - listWidgetContainer = new QWidget(this); - listLayout = new QVBoxLayout(listWidgetContainer); - listLayout->setSpacing(10); - listLayout->setContentsMargins(0, 0, 0, 0); - - confirmButton = new QPushButton(tr("Select")); - confirmButton->setObjectName("confirm_btn"); - confirmButton->setEnabled(!selectionKey.isEmpty()); - - scrollView = new ScrollView(listWidgetContainer, this); - scrollView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - if (scrollView->viewport()) { - scrollView->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true); - } - - QWidget *listContainer = new QWidget(container); - QGridLayout *overlayLayout = new QGridLayout(listContainer); - overlayLayout->setContentsMargins(0, 0, 0, 0); - overlayLayout->setSpacing(0); - overlayLayout->addWidget(scrollView, 0, 0); - overlayLayout->setRowStretch(0, 1); - overlayLayout->setColumnStretch(0, 1); - overlayLayout->addWidget(sortWidget, 0, 0, Qt::AlignRight | Qt::AlignTop); - - // Create series headers and their expandable content - rebuildModelList(seriesToModels.keys(), seriesToModels); - - main_layout->addWidget(listContainer); - main_layout->addSpacing(35); - - // Cancel + confirm buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *cancel_btn = new QPushButton(tr("Cancel")); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - QObject::connect(confirmButton, &QPushButton::clicked, this, &ConfirmationDialog::accept); - blayout->addWidget(cancel_btn); - blayout->addWidget(confirmButton); - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(50, 50, 50, 50); - outer_layout->addWidget(container); - - // Initial sorting - updateSorting(); -} - -void ExpandableMultiOptionDialog::toggleSeries(const QString &series, QPushButton *headerButton) { - if (!headerButton) return; - - QWidget *container = seriesWidgets.value(series, nullptr); - if (!container) return; - - bool expanded = seriesExpanded[series]; - QString seriesName = series; - - if (expanded) { - container->hide(); - seriesExpanded[series] = false; - headerButton->setText("▶ " + seriesName); - } else { - container->show(); - seriesExpanded[series] = true; - headerButton->setText("▼ " + seriesName); - - // Auto-scroll to place the series at the top of the viewport when expanded - if (scrollView) { - QPointer headerPtr(headerButton); - QPointer scrollPtr(scrollView); - QTimer::singleShot(50, [headerPtr, scrollPtr]() { - if (!scrollPtr || !headerPtr) return; - QWidget *contents = scrollPtr->widget(); - if (!contents) return; - if (QScrollBar *vScrollBar = scrollPtr->verticalScrollBar()) { - QPoint headerTop = headerPtr->mapTo(contents, QPoint(0, 0)); - int targetValue = qMax(headerTop.y() - 20, 0); - vScrollBar->setValue(targetValue); - } - }); - } - } - - // Update the button's appearance - headerButton->update(); -} - -QString ExpandableMultiOptionDialog::getSelection(const QString &prompt_text, - const QMap &seriesToModels, - const QString ¤t, QWidget *parent, - const QStringList &userFavorites, - const QStringList &communityFavorites, - const QMap &modelReleasedDates, - const QMap &modelFileToNameMap, - const QString &initialSortMode) { - ExpandableMultiOptionDialog d(prompt_text, seriesToModels, current, parent, - userFavorites, communityFavorites, modelReleasedDates, modelFileToNameMap, initialSortMode); - if (d.exec()) { - return d.selection; - } - return ""; -} - -QStringList ExpandableMultiOptionDialog::getUserFavorites() const { - QStringList filteredFavorites; - for (const QString &fav : userFavorites) { - if (modelFileToNameMap.contains(fav) && !filteredFavorites.contains(fav)) { - filteredFavorites.append(fav); - } - } - return filteredFavorites; -} - -void ExpandableMultiOptionDialog::stopActiveScroll() { - if (!scrollView) { - return; - } - - if (QScroller *scroller = QScroller::scroller(scrollView->viewport())) { - if (scroller->state() == QScroller::Scrolling) { - scroller->stop(); - } - } -} - -void ExpandableMultiOptionDialog::stopActiveScrollForInteraction() { - if (!scrollView) { - return; - } - - if (QScroller *scroller = QScroller::scroller(scrollView->viewport())) { - const QScroller::State state = scroller->state(); - if (state == QScroller::Scrolling || state == QScroller::Dragging || state == QScroller::Pressed) { - scroller->stop(); - } - } -} - -void ExpandableMultiOptionDialog::createModelButton(const QString &modelKey, const QString &modelName, const QString &displayName, - QVBoxLayout *layout) { - QString effectiveKey = modelKey.isEmpty() ? modelName : modelKey; - if (effectiveKey.isEmpty()) { - return; - } - - if (!modelFileToNameMap.contains(effectiveKey)) { - const QString storedName = !modelName.isEmpty() ? modelName : displayName; - modelFileToNameMap.insert(effectiveKey, storedName); - } - - if (!modelName.isEmpty()) { - modelNameToFileMap.insert(modelName, effectiveKey); - } - - QWidget *modelWidget = new QWidget(); - QHBoxLayout *modelLayout = new QHBoxLayout(modelWidget); - modelLayout->setContentsMargins(0, 0, 0, 0); - modelLayout->setSpacing(10); - - // Star button - QPushButton *starButton = new QPushButton(); - starButton->setProperty("class", "favorite-button"); - starButton->setCheckable(true); - starButton->setCursor(Qt::PointingHandCursor); - starButton->setFocusPolicy(Qt::NoFocus); - - // Check if this model is a favorite - bool isCommunityFav = communityFavorites.contains(effectiveKey); - bool isUserFav = userFavorites.contains(effectiveKey); - bool isFavorite = isCommunityFav || isUserFav; - - starButton->setChecked(isFavorite); - starButton->setText(isFavorite ? QString::fromUtf16(u"\u2665") : QString::fromUtf16(u"\u2661")); - - QObject::connect(starButton, &QPushButton::clicked, [this, effectiveKey]() { - stopActiveScrollForInteraction(); - toggleFavorite(effectiveKey); - }); - - favoriteButtons[effectiveKey].append(starButton); - modelLayout->addWidget(starButton); - - // Model button - QPushButton *modelButton = new QPushButton(displayName); - modelButton->setCheckable(true); - modelButton->setProperty("class", "model-option"); - modelButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - modelButton->setCursor(Qt::PointingHandCursor); - modelButton->setFocusPolicy(Qt::NoFocus); - modelButton->setProperty("modelKey", effectiveKey); - modelButton->setProperty("modelName", modelName); - - modelButtons[effectiveKey].append(modelButton); - if (selectionKey == effectiveKey && currentSelectionButton.isNull()) { - currentSelectionButton = modelButton; - } - modelLayout->addWidget(modelButton); - - const QString resolvedSelection = modelFileToNameMap.value(effectiveKey, !modelName.isEmpty() ? modelName : displayName); - - QObject::connect(modelButton, &QPushButton::clicked, this, [this, effectiveKey, modelButton, resolvedSelection]() { - stopActiveScrollForInteraction(); - selectionKey = effectiveKey; - currentSelectionKey = effectiveKey; - selection = resolvedSelection; - currentSelection = resolvedSelection; - currentSelectionButton = modelButton; - if (confirmButton) { - confirmButton->setEnabled(true); - } - - updateButtonStyles(); - }); - - layout->addWidget(modelWidget); -} - -void ExpandableMultiOptionDialog::toggleFavorite(const QString &modelKey) { - // Update local state - if (modelKey.isEmpty()) { - return; - } - - if (userFavorites.contains(modelKey)) { - userFavorites.removeAll(modelKey); - } else { - userFavorites.append(modelKey); - } - - updateSorting(); -} - -void ExpandableMultiOptionDialog::updateSorting() { - const QString favoritesSeriesName = QStringLiteral("♥ Favorites"); - QMap newSeriesToModels; - QStringList orderedSeries; - QSet validSeries; - QSet favoriteModelKeys; - QSet availableModelKeys; - displayOverrides.clear(); - - const bool sortByDate = (currentSortMode == "date" || currentSortMode == "date_oldest"); - const bool sortDateNewestFirst = (currentSortMode == "date"); - - for (auto it = baseSeriesToModels.constBegin(); it != baseSeriesToModels.constEnd(); ++it) { - const QStringList &models = it.value(); - for (const QString &modelName : models) { - const QString modelKey = modelNameToFileMap.value(modelName, modelName); - if (!modelKey.isEmpty()) { - availableModelKeys.insert(modelKey); - } - } - } - - if (currentSortMode == "favorites") { - QStringList favoritesList; - - for (const QString &modelKey : communityFavorites) { - if (availableModelKeys.contains(modelKey)) { - const QString modelName = modelFileToNameMap.value(modelKey); - favoritesList.append(modelName); - favoriteModelKeys.insert(modelKey); - displayOverrides.insert(modelKey, tr("%1 (Community Fav)").arg(modelName)); - } - } - - for (const QString &modelKey : userFavorites) { - if (availableModelKeys.contains(modelKey) && !favoriteModelKeys.contains(modelKey)) { - favoritesList.append(modelFileToNameMap.value(modelKey)); - favoriteModelKeys.insert(modelKey); - } - } - - if (!favoritesList.isEmpty()) { - std::sort(favoritesList.begin(), favoritesList.end()); - newSeriesToModels.insert(favoritesSeriesName, favoritesList); - orderedSeries.append(favoritesSeriesName); - validSeries.insert(favoritesSeriesName); - seriesExpanded.insert(favoritesSeriesName, true); - } else { - seriesExpanded.remove(favoritesSeriesName); - } - } else { - seriesExpanded.remove(favoritesSeriesName); - } - - struct SeriesInfo { - QString name; - QStringList models; - QString newestDate; - QString oldestDate; - }; - - QVector seriesInfos; - - for (auto it = baseSeriesToModels.constBegin(); it != baseSeriesToModels.constEnd(); ++it) { - QString series = it.key(); - QStringList models = it.value(); - - if (sortByDate) { - std::sort(models.begin(), models.end(), [this, sortDateNewestFirst](const QString &a, const QString &b) { - QString keyA = modelNameToFileMap.value(a, a); - QString keyB = modelNameToFileMap.value(b, b); - QString dateA = modelReleasedDates.value(keyA, QStringLiteral("1970-01-01")); - QString dateB = modelReleasedDates.value(keyB, QStringLiteral("1970-01-01")); - if (dateA == dateB) { - return a < b; - } - return sortDateNewestFirst ? (dateA > dateB) : (dateA < dateB); - }); - } else { - std::sort(models.begin(), models.end()); - } - - if (currentSortMode == "favorites" && !favoriteModelKeys.isEmpty()) { - QStringList filteredModels; - for (const QString &modelName : models) { - QString key = modelNameToFileMap.value(modelName, modelName); - if (!favoriteModelKeys.contains(key)) { - filteredModels.append(modelName); - } - } - models = filteredModels; - } - - if (models.isEmpty()) { - continue; - } - - QString newestDate = QStringLiteral("1970-01-01"); - QString oldestDate = QStringLiteral("1970-01-01"); - bool hasDate = false; - for (const QString &modelName : models) { - const QString key = modelNameToFileMap.value(modelName, modelName); - const QString date = modelReleasedDates.value(key, QStringLiteral("1970-01-01")); - if (!hasDate) { - newestDate = date; - oldestDate = date; - hasDate = true; - } else { - if (date > newestDate) { - newestDate = date; - } - if (date < oldestDate) { - oldestDate = date; - } - } - } - - if (!hasDate) { - oldestDate = QStringLiteral("1970-01-01"); - } - - seriesInfos.push_back({series, models, newestDate, oldestDate}); - newSeriesToModels.insert(series, models); - } - - if (sortByDate) { - std::sort(seriesInfos.begin(), seriesInfos.end(), [sortDateNewestFirst](const SeriesInfo &a, const SeriesInfo &b) { - if (sortDateNewestFirst) { - if (a.newestDate == b.newestDate) { - return a.name < b.name; - } - return a.newestDate > b.newestDate; - } else { - if (a.oldestDate == b.oldestDate) { - return a.name < b.name; - } - return a.oldestDate < b.oldestDate; - } - }); - } else { - std::sort(seriesInfos.begin(), seriesInfos.end(), [](const SeriesInfo &a, const SeriesInfo &b) { - return a.name < b.name; - }); - } - - for (const SeriesInfo &info : seriesInfos) { - orderedSeries.append(info.name); - validSeries.insert(info.name); - } - - for (auto it = seriesExpanded.begin(); it != seriesExpanded.end(); ) { - if (!validSeries.contains(it.key())) { - it = seriesExpanded.erase(it); - } else { - ++it; - } - } - - rebuildModelList(orderedSeries, newSeriesToModels); - refreshFavoriteIcons(); -} - -void ExpandableMultiOptionDialog::rebuildModelList(const QStringList &orderedSeries, const QMap &newSeriesToModels) { - if (!listLayout) return; - - stopActiveScroll(); - - while (QLayoutItem *item = listLayout->takeAt(0)) { - if (QWidget *w = item->widget()) { - delete w; - } else if (QLayout *layout = item->layout()) { - delete layout; - } - delete item; - } - - seriesWidgets.clear(); - modelButtons.clear(); - favoriteButtons.clear(); - currentSelectionButton = nullptr; - - for (const QString &series : orderedSeries) { - const QStringList models = newSeriesToModels.value(series); - if (models.isEmpty()) { - continue; - } - - QPushButton *seriesHeader = new QPushButton("▶ " + series); - seriesHeader->setProperty("class", "series-header"); - seriesHeader->setCheckable(false); - - bool expanded = seriesExpanded.value(series, false); - seriesExpanded.insert(series, expanded); - - QObject::connect(seriesHeader, &QPushButton::clicked, [this, series, seriesHeader]() { - toggleSeries(series, seriesHeader); - }); - - QWidget *seriesContainer = new QWidget(); - QVBoxLayout *seriesLayout = new QVBoxLayout(seriesContainer); - seriesLayout->setContentsMargins(20, 0, 0, 0); - seriesLayout->setSpacing(10); - - for (const QString &modelName : models) { - QString modelKey = modelNameToFileMap.value(modelName, modelName); - if (!modelFileToNameMap.contains(modelKey)) { - modelFileToNameMap.insert(modelKey, modelName); - } - QString displayName = displayOverrides.value(modelKey, modelName); - createModelButton(modelKey, modelName, displayName, seriesLayout); - } - - if (expanded) { - seriesContainer->show(); - seriesHeader->setText("▼ " + series); - } else { - seriesContainer->hide(); - seriesHeader->setText("▶ " + series); - } - - seriesWidgets.insert(series, seriesContainer); - - listLayout->addWidget(seriesHeader); - listLayout->addWidget(seriesContainer); - } - - listLayout->addStretch(1); - - seriesToModels = newSeriesToModels; - - listWidgetContainer->updateGeometry(); - listWidgetContainer->adjustSize(); - if (scrollView && scrollView->widget()) { - scrollView->widget()->updateGeometry(); - scrollView->widget()->adjustSize(); - } - - updateButtonStyles(); -} - -void ExpandableMultiOptionDialog::refreshFavoriteIcons() { - for (auto it = favoriteButtons.begin(); it != favoriteButtons.end(); ++it) { - const QString &modelKey = it.key(); - const QList &buttons = it.value(); - bool isCommunityFav = communityFavorites.contains(modelKey); - bool isUserFav = userFavorites.contains(modelKey); - bool isFavorite = isCommunityFav || isUserFav; - - for (QPushButton *button : buttons) { - if (!button) continue; - button->setChecked(isFavorite); - button->setText(isFavorite ? QString::fromUtf16(u"\u2665") : QString::fromUtf16(u"\u2661")); - } - } - - if (confirmButton && !selectionKey.isEmpty()) { - confirmButton->setEnabled(true); - } - - updateButtonStyles(); -} - -void ExpandableMultiOptionDialog::updateButtonStyles() { - const QString selectedKey = selectionKey; - const QString selectedStyle = QStringLiteral( - "QPushButton {" - "background-color: #465BEA;" - "border: 3px solid #FFFFFF;" - "color: white;" - "font-weight: 500;" - "height: 135;" - "padding: 0px 50px;" - "text-align: left;" - "font-size: 55px;" - "border-radius: 10px;" - "}"); - - if (selectedKey.isEmpty()) { - currentSelectionButton = nullptr; - } - - QPushButton *explicitButton = currentSelectionButton.data(); - if (explicitButton && explicitButton->property("modelKey").toString() != selectedKey) { - explicitButton = nullptr; - } - - for (auto it = modelButtons.begin(); it != modelButtons.end(); ++it) { - const QString &modelKey = it.key(); - const QList &buttons = it.value(); - const bool keyMatches = (!selectedKey.isEmpty() && modelKey == selectedKey); - bool activatedForKey = false; - - for (QPushButton *button : buttons) { - if (!button) continue; - - bool isActive = false; - if (explicitButton) { - isActive = (button == explicitButton); - } else if (keyMatches && !activatedForKey) { - isActive = true; - activatedForKey = true; - currentSelectionButton = button; - } - - QSignalBlocker blocker(button); - button->setChecked(isActive); - button->setStyleSheet(isActive ? selectedStyle : QString()); - } - } -} diff --git a/starpilot/ui/qt/offroad/expandable_multi_option_dialog.h b/starpilot/ui/qt/offroad/expandable_multi_option_dialog.h deleted file mode 100644 index 2c0b1e61d..000000000 --- a/starpilot/ui/qt/offroad/expandable_multi_option_dialog.h +++ /dev/null @@ -1,76 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -class QPushButton; -class ExpandableMultiOptionDialog : public DialogBase { - Q_OBJECT - -public: - explicit ExpandableMultiOptionDialog(const QString &prompt_text, const QMap &seriesToModels, - const QString ¤t, QWidget *parent, - const QStringList &userFavorites = QStringList(), - const QStringList &communityFavorites = QStringList(), - const QMap &modelReleasedDates = QMap(), - const QMap &modelFileToNameMap = QMap(), - const QString &initialSortMode = "alphabetical"); - static QString getSelection(const QString &prompt_text, const QMap &seriesToModels, - const QString ¤t, QWidget *parent, - const QStringList &userFavorites = QStringList(), - const QStringList &communityFavorites = QStringList(), - const QMap &modelReleasedDates = QMap(), - const QMap &modelFileToNameMap = QMap(), - const QString &initialSortMode = QString()); - QString selection; - - QString getCurrentSortMode() const { return currentSortMode; } - QStringList getUserFavorites() const; - -private: - void toggleSeries(const QString &series, QPushButton *headerButton); - void toggleFavorite(const QString &modelKey); - void updateSorting(); - void rebuildModelList(const QStringList &orderedSeries, const QMap &newSeriesToModels); - void createModelButton(const QString &modelKey, const QString &modelName, const QString &displayName, - QVBoxLayout *layout); - void refreshFavoriteIcons(); - void updateButtonStyles(); - void stopActiveScroll(); - void stopActiveScrollForInteraction(); - - QMap seriesToModels; - QMap baseSeriesToModels; - QMap seriesWidgets; - QMap seriesExpanded; - QMap> modelButtons; - QMap> favoriteButtons; - - QStringList userFavorites; - QStringList communityFavorites; - QMap modelReleasedDates; - QMap modelFileToNameMap; - QMap modelNameToFileMap; - QMap displayOverrides; - - QString currentSortMode; - QString currentSelection; - QString currentSelectionKey; - QString selectionKey; - - ScrollView *scrollView = nullptr; - QVBoxLayout *listLayout = nullptr; - QPushButton *confirmButton = nullptr; - QWidget *listWidgetContainer = nullptr; - QPointer currentSelectionButton; -}; diff --git a/starpilot/ui/qt/offroad/lateral_settings.cc b/starpilot/ui/qt/offroad/lateral_settings.cc deleted file mode 100644 index 555268428..000000000 --- a/starpilot/ui/qt/offroad/lateral_settings.cc +++ /dev/null @@ -1,447 +0,0 @@ -#include "starpilot/ui/qt/offroad/lateral_settings.h" - -StarPilotLateralPanel::StarPilotLateralPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *lateralLayout = new QStackedLayout(); - addItem(lateralLayout); - - StarPilotListWidget *lateralList = new StarPilotListWidget(this); - - ScrollView *lateralPanel = new ScrollView(lateralList, this); - - lateralLayout->addWidget(lateralPanel); - - StarPilotListWidget *advancedLateralTuneList = new StarPilotListWidget(this); - StarPilotListWidget *aolList = new StarPilotListWidget(this); - StarPilotListWidget *laneChangeList = new StarPilotListWidget(this); - StarPilotListWidget *lateralTuneList = new StarPilotListWidget(this); - StarPilotListWidget *qolList = new StarPilotListWidget(this); - - ScrollView *advancedLateralTunePanel = new ScrollView(advancedLateralTuneList, this); - ScrollView *aolPanel = new ScrollView(aolList, this); - ScrollView *laneChangePanel = new ScrollView(laneChangeList, this); - ScrollView *lateralTunePanel = new ScrollView(lateralTuneList, this); - ScrollView *qolPanel = new ScrollView(qolList, this); - - lateralLayout->addWidget(advancedLateralTunePanel); - lateralLayout->addWidget(aolPanel); - lateralLayout->addWidget(laneChangePanel); - lateralLayout->addWidget(lateralTunePanel); - lateralLayout->addWidget(qolPanel); - - const std::vector> lateralToggles { - {"AdvancedLateralTune", tr("Advanced Lateral Tuning"), tr("Advanced steering control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_advanced_lateral_tune.png"}, - {"SteerDelay", parent->steerActuatorDelay != 0 ? QString(tr("Actuator Delay (Default: %1)")).arg(QString::number(parent->steerActuatorDelay, 'f', 2)) : tr("Actuator Delay"), tr("The time between openpilot's steering command and the vehicle's response. Increase if the vehicle reacts late; decrease if it feels jumpy. Auto-learned by default."), ""}, - {"SteerFriction", parent->friction != 0 ? QString(tr("Friction (Default: %1)")).arg(QString::number(parent->friction, 'f', 2)) : tr("Friction"), tr("Compensates for steering friction. Increase if the wheel sticks near center; decrease if it jitters. Auto-learned by default."), ""}, - {"SteerKP", parent->steerKp != 0 ? QString(tr("Kp Factor (Default: %1)")).arg(QString::number(parent->steerKp, 'f', 2)) : tr("Kp Factor"), tr("How strongly openpilot corrects lane position. Higher is tighter but twitchier; lower is smoother but slower. Auto-learned by default."), ""}, - {"SteerLatAccel", parent->latAccelFactor != 0 ? QString(tr("Lateral Acceleration (Default: %1)")).arg(QString::number(parent->latAccelFactor, 'f', 2)) : tr("Lateral Acceleration"), tr("Maps steering torque to turning response. Increase for sharper turns; decrease for gentler steering. Auto-learned by default."), ""}, - {"SteerRatio", parent->steerRatio != 0 ? QString(tr("Steer Ratio (Default: %1)")).arg(QString::number(parent->steerRatio, 'f', 2)) : tr("Steer Ratio"), tr("The relationship between steering wheel rotation and road wheel angle. Increase if steering feels too quick or twitchy; decrease if it feels too slow or weak. Auto-learned by default."), ""}, - {"ForceAutoTune", tr("Force Auto-Tune On"), tr("Force-enable openpilot's live auto-tuning for \"Friction\" and \"Lateral Acceleration\"."), ""}, - {"ForceAutoTuneOff", tr("Force Auto-Tune Off"), tr("Force-disable openpilot's live auto-tuning for \"Friction\" and \"Lateral Acceleration\" and use the set value instead."), ""}, - {"ForceTorqueController", tr("Force Torque Controller"), tr("Use torque-based steering control instead of angle-based control for smoother lane keeping, especially in curves."), ""}, - - {"AlwaysOnLateral", tr("Always On Lateral"), tr("openpilot's steering remains active even when the accelerator or brake pedals are pressed."), "../../starpilot/assets/toggle_icons/icon_always_on_lateral.png"}, - {"PauseAOLOnBrake", tr("Pause on Brake Press Below"), tr("Pause \"Always On Lateral\" below the set speed while the brake pedal is pressed."), ""}, - - {"LaneChanges", tr("Lane Changes"), tr("Allow openpilot to change lanes."), "../../starpilot/assets/toggle_icons/icon_lane.png"}, - {"NudgelessLaneChange", tr("Automatic Lane Changes"), tr("When the turn signal is on, openpilot will automatically change lanes. No steering-wheel nudge required!"), ""}, - {"LaneChangeTime", tr("Lane Change Delay"), tr("Delay between turn signal activation and the start of an automatic lane change."), ""}, - {"MinimumLaneChangeSpeed", tr("Minimum Lane Change Speed"), tr("Lowest speed at which openpilot will change lanes."), ""}, - {"LaneDetectionWidth", tr("Minimum Lane Width"), tr("Prevent automatic lane changes into lanes narrower than the set width."), ""}, - {"OneLaneChange", tr("One Lane Change Per Signal"), tr("Limit automatic lane changes to one per turn-signal activation."), ""}, - {"LaneChangeSmoothing", tr("Lane Change Smoothing"), tr("Controls how smoothly openpilot commits to a lane change. 10 is stock behavior; lower values produce a gentler, more gradual maneuver. 1 stretches the maneuver to ~8 seconds."), ""}, - - {"LateralTune", tr("Lateral Tuning"), tr("Miscellaneous steering control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_lateral_tune.png"}, - {"TurnDesires", tr("Force Turn Desires Below Lane Change Speed"), tr("While driving below the minimum lane change speed with an active turn signal, instruct openpilot to turn left/right."), ""}, - {"NavDesiresAllowed", tr("Use Route Desires"), tr("Allow an active navigation route to request keep-left, keep-right, and low-speed turn desires."), ""}, - {"NNFF", tr("Neural Network Feedforward (NNFF)"), tr("Twilsonco's \"Neural Network FeedForward\" controller. Uses a trained neural network model to predict steering torque based on vehicle speed, roll, and past/future planned path data for smoother, model-based steering."), ""}, - {"NNFFLite", tr("Neural Network Feedforward (NNFF) Lite"), tr("A lightweight version of Twilsonco's \"Neural Network FeedForward\" controller. Uses the \"look-ahead\" planned lateral jerk logic from the full model to help smoothen steering adjustments in curves, but does not use the full neural network for torque calculation."), ""}, - - {"QOLLateral", tr("Quality of Life"), tr("Steering control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_quality_of_life.png"}, - {"PauseLateralSpeed", tr("Pause Steering Below"), tr("Pause steering below the set speed."), ""}, - {"LateralResumeDelay", tr("Lateral Resume Delay"), tr("Delay before lateral control resumes after the turn signal is turned off. Only applies when the vehicle speed dropped below half the \"Pause Steering Below\" speed during the turn signal. Set to 0 to disable."), ""} - }; - - for (const auto &[param, title, desc, icon] : lateralToggles) { - AbstractControl *lateralToggle; - - if (param == "AdvancedLateralTune") { - StarPilotManageControl *advancedLateralTuneToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(advancedLateralTuneToggle, &StarPilotManageControl::manageButtonClicked, [lateralLayout, advancedLateralTunePanel]() { - lateralLayout->setCurrentWidget(advancedLateralTunePanel); - }); - lateralToggle = advancedLateralTuneToggle; - } else if (param == "SteerDelay") { - std::vector steerDelayButton{"Reset"}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0.01, 1, QString(), std::map(), 0.01, false, {}, steerDelayButton, false, false); - } else if (param == "SteerFriction") { - std::vector steerFrictionButton{"Reset"}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0, 1, QString(), std::map(), 0.01, false, {}, steerFrictionButton, false, false); - } else if (param == "SteerKP") { - std::vector steerKPButton{"Reset"}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, parent->steerKp * 0.5, parent->steerKp * 1.5, QString(), std::map(), 0.01, false, {}, steerKPButton, false, false); - } else if (param == "SteerLatAccel") { - std::vector steerLatAccelButton{"Reset"}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, parent->latAccelFactor * 0.5, parent->latAccelFactor * 1.5, QString(), std::map(), 0.01, false, {}, steerLatAccelButton, false, false); - } else if (param == "SteerRatio") { - std::vector steerRatioButton{"Reset"}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, parent->steerRatio * 0.5, parent->steerRatio * 1.5, QString(), std::map(), 0.01, false, {}, steerRatioButton, false, false); - - } else if (param == "AlwaysOnLateral") { - StarPilotManageControl *aolToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(aolToggle, &StarPilotManageControl::manageButtonClicked, [lateralLayout, aolPanel]() { - lateralLayout->setCurrentWidget(aolPanel); - }); - lateralToggle = aolToggle; - } else if (param == "PauseAOLOnBrake") { - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, QString(), std::map(), 1, true); - - } else if (param == "LaneChanges") { - StarPilotManageControl *laneChangeToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(laneChangeToggle, &StarPilotManageControl::manageButtonClicked, [lateralLayout, laneChangePanel]() { - lateralLayout->setCurrentWidget(laneChangePanel); - }); - lateralToggle = laneChangeToggle; - } else if (param == "LaneChangeTime") { - std::map laneChangeTimeLabels; - for (float i = 0; i <= 5; i += 0.1) { - laneChangeTimeLabels[i] = i == 0 ? tr("Instant") : std::lround(i / 0.1) == 1 / 0.1 ? QString::number(i, 'f', 1) + tr(" second") : QString::number(i, 'f', 1) + tr(" seconds"); - } - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 5, QString(), laneChangeTimeLabels, 0.1); - } else if (param == "LaneDetectionWidth") { - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 15, QString(), std::map(), 0.1, true); - } else if (param == "MinimumLaneChangeSpeed") { - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, QString(), std::map(), 1, true); - } else if (param == "LaneChangeSmoothing") { - std::map smoothingLabels; - smoothingLabels[10] = tr("Stock"); - smoothingLabels[1] = tr("Smoothest"); - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 1, 10, QString(), smoothingLabels, 1); - - } else if (param == "LateralTune") { - StarPilotManageControl *lateralTuneToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(lateralTuneToggle, &StarPilotManageControl::manageButtonClicked, [lateralLayout, lateralTunePanel]() { - lateralLayout->setCurrentWidget(lateralTunePanel); - }); - lateralToggle = lateralTuneToggle; - - } else if (param == "QOLLateral") { - StarPilotManageControl *qolLateralToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(qolLateralToggle, &StarPilotManageControl::manageButtonClicked, [lateralLayout, qolPanel]() { - lateralLayout->setCurrentWidget(qolPanel); - }); - lateralToggle = qolLateralToggle; - } else if (param == "PauseLateralSpeed") { - std::vector pauseLateralToggles{"PauseLateralOnSignal"}; - std::vector pauseLateralToggleNames{tr("Turn Signal Only")}; - lateralToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0, 99, QString(), std::map(), 1, true, pauseLateralToggles, pauseLateralToggleNames, true); - - } else if (param == "LateralResumeDelay") { - std::map delayLabels; - for (int i = 0; i <= 50; ++i) { - float key = i / 10.0f; - delayLabels[key] = key == 0.0f ? tr("Off") : QString::number(key, 'f', 1) + tr(" s"); - } - lateralToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 5, QString(), delayLabels, 0.1); - - } else { - lateralToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = lateralToggle; - - if (advancedLateralTuneKeys.contains(param)) { - advancedLateralTuneList->addItem(lateralToggle); - } else if (aolKeys.contains(param)) { - aolList->addItem(lateralToggle); - } else if (laneChangeKeys.contains(param)) { - laneChangeList->addItem(lateralToggle); - } else if (lateralTuneKeys.contains(param)) { - lateralTuneList->addItem(lateralToggle); - } else if (qolKeys.contains(param)) { - qolList ->addItem(lateralToggle); - } else { - lateralList->addItem(lateralToggle); - - parentKeys.insert(param); - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(lateralToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(lateralToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(lateralToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - QSet forceUpdateKeys = {"ForceAutoTune", "ForceAutoTuneOff", "LateralTune", "NNFF", "NudgelessLaneChange"}; - for (const QString &key : forceUpdateKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, this, &StarPilotLateralPanel::updateToggles); - } - - QSet rebootKeys = {"AlwaysOnLateral", "ForceTorqueController", "NNFF", "NNFFLite"}; - for (const QString &key : rebootKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, [key, this](bool state) { - if (started) { - if (key == "AlwaysOnLateral" && state) { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - } else if (key != "AlwaysOnLateral") { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - } - } - }); - } - - steerDelayToggle = static_cast(toggles["SteerDelay"]); - QObject::connect(steerDelayToggle, &StarPilotParamValueButtonControl::buttonClicked, [parent, this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Reset Actuator Delay to its default value?"), this)) { - params.putFloat("SteerDelay", parent->steerActuatorDelay); - steerDelayToggle->refresh(); - } - }); - - steerFrictionToggle = static_cast(toggles["SteerFriction"]); - QObject::connect(steerFrictionToggle, &StarPilotParamValueButtonControl::buttonClicked, [parent, this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Reset Friction to its default value?"), this)) { - params.putFloat("SteerFriction", parent->friction); - steerFrictionToggle->refresh(); - } - }); - - steerKPToggle = static_cast(toggles["SteerKP"]); - QObject::connect(steerKPToggle, &StarPilotParamValueButtonControl::buttonClicked, [parent, this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Reset Kp Factor to its default value?"), this)) { - params.putFloat("SteerKP", parent->steerKp); - steerKPToggle->refresh(); - } - }); - - steerLatAccelToggle = static_cast(toggles["SteerLatAccel"]); - QObject::connect(steerLatAccelToggle, &StarPilotParamValueButtonControl::buttonClicked, [parent, this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Reset Lateral Accel to its default value?"), this)) { - params.putFloat("SteerLatAccel", parent->latAccelFactor); - steerLatAccelToggle->refresh(); - } - }); - - steerRatioToggle = static_cast(toggles["SteerRatio"]); - QObject::connect(steerRatioToggle, &StarPilotParamValueButtonControl::buttonClicked, [parent, this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Reset Steer Ratio to its default value?"), this)) { - params.putFloat("SteerRatio", parent->steerRatio); - steerRatioToggle->refresh(); - } - }); - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [lateralLayout, lateralPanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - lateralLayout->setCurrentWidget(lateralPanel); - }); - QObject::connect(parent, &StarPilotSettingsWindow::updateMetric, this, &StarPilotLateralPanel::updateMetric); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotLateralPanel::updateState); -} - -void StarPilotLateralPanel::showEvent(QShowEvent *event) { - steerDelayToggle->setTitle(QString(tr("Actuator Delay (Default: %1)")).arg(QString::number(parent->steerActuatorDelay, 'f', 2))); - steerFrictionToggle->setTitle(QString(tr("Friction (Default: %1)")).arg(QString::number(parent->friction, 'f', 2))); - steerKPToggle->setTitle(QString(tr("Kp Factor (Default: %1)")).arg(QString::number(parent->steerKp, 'f', 2))); - steerKPToggle->updateControl(parent->steerKp * 0.5, parent->steerKp * 1.5); - steerLatAccelToggle->setTitle(QString(tr("Lateral Accel (Default: %1)")).arg(QString::number(parent->latAccelFactor, 'f', 2))); - steerLatAccelToggle->updateControl(parent->latAccelFactor * 0.5, parent->latAccelFactor * 1.5); - steerRatioToggle->setTitle(QString(tr("Steer Ratio (Default: %1)")).arg(QString::number(parent->steerRatio, 'f', 2))); - steerRatioToggle->updateControl(parent->steerRatio * 0.5, parent->steerRatio * 1.5); - - updateToggles(); -} - -void StarPilotLateralPanel::updateState(const UIState &s) { - if (!isVisible()) return; - - started = s.scene.started; -} - -void StarPilotLateralPanel::updateMetric(bool metric, bool bootRun) { - static bool previousMetric; - if (metric != previousMetric && !bootRun) { - double distanceConversion = metric ? FOOT_TO_METER : METER_TO_FOOT; - double speedConversion = metric ? MILE_TO_KM : KM_TO_MILE; - - params.putFloatNonBlocking("LaneDetectionWidth", params.getFloat("LaneDetectionWidth") * distanceConversion); - - params.putIntNonBlocking("MinimumLaneChangeSpeed", params.getInt("MinimumLaneChangeSpeed") * speedConversion); - params.putIntNonBlocking("PauseAOLOnBrake", params.getInt("PauseAOLOnBrake") * speedConversion); - params.putIntNonBlocking("PauseLateralSpeed", params.getInt("PauseLateralSpeed") * speedConversion); - } - previousMetric = metric; - - static std::map imperialDistanceLabels; - static std::map imperialSpeedLabels; - static std::map metricDistanceLabels; - static std::map metricSpeedLabels; - - static bool labelsInitialized = false; - if (!labelsInitialized) { - for (int i = 0; i <= 150; ++i) { - float key = i / 10.0f; - imperialDistanceLabels[key] = key == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" foot") : QString::number(key, 'f', 1) + tr(" feet"); - } - - for (int i = 0; i <= 99; ++i) { - imperialSpeedLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" mph"); - } - - for (int i = 0; i <= 50; ++i) { - float key = i / 10.0f; - metricDistanceLabels[key] = key == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" meter") : QString::number(key, 'f', 1) + tr(" meters"); - } - - for (int i = 0; i <= 150; ++i) { - metricSpeedLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" km/h"); - } - - labelsInitialized = true; - } - - StarPilotParamValueControl *laneWidthToggle = static_cast(toggles["LaneDetectionWidth"]); - StarPilotParamValueControl *minimumLaneChangeSpeedToggle = static_cast(toggles["MinimumLaneChangeSpeed"]); - StarPilotParamValueControl *pauseAOLOnBrakeToggle = static_cast(toggles["PauseAOLOnBrake"]); - StarPilotParamValueControl *pauseLateralToggle = static_cast(toggles["PauseLateralSpeed"]); - - if (metric) { - laneWidthToggle->updateControl(0, 5, metricDistanceLabels); - - minimumLaneChangeSpeedToggle->updateControl(0, 150, metricSpeedLabels); - pauseAOLOnBrakeToggle->updateControl(0, 150, metricSpeedLabels); - pauseLateralToggle->updateControl(0, 150, metricSpeedLabels); - } else { - laneWidthToggle->updateControl(0, 15, imperialDistanceLabels); - - minimumLaneChangeSpeedToggle->updateControl(0, 99, imperialSpeedLabels); - pauseAOLOnBrakeToggle->updateControl(0, 99, imperialSpeedLabels); - pauseLateralToggle->updateControl(0, 99, imperialSpeedLabels); - } -} - -void StarPilotLateralPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - bool forcingAutoTune = !parent->hasAutoTune && params.getBool("ForceAutoTune"); - bool forcingAutoTuneOff = parent->hasAutoTune && params.getBool("ForceAutoTuneOff"); - bool forcingTorqueController = !parent->isAngleCar && params.getBool("ForceTorqueController"); - bool usingNNFF = parent->hasNNFFLog && params.getBool("LateralTune") && params.getBool("NNFF"); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "ForceAutoTune") { - setVisible &= !parent->hasAutoTune; - setVisible &= !parent->isAngleCar; - setVisible &= parent->isTorqueCar || forcingTorqueController || usingNNFF; - } - - else if (key == "ForceAutoTuneOff") { - setVisible &= parent->hasAutoTune; - } - - else if (key == "ForceTorqueController") { - setVisible &= !parent->isAngleCar; - setVisible &= !parent->isTorqueCar; - } - - else if (key == "LaneChangeTime") { - setVisible &= params.getBool("LaneChanges") && params.getBool("NudgelessLaneChange"); - } - - else if (key == "LaneDetectionWidth") { - setVisible &= params.getBool("LaneChanges") && params.getBool("NudgelessLaneChange"); - } - - else if (key == "LateralResumeDelay") { - setVisible &= params.getBool("PauseLateralOnSignal"); - } - - else if (key == "NNFF") { - setVisible &= parent->hasNNFFLog; - setVisible &= !parent->isAngleCar; - } - - else if (key == "NNFFLite") { - setVisible &= !usingNNFF; - setVisible &= !parent->isAngleCar; - } - - else if (key == "SteerDelay") { - setVisible &= parent->steerActuatorDelay != 0; - } - - else if (key == "SteerFriction") { - setVisible &= parent->friction != 0; - setVisible &= parent->hasAutoTune ? forcingAutoTuneOff : !forcingAutoTune; - setVisible &= parent->isTorqueCar || forcingTorqueController || usingNNFF; - setVisible &= !usingNNFF; - } - - else if (key == "SteerKP") { - setVisible &= parent->steerKp != 0; - setVisible &= parent->isTorqueCar || forcingTorqueController || usingNNFF; - setVisible &= !parent->isAngleCar; - } - - else if (key == "SteerLatAccel") { - setVisible &= parent->latAccelFactor != 0; - setVisible &= parent->hasAutoTune ? forcingAutoTuneOff : !forcingAutoTune; - setVisible &= parent->isTorqueCar || forcingTorqueController || usingNNFF; - setVisible &= !usingNNFF; - } - - else if (key == "SteerRatio") { - setVisible &= parent->steerRatio != 0; - setVisible &= parent->hasAutoTune ? forcingAutoTuneOff : !forcingAutoTune; - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (advancedLateralTuneKeys.contains(key)) { - toggles["AdvancedLateralTune"]->setVisible(true); - } else if (aolKeys.contains(key)) { - toggles["AlwaysOnLateral"]->setVisible(true); - } else if (laneChangeKeys.contains(key)) { - toggles["LaneChanges"]->setVisible(true); - } else if (lateralTuneKeys.contains(key)) { - toggles["LateralTune"]->setVisible(true); - } else if (qolKeys.contains(key)) { - toggles["QOLLateral"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/lateral_settings.h b/starpilot/ui/qt/offroad/lateral_settings.h deleted file mode 100644 index 9693989e0..000000000 --- a/starpilot/ui/qt/offroad/lateral_settings.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotLateralPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotLateralPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateMetric(bool metric, bool bootRun); - void updateState(const UIState &s); - void updateToggles(); - - bool forceOpenDescriptions; - bool started; - - std::map toggles; - - QSet advancedLateralTuneKeys = {"ForceAutoTune", "ForceAutoTuneOff", "ForceTorqueController", "SteerDelay", "SteerFriction", "SteerLatAccel", "SteerKP", "SteerRatio"}; - QSet aolKeys = {"PauseAOLOnBrake"}; - QSet laneChangeKeys = {"LaneChangeSmoothing", "LaneChangeTime", "LaneDetectionWidth", "MinimumLaneChangeSpeed", "NudgelessLaneChange", "OneLaneChange"}; - QSet lateralTuneKeys = {"NNFF", "NNFFLite", "TurnDesires", "NavDesiresAllowed"}; - QSet qolKeys = {"PauseLateralSpeed", "LateralResumeDelay"}; - - QSet parentKeys; - - StarPilotParamValueButtonControl *steerDelayToggle; - StarPilotParamValueButtonControl *steerFrictionToggle; - StarPilotParamValueButtonControl *steerLatAccelToggle; - StarPilotParamValueButtonControl *steerKPToggle; - StarPilotParamValueButtonControl *steerRatioToggle; - - StarPilotSettingsWindow *parent; - - Params params; -}; diff --git a/starpilot/ui/qt/offroad/longitudinal_settings.cc b/starpilot/ui/qt/offroad/longitudinal_settings.cc deleted file mode 100644 index 28ea8eb3b..000000000 --- a/starpilot/ui/qt/offroad/longitudinal_settings.cc +++ /dev/null @@ -1,1118 +0,0 @@ -#include "starpilot/ui/qt/offroad/longitudinal_settings.h" - -StarPilotLongitudinalPanel::StarPilotLongitudinalPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - networkManager = new QNetworkAccessManager(this); - - QStackedLayout *longitudinalLayout = new QStackedLayout(); - addItem(longitudinalLayout); - - StarPilotListWidget *longitudinalList = new StarPilotListWidget(this); - - ScrollView *longitudinalPanel = new ScrollView(longitudinalList, this); - - longitudinalLayout->addWidget(longitudinalPanel); - - StarPilotListWidget *advancedLongitudinalTuneList = new StarPilotListWidget(this); - StarPilotListWidget *aggressivePersonalityList = new StarPilotListWidget(this); - StarPilotListWidget *conditionalChillList = new StarPilotListWidget(this); - StarPilotListWidget *conditionalExperimentalList = new StarPilotListWidget(this); - StarPilotListWidget *curveSpeedList = new StarPilotListWidget(this); - StarPilotListWidget *customDrivingPersonalityList = new StarPilotListWidget(this); - StarPilotListWidget *longitudinalTuneList = new StarPilotListWidget(this); - StarPilotListWidget *qolList = new StarPilotListWidget(this); - StarPilotListWidget *relaxedPersonalityList = new StarPilotListWidget(this); - StarPilotListWidget *speedLimitControllerList = new StarPilotListWidget(this); - StarPilotListWidget *speedLimitControllerOffsetsList = new StarPilotListWidget(this); - StarPilotListWidget *speedLimitControllerQOLList = new StarPilotListWidget(this); - StarPilotListWidget *speedLimitControllerVisualList = new StarPilotListWidget(this); - StarPilotListWidget *standardPersonalityList = new StarPilotListWidget(this); - StarPilotListWidget *trafficPersonalityList = new StarPilotListWidget(this); - StarPilotListWidget *weatherList = new StarPilotListWidget(this); - StarPilotListWidget *weatherLowVisibilityList = new StarPilotListWidget(this); - StarPilotListWidget *weatherRainList = new StarPilotListWidget(this); - StarPilotListWidget *weatherRainStormList = new StarPilotListWidget(this); - StarPilotListWidget *weatherSnowList = new StarPilotListWidget(this); - - ScrollView *advancedLongitudinalTunePanel = new ScrollView(advancedLongitudinalTuneList, this); - ScrollView *aggressivePersonalityPanel = new ScrollView(aggressivePersonalityList, this); - ScrollView *conditionalChillPanel = new ScrollView(conditionalChillList, this); - ScrollView *conditionalExperimentalPanel = new ScrollView(conditionalExperimentalList, this); - ScrollView *curveSpeedPanel = new ScrollView(curveSpeedList, this); - ScrollView *customDrivingPersonalityPanel = new ScrollView(customDrivingPersonalityList, this); - ScrollView *longitudinalTunePanel = new ScrollView(longitudinalTuneList, this); - ScrollView *qolPanel = new ScrollView(qolList, this); - ScrollView *relaxedPersonalityPanel = new ScrollView(relaxedPersonalityList, this); - ScrollView *speedLimitControllerPanel = new ScrollView(speedLimitControllerList, this); - ScrollView *speedLimitControllerOffsetsPanel = new ScrollView(speedLimitControllerOffsetsList, this); - ScrollView *speedLimitControllerQOLPanel = new ScrollView(speedLimitControllerQOLList, this); - ScrollView *speedLimitControllerVisualPanel = new ScrollView(speedLimitControllerVisualList, this); - ScrollView *standardPersonalityPanel = new ScrollView(standardPersonalityList, this); - ScrollView *trafficPersonalityPanel = new ScrollView(trafficPersonalityList, this); - ScrollView *weatherLowVisibilityPanel = new ScrollView(weatherLowVisibilityList, this); - ScrollView *weatherPanel = new ScrollView(weatherList, this); - ScrollView *weatherRainPanel = new ScrollView(weatherRainList, this); - ScrollView *weatherRainStormPanel = new ScrollView(weatherRainStormList, this); - ScrollView *weatherSnowPanel = new ScrollView(weatherSnowList, this); - - longitudinalLayout->addWidget(advancedLongitudinalTunePanel); - longitudinalLayout->addWidget(aggressivePersonalityPanel); - longitudinalLayout->addWidget(conditionalChillPanel); - longitudinalLayout->addWidget(conditionalExperimentalPanel); - longitudinalLayout->addWidget(curveSpeedPanel); - longitudinalLayout->addWidget(customDrivingPersonalityPanel); - longitudinalLayout->addWidget(longitudinalTunePanel); - longitudinalLayout->addWidget(qolPanel); - longitudinalLayout->addWidget(relaxedPersonalityPanel); - longitudinalLayout->addWidget(speedLimitControllerPanel); - longitudinalLayout->addWidget(speedLimitControllerOffsetsPanel); - longitudinalLayout->addWidget(speedLimitControllerQOLPanel); - longitudinalLayout->addWidget(speedLimitControllerVisualPanel); - longitudinalLayout->addWidget(standardPersonalityPanel); - longitudinalLayout->addWidget(trafficPersonalityPanel); - longitudinalLayout->addWidget(weatherLowVisibilityPanel); - longitudinalLayout->addWidget(weatherPanel); - longitudinalLayout->addWidget(weatherRainPanel); - longitudinalLayout->addWidget(weatherRainStormPanel); - longitudinalLayout->addWidget(weatherSnowPanel); - - const std::vector> longitudinalToggles { - {"AdvancedLongitudinalTune", tr("Advanced Longitudinal Tuning"), tr("Advanced acceleration and braking control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_advanced_longitudinal_tune.png"}, - {"EVTuning", tr("EV Tuning"), tr("Use acceleration profiles tuned for EVs. Defaults to the vehicle's detected powertrain type but can be overridden if the automatic choice doesn't match."), ""}, - {"TruckTuning", tr("Truck Tuning"), tr("Use aggressive acceleration profiles tuned for trucks. Intended for heavy vehicles that need stronger throttle."), ""}, - {"TrailerLoad", tr("Trailer Load"), tr("Add trailer weight to vehicle mass for tow-aware gas, brake, and conservative lateral assist. Enter the loaded trailer weight in pounds."), ""}, - {"LongitudinalActuatorDelay", parent->longitudinalActuatorDelay != 0 ? QString(tr("Actuator Delay (Default: %1)")).arg(QString::number(parent->longitudinalActuatorDelay, 'f', 2)) : tr("Actuator Delay"), tr("The time between openpilot's throttle or brake command and the vehicle's response. Increase if the vehicle feels slow to react; decrease if it feels too eager or overshoots."), ""}, - {"MaxDesiredAcceleration", tr("Maximum Acceleration"), tr("Limit the strongest acceleration openpilot can command."), ""}, - {"StartAccel", parent->startAccel != 0 ? QString(tr("Start Acceleration (Default: %1)")).arg(QString::number(parent->startAccel, 'f', 2)) : tr("Start Acceleration"), tr("Extra acceleration applied when starting from a stop. Increase for quicker takeoffs; decrease for smoother, gentler starts."), ""}, - {"VEgoStarting", parent->vEgoStarting != 0 ? QString(tr("Start Speed (Default: %1)")).arg(QString::number(parent->vEgoStarting, 'f', 2)) : tr("Start Speed"), tr("The speed at which openpilot exits the stopped state. Increase to reduce creeping; decrease to move sooner after stopping."), ""}, - {"StopAccel", parent->stopAccel != 0 ? QString(tr("Stop Acceleration (Default: %1)")).arg(QString::number(parent->stopAccel, 'f', 2)) : tr("Stop Acceleration"), tr("Brake force applied to hold the vehicle at a standstill. Increase to prevent rolling on hills; decrease for smoother, softer stops."), ""}, - {"StoppingDecelRate", parent->stoppingDecelRate != 0 ? QString(tr("Stopping Rate (Default: %1)")).arg(QString::number(parent->stoppingDecelRate, 'f', 2)) : tr("Stopping Rate"), tr("How quickly braking ramps up when stopping. Increase for shorter, firmer stops; decrease for smoother, longer stops."), ""}, - {"VEgoStopping", parent->vEgoStopping != 0 ? QString(tr("Stop Speed (Default: %1)")).arg(QString::number(parent->vEgoStopping, 'f', 2)) : tr("Stop Speed"), tr("The speed at which openpilot considers the vehicle stopped. Increase to brake earlier and stop smoothly; decrease to wait longer but risk overshooting."), ""}, - - {"ConditionalExperimental", tr("Conditional Experimental Mode"), tr("Automatically switch to \"Experimental Mode\" when set conditions are met. Allows the model to handle challenging situations with smarter decision making."), "../../starpilot/assets/toggle_icons/icon_conditional.png"}, - {"PersistExperimentalState", tr("Persist Experimental State"), tr("Keep your manual Conditional Experimental override through reboots until you manually clear it."), ""}, - {"CESpeed", tr("Below"), tr("Switch to \"Experimental Mode\" when driving below this speed without a lead to help openpilot handle low-speed situations more smoothly."), ""}, - {"CECurves", tr("Curve Detected Ahead"), tr("Switch to \"Experimental Mode\" when a curve is detected to allow the model to set an appropriate speed for the curve."), ""}, - {"CEStopLights", tr("\"Detected\" Stop Lights/Signs"), tr("Switch to \"Experimental Mode\" whenever the driving model \"detects\" a red light or stop sign.

Disclaimer: openpilot does not explicitly detect traffic lights or stop signs. In \"Experimental Mode\", openpilot makes end-to-end driving decisions from camera input, which means it may stop even when there's no clear reason!"), ""}, - {"CELead", tr("Lead Detected Ahead"), tr("Switch to \"Experimental Mode\" when a slower or stopped vehicle is detected. Can make braking smoother and more reliable on some vehicles."), ""}, - {"CEModelStopTime", tr("Predicted Stop In"), tr("Switch to \"Experimental Mode\" when openpilot predicts a stop within the set time. This is usually triggered when the model \"sees\" a red light or stop sign ahead.

Disclaimer: openpilot does not explicitly detect traffic lights or stop signs. In \"Experimental Mode\", openpilot makes end-to-end driving decisions from camera input, which means it may stop even when there's no clear reason!"), ""}, - {"CESignalSpeed", tr("Turn Signal Below"), tr("Switch to \"Experimental Mode\" when using a turn signal below the set speed to allow the model to choose an appropriate speed for smoother left and right turns."), ""}, - {"ShowCEMStatus", tr("Status Widget"), tr("Show which condition triggered \"Experimental Mode\" on the driving screen."), ""}, - {"ConditionalChill", tr("Conditional Chill Mode"), tr("Keep \"Experimental Mode\" on by default, but temporarily switch to \"Chill Mode\" in simple cruising scenes where speed holding is usually better."), "../../starpilot/assets/toggle_icons/icon_conditional.png"}, - {"PersistChillState", tr("Persist Chill State"), tr("Keep your manual Conditional Chill override through reboots until you manually clear it."), ""}, - {"CCMSpeed", tr("Above"), tr("Switch to \"Chill Mode\" on open roads above this speed when no lead is detected and the car is still below the set speed."), ""}, - {"CCMLead", tr("Stable Lead Ahead"), tr("Switch to \"Chill Mode\" when following a steady, well-tracked lead vehicle at cruising speeds."), ""}, - {"CCMLaunchAssist", tr("Launch Assist"), tr("Temporarily switch to \"Chill Mode\" when starting from a stop if planner is already allowing throttle. Useful if your car launches too slowly from lights or stop signs."), ""}, - {"CCMSetSpeedMargin", tr("Set Speed Margin"), tr("How far below the set speed the car must be before open-road Conditional Chill can engage."), ""}, - {"ShowCCMStatus", tr("Status Widget"), tr("Show which condition triggered \"Chill Mode\" on the driving screen."), ""}, - - {"CurveSpeedController", tr("Curve Speed Controller"), tr("Automatically slow down for upcoming curves using data learned from your driving style, adapting to curves as you would."), "../../starpilot/assets/toggle_icons/icon_speed_map.png"}, - {"CalibratedLateralAcceleration", tr("Calibrated Lateral Acceleration"), tr("The learned lateral acceleration from collected driving data. This sets how fast openpilot will take curves. Higher values allow faster cornering; lower values slow the vehicle for gentler turns."), ""}, - {"CalibrationProgress", tr("Calibration Progress"), tr("How much curve data has been collected. This is a progress meter; it is normal for the value to stay low and rarely reach 100%."), ""}, - {"ResetCurveData", tr("Reset Curve Data"), tr("Reset collected user data for \"Curve Speed Controller\"."), ""}, - {"ShowCSCStatus", tr("Status Widget"), tr("Show the \"Curve Speed Controller\" target speed on the driving screen."), ""}, - - {"CustomPersonalities", tr("Driving Personalities"), tr("Customize the \"Driving Personalities\" to better match your driving style."), "../../starpilot/assets/toggle_icons/icon_personality.png"}, - - {"TrafficPersonalityProfile", tr("Traffic Mode"), tr("Customize the \"Traffic Mode\" personality profile. Designed for stop-and-go driving."), "../../starpilot/assets/stock_theme/distance_icons/traffic.png"}, - {"TrafficFollow", tr("Following Distance"), tr("The minimum following distance to the lead vehicle in \"Traffic Mode\". openpilot blends between this value and the \"Relaxed\" profile as speed increases. Increase for more space; decrease for tighter gaps."), ""}, - {"TrafficJerkAcceleration", tr("Acceleration Smoothness"), tr("How smoothly openpilot accelerates in \"Traffic Mode\". Increase for gentler starts; decrease for faster but more abrupt takeoffs."), ""}, - {"TrafficJerkDeceleration", tr("Braking Smoothness"), tr("How smoothly openpilot brakes in \"Traffic Mode\". Increase for gentler stops; decrease for quicker but sharper braking."), ""}, - {"TrafficJerkDanger", tr("Safety Gap Bias"), tr("How much extra space openpilot keeps from the vehicle ahead in \"Traffic Mode\". Increase for larger gaps and more cautious following; decrease for tighter gaps and closer following."), ""}, - {"TrafficJerkSpeedDecrease", tr("Slowdown Response"), tr("How smoothly openpilot slows down in \"Traffic Mode\". Increase for more gradual deceleration; decrease for faster but sharper slowdowns."), ""}, - {"TrafficJerkSpeed", tr("Speed-Up Response"), tr("How smoothly openpilot speeds up in \"Traffic Mode\". Increase for more gradual acceleration; decrease for quicker but more jolting acceleration."), ""}, - {"ResetTrafficPersonality", tr("Reset to Defaults"), tr("Reset \"Traffic Mode\" settings to defaults."), ""}, - - {"AggressivePersonalityProfile", tr("Aggressive"), tr("Customize the \"Aggressive\" personality profile. Designed for assertive driving with tighter gaps."), "../../starpilot/assets/stock_theme/distance_icons/aggressive.png"}, - {"AggressiveFollow", tr("Following Distance"), tr("How many seconds openpilot follows behind lead vehicles when using the \"Aggressive\" profile. Increase for more space; decrease for tighter gaps.

Default: 1.25 seconds."), ""}, - {"AggressiveFollowHigh", tr("High Speed Following Distance"), tr("Following distance for higher speeds in the \"Aggressive\" profile. openpilot smoothly blends from the base value to this value as speed rises."), ""}, - {"AggressiveJerkAcceleration", tr("Acceleration Smoothness"), tr("How smoothly openpilot accelerates with the \"Aggressive\" profile. Increase for gentler starts; decrease for faster but more abrupt takeoffs."), ""}, - {"AggressiveJerkDeceleration", tr("Braking Smoothness"), tr("How smoothly openpilot brakes with the \"Aggressive\" profile. Increase for gentler stops; decrease for quicker but sharper braking."), ""}, - {"AggressiveJerkDanger", tr("Safety Gap Bias"), tr("How much extra space openpilot keeps from the vehicle ahead with the \"Aggressive\" profile. Increase for larger gaps and more cautious following; decrease for tighter gaps and closer following."), ""}, - {"AggressiveJerkSpeedDecrease", tr("Slowdown Response"), tr("How smoothly openpilot slows down with the \"Aggressive\" profile. Increase for more gradual deceleration; decrease for faster but sharper slowdowns."), ""}, - {"AggressiveJerkSpeed", tr("Speed-Up Response"), tr("How smoothly openpilot speeds up with the \"Aggressive\" profile. Increase for more gradual acceleration; decrease for quicker but more jolting acceleration."), ""}, - {"ResetAggressivePersonality", tr("Reset to Defaults"), tr("Reset the \"Aggressive\" profile to defaults."), ""}, - - {"StandardPersonalityProfile", tr("Standard"), tr("Customize the \"Standard\" personality profile. Designed for balanced driving with moderate gaps."), "../../starpilot/assets/stock_theme/distance_icons/standard.png"}, - {"StandardFollow", tr("Following Distance"), tr("How many seconds openpilot follows behind lead vehicles when using the \"Standard\" profile. Increase for more space; decrease for tighter gaps.

Default: 1.45 seconds."), ""}, - {"StandardFollowHigh", tr("High Speed Following Distance"), tr("Following distance for higher speeds in the \"Standard\" profile. openpilot smoothly blends from the base value to this value as speed rises."), ""}, - {"StandardJerkAcceleration", tr("Acceleration Smoothness"), tr("How smoothly openpilot accelerates with the \"Standard\" profile. Increase for gentler starts; decrease for faster but more abrupt takeoffs."), ""}, - {"StandardJerkDeceleration", tr("Braking Smoothness"), tr("How smoothly openpilot brakes with the \"Standard\" profile. Increase for gentler stops; decrease for quicker but sharper braking."), ""}, - {"StandardJerkDanger", tr("Safety Gap Bias"), tr("How much extra space openpilot keeps from the vehicle ahead with the \"Standard\" profile. Increase for larger gaps and more cautious following; decrease for tighter gaps and closer following."), ""}, - {"StandardJerkSpeedDecrease", tr("Slowdown Response"), tr("How smoothly openpilot slows down with the \"Standard\" profile. Increase for more gradual deceleration; decrease for faster but sharper slowdowns."), ""}, - {"StandardJerkSpeed", tr("Speed-Up Response"), tr("How smoothly openpilot speeds up with the \"Standard\" profile. Increase for more gradual acceleration; decrease for quicker but more jolting acceleration."), ""}, - {"ResetStandardPersonality", tr("Reset to Defaults"), tr("Reset the \"Standard\" profile to defaults."), ""}, - - {"RelaxedPersonalityProfile", tr("Relaxed"), tr("Customize the \"Relaxed\" personality profile. Designed for smoother, more comfortable driving with larger gaps."), "../../starpilot/assets/stock_theme/distance_icons/relaxed.png"}, - {"RelaxedFollow", tr("Following Distance"), tr("How many seconds openpilot follows behind lead vehicles when using the \"Relaxed\" profile. Increase for more space; decrease for tighter gaps.

Default: 1.6 seconds."), ""}, - {"RelaxedFollowHigh", tr("High Speed Following Distance"), tr("Following distance for higher speeds in the \"Relaxed\" profile. openpilot smoothly blends from the base value to this value as speed rises."), ""}, - {"RelaxedJerkAcceleration", tr("Acceleration Smoothness"), tr("How smoothly openpilot accelerates with the \"Relaxed\" profile. Increase for gentler starts; decrease for faster but more abrupt takeoffs."), ""}, - {"RelaxedJerkDeceleration", tr("Braking Smoothness"), tr("How smoothly openpilot brakes with the \"Relaxed\" profile. Increase for gentler stops; decrease for quicker but sharper braking."), ""}, - {"RelaxedJerkDanger", tr("Safety Gap Bias"), tr("How much extra space openpilot keeps from the vehicle ahead with the \"Relaxed\" profile. Increase for larger gaps and more cautious following; decrease for tighter gaps and closer following."), ""}, - {"RelaxedJerkSpeedDecrease", tr("Slowdown Response"), tr("How smoothly openpilot slows down with the \"Relaxed\" profile. Increase for more gradual deceleration; decrease for faster but sharper slowdowns."), ""}, - {"RelaxedJerkSpeed", tr("Speed-Up Response"), tr("How smoothly openpilot speeds up with the \"Relaxed\" profile. Increase for more gradual acceleration; decrease for quicker but more jolting acceleration."), ""}, - {"ResetRelaxedPersonality", tr("Reset to Defaults"), tr("Reset the \"Relaxed\" profile to defaults."), ""}, - - {"LongitudinalTune", tr("Longitudinal Tuning"), tr("Acceleration and braking control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_longitudinal_tune.png"}, - {"AccelerationProfile", tr("Acceleration Profile"), tr("How quickly openpilot speeds up. \"Eco\" is gentle and efficient, \"Sport\" is firmer and more responsive, and \"Sport+\" accelerates at the maximum rate allowed."), ""}, - {"DecelerationProfile", tr("Deceleration Profile"), tr("How firmly openpilot slows down. \"Eco\" favors coasting, \"Sport\" applies stronger braking."), ""}, - {"HumanLaneChanges", tr("Human-Like Lane Changes"), tr("Lane-change behavior that mimics human drivers by anticipating and tracking adjacent vehicles during lane changes."), ""}, - {"LeadDetectionThreshold", tr("Lead Detection Sensitivity"), tr("How sensitive openpilot is to detecting vehicles. Higher sensitivity allows quicker detection at longer distances but may react to non-vehicle objects; lower sensitivity is more conservative and reduces false detections."), ""}, - {"TacoTune", tr("\"Taco Bell Run\" Turn Speed Hack"), tr("The turn-speed hack from comma's 2022 \"Taco Bell Run\". Designed to slow down for left and right turns."), ""}, - {"NavLongitudinalAllowed", tr("Use Route Speed Control"), tr("Allow an active navigation route to reduce cruise speed for upcoming turns, ramps, and roundabouts."), ""}, - - {"QOLLongitudinal", tr("Quality of Life"), tr("Miscellaneous acceleration and braking control changes to fine-tune how openpilot drives."), "../../starpilot/assets/toggle_icons/icon_quality_of_life.png"}, - {"CustomCruise", tr("Cruise Interval"), tr("How much the set speed increases or decreases for each + or – cruise control button press."), ""}, - {"CustomCruiseLong", tr("Cruise Interval (Hold)"), tr("How much the set speed increases or decreases while holding the + or – cruise control buttons."), ""}, - {"ForceStops", tr("Force Stop at \"Detected\" Stop Lights/Signs"), tr("Force openpilot to stop whenever the driving model \"detects\" a red light or stop sign.

Disclaimer: openpilot does not explicitly detect traffic lights or stop signs. In \"Experimental Mode\", openpilot makes end-to-end driving decisions from camera input, which means it may stop even when there's no clear reason!"), ""}, - {"ForceStopDistanceOffset", tr("Force Stop Distance Offset"), tr("Tune where Force Stops bring the car to rest. Positive values let the car roll further before stopping (longer stop, closer to the line). Negative values stop the car sooner (more buffer before the line)."), ""}, - {"ForceStandstill", tr("Force Standstill State"), tr("Keep openpilot in the standstill state until you press the gas pedal or the Resume/+ cruise button.

This applies to any engaged stop, not just red lights or stop signs."), ""}, - {"RadarTakeoffs", tr("Radar for Takeoffs"), tr("Turns on/off using radar data to track leads at standstill, making following/takeoffs more responsive once leads move."), ""}, - {"IncreasedStoppedDistance", tr("Increase Stopped Distance by:"), tr("Add extra space when stopped behind vehicles. Increase for more room; decrease for shorter gaps."), ""}, - {"MapGears", tr("Map Accel/Decel to Gears"), tr("Map the Acceleration or Deceleration profiles to the vehicle's \"Eco\" and \"Sport\" gear modes."), ""}, - {"SetSpeedOffset", tr("Offset Set Speed by:"), tr("Increase the set speed by the chosen offset. For example, set +5 if you usually drive 5 over the limit."), ""}, - {"ReverseCruise", tr("Reverse Cruise Increase"), tr("Reverse the cruise control button behavior so a short press increases the set speed by 5 instead of 1."), ""}, - {"WeatherPresets", tr("Weather Condition Offsets"), tr("Automatically adjust driving behavior based on real-time weather. Helps maintain comfort and safety in low visibility, rain, or snow."), ""}, - - {"LowVisibilityOffsets", tr("Low Visibility"), tr("Driving adjustments for fog, haze, or other low-visibility conditions."), ""}, - {"IncreaseFollowingLowVisibility", tr("Increase Following Distance by:"), tr("Add extra space behind lead vehicles in low visibility. Increase for more space; decrease for tighter gaps."), ""}, - {"IncreasedStoppedDistanceLowVisibility", tr("Increase Stopped Distance by:"), tr("Add extra buffer when stopped behind vehicles in low visibility. Increase for more room; decrease for shorter gaps."), ""}, - {"ReduceAccelerationLowVisibility", tr("Reduce Acceleration by:"), tr("Lower the maximum acceleration in low visibility. Increase for softer takeoffs; decrease for quicker but less stable takeoffs."), ""}, - {"ReduceLateralAccelerationLowVisibility", tr("Reduce Speed in Curves by:"), tr("Lower the desired speed while driving through curves in low visibility. Increase for safer, gentler turns; decrease for more aggressive driving in curves."), ""}, - - {"RainOffsets", tr("Rain"), tr("Driving adjustments for rainy conditions."), ""}, - {"IncreaseFollowingRain", tr("Increase Following Distance by:"), tr("Add extra space behind lead vehicles in rain. Increase for more space; decrease for tighter gaps."), ""}, - {"IncreasedStoppedDistanceRain", tr("Increase Stopped Distance by:"), tr("Add extra buffer when stopped behind vehicles in rain. Increase for more room; decrease for shorter gaps."), ""}, - {"ReduceAccelerationRain", tr("Reduce Acceleration by:"), tr("Lower the maximum acceleration in rain. Increase for softer takeoffs; decrease for quicker but less stable takeoffs."), ""}, - {"ReduceLateralAccelerationRain", tr("Reduce Speed in Curves by:"), tr("Lower the desired speed while driving through curves in rain. Increase for safer, gentler turns; decrease for more aggressive driving in curves."), ""}, - - {"RainStormOffsets", tr("Rainstorms"), tr("Driving adjustments for rainstorms."), ""}, - {"IncreaseFollowingRainStorm", tr("Increase Following Distance by:"), tr("Add extra space behind lead vehicles in a rainstorm. Increase for more space; decrease for tighter gaps."), ""}, - {"IncreasedStoppedDistanceRainStorm", tr("Increase Stopped Distance by:"), tr("Add extra buffer when stopped behind vehicles in a rainstorm. Increase for more room; decrease for shorter gaps."), ""}, - {"ReduceAccelerationRainStorm", tr("Reduce Acceleration by:"), tr("Lower the maximum acceleration in a rainstorm. Increase for softer takeoffs; decrease for quicker but less stable takeoffs."), ""}, - {"ReduceLateralAccelerationRainStorm", tr("Reduce Speed in Curves by:"), tr("Lower the desired speed while driving through curves in a rainstorm. Increase for safer, gentler turns; decrease for more aggressive driving in curves."), ""}, - - {"SnowOffsets", tr("Snow"), tr("Driving adjustments for snowy conditions."), ""}, - {"IncreaseFollowingSnow", tr("Increase Following Distance by:"), tr("Add extra space behind lead vehicles in snow. Increase for more space; decrease for tighter gaps."), ""}, - {"IncreasedStoppedDistanceSnow", tr("Increase Stopped Distance by:"), tr("Add extra buffer when stopped behind vehicles in snow. Increase for more room; decrease for shorter gaps."), ""}, - {"ReduceAccelerationSnow", tr("Reduce Acceleration by:"), tr("Lower the maximum acceleration in snow. Increase for softer takeoffs; decrease for quicker but less stable takeoffs."), ""}, - {"ReduceLateralAccelerationSnow", tr("Reduce Speed in Curves by:"), tr("Lower the desired speed while driving through curves in snow. Increase for safer, gentler turns; decrease for more aggressive driving in curves."), ""}, - - - {"SpeedLimitController", tr("Speed Limit Controller"), tr("Limit openpilot's maximum driving speed to the current speed limit obtained from downloaded maps, Mapbox, the dashboard, or vision-detected signs."), "../../starpilot/assets/toggle_icons/icon_speed_limit.png"}, - {"SLCFallback", tr("Fallback Speed"), tr("The speed used by \"Speed Limit Controller\" when no speed limit is found.

- Set Speed: Use the cruise set speed
- Experimental Mode: Estimate the limit using the driving model
- Previous Limit: Keep using the last confirmed limit"), ""}, - {"SLCOverride", tr("Override Speed"), tr("The speed used by \"Speed Limit Controller\" after you manually drive faster than the posted limit.

- Set with Gas Pedal: Use the highest speed reached while pressing the gas
- Max Set Speed: Use the cruise set speed

Overrides clear when openpilot disengages."), ""}, - {"SLCQOL", tr("Quality of Life"), tr("Miscellaneous \"Speed Limit Controller\" changes to fine-tune how openpilot drives."), ""}, - {"SLCConfirmation", tr("Confirm New Speed Limits"), tr("Ask before changing to a new speed limit. To accept, tap the flashing on-screen widget or press the Cruise Increase button. To deny, press the Cruise Decrease button or ignore the prompt for 30 seconds."), ""}, - {"SLCLookaheadHigher", tr("Higher Limit Lookahead Time"), tr("How far ahead openpilot anticipates upcoming higher speed limits from downloaded map data."), ""}, - {"SLCLookaheadLower", tr("Lower Limit Lookahead Time"), tr("How far ahead openpilot anticipates upcoming lower speed limits from downloaded map data."), ""}, - {"SetSpeedLimit", tr("Match Speed Limit on Engage"), tr("When openpilot is first enabled, automatically set the max speed to the current posted limit."), ""}, - {"SLCMapboxFiller", tr("Use Mapbox as Fallback"), tr("Use Mapbox speed-limit data when no other source is available."), ""}, - {"VisionSpeedLimitDetection", tr("Vision Speed Limit Detection"), tr("Use the road camera to detect speed limit signs for SLC and speed limit filling."), ""}, - {"SLCPriority", tr("Speed Limit Source Priority"), tr("The source order for speed limits when more than one is available."), ""}, - {"SLCOffsets", tr("Speed Limit Offsets"), tr("Add an offset to the posted speed limit to better match your driving style."), ""}, - {"Offset1", tr("Speed Offset (0–24 mph)"), tr("How much to offset posted speed-limits between 0 and 24 mph."), ""}, - {"Offset2", tr("Speed Offset (25–34 mph)"), tr("How much to offset posted speed-limits between 25 and 34 mph."), ""}, - {"Offset3", tr("Speed Offset (35–44 mph)"), tr("How much to offset posted speed-limits between 35 and 44 mph."), ""}, - {"Offset4", tr("Speed Offset (45–54 mph)"), tr("How much to offset posted speed-limits between 45 and 54 mph."), ""}, - {"Offset5", tr("Speed Offset (55–64 mph)"), tr("How much to offset posted speed-limits between 55 and 64 mph."), ""}, - {"Offset6", tr("Speed Offset (65–74 mph)"), tr("How much to offset posted speed-limits between 65 and 74 mph."), ""}, - {"Offset7", tr("Speed Offset (75–99 mph)"), tr("How much to offset posted speed-limits between 75 and 99 mph."), ""}, - {"SLCVisuals", tr("Visual Settings"), tr("Visual \"Speed Limit Controller\" changes to fine-tune how the driving screen looks."), ""}, - {"ShowSLCOffset", tr("Show Speed Limit Offset"), tr("Show the current offset from the posted limit on the driving screen."), ""}, - {"SpeedLimitSources", tr("Show Speed Limit Sources"), tr("Display the speed-limit sources and their current values on the driving screen."), ""}, - {"SLCAbbreviatedSources", tr("Show Abbreviated Icon Sources"), tr("Render the speed-limit sources as compact text labels (e.g. \"Dash-45\", \"MapD-30\") without icons."), ""}, - {"SLCActiveSourcesOnly", tr("Only Show Sources With Speed Limits"), tr("Hide source rows that have no current speed limit reading. Works with both abbreviated and full display."), ""} - }; - - for (const auto &[param, title, desc, icon] : longitudinalToggles) { - AbstractControl *longitudinalToggle; - - if (param == "AdvancedLongitudinalTune") { - StarPilotManageControl *advancedLongitudinalTuneToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(advancedLongitudinalTuneToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, advancedLongitudinalTunePanel]() { - longitudinalLayout->setCurrentWidget(advancedLongitudinalTunePanel); - }); - longitudinalToggle = advancedLongitudinalTuneToggle; - } else if (param == "LongitudinalActuatorDelay") { - longitudinalActuatorDelayToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 1, tr(" seconds"), std::map(), 0.01); - longitudinalToggle = longitudinalActuatorDelayToggle; - } else if (param == "MaxDesiredAcceleration") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0.1, 4.0, tr(" m/s²"), std::map(), 0.1); - } else if (param == "TrailerLoad") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 15000, tr(" lbs"), std::map(), 500); - } else if (param == "StartAccel") { - startAccelToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 4, tr(" m/s²"), std::map(), 0.01, true); - longitudinalToggle = startAccelToggle; - } else if (param == "VEgoStarting") { - vEgoStartingToggle = new StarPilotParamValueControl(param, title, desc, icon, 0.01, 1, tr(" m/s²"), std::map(), 0.01); - longitudinalToggle = vEgoStartingToggle; - } else if (param == "StopAccel") { - stopAccelToggle = new StarPilotParamValueControl(param, title, desc, icon, -4, 0, tr(" m/s²"), std::map(), 0.01, true); - longitudinalToggle = stopAccelToggle; - } else if (param == "StoppingDecelRate") { - stoppingDecelRateToggle = new StarPilotParamValueControl(param, title, desc, icon, 0.001, 1, tr(" m/s²"), std::map(), 0.001, true); - longitudinalToggle = stoppingDecelRateToggle; - } else if (param == "VEgoStopping") { - vEgoStoppingToggle = new StarPilotParamValueControl(param, title, desc, icon, 0.01, 1, tr(" m/s²"), std::map(), 0.01); - longitudinalToggle = vEgoStoppingToggle; - - } else if (param == "ConditionalExperimental") { - StarPilotManageControl *conditionalExperimentalToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(conditionalExperimentalToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, conditionalExperimentalPanel]() { - longitudinalLayout->setCurrentWidget(conditionalExperimentalPanel); - }); - longitudinalToggle = conditionalExperimentalToggle; - } else if (param == "ConditionalChill") { - StarPilotManageControl *conditionalChillToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(conditionalChillToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, conditionalChillPanel]() { - longitudinalLayout->setCurrentWidget(conditionalChillPanel); - }); - longitudinalToggle = conditionalChillToggle; - } else if (param == "CESpeed") { - StarPilotParamValueControl *CESpeed = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, tr(" mph"), std::map(), 1, true, 175); - StarPilotParamValueControl *CESpeedLead = new StarPilotParamValueControl("CESpeedLead", tr("With Lead"), tr("Switch to \"Experimental Mode\" when driving below this speed with a lead to help openpilot handle low-speed situations more smoothly."), icon, 0, 99, tr(" mph"), std::map(), 1, true, 175); - StarPilotDualParamValueControl *conditionalSpeeds = new StarPilotDualParamValueControl(CESpeed, CESpeedLead); - longitudinalToggle = reinterpret_cast(conditionalSpeeds); - } else if (param == "CCMSpeed") { - StarPilotParamValueControl *CCMSpeed = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, tr(" mph"), std::map(), 1, true, 175); - StarPilotParamValueControl *CCMSpeedLead = new StarPilotParamValueControl("CCMSpeedLead", tr("With Lead"), tr("Switch to \"Chill Mode\" when a stable lead is being followed above this speed."), icon, 0, 99, tr(" mph"), std::map(), 1, true, 175); - StarPilotDualParamValueControl *conditionalSpeeds = new StarPilotDualParamValueControl(CCMSpeed, CCMSpeedLead); - longitudinalToggle = reinterpret_cast(conditionalSpeeds); - } else if (param == "CECurves") { - std::vector curveToggles{"CECurvesLead"}; - std::vector curveToggleNames{tr("With Lead")}; - longitudinalToggle = new StarPilotButtonToggleControl(param, title, desc, icon, curveToggles, curveToggleNames); - } else if (param == "CELead") { - std::vector leadToggles{"CESlowerLead", "CEStoppedLead"}; - std::vector leadToggleNames{tr("Slower Lead"), tr("Stopped Lead")}; - longitudinalToggle = new StarPilotButtonToggleControl(param, title, desc, icon, leadToggles, leadToggleNames); - } else if (param == "CCMSetSpeedMargin") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 15, tr(" mph"), std::map(), 1, true, 175); - } else if (param == "CEModelStopTime") { - std::map stopTimeLabels{{0.0f, tr("Off")}}; - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 9, tr(" seconds"), stopTimeLabels, 0.1); - } else if (param == "CESignalSpeed") { - std::vector ceSignalToggles{"CESignalLaneDetection"}; - std::vector ceSignalToggleNames{tr("Not For Detected Lanes")}; - longitudinalToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0, 99, tr(" mph"), std::map(), 1.0, true, ceSignalToggles, ceSignalToggleNames, true); - - } else if (param == "CurveSpeedController") { - StarPilotManageControl *curveControlToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(curveControlToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, curveSpeedPanel]() { - longitudinalLayout->setCurrentWidget(curveSpeedPanel); - }); - longitudinalToggle = curveControlToggle; - } else if (param == "CalibrationProgress") { - calibrationProgressLabel = new LabelControl(title, QString::number(params.getFloat("CalibrationProgress"), 'f', 2) + "%", desc); - longitudinalToggle = calibrationProgressLabel; - } else if (param == "CalibratedLateralAcceleration") { - calibratedLateralAccelerationLabel = new LabelControl(title, QString::number(params.getFloat("CalibratedLateralAcceleration"), 'f', 2) + tr(" m/s²"), desc); - longitudinalToggle = calibratedLateralAccelerationLabel; - } else if (param == "ResetCurveData") { - ButtonControl *resetCurveDataButton = new ButtonControl(title, tr("RESET"), desc); - QObject::connect(resetCurveDataButton, &ButtonControl::clicked, [this]() { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your curvature data?"), this)) { - params.putFloat("CalibratedLateralAcceleration", 2.00); - params.remove("CalibrationProgress"); - params.remove("CurvatureData"); - - calibratedLateralAccelerationLabel->setText(QString::number(2.00, 'f', 2) + tr(" m/s²")); - calibrationProgressLabel->setText(QString::number(0.00, 'f', 2) + "%"); - } - }); - longitudinalToggle = resetCurveDataButton; - - } else if (param == "CustomPersonalities") { - StarPilotManageControl *customPersonalitiesToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(customPersonalitiesToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, customDrivingPersonalityPanel]() { - longitudinalLayout->setCurrentWidget(customDrivingPersonalityPanel); - }); - longitudinalToggle = customPersonalitiesToggle; - } else if (param == "ResetTrafficPersonality" || param == "ResetAggressivePersonality" || param == "ResetStandardPersonality" || param == "ResetRelaxedPersonality") { - ButtonControl *resetButton = new ButtonControl(title, tr("RESET"), desc); - longitudinalToggle = resetButton; - } else if (param == "TrafficPersonalityProfile") { - StarPilotButtonsControl *trafficPersonalityToggle = new StarPilotButtonsControl(title, desc, icon, {tr("MANAGE")}); - QObject::connect(trafficPersonalityToggle, &StarPilotButtonsControl::buttonClicked, [longitudinalLayout, trafficPersonalityPanel, this](int id) { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(trafficPersonalityPanel); - - customPersonalityOpen = true; - }); - longitudinalToggle = trafficPersonalityToggle; - } else if (param == "AggressivePersonalityProfile") { - StarPilotButtonsControl *aggressivePersonalityToggle = new StarPilotButtonsControl(title, desc, icon, {tr("MANAGE")}); - QObject::connect(aggressivePersonalityToggle, &StarPilotButtonsControl::buttonClicked, [longitudinalLayout, aggressivePersonalityPanel, this](int id) { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(aggressivePersonalityPanel); - - customPersonalityOpen = true; - }); - longitudinalToggle = aggressivePersonalityToggle; - } else if (param == "StandardPersonalityProfile") { - StarPilotButtonsControl *standardPersonalityToggle = new StarPilotButtonsControl(title, desc, icon, {tr("MANAGE")}); - QObject::connect(standardPersonalityToggle, &StarPilotButtonsControl::buttonClicked, [longitudinalLayout, standardPersonalityPanel, this](int id) { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(standardPersonalityPanel); - - customPersonalityOpen = true; - }); - longitudinalToggle = standardPersonalityToggle; - } else if (param == "RelaxedPersonalityProfile") { - StarPilotButtonsControl *relaxedPersonalityToggle = new StarPilotButtonsControl(title, desc, icon, {tr("MANAGE")}); - QObject::connect(relaxedPersonalityToggle, &StarPilotButtonsControl::buttonClicked, [longitudinalLayout, relaxedPersonalityPanel, this](int id) { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(relaxedPersonalityPanel); - - customPersonalityOpen = true; - }); - longitudinalToggle = relaxedPersonalityToggle; - } else if (aggressivePersonalityKeys.contains(param) || standardPersonalityKeys.contains(param) || relaxedPersonalityKeys.contains(param) || trafficPersonalityKeys.contains(param)) { - if (param == "TrafficFollow" || param == "AggressiveFollow" || param == "AggressiveFollowHigh" || - param == "StandardFollow" || param == "StandardFollowHigh" || param == "RelaxedFollow" || param == "RelaxedFollowHigh") { - std::map followTimeLabels; - for (float i = 0; i <= 3; i += 0.01) { - followTimeLabels[i] = std::lround(i / 0.01) == 1 / 0.01 ? QString::number(i, 'f', 2) + tr(" second") : QString::number(i, 'f', 2) + tr(" seconds"); - } - if (param == "TrafficFollow") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0.5, 3, QString(), followTimeLabels, 0.01, true); - } else { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 1, 3, QString(), followTimeLabels, 0.01, true); - } - } else { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 25, 200, "%"); - } - - } else if (param == "LongitudinalTune") { - StarPilotManageControl *longitudinalTuneToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(longitudinalTuneToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, longitudinalTunePanel]() { - longitudinalLayout->setCurrentWidget(longitudinalTunePanel); - }); - longitudinalToggle = longitudinalTuneToggle; - } else if (param == "AccelerationProfile") { - std::vector accelerationProfiles{tr("Standard"), tr("Eco"), tr("Sport"), tr("Sport+")}; - ButtonParamControl *accelerationProfileToggle = new ButtonParamControl(param, title, desc, icon, accelerationProfiles); - longitudinalToggle = accelerationProfileToggle; - } else if (param == "DecelerationProfile") { - std::vector decelerationProfiles{tr("Standard"), tr("Eco"), tr("Sport")}; - ButtonParamControl *decelerationProfileToggle = new ButtonParamControl(param, title, desc, icon, decelerationProfiles); - longitudinalToggle = decelerationProfileToggle; - } else if (param == "LeadDetectionThreshold") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 25, 50, "%"); - - } else if (param == "QOLLongitudinal") { - StarPilotManageControl *qolLongitudinalToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(qolLongitudinalToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, qolPanel]() { - longitudinalLayout->setCurrentWidget(qolPanel); - }); - longitudinalToggle = qolLongitudinalToggle; - } else if (param == "CustomCruise") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 1, 99, tr(" mph")); - } else if (param == "CustomCruiseLong") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 1, 99, tr(" mph")); - } else if (param == "IncreasedStoppedDistance") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 10, tr(" feet")); - } else if (param == "ForceStopDistanceOffset") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, -20, 20, tr(" feet")); - } else if (param == "MapGears") { - std::vector mapGearsToggles{"MapAcceleration", "MapDeceleration"}; - std::vector mapGearsToggleNames{tr("Acceleration"), tr("Deceleration")}; - longitudinalToggle = new StarPilotButtonToggleControl(param, title, desc, icon, mapGearsToggles, mapGearsToggleNames); - } else if (param == "SetSpeedOffset") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, tr(" mph")); - } else if (param == "WeatherPresets") { - StarPilotManageControl *weatherToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(weatherToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, weatherPanel, this]() { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(weatherPanel); - - qolOpen = true; - }); - longitudinalToggle = weatherToggle; - } else if (param == "LowVisibilityOffsets") { - ButtonControl *manageLowVisibilitOffsetsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageLowVisibilitOffsetsButton, &ButtonControl::clicked, [longitudinalLayout, weatherLowVisibilityPanel, this]() { - openSubSubSubPanel(); - - longitudinalLayout->setCurrentWidget(weatherLowVisibilityPanel); - - weatherOpen = true; - }); - longitudinalToggle = manageLowVisibilitOffsetsButton; - } else if (param == "RainOffsets") { - ButtonControl *manageRainOffsetsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageRainOffsetsButton, &ButtonControl::clicked, [longitudinalLayout, weatherRainPanel, this]() { - openSubSubSubPanel(); - - longitudinalLayout->setCurrentWidget(weatherRainPanel); - - weatherOpen = true; - }); - longitudinalToggle = manageRainOffsetsButton; - } else if (param == "RainStormOffsets") { - ButtonControl *manageRainStormOffsetsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageRainStormOffsetsButton, &ButtonControl::clicked, [longitudinalLayout, weatherRainStormPanel, this]() { - openSubSubSubPanel(); - - longitudinalLayout->setCurrentWidget(weatherRainStormPanel); - - weatherOpen = true; - }); - longitudinalToggle = manageRainStormOffsetsButton; - } else if (param == "SnowOffsets") { - ButtonControl *manageSnowOffsetsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageSnowOffsetsButton, &ButtonControl::clicked, [longitudinalLayout, weatherSnowPanel, this]() { - openSubSubSubPanel(); - - longitudinalLayout->setCurrentWidget(weatherSnowPanel); - - weatherOpen = true; - }); - longitudinalToggle = manageSnowOffsetsButton; - } else if (param == "IncreaseFollowingLowVisibility" || param == "IncreaseFollowingRain" || param == "IncreaseFollowingRainStorm" || param == "IncreaseFollowingSnow") { - std::map followTimeLabels; - for (float i = 0; i <= 3; i += 0.01) { - followTimeLabels[i] = std::lround(i / 0.01) == 1 / 0.01 ? QString::number(i, 'f', 2) + tr(" second") : QString::number(i, 'f', 2) + tr(" seconds"); - } - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 3, QString(), followTimeLabels, 0.01, true); - } else if (param == "IncreasedStoppedDistanceLowVisibility" || param == "IncreasedStoppedDistanceRain" || param == "IncreasedStoppedDistanceRainStorm" || param == "IncreasedStoppedDistanceSnow") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 10, tr(" feet")); - } else if (param == "ReduceAccelerationLowVisibility" || param == "ReduceAccelerationRain" || param == "ReduceAccelerationRainStorm" || param == "ReduceAccelerationSnow") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, "%", std::map(), 1); - } else if (param == "ReduceLateralAccelerationLowVisibility" || param == "ReduceLateralAccelerationRain" || param == "ReduceLateralAccelerationRainStorm" || param == "ReduceLateralAccelerationSnow") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 99, "%", std::map(), 1); - - } else if (param == "SpeedLimitController") { - StarPilotManageControl *speedLimitControllerToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(speedLimitControllerToggle, &StarPilotManageControl::manageButtonClicked, [longitudinalLayout, speedLimitControllerPanel]() { - longitudinalLayout->setCurrentWidget(speedLimitControllerPanel); - }); - longitudinalToggle = speedLimitControllerToggle; - } else if (param == "SLCFallback") { - std::vector fallbackOptions{tr("Set Speed"), tr("Experimental Mode"), tr("Previous Limit")}; - ButtonParamControl *fallbackSelection = new ButtonParamControl(param, title, desc, icon, fallbackOptions); - longitudinalToggle = fallbackSelection; - } else if (param == "SLCOverride") { - std::vector overrideOptions{tr("None"), tr("Set With Gas Pedal"), tr("Max Set Speed")}; - ButtonParamControl *overrideSelection = new ButtonParamControl(param, title, desc, icon, overrideOptions); - longitudinalToggle = overrideSelection; - } else if (param == "SLCPriority") { - ButtonControl *slcPriorityButton = new ButtonControl(title, tr("SELECT"), desc); - QStringList primaryPriorities = {tr("Dashboard"), tr("Map Data"), tr("Vision"), tr("Highest"), tr("Lowest")}; - QStringList otherPriorities = {tr("None"), tr("Dashboard"), tr("Map Data"), tr("Vision")}; - QStringList priorityPrompts = {tr("Select your primary priority"), tr("Select your secondary priority")}; - - QObject::connect(slcPriorityButton, &ButtonControl::clicked, [=]() { - QStringList selectedPriorities; - - for (int i = 1; i <= 2; ++i) { - QStringList availablePriorities = i == 1 ? primaryPriorities : otherPriorities; - availablePriorities = availablePriorities.toSet().subtract(selectedPriorities.toSet()).toList(); - - if (!parent->hasDashSpeedLimits) { - availablePriorities.removeAll(tr("Dashboard")); - } - if (availablePriorities.size() == 1 && availablePriorities.contains(tr("None"))) { - break; - } - - QString selection = MultiOptionDialog::getSelection(priorityPrompts[i - 1], availablePriorities, "", this); - if (selection.isEmpty()) { - if (i == 2 && !selectedPriorities.isEmpty()) { - params.put("SLCPriority2", tr("None").toStdString()); - } - break; - } - - selectedPriorities.append(selection); - - params.put(QString("SLCPriority%1").arg(i).toStdString(), selection.toStdString()); - if (selection == tr("None") || selection == tr("Lowest") || selection == tr("Highest")) { - for (int j = i + 1; j <= 2; ++j) { - params.put(QString("SLCPriority%1").arg(j).toStdString(), tr("None").toStdString()); - } - break; - } - } - - selectedPriorities.removeAll(tr("None")); - if (!selectedPriorities.isEmpty()) { - slcPriorityButton->setValue(selectedPriorities.join(", ")); - } - }); - - QStringList selectedPriorities; - for (int i = 1; i <= 2; ++i) { - QString priority = QString::fromStdString(params.get(QString("SLCPriority%1").arg(i).toStdString())); - if (primaryPriorities.contains(priority)) { - selectedPriorities.append(priority); - } - } - slcPriorityButton->setValue(selectedPriorities.join(", ")); - - longitudinalToggle = slcPriorityButton; - } else if (param == "SLCOffsets") { - ButtonControl *manageSLCOffsetsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageSLCOffsetsButton, &ButtonControl::clicked, [longitudinalLayout, speedLimitControllerOffsetsPanel, this]() { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(speedLimitControllerOffsetsPanel); - - slcOpen = true; - }); - longitudinalToggle = manageSLCOffsetsButton; - } else if (speedLimitControllerOffsetsKeys.contains(param)) { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, -99, 99, tr(" mph")); - } else if (param == "SLCQOL") { - ButtonControl *manageSLCQOLButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageSLCQOLButton, &ButtonControl::clicked, [longitudinalLayout, speedLimitControllerQOLPanel, this]() { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(speedLimitControllerQOLPanel); - - slcOpen = true; - }); - longitudinalToggle = manageSLCQOLButton; - } else if (param == "SLCConfirmation") { - std::vector confirmationToggles{"SLCConfirmationLower", "SLCConfirmationHigher"}; - std::vector confirmationToggleNames{tr("Lower Limits"), tr("Higher Limits")}; - longitudinalToggle = new StarPilotButtonToggleControl(param, title, desc, icon, confirmationToggles, confirmationToggleNames); - } else if (param == "SLCLookaheadHigher" || param == "SLCLookaheadLower") { - longitudinalToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 30, tr(" seconds")); - } else if (param == "SLCVisuals") { - ButtonControl *manageSLCVisualsButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(manageSLCVisualsButton, &ButtonControl::clicked, [longitudinalLayout, speedLimitControllerVisualPanel, this]() { - openSubSubPanel(); - - longitudinalLayout->setCurrentWidget(speedLimitControllerVisualPanel); - - slcOpen = true; - }); - longitudinalToggle = manageSLCVisualsButton; - - } else { - longitudinalToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = longitudinalToggle; - - if (advancedLongitudinalTuneKeys.contains(param)) { - advancedLongitudinalTuneList->addItem(longitudinalToggle); - } else if (aggressivePersonalityKeys.contains(param)) { - aggressivePersonalityList->addItem(longitudinalToggle); - } else if (conditionalChillKeys.contains(param)) { - conditionalChillList->addItem(longitudinalToggle); - } else if (conditionalExperimentalKeys.contains(param)) { - conditionalExperimentalList->addItem(longitudinalToggle); - } else if (curveSpeedKeys.contains(param)) { - curveSpeedList->addItem(longitudinalToggle); - } else if (customDrivingPersonalityKeys.contains(param)) { - customDrivingPersonalityList->addItem(longitudinalToggle); - } else if (longitudinalTuneKeys.contains(param)) { - longitudinalTuneList->addItem(longitudinalToggle); - } else if (qolKeys.contains(param)) { - qolList->addItem(longitudinalToggle); - } else if (relaxedPersonalityKeys.contains(param)) { - relaxedPersonalityList->addItem(longitudinalToggle); - } else if (speedLimitControllerKeys.contains(param)) { - speedLimitControllerList->addItem(longitudinalToggle); - } else if (speedLimitControllerOffsetsKeys.contains(param)) { - speedLimitControllerOffsetsList->addItem(longitudinalToggle); - } else if (speedLimitControllerQOLKeys.contains(param)) { - speedLimitControllerQOLList->addItem(longitudinalToggle); - } else if (speedLimitControllerVisualKeys.contains(param)) { - speedLimitControllerVisualList->addItem(longitudinalToggle); - } else if (standardPersonalityKeys.contains(param)) { - standardPersonalityList->addItem(longitudinalToggle); - } else if (trafficPersonalityKeys.contains(param)) { - trafficPersonalityList->addItem(longitudinalToggle); - } else if (weatherKeys.contains(param)) { - weatherList->addItem(longitudinalToggle); - } else if (weatherLowVisibilityKeys.contains(param)) { - weatherLowVisibilityList->addItem(longitudinalToggle); - } else if (weatherRainKeys.contains(param)) { - weatherRainList->addItem(longitudinalToggle); - } else if (weatherRainStormKeys.contains(param)) { - weatherRainStormList->addItem(longitudinalToggle); - } else if (weatherSnowKeys.contains(param)) { - weatherSnowList->addItem(longitudinalToggle); - } else { - longitudinalList->addItem(longitudinalToggle); - - parentKeys.insert(param); - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(longitudinalToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(longitudinalToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(longitudinalToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - QSet forceUpdateKeys = {"LongitudinalTune"}; - for (const QString &key : forceUpdateKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, this, &StarPilotLongitudinalPanel::updateToggles); - } - - QObject::connect(static_cast(toggles["EVTuning"]), &ToggleControl::toggleFlipped, this, [this]() { - if (params.getBool("EVTuning")) { - params.putBool("TruckTuning", false); - } - updateToggles(); - }); - QObject::connect(static_cast(toggles["TruckTuning"]), &ToggleControl::toggleFlipped, this, [this]() { - if (params.getBool("TruckTuning")) { - params.putBool("EVTuning", false); - } - updateToggles(); - }); - QObject::connect(static_cast(toggles["ConditionalExperimental"]), &ToggleControl::toggleFlipped, this, [this]() { - if (params.getBool("ConditionalExperimental")) { - params.putBool("ConditionalChill", false); - static_cast(toggles["ConditionalChill"])->refresh(); - } - updateToggles(); - }); - QObject::connect(static_cast(toggles["ConditionalChill"]), &ToggleControl::toggleFlipped, this, [this]() { - if (params.getBool("ConditionalChill")) { - params.putBool("ConditionalExperimental", false); - static_cast(toggles["ConditionalExperimental"])->refresh(); - } - updateToggles(); - }); - - StarPilotParamValueControl *trafficFollowToggle = static_cast(toggles["TrafficFollow"]); - StarPilotParamValueControl *trafficAccelerationToggle = static_cast(toggles["TrafficJerkAcceleration"]); - StarPilotParamValueControl *trafficDecelerationToggle = static_cast(toggles["TrafficJerkDeceleration"]); - StarPilotParamValueControl *trafficDangerToggle = static_cast(toggles["TrafficJerkDanger"]); - StarPilotParamValueControl *trafficSpeedToggle = static_cast(toggles["TrafficJerkSpeed"]); - StarPilotParamValueControl *trafficSpeedDecreaseToggle = static_cast(toggles["TrafficJerkSpeedDecrease"]); - StarPilotButtonsControl *trafficResetButton = static_cast(toggles["ResetTrafficPersonality"]); - QObject::connect(trafficResetButton, &StarPilotButtonsControl::buttonClicked, [=]() { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for Traffic Mode?"), this)) { - params.putFloat("TrafficFollow", std::stof(params.getKeyDefaultValue("TrafficFollow").value())); - params.putFloat("TrafficJerkAcceleration", std::stof(params.getKeyDefaultValue("TrafficJerkAcceleration").value())); - params.putFloat("TrafficJerkDeceleration", std::stof(params.getKeyDefaultValue("TrafficJerkDeceleration").value())); - params.putFloat("TrafficJerkDanger", std::stof(params.getKeyDefaultValue("TrafficJerkDanger").value())); - params.putFloat("TrafficJerkSpeed", std::stof(params.getKeyDefaultValue("TrafficJerkSpeed").value())); - params.putFloat("TrafficJerkSpeedDecrease", std::stof(params.getKeyDefaultValue("TrafficJerkSpeedDecrease").value())); - - trafficFollowToggle->refresh(); - trafficAccelerationToggle->refresh(); - trafficDecelerationToggle->refresh(); - trafficDangerToggle->refresh(); - trafficSpeedToggle->refresh(); - trafficSpeedDecreaseToggle->refresh(); - } - }); - - StarPilotParamValueControl *aggressiveFollowToggle = static_cast(toggles["AggressiveFollow"]); - StarPilotParamValueControl *aggressiveFollowHighToggle = static_cast(toggles["AggressiveFollowHigh"]); - StarPilotParamValueControl *aggressiveAccelerationToggle = static_cast(toggles["AggressiveJerkAcceleration"]); - StarPilotParamValueControl *aggressiveDecelerationToggle = static_cast(toggles["AggressiveJerkDeceleration"]); - StarPilotParamValueControl *aggressiveDangerToggle = static_cast(toggles["AggressiveJerkDanger"]); - StarPilotParamValueControl *aggressiveSpeedToggle = static_cast(toggles["AggressiveJerkSpeed"]); - StarPilotParamValueControl *aggressiveSpeedDecreaseToggle = static_cast(toggles["AggressiveJerkSpeedDecrease"]); - StarPilotButtonsControl *aggressiveResetButton = static_cast(toggles["ResetAggressivePersonality"]); - QObject::connect(aggressiveResetButton, &StarPilotButtonsControl::buttonClicked, [=]() { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the Aggressive personality?"), this)) { - params.putFloat("AggressiveFollow", std::stof(params.getKeyDefaultValue("AggressiveFollow").value())); - params.putFloat("AggressiveFollowHigh", std::stof(params.getKeyDefaultValue("AggressiveFollowHigh").value())); - params.putFloat("AggressiveJerkAcceleration", std::stof(params.getKeyDefaultValue("AggressiveJerkAcceleration").value())); - params.putFloat("AggressiveJerkDeceleration", std::stof(params.getKeyDefaultValue("AggressiveJerkDeceleration").value())); - params.putFloat("AggressiveJerkDanger", std::stof(params.getKeyDefaultValue("AggressiveJerkDanger").value())); - params.putFloat("AggressiveJerkSpeed", std::stof(params.getKeyDefaultValue("AggressiveJerkSpeed").value())); - params.putFloat("AggressiveJerkSpeedDecrease", std::stof(params.getKeyDefaultValue("AggressiveJerkSpeedDecrease").value())); - - aggressiveFollowToggle->refresh(); - aggressiveFollowHighToggle->refresh(); - aggressiveAccelerationToggle->refresh(); - aggressiveDecelerationToggle->refresh(); - aggressiveDangerToggle->refresh(); - aggressiveSpeedToggle->refresh(); - aggressiveSpeedDecreaseToggle->refresh(); - } - }); - - StarPilotParamValueControl *standardFollowToggle = static_cast(toggles["StandardFollow"]); - StarPilotParamValueControl *standardFollowHighToggle = static_cast(toggles["StandardFollowHigh"]); - StarPilotParamValueControl *standardAccelerationToggle = static_cast(toggles["StandardJerkAcceleration"]); - StarPilotParamValueControl *standardDecelerationToggle = static_cast(toggles["StandardJerkDeceleration"]); - StarPilotParamValueControl *standardDangerToggle = static_cast(toggles["StandardJerkDanger"]); - StarPilotParamValueControl *standardSpeedToggle = static_cast(toggles["StandardJerkSpeed"]); - StarPilotParamValueControl *standardSpeedDecreaseToggle = static_cast(toggles["StandardJerkSpeedDecrease"]); - StarPilotButtonsControl *standardResetButton = static_cast(toggles["ResetStandardPersonality"]); - QObject::connect(standardResetButton, &StarPilotButtonsControl::buttonClicked, [=]() { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the Standard personality?"), this)) { - params.putFloat("StandardFollow", std::stof(params.getKeyDefaultValue("StandardFollow").value())); - params.putFloat("StandardFollowHigh", std::stof(params.getKeyDefaultValue("StandardFollowHigh").value())); - params.putFloat("StandardJerkAcceleration", std::stof(params.getKeyDefaultValue("StandardJerkAcceleration").value())); - params.putFloat("StandardJerkDeceleration", std::stof(params.getKeyDefaultValue("StandardJerkDeceleration").value())); - params.putFloat("StandardJerkDanger", std::stof(params.getKeyDefaultValue("StandardJerkDanger").value())); - params.putFloat("StandardJerkSpeed", std::stof(params.getKeyDefaultValue("StandardJerkSpeed").value())); - params.putFloat("StandardJerkSpeedDecrease", std::stof(params.getKeyDefaultValue("StandardJerkSpeedDecrease").value())); - - standardFollowToggle->refresh(); - standardFollowHighToggle->refresh(); - standardAccelerationToggle->refresh(); - standardDecelerationToggle->refresh(); - standardDangerToggle->refresh(); - standardSpeedToggle->refresh(); - standardSpeedDecreaseToggle->refresh(); - } - }); - - StarPilotParamValueControl *relaxedFollowToggle = static_cast(toggles["RelaxedFollow"]); - StarPilotParamValueControl *relaxedFollowHighToggle = static_cast(toggles["RelaxedFollowHigh"]); - StarPilotParamValueControl *relaxedAccelerationToggle = static_cast(toggles["RelaxedJerkAcceleration"]); - StarPilotParamValueControl *relaxedDecelerationToggle = static_cast(toggles["RelaxedJerkDeceleration"]); - StarPilotParamValueControl *relaxedDangerToggle = static_cast(toggles["RelaxedJerkDanger"]); - StarPilotParamValueControl *relaxedSpeedToggle = static_cast(toggles["RelaxedJerkSpeed"]); - StarPilotParamValueControl *relaxedSpeedDecreaseToggle = static_cast(toggles["RelaxedJerkSpeedDecrease"]); - StarPilotButtonsControl *relaxedResetButton = static_cast(toggles["ResetRelaxedPersonality"]); - QObject::connect(relaxedResetButton, &StarPilotButtonsControl::buttonClicked, [=]() { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the Relaxed personality?"), this)) { - params.putFloat("RelaxedFollow", std::stof(params.getKeyDefaultValue("RelaxedFollow").value())); - params.putFloat("RelaxedFollowHigh", std::stof(params.getKeyDefaultValue("RelaxedFollowHigh").value())); - params.putFloat("RelaxedJerkAcceleration", std::stof(params.getKeyDefaultValue("RelaxedJerkAcceleration").value())); - params.putFloat("RelaxedJerkDeceleration", std::stof(params.getKeyDefaultValue("RelaxedJerkDeceleration").value())); - params.putFloat("RelaxedJerkDanger", std::stof(params.getKeyDefaultValue("RelaxedJerkDanger").value())); - params.putFloat("RelaxedJerkSpeed", std::stof(params.getKeyDefaultValue("RelaxedJerkSpeed").value())); - params.putFloat("RelaxedJerkSpeedDecrease", std::stof(params.getKeyDefaultValue("RelaxedJerkSpeedDecrease").value())); - - relaxedFollowToggle->refresh(); - relaxedFollowHighToggle->refresh(); - relaxedAccelerationToggle->refresh(); - relaxedDecelerationToggle->refresh(); - relaxedDangerToggle->refresh(); - relaxedSpeedToggle->refresh(); - relaxedSpeedDecreaseToggle->refresh(); - } - }); - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [longitudinalLayout, longitudinalPanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - longitudinalLayout->setCurrentWidget(longitudinalPanel); - }); - QObject::connect(parent, &StarPilotSettingsWindow::closeSubSubPanel, [longitudinalLayout, customDrivingPersonalityPanel, qolPanel, speedLimitControllerPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - - if (customPersonalityOpen) { - longitudinalLayout->setCurrentWidget(customDrivingPersonalityPanel); - - customPersonalityOpen = false; - } else if (qolOpen) { - longitudinalLayout->setCurrentWidget(qolPanel); - - qolOpen = false; - } else if (slcOpen) { - longitudinalLayout->setCurrentWidget(speedLimitControllerPanel); - - slcOpen = false; - } - }); - QObject::connect(parent, &StarPilotSettingsWindow::closeSubSubSubPanel, [longitudinalLayout, weatherPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - - if (weatherOpen) { - longitudinalLayout->setCurrentWidget(weatherPanel); - - weatherOpen = false; - } - }); - QObject::connect(parent, &StarPilotSettingsWindow::updateMetric, this, &StarPilotLongitudinalPanel::updateMetric); -} - -void StarPilotLongitudinalPanel::showEvent(QShowEvent *event) { - calibratedLateralAccelerationLabel->setText(QString::number(params.getFloat("CalibratedLateralAcceleration"), 'f', 2) + tr(" m/s²")); - calibrationProgressLabel->setText(QString::number(params.getFloat("CalibrationProgress"), 'f', 2) + "%"); - - longitudinalActuatorDelayToggle->setTitle(QString(tr("Actuator Delay (Default: %1)")).arg(QString::number(parent->longitudinalActuatorDelay, 'f', 2))); - startAccelToggle->setTitle(QString(tr("Start Acceleration (Default: %1)")).arg(QString::number(parent->startAccel, 'f', 2))); - stopAccelToggle->setTitle(QString(tr("Stop Acceleration (Default: %1)")).arg(QString::number(parent->stopAccel, 'f', 2))); - stoppingDecelRateToggle->setTitle(QString(tr("Stopping Rate (Default: %1)")).arg(QString::number(parent->stoppingDecelRate, 'f', 2))); - vEgoStartingToggle->setTitle(QString(tr("Start Speed (Default: %1)")).arg(QString::number(parent->vEgoStarting, 'f', 2))); - vEgoStoppingToggle->setTitle(QString(tr("Stop Speed (Default: %1)")).arg(QString::number(parent->vEgoStopping, 'f', 2))); - - - - updateToggles(); -} - -void StarPilotLongitudinalPanel::updateMetric(bool metric, bool bootRun) { - static bool previousMetric; - if (metric != previousMetric && !bootRun) { - double distanceConversion = metric ? FOOT_TO_METER : METER_TO_FOOT; - double speedConversion = metric ? MILE_TO_KM : KM_TO_MILE; - - params.putIntNonBlocking("IncreasedStoppedDistance", params.getInt("IncreasedStoppedDistance") * distanceConversion); - params.putIntNonBlocking("IncreasedStoppedDistanceLowVisibility", params.getInt("IncreasedStoppedDistanceLowVisibility") * distanceConversion); - params.putIntNonBlocking("IncreasedStoppedDistanceRain", params.getInt("IncreasedStoppedDistanceRain") * distanceConversion); - params.putIntNonBlocking("IncreasedStoppedDistanceRainStorm", params.getInt("IncreasedStoppedDistanceRainStorm") * distanceConversion); - params.putIntNonBlocking("IncreasedStoppedDistanceSnow", params.getInt("IncreasedStoppedDistanceSnow") * distanceConversion); - - params.putIntNonBlocking("CCMSpeed", params.getInt("CCMSpeed") * speedConversion); - params.putIntNonBlocking("CCMSpeedLead", params.getInt("CCMSpeedLead") * speedConversion); - params.putIntNonBlocking("CCMSetSpeedMargin", params.getInt("CCMSetSpeedMargin") * speedConversion); - params.putIntNonBlocking("CESignalSpeed", params.getInt("CESignalSpeed") * speedConversion); - params.putIntNonBlocking("CESpeed", params.getInt("CESpeed") * speedConversion); - params.putIntNonBlocking("CESpeedLead", params.getInt("CESpeedLead") * speedConversion); - params.putIntNonBlocking("CustomCruise", params.getInt("CustomCruise") * speedConversion); - params.putIntNonBlocking("CustomCruiseLong", params.getInt("CustomCruiseLong") * speedConversion); - params.putIntNonBlocking("Offset1", params.getInt("Offset1") * speedConversion); - params.putIntNonBlocking("Offset2", params.getInt("Offset2") * speedConversion); - params.putIntNonBlocking("Offset3", params.getInt("Offset3") * speedConversion); - params.putIntNonBlocking("Offset4", params.getInt("Offset4") * speedConversion); - params.putIntNonBlocking("Offset5", params.getInt("Offset5") * speedConversion); - params.putIntNonBlocking("Offset6", params.getInt("Offset6") * speedConversion); - params.putIntNonBlocking("Offset7", params.getInt("Offset7") * speedConversion); - params.putIntNonBlocking("SetSpeedOffset", params.getInt("SetSpeedOffset") * speedConversion); - } - previousMetric = metric; - - static std::map imperialDistanceLabels; - static std::map imperialSpeedLabels; - static std::map imperialOffsetLabels; - static std::map metricDistanceLabels; - static std::map metricSpeedLabels; - static std::map metricOffsetLabels; - - static bool labelsInitialized = false; - if (!labelsInitialized) { - for (int i = 0; i <= 10; ++i) { - imperialDistanceLabels[i] = i == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" foot") : QString::number(i) + tr(" feet"); - } - - for (int i = 0; i <= 99; ++i) { - imperialSpeedLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" mph"); - } - for (int i = -99; i <= 99; ++i) { - imperialOffsetLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" mph"); - } - - for (int i = 0; i <= 3; ++i) { - metricDistanceLabels[i] = i == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" meter") : QString::number(i) + tr(" meters"); - } - - for (int i = 0; i <= 150; ++i) { - metricSpeedLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" km/h"); - } - for (int i = -150; i <= 150; ++i) { - metricOffsetLabels[i] = i == 0 ? tr("Off") : QString::number(i) + tr(" km/h"); - } - - labelsInitialized = true; - } - - StarPilotDualParamValueControl *ccmSpeedToggle = reinterpret_cast(toggles["CCMSpeed"]); - StarPilotDualParamValueControl *ceSpeedToggle = reinterpret_cast(toggles["CESpeed"]); - StarPilotParamValueControl *ccmSetSpeedMarginToggle = static_cast(toggles["CCMSetSpeedMargin"]); - StarPilotParamValueButtonControl *ceSignal = static_cast(toggles["CESignalSpeed"]); - StarPilotParamValueControl *customCruiseToggle = static_cast(toggles["CustomCruise"]); - StarPilotParamValueControl *customCruiseLongToggle = static_cast(toggles["CustomCruiseLong"]); - StarPilotParamValueControl *offset1Toggle = static_cast(toggles["Offset1"]); - StarPilotParamValueControl *offset2Toggle = static_cast(toggles["Offset2"]); - StarPilotParamValueControl *offset3Toggle = static_cast(toggles["Offset3"]); - StarPilotParamValueControl *offset4Toggle = static_cast(toggles["Offset4"]); - StarPilotParamValueControl *offset5Toggle = static_cast(toggles["Offset5"]); - StarPilotParamValueControl *offset6Toggle = static_cast(toggles["Offset6"]); - StarPilotParamValueControl *offset7Toggle = static_cast(toggles["Offset7"]); - StarPilotParamValueControl *increasedStoppedDistanceToggle = static_cast(toggles["IncreasedStoppedDistance"]); - StarPilotParamValueControl *increasedStoppedDistanceLowVisibilityToggle = static_cast(toggles["IncreasedStoppedDistanceLowVisibility"]); - StarPilotParamValueControl *increasedStoppedDistanceRainToggle = static_cast(toggles["IncreasedStoppedDistanceRain"]); - StarPilotParamValueControl *increasedStoppedDistanceRainStormToggle = static_cast(toggles["IncreasedStoppedDistanceRainStorm"]); - StarPilotParamValueControl *increasedStoppedDistanceSnowToggle = static_cast(toggles["IncreasedStoppedDistanceSnow"]); - StarPilotParamValueControl *setSpeedOffsetToggle = static_cast(toggles["SetSpeedOffset"]); - - if (metric) { - offset1Toggle->setTitle(tr("Speed Offset (0–29 km/h)")); - offset2Toggle->setTitle(tr("Speed Offset (30–49 km/h)")); - offset3Toggle->setTitle(tr("Speed Offset (50–59 km/h)")); - offset4Toggle->setTitle(tr("Speed Offset (60–79 km/h)")); - offset5Toggle->setTitle(tr("Speed Offset (80–99 km/h)")); - offset6Toggle->setTitle(tr("Speed Offset (100–119 km/h)")); - offset7Toggle->setTitle(tr("Speed Offset (120–140 km/h)")); - - offset1Toggle->setDescription(tr("How much to offset posted speed-limits between 0 and 24 mph.")); - offset2Toggle->setDescription(tr("How much to offset posted speed-limits between 25 and 34 mph.")); - offset3Toggle->setDescription(tr("How much to offset posted speed-limits between 35 and 44 mph.")); - offset4Toggle->setDescription(tr("How much to offset posted speed-limits between 45 and 54 mph.")); - offset5Toggle->setDescription(tr("How much to offset posted speed-limits between 55 and 64 mph.")); - offset6Toggle->setDescription(tr("How much to offset posted speed-limits between 65 and 74 mph.")); - offset7Toggle->setDescription(tr("How much to offset posted speed-limits between 75 and 99 mph.")); - - increasedStoppedDistanceToggle->updateControl(0, 3, metricDistanceLabels); - increasedStoppedDistanceLowVisibilityToggle->updateControl(0, 3, metricDistanceLabels); - increasedStoppedDistanceRainToggle->updateControl(0, 3, metricDistanceLabels); - increasedStoppedDistanceRainStormToggle->updateControl(0, 3, metricDistanceLabels); - increasedStoppedDistanceSnowToggle->updateControl(0, 3, metricDistanceLabels); - - ccmSpeedToggle->updateControl(0, 150, metricSpeedLabels); - ccmSetSpeedMarginToggle->updateControl(0, 25, metricSpeedLabels); - ceSignal->updateControl(0, 150, metricSpeedLabels); - ceSpeedToggle->updateControl(0, 150, metricSpeedLabels); - customCruiseToggle->updateControl(1, 150, metricSpeedLabels); - customCruiseLongToggle->updateControl(1, 150, metricSpeedLabels); - offset1Toggle->updateControl(-150, 150, metricOffsetLabels); - offset2Toggle->updateControl(-150, 150, metricOffsetLabels); - offset3Toggle->updateControl(-150, 150, metricOffsetLabels); - offset4Toggle->updateControl(-150, 150, metricOffsetLabels); - offset5Toggle->updateControl(-150, 150, metricOffsetLabels); - offset6Toggle->updateControl(-150, 150, metricOffsetLabels); - offset7Toggle->updateControl(-150, 150, metricOffsetLabels); - setSpeedOffsetToggle->updateControl(-150, 150, metricSpeedLabels); - } else { - offset1Toggle->setTitle(tr("Speed Offset (0–24 mph)")); - offset2Toggle->setTitle(tr("Speed Offset (25–34 mph)")); - offset3Toggle->setTitle(tr("Speed Offset (35–44 mph)")); - offset4Toggle->setTitle(tr("Speed Offset (45–54 mph)")); - offset5Toggle->setTitle(tr("Speed Offset (55–64 mph)")); - offset6Toggle->setTitle(tr("Speed Offset (65–74 mph)")); - offset7Toggle->setTitle(tr("Speed Offset (75–99 mph)")); - - offset1Toggle->setDescription(tr("How much to offset posted speed-limits between 0 and 24 mph.")); - offset2Toggle->setDescription(tr("How much to offset posted speed-limits between 25 and 34 mph.")); - offset3Toggle->setDescription(tr("How much to offset posted speed-limits between 35 and 44 mph.")); - offset4Toggle->setDescription(tr("How much to offset posted speed-limits between 45 and 54 mph.")); - offset5Toggle->setDescription(tr("How much to offset posted speed-limits between 55 and 64 mph.")); - offset6Toggle->setDescription(tr("How much to offset posted speed-limits between 65 and 74 mph.")); - offset7Toggle->setDescription(tr("How much to offset posted speed-limits between 75 and 99 mph.")); - - increasedStoppedDistanceToggle->updateControl(0, 10, imperialDistanceLabels); - increasedStoppedDistanceLowVisibilityToggle->updateControl(0, 10, imperialDistanceLabels); - increasedStoppedDistanceRainToggle->updateControl(0, 10, imperialDistanceLabels); - increasedStoppedDistanceRainStormToggle->updateControl(0, 10, imperialDistanceLabels); - increasedStoppedDistanceSnowToggle->updateControl(0, 10, imperialDistanceLabels); - - ccmSpeedToggle->updateControl(0, 99, imperialSpeedLabels); - ccmSetSpeedMarginToggle->updateControl(0, 15, imperialSpeedLabels); - ceSignal->updateControl(0, 99, imperialSpeedLabels); - ceSpeedToggle->updateControl(0, 99, imperialSpeedLabels); - customCruiseToggle->updateControl(1, 99, imperialSpeedLabels); - customCruiseLongToggle->updateControl(1, 99, imperialSpeedLabels); - offset1Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset2Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset3Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset4Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset5Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset6Toggle->updateControl(-99, 99, imperialOffsetLabels); - offset7Toggle->updateControl(-99, 99, imperialOffsetLabels); - setSpeedOffsetToggle->updateControl(0, 99, imperialSpeedLabels); - } -} - -void StarPilotLongitudinalPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "CEStopLights") { - setVisible &= parent->tuningLevel < parent->starpilotToggleLevels["CEModelStopTime"].toDouble(); - } - - else if (key == "CustomCruise" || key == "CustomCruiseLong" || key == "SetSpeedLimit" || key == "SetSpeedOffset") { - setVisible &= !parent->hasPCMCruise; - } - - else if (key == "HumanLaneChanges") { - setVisible &= parent->hasRadar; - } - - else if (key == "RadarTakeoffs") { - setVisible &= parent->hasRadar; - } - - else if (key == "MapGears") { - setVisible &= parent->isToyota || parent->isHKG; - setVisible &= !parent->isTSK; - } - - else if (key == "ReverseCruise") { - setVisible &= parent->isToyota; - } - - else if (key == "SLCMapboxFiller") { - setVisible &= !params.get("MapboxSecretKey").empty(); - } - - else if (key == "StoppingDecelRate" || key == "VEgoStarting" || key == "VEgoStopping") { - setVisible &= !parent->isGM || !params.getBool("ExperimentalGMTune"); - } - } - - if (key == "EVTuning") { - toggle->setEnabled(!params.getBool("TruckTuning")); - } else if (key == "TruckTuning") { - toggle->setEnabled(!params.getBool("EVTuning")); - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (advancedLongitudinalTuneKeys.contains(key)) { - toggles["AdvancedLongitudinalTune"]->setVisible(true); - } else if (aggressivePersonalityKeys.contains(key)) { - toggles["AggressivePersonalityProfile"]->setVisible(true); - } else if (conditionalChillKeys.contains(key)) { - toggles["ConditionalChill"]->setVisible(true); - } else if (conditionalExperimentalKeys.contains(key)) { - toggles["ConditionalExperimental"]->setVisible(true); - } else if (curveSpeedKeys.contains(key)) { - toggles["CurveSpeedController"]->setVisible(true); - } else if (customDrivingPersonalityKeys.contains(key)) { - toggles["CustomPersonalities"]->setVisible(true); - } else if (longitudinalTuneKeys.contains(key)) { - toggles["LongitudinalTune"]->setVisible(true); - } else if (qolKeys.contains(key)) { - toggles["QOLLongitudinal"]->setVisible(true); - } else if (relaxedPersonalityKeys.contains(key)) { - toggles["RelaxedPersonalityProfile"]->setVisible(true); - } else if (speedLimitControllerKeys.contains(key)) { - toggles["SpeedLimitController"]->setVisible(true); - } else if (speedLimitControllerOffsetsKeys.contains(key)) { - toggles["SLCOffsets"]->setVisible(true); - } else if (speedLimitControllerQOLKeys.contains(key)) { - toggles["SLCQOL"]->setVisible(true); - } else if (speedLimitControllerVisualKeys.contains(key)) { - toggles["SLCVisuals"]->setVisible(true); - } else if (standardPersonalityKeys.contains(key)) { - toggles["StandardPersonalityProfile"]->setVisible(true); - } else if (trafficPersonalityKeys.contains(key)) { - toggles["TrafficPersonalityProfile"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/longitudinal_settings.h b/starpilot/ui/qt/offroad/longitudinal_settings.h deleted file mode 100644 index a0166c2c3..000000000 --- a/starpilot/ui/qt/offroad/longitudinal_settings.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotLongitudinalPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotLongitudinalPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - void openSubSubPanel(); - void openSubSubSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateMetric(bool metric, bool bootRun); - void updateToggles(); - - bool customPersonalityOpen; - bool forceOpenDescriptions; - bool qolOpen; - bool slcOpen; - bool weatherOpen; - - std::map toggles; - - QSet advancedLongitudinalTuneKeys = {"EVTuning", "TruckTuning", "TrailerLoad", "LongitudinalActuatorDelay", "MaxDesiredAcceleration", "StartAccel", "StopAccel", "StoppingDecelRate", "VEgoStarting", "VEgoStopping"}; - QSet aggressivePersonalityKeys = {"AggressiveFollow", "AggressiveFollowHigh", "AggressiveJerkAcceleration", "AggressiveJerkDeceleration", "AggressiveJerkDanger", "AggressiveJerkSpeed", "AggressiveJerkSpeedDecrease", "ResetAggressivePersonality"}; - QSet conditionalChillKeys = {"PersistChillState", "CCMSpeed", "CCMSpeedLead", "CCMLead", "CCMLaunchAssist", "CCMSetSpeedMargin", "ShowCCMStatus"}; - QSet conditionalExperimentalKeys = {"PersistExperimentalState", "CESpeed", "CESpeedLead", "CECurves", "CELead", "CEModelStopTime", "CESignalSpeed", "CEStopLights", "ShowCEMStatus"}; - QSet curveSpeedKeys = {"CalibratedLateralAcceleration", "CalibrationProgress", "ResetCurveData", "ShowCSCStatus"}; - QSet customDrivingPersonalityKeys = {"AggressivePersonalityProfile", "RelaxedPersonalityProfile", "StandardPersonalityProfile", "TrafficPersonalityProfile"}; - QSet longitudinalTuneKeys = {"AccelerationProfile", "DecelerationProfile", "HumanLaneChanges", "LeadDetectionThreshold", "TacoTune", "NavLongitudinalAllowed"}; - QSet qolKeys = {"CustomCruise", "CustomCruiseLong", "ForceStops", "ForceStopDistanceOffset", "ForceStandstill", "RadarTakeoffs", "IncreasedStoppedDistance", "MapGears", "ReverseCruise", "SetSpeedOffset", "WeatherPresets"}; - QSet relaxedPersonalityKeys = {"RelaxedFollow", "RelaxedFollowHigh", "RelaxedJerkAcceleration", "RelaxedJerkDeceleration", "RelaxedJerkDanger", "RelaxedJerkSpeed", "RelaxedJerkSpeedDecrease", "ResetRelaxedPersonality"}; - QSet speedLimitControllerKeys = {"SLCOffsets", "SLCFallback", "SLCOverride", "SLCPriority", "SLCQOL", "SLCVisuals"}; - QSet speedLimitControllerOffsetsKeys = {"Offset1", "Offset2", "Offset3", "Offset4", "Offset5", "Offset6", "Offset7"}; - QSet speedLimitControllerQOLKeys = {"SetSpeedLimit", "SLCConfirmation", "SLCLookaheadHigher", "SLCLookaheadLower", "SLCMapboxFiller", "VisionSpeedLimitDetection"}; - QSet speedLimitControllerVisualKeys = {"ShowSLCOffset", "SLCAbbreviatedSources", "SLCActiveSourcesOnly", "SpeedLimitSources"}; - QSet standardPersonalityKeys = {"StandardFollow", "StandardFollowHigh", "StandardJerkAcceleration", "StandardJerkDeceleration", "StandardJerkDanger", "StandardJerkSpeed", "StandardJerkSpeedDecrease", "ResetStandardPersonality"}; - QSet trafficPersonalityKeys = {"TrafficFollow", "TrafficJerkAcceleration", "TrafficJerkDeceleration", "TrafficJerkDanger", "TrafficJerkSpeed", "TrafficJerkSpeedDecrease", "ResetTrafficPersonality"}; - QSet weatherKeys = {"LowVisibilityOffsets", "RainOffsets", "RainStormOffsets", "SetWeatherKey", "SnowOffsets"}; - QSet weatherLowVisibilityKeys = {"IncreaseFollowingLowVisibility", "IncreasedStoppedDistanceLowVisibility", "ReduceAccelerationLowVisibility", "ReduceLateralAccelerationLowVisibility"}; - QSet weatherRainKeys = {"IncreaseFollowingRain", "IncreasedStoppedDistanceRain", "ReduceAccelerationRain", "ReduceLateralAccelerationRain"}; - QSet weatherRainStormKeys = {"IncreaseFollowingRainStorm", "IncreasedStoppedDistanceRainStorm", "ReduceAccelerationRainStorm", "ReduceLateralAccelerationRainStorm"}; - QSet weatherSnowKeys = {"IncreaseFollowingSnow", "IncreasedStoppedDistanceSnow", "ReduceAccelerationSnow", "ReduceLateralAccelerationSnow"}; - - QSet parentKeys; - - - - StarPilotParamValueControl *longitudinalActuatorDelayToggle; - StarPilotParamValueControl *startAccelToggle; - StarPilotParamValueControl *stopAccelToggle; - StarPilotParamValueControl *stoppingDecelRateToggle; - StarPilotParamValueControl *vEgoStartingToggle; - StarPilotParamValueControl *vEgoStoppingToggle; - - StarPilotSettingsWindow *parent; - - LabelControl *calibratedLateralAccelerationLabel; - LabelControl *calibrationProgressLabel; - - Params params; - - QNetworkAccessManager *networkManager; -}; diff --git a/starpilot/ui/qt/offroad/maps_settings.cc b/starpilot/ui/qt/offroad/maps_settings.cc deleted file mode 100644 index 24af3c8bb..000000000 --- a/starpilot/ui/qt/offroad/maps_settings.cc +++ /dev/null @@ -1,290 +0,0 @@ -#include -#include - -#include "starpilot/ui/qt/offroad/maps_settings.h" - -namespace { -bool hasDownloadedMaps(const QDir &dir) { - if (!dir.exists()) { - return false; - } - - QDirIterator it(dir.absolutePath(), QDir::Files, QDirIterator::Subdirectories); - return it.hasNext(); -} -} // namespace - -StarPilotMapsPanel::StarPilotMapsPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *mapsLayout = new QStackedLayout(); - addItem(mapsLayout); - - StarPilotListWidget *settingsList = new StarPilotListWidget(this); - - std::vector scheduleOptions{tr("Manually"), tr("Weekly"), tr("Monthly")}; - preferredSchedule = new ButtonParamControl("PreferredSchedule", tr("Automatically Update Maps"), - tr("How often maps update from \"OpenStreetMap (OSM)\" with the latest speed limit information. " - "Weekly updates run every Sunday; monthly updates run on the 1st."), - "", - scheduleOptions); - settingsList->addItem(preferredSchedule); - - downloadMapsButton = new ButtonControl(tr("Download Maps"), tr("DOWNLOAD"), tr("Manually update your selected map sources so \"Speed Limit Controller\" has the latest speed limit information.")); - QObject::connect(downloadMapsButton, &ButtonControl::clicked, [this] { - if (downloadMapsButton->text() == tr("CANCEL")) { - if (StarPilotConfirmationDialog::yesorno(tr("Cancel the download?"), this)) { - cancelDownload(); - } - } else { - startDownload(); - } - }); - settingsList->addItem(downloadMapsButton); - - settingsList->addItem(lastMapsDownload = new LabelControl(tr("Last Updated"), params.get("LastMapsUpdate").empty() ? "Never" : QString::fromStdString(params.get("LastMapsUpdate")))); - - selectMaps = new StarPilotButtonsControl(tr("Map Sources"), - tr("Select the countries or U.S. states to use with \"Speed Limit Controller\".") , - "", {tr("COUNTRIES"), tr("STATES")}); - QObject::connect(selectMaps, &StarPilotButtonsControl::buttonClicked, [mapsLayout, this](int id) { - mapsLayout->setCurrentIndex(id + 1); - - openSubPanel(); - }); - settingsList->addItem(selectMaps); - - settingsList->addItem(downloadStatus = new LabelControl(tr("Progress"))); - settingsList->addItem(downloadTimeElapsed = new LabelControl(tr("Time Elapsed"))); - settingsList->addItem(downloadETA = new LabelControl(tr("Time Remaining"))); - - downloadETA->setVisible(false); - downloadStatus->setVisible(false); - downloadTimeElapsed->setVisible(false); - - removeMapsButton = new ButtonControl(tr("Remove Maps"), tr("REMOVE"), tr("Delete downloaded map data to free up storage space.")); - QObject::connect(removeMapsButton, &ButtonControl::clicked, [this] { - if (StarPilotConfirmationDialog::yesorno(tr("Delete all downloaded maps?"), this)) { - std::thread([this] { - mapsSize->setText(tr("0 MB")); - - mapsFolderPath.removeRecursively(); - }).detach(); - } - }); - settingsList->addItem(removeMapsButton); - - settingsList->addItem(mapsSize = new LabelControl(tr("Storage Used"), calculateDirectorySize(mapsFolderPath))); - - ScrollView *settingsPanel = new ScrollView(settingsList, this); - mapsLayout->addWidget(settingsPanel); - - StarPilotListWidget *countriesList = new StarPilotListWidget(this); - std::vector>> countries = { - {tr("Africa"), africaMap}, - {tr("Antarctica"), antarcticaMap}, - {tr("Asia"), asiaMap}, - {tr("Europe"), europeMap}, - {tr("North America"), northAmericaMap}, - {tr("Oceania"), oceaniaMap}, - {tr("South America"), southAmericaMap} - }; - - for (std::pair> country : countries) { - countriesList->addItem(new LabelControl(country.first, "")); - countriesList->addItem(new MapSelectionControl(country.second, true)); - } - - ScrollView *countryMapsPanel = new ScrollView(countriesList, this); - mapsLayout->addWidget(countryMapsPanel); - - StarPilotListWidget *statesList = new StarPilotListWidget(this); - std::vector>> states = { - {tr("United States - Midwest"), midwestMap}, - {tr("United States - Northeast"), northeastMap}, - {tr("United States - South"), southMap}, - {tr("United States - West"), westMap}, - {tr("United States - Territories"), territoriesMap} - }; - - for (std::pair> state : states) { - statesList->addItem(new LabelControl(state.first, "")); - statesList->addItem(new MapSelectionControl(state.second)); - } - - ScrollView *stateMapsPanel = new ScrollView(statesList, this); - mapsLayout->addWidget(stateMapsPanel); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [mapsLayout, settingsPanel, this] { - if (forceOpenDescriptions) { - downloadMapsButton->showDescription(); - preferredSchedule->showDescription(); - removeMapsButton->showDescription(); - selectMaps->showDescription(); - } - - hasMapsSelected = !params.get("MapsSelected").empty(); - - mapsLayout->setCurrentWidget(settingsPanel); - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotMapsPanel::updateState); -} - -void StarPilotMapsPanel::showEvent(QShowEvent *event) { - if (forceOpenDescriptions) { - downloadMapsButton->showDescription(); - preferredSchedule->showDescription(); - removeMapsButton->showDescription(); - selectMaps->showDescription(); - } - - UIState &s = *uiState(); - UIScene &scene = s.scene; - - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - SubMaster &fpsm = *(fs.sm); - - const cereal::MapdExtendedOut::Reader &mapdExtendedOut = fpsm["mapdExtendedOut"].getMapdExtendedOut(); - const cereal::MapdDownloadProgress::Reader &downloadProgress = mapdExtendedOut.getDownloadProgress(); - - bool mapDownloadActive = downloadProgress.getActive(); - - int mapDownloadDownloaded = downloadProgress.getDownloadedFiles(); - int mapDownloadTotal = downloadProgress.getTotalFiles(); - - hasMapsSelected = !params.get("MapsSelected").empty(); - - bool parked = !scene.started || starpilot_scene.parked || parent->isFrogsGoMoo; - - removeMapsButton->setVisible(hasDownloadedMaps(mapsFolderPath)); - - if (mapDownloadActive) { - downloadMapsButton->setText(tr("CANCEL")); - downloadStatus->setText(tr("Calculating...")); - - downloadStatus->setVisible(true); - - lastMapsDownload->setVisible(false); - removeMapsButton->setVisible(false); - - updateDownloadLabels(mapDownloadDownloaded, mapDownloadTotal); - } else { - downloadMapsButton->setEnabled(!cancellingDownload && hasMapsSelected && starpilot_scene.online && parked); - downloadMapsButton->setValue(starpilot_scene.online ? (parked ? "" : tr("Not parked")) : tr("Offline...")); - } -} - - -void StarPilotMapsPanel::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible()) { - return; - } - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const UIScene &scene = s.scene; - const SubMaster &fpsm = *(fs.sm); - - const cereal::MapdExtendedOut::Reader &mapdExtendedOut = fpsm["mapdExtendedOut"].getMapdExtendedOut(); - const cereal::MapdDownloadProgress::Reader &downloadProgress = mapdExtendedOut.getDownloadProgress(); - - bool mapDownloadActive = downloadProgress.getActive(); - bool parked = !scene.started || starpilot_scene.parked || parent->isFrogsGoMoo; - - int mapDownloadDownloaded = downloadProgress.getDownloadedFiles(); - int mapDownloadTotal = downloadProgress.getTotalFiles(); - - if (mapDownloadActive && !cancellingDownload) { - updateDownloadLabels(mapDownloadDownloaded, mapDownloadTotal); - } else if (downloadMapsButton->text() == tr("CANCEL")) { - updateDownloadLabels(mapDownloadDownloaded, mapDownloadTotal); - } else { - downloadMapsButton->setEnabled(!cancellingDownload && hasMapsSelected && starpilot_scene.online && parked); - downloadMapsButton->setValue(starpilot_scene.online ? (parked ? "" : tr("Not parked")) : tr("Offline...")); - } - - parent->keepScreenOn = mapDownloadActive; -} - -void StarPilotMapsPanel::cancelDownload() { - cancellingDownload = true; - - downloadMapsButton->setEnabled(false); - - downloadETA->setText(tr("Calculating...")); - downloadMapsButton->setText(tr("CANCEL")); - downloadStatus->setText(tr("Calculating...")); - downloadTimeElapsed->setText(tr("Calculating...")); - - params_memory.putBool("CancelDownloadMaps", true); - params_memory.remove("DownloadMaps"); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - - downloadMapsButton->setEnabled(true); - - downloadMapsButton->setText(tr("DOWNLOAD")); - - downloadETA->setVisible(false); - downloadStatus->setVisible(false); - downloadTimeElapsed->setVisible(false); - - lastMapsDownload->setVisible(true); - removeMapsButton->setVisible(hasDownloadedMaps(mapsFolderPath)); - - update(); - }); -} - -void StarPilotMapsPanel::startDownload() { - downloadETA->setText(tr("Calculating...")); - downloadMapsButton->setText(tr("CANCEL")); - downloadStatus->setText(tr("Calculating...")); - downloadTimeElapsed->setText(tr("Calculating...")); - - downloadETA->setVisible(true); - downloadStatus->setVisible(true); - downloadTimeElapsed->setVisible(true); - - lastMapsDownload->setVisible(false); - removeMapsButton->setVisible(false); - - elapsedTime.start(); - startTime = QDateTime::currentDateTime(); - - params_memory.putBool("DownloadMaps", true); -} - -void StarPilotMapsPanel::updateDownloadLabels(int downloadedFiles, int totalFiles) { - if (downloadedFiles == totalFiles && totalFiles != 0) { - downloadMapsButton->setText(tr("DOWNLOAD")); - lastMapsDownload->setText(formatCurrentDate()); - - downloadETA->setVisible(false); - downloadStatus->setVisible(false); - downloadTimeElapsed->setVisible(false); - - lastMapsDownload->setVisible(true); - removeMapsButton->setVisible(hasDownloadedMaps(mapsFolderPath)); - - params.put("LastMapsUpdate", formatCurrentDate().toStdString()); - - update(); - - return; - } - - static int previousDownloadedFiles = 0; - if (downloadedFiles != previousDownloadedFiles) { - std::thread([this]() { - mapsSize->setText(calculateDirectorySize(mapsFolderPath)); - }).detach(); - } - - downloadETA->setText(QString("%1").arg(formatETA(elapsedTime.elapsed(), downloadedFiles, previousDownloadedFiles, totalFiles, startTime))); - downloadStatus->setText(QString("%1 / %2 (%3%)").arg(downloadedFiles).arg(totalFiles).arg((downloadedFiles * 100) / (totalFiles == 0 ? 1 : totalFiles))); - downloadTimeElapsed->setText(formatElapsedTime(elapsedTime.elapsed())); - - previousDownloadedFiles = downloadedFiles; -} diff --git a/starpilot/ui/qt/offroad/maps_settings.h b/starpilot/ui/qt/offroad/maps_settings.h deleted file mode 100644 index eb12ddbd9..000000000 --- a/starpilot/ui/qt/offroad/maps_settings.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" -#include "starpilot/ui/qt/widgets/navigation_functions.h" - -class StarPilotMapsPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotMapsPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void cancelDownload(); - void startDownload(); - void updateDownloadLabels(int downloadedFiles, int totalFiles); - void updateState(const UIState &s, const StarPilotUIState &fs); - - bool cancellingDownload; - bool forceOpenDescriptions; - bool hasMapsSelected; - - ButtonControl *downloadMapsButton; - ButtonControl *removeMapsButton; - - ButtonParamControl *preferredSchedule; - - StarPilotButtonsControl *selectMaps; - - StarPilotSettingsWindow *parent; - - LabelControl *downloadETA; - LabelControl *downloadStatus; - LabelControl *downloadTimeElapsed; - LabelControl *lastMapsDownload; - LabelControl *mapsSize; - - Params params; - Params params_memory{"", true}; - - QDateTime startTime; - - QDir mapsFolderPath{"/data/media/0/osm/offline"}; - - QElapsedTimer elapsedTime; -}; diff --git a/starpilot/ui/qt/offroad/moc_data_settings.cc b/starpilot/ui/qt/offroad/moc_data_settings.cc deleted file mode 100644 index aa212342f..000000000 --- a/starpilot/ui/qt/offroad/moc_data_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'data_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "data_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'data_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotDataPanel_t { - QByteArrayData data[3]; - char stringdata0[33]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotDataPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotDataPanel_t qt_meta_stringdata_StarPilotDataPanel = { - { -QT_MOC_LITERAL(0, 0, 18), // "StarPilotDataPanel" -QT_MOC_LITERAL(1, 19, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 32, 0) // "" - - }, - "StarPilotDataPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotDataPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotDataPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotDataPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotDataPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotDataPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotDataPanel.data, - qt_meta_data_StarPilotDataPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotDataPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotDataPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotDataPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotDataPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotDataPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_device_settings.cc b/starpilot/ui/qt/offroad/moc_device_settings.cc deleted file mode 100644 index a00bda66b..000000000 --- a/starpilot/ui/qt/offroad/moc_device_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'device_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "device_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'device_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotDevicePanel_t { - QByteArrayData data[3]; - char stringdata0[35]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotDevicePanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotDevicePanel_t qt_meta_stringdata_StarPilotDevicePanel = { - { -QT_MOC_LITERAL(0, 0, 20), // "StarPilotDevicePanel" -QT_MOC_LITERAL(1, 21, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 34, 0) // "" - - }, - "StarPilotDevicePanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotDevicePanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotDevicePanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotDevicePanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotDevicePanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotDevicePanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotDevicePanel.data, - qt_meta_data_StarPilotDevicePanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotDevicePanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotDevicePanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotDevicePanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotDevicePanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotDevicePanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_expandable_multi_option_dialog.cc b/starpilot/ui/qt/offroad/moc_expandable_multi_option_dialog.cc deleted file mode 100644 index 5adae0880..000000000 --- a/starpilot/ui/qt/offroad/moc_expandable_multi_option_dialog.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'expandable_multi_option_dialog.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "expandable_multi_option_dialog.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'expandable_multi_option_dialog.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ExpandableMultiOptionDialog_t { - QByteArrayData data[1]; - char stringdata0[28]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ExpandableMultiOptionDialog_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ExpandableMultiOptionDialog_t qt_meta_stringdata_ExpandableMultiOptionDialog = { - { -QT_MOC_LITERAL(0, 0, 27) // "ExpandableMultiOptionDialog" - - }, - "ExpandableMultiOptionDialog" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ExpandableMultiOptionDialog[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void ExpandableMultiOptionDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ExpandableMultiOptionDialog::staticMetaObject = { { - &DialogBase::staticMetaObject, - qt_meta_stringdata_ExpandableMultiOptionDialog.data, - qt_meta_data_ExpandableMultiOptionDialog, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ExpandableMultiOptionDialog::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ExpandableMultiOptionDialog::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ExpandableMultiOptionDialog.stringdata0)) - return static_cast(this); - return DialogBase::qt_metacast(_clname); -} - -int ExpandableMultiOptionDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = DialogBase::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_lateral_settings.cc b/starpilot/ui/qt/offroad/moc_lateral_settings.cc deleted file mode 100644 index 269b02a23..000000000 --- a/starpilot/ui/qt/offroad/moc_lateral_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'lateral_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "lateral_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'lateral_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotLateralPanel_t { - QByteArrayData data[3]; - char stringdata0[36]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotLateralPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotLateralPanel_t qt_meta_stringdata_StarPilotLateralPanel = { - { -QT_MOC_LITERAL(0, 0, 21), // "StarPilotLateralPanel" -QT_MOC_LITERAL(1, 22, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 35, 0) // "" - - }, - "StarPilotLateralPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotLateralPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotLateralPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotLateralPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotLateralPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotLateralPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotLateralPanel.data, - qt_meta_data_StarPilotLateralPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotLateralPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotLateralPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotLateralPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotLateralPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotLateralPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_longitudinal_settings.cc b/starpilot/ui/qt/offroad/moc_longitudinal_settings.cc deleted file mode 100644 index e7529eb1f..000000000 --- a/starpilot/ui/qt/offroad/moc_longitudinal_settings.cc +++ /dev/null @@ -1,168 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'longitudinal_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "longitudinal_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'longitudinal_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotLongitudinalPanel_t { - QByteArrayData data[5]; - char stringdata0[76]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotLongitudinalPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotLongitudinalPanel_t qt_meta_stringdata_StarPilotLongitudinalPanel = { - { -QT_MOC_LITERAL(0, 0, 26), // "StarPilotLongitudinalPanel" -QT_MOC_LITERAL(1, 27, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 40, 0), // "" -QT_MOC_LITERAL(3, 41, 15), // "openSubSubPanel" -QT_MOC_LITERAL(4, 57, 18) // "openSubSubSubPanel" - - }, - "StarPilotLongitudinalPanel\0openSubPanel\0" - "\0openSubSubPanel\0openSubSubSubPanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotLongitudinalPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 3, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 3, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 29, 2, 0x06 /* Public */, - 3, 0, 30, 2, 0x06 /* Public */, - 4, 0, 31, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void StarPilotLongitudinalPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - case 1: _t->openSubSubPanel(); break; - case 2: _t->openSubSubSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotLongitudinalPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotLongitudinalPanel::openSubPanel)) { - *result = 0; - return; - } - } - { - using _t = void (StarPilotLongitudinalPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotLongitudinalPanel::openSubSubPanel)) { - *result = 1; - return; - } - } - { - using _t = void (StarPilotLongitudinalPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotLongitudinalPanel::openSubSubSubPanel)) { - *result = 2; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotLongitudinalPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotLongitudinalPanel.data, - qt_meta_data_StarPilotLongitudinalPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotLongitudinalPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotLongitudinalPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotLongitudinalPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotLongitudinalPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 3) - qt_static_metacall(this, _c, _id, _a); - _id -= 3; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 3) - *reinterpret_cast(_a[0]) = -1; - _id -= 3; - } - return _id; -} - -// SIGNAL 0 -void StarPilotLongitudinalPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void StarPilotLongitudinalPanel::openSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} - -// SIGNAL 2 -void StarPilotLongitudinalPanel::openSubSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_maps_settings.cc b/starpilot/ui/qt/offroad/moc_maps_settings.cc deleted file mode 100644 index ec40879cb..000000000 --- a/starpilot/ui/qt/offroad/moc_maps_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'maps_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "maps_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'maps_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotMapsPanel_t { - QByteArrayData data[3]; - char stringdata0[33]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotMapsPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotMapsPanel_t qt_meta_stringdata_StarPilotMapsPanel = { - { -QT_MOC_LITERAL(0, 0, 18), // "StarPilotMapsPanel" -QT_MOC_LITERAL(1, 19, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 32, 0) // "" - - }, - "StarPilotMapsPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotMapsPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotMapsPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotMapsPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotMapsPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotMapsPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotMapsPanel.data, - qt_meta_data_StarPilotMapsPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotMapsPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotMapsPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotMapsPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotMapsPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotMapsPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_model_settings.cc b/starpilot/ui/qt/offroad/moc_model_settings.cc deleted file mode 100644 index aa73fde7e..000000000 --- a/starpilot/ui/qt/offroad/moc_model_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'model_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "model_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'model_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotModelPanel_t { - QByteArrayData data[3]; - char stringdata0[34]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotModelPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotModelPanel_t qt_meta_stringdata_StarPilotModelPanel = { - { -QT_MOC_LITERAL(0, 0, 19), // "StarPilotModelPanel" -QT_MOC_LITERAL(1, 20, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 33, 0) // "" - - }, - "StarPilotModelPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotModelPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotModelPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotModelPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotModelPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotModelPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotModelPanel.data, - qt_meta_data_StarPilotModelPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotModelPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotModelPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotModelPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotModelPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotModelPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_navigation_settings.cc b/starpilot/ui/qt/offroad/moc_navigation_settings.cc deleted file mode 100644 index 42d738dd3..000000000 --- a/starpilot/ui/qt/offroad/moc_navigation_settings.cc +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'navigation_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "navigation_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'navigation_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotNavigationPanel_t { - QByteArrayData data[4]; - char stringdata0[53]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotNavigationPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotNavigationPanel_t qt_meta_stringdata_StarPilotNavigationPanel = { - { -QT_MOC_LITERAL(0, 0, 24), // "StarPilotNavigationPanel" -QT_MOC_LITERAL(1, 25, 13), // "closeSubPanel" -QT_MOC_LITERAL(2, 39, 0), // "" -QT_MOC_LITERAL(3, 40, 12) // "openSubPanel" - - }, - "StarPilotNavigationPanel\0closeSubPanel\0" - "\0openSubPanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotNavigationPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 24, 2, 0x06 /* Public */, - 3, 0, 25, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void StarPilotNavigationPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->closeSubPanel(); break; - case 1: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotNavigationPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotNavigationPanel::closeSubPanel)) { - *result = 0; - return; - } - } - { - using _t = void (StarPilotNavigationPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotNavigationPanel::openSubPanel)) { - *result = 1; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotNavigationPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotNavigationPanel.data, - qt_meta_data_StarPilotNavigationPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotNavigationPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotNavigationPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotNavigationPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotNavigationPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void StarPilotNavigationPanel::closeSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void StarPilotNavigationPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_sounds_settings.cc b/starpilot/ui/qt/offroad/moc_sounds_settings.cc deleted file mode 100644 index 0d51e65a0..000000000 --- a/starpilot/ui/qt/offroad/moc_sounds_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'sounds_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "sounds_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'sounds_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotSoundsPanel_t { - QByteArrayData data[3]; - char stringdata0[35]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotSoundsPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotSoundsPanel_t qt_meta_stringdata_StarPilotSoundsPanel = { - { -QT_MOC_LITERAL(0, 0, 20), // "StarPilotSoundsPanel" -QT_MOC_LITERAL(1, 21, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 34, 0) // "" - - }, - "StarPilotSoundsPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotSoundsPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotSoundsPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotSoundsPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSoundsPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotSoundsPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotSoundsPanel.data, - qt_meta_data_StarPilotSoundsPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotSoundsPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotSoundsPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotSoundsPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotSoundsPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotSoundsPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_starpilot_settings.cc b/starpilot/ui/qt/offroad/moc_starpilot_settings.cc deleted file mode 100644 index 2b27a8e5d..000000000 --- a/starpilot/ui/qt/offroad/moc_starpilot_settings.cc +++ /dev/null @@ -1,280 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotSettingsWindow_t { - QByteArrayData data[14]; - char stringdata0[187]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotSettingsWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotSettingsWindow_t qt_meta_stringdata_StarPilotSettingsWindow = { - { -QT_MOC_LITERAL(0, 0, 23), // "StarPilotSettingsWindow" -QT_MOC_LITERAL(1, 24, 13), // "closeSubPanel" -QT_MOC_LITERAL(2, 38, 0), // "" -QT_MOC_LITERAL(3, 39, 16), // "closeSubSubPanel" -QT_MOC_LITERAL(4, 56, 19), // "closeSubSubSubPanel" -QT_MOC_LITERAL(5, 76, 9), // "openPanel" -QT_MOC_LITERAL(6, 86, 12), // "openSubPanel" -QT_MOC_LITERAL(7, 99, 15), // "openSubSubPanel" -QT_MOC_LITERAL(8, 115, 18), // "openSubSubSubPanel" -QT_MOC_LITERAL(9, 134, 18), // "tuningLevelChanged" -QT_MOC_LITERAL(10, 153, 5), // "level" -QT_MOC_LITERAL(11, 159, 12), // "updateMetric" -QT_MOC_LITERAL(12, 172, 6), // "metric" -QT_MOC_LITERAL(13, 179, 7) // "bootRun" - - }, - "StarPilotSettingsWindow\0closeSubPanel\0" - "\0closeSubSubPanel\0closeSubSubSubPanel\0" - "openPanel\0openSubPanel\0openSubSubPanel\0" - "openSubSubSubPanel\0tuningLevelChanged\0" - "level\0updateMetric\0metric\0bootRun" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotSettingsWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 10, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 10, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 64, 2, 0x06 /* Public */, - 3, 0, 65, 2, 0x06 /* Public */, - 4, 0, 66, 2, 0x06 /* Public */, - 5, 0, 67, 2, 0x06 /* Public */, - 6, 0, 68, 2, 0x06 /* Public */, - 7, 0, 69, 2, 0x06 /* Public */, - 8, 0, 70, 2, 0x06 /* Public */, - 9, 1, 71, 2, 0x06 /* Public */, - 11, 2, 74, 2, 0x06 /* Public */, - 11, 1, 79, 2, 0x26 /* Public | MethodCloned */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, - QMetaType::Void, QMetaType::Int, 10, - QMetaType::Void, QMetaType::Bool, QMetaType::Bool, 12, 13, - QMetaType::Void, QMetaType::Bool, 12, - - 0 // eod -}; - -void StarPilotSettingsWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->closeSubPanel(); break; - case 1: _t->closeSubSubPanel(); break; - case 2: _t->closeSubSubSubPanel(); break; - case 3: _t->openPanel(); break; - case 4: _t->openSubPanel(); break; - case 5: _t->openSubSubPanel(); break; - case 6: _t->openSubSubSubPanel(); break; - case 7: _t->tuningLevelChanged((*reinterpret_cast< int(*)>(_a[1]))); break; - case 8: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; - case 9: _t->updateMetric((*reinterpret_cast< bool(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::closeSubPanel)) { - *result = 0; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::closeSubSubPanel)) { - *result = 1; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::closeSubSubSubPanel)) { - *result = 2; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::openPanel)) { - *result = 3; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::openSubPanel)) { - *result = 4; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::openSubSubPanel)) { - *result = 5; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::openSubSubSubPanel)) { - *result = 6; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::tuningLevelChanged)) { - *result = 7; - return; - } - } - { - using _t = void (StarPilotSettingsWindow::*)(bool , bool ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotSettingsWindow::updateMetric)) { - *result = 8; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotSettingsWindow::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_StarPilotSettingsWindow.data, - qt_meta_data_StarPilotSettingsWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotSettingsWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotSettingsWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotSettingsWindow.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int StarPilotSettingsWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 10) - qt_static_metacall(this, _c, _id, _a); - _id -= 10; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 10) - *reinterpret_cast(_a[0]) = -1; - _id -= 10; - } - return _id; -} - -// SIGNAL 0 -void StarPilotSettingsWindow::closeSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void StarPilotSettingsWindow::closeSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} - -// SIGNAL 2 -void StarPilotSettingsWindow::closeSubSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 2, nullptr); -} - -// SIGNAL 3 -void StarPilotSettingsWindow::openPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 3, nullptr); -} - -// SIGNAL 4 -void StarPilotSettingsWindow::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 4, nullptr); -} - -// SIGNAL 5 -void StarPilotSettingsWindow::openSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 5, nullptr); -} - -// SIGNAL 6 -void StarPilotSettingsWindow::openSubSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 6, nullptr); -} - -// SIGNAL 7 -void StarPilotSettingsWindow::tuningLevelChanged(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 7, _a); -} - -// SIGNAL 8 -void StarPilotSettingsWindow::updateMetric(bool _t1, bool _t2) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; - QMetaObject::activate(this, &staticMetaObject, 8, _a); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_theme_settings.cc b/starpilot/ui/qt/offroad/moc_theme_settings.cc deleted file mode 100644 index f57592f48..000000000 --- a/starpilot/ui/qt/offroad/moc_theme_settings.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'theme_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "theme_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'theme_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotThemesPanel_t { - QByteArrayData data[3]; - char stringdata0[35]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotThemesPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotThemesPanel_t qt_meta_stringdata_StarPilotThemesPanel = { - { -QT_MOC_LITERAL(0, 0, 20), // "StarPilotThemesPanel" -QT_MOC_LITERAL(1, 21, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 34, 0) // "" - - }, - "StarPilotThemesPanel\0openSubPanel\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotThemesPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotThemesPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotThemesPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotThemesPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotThemesPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotThemesPanel.data, - qt_meta_data_StarPilotThemesPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotThemesPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotThemesPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotThemesPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotThemesPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotThemesPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_utilities.cc b/starpilot/ui/qt/offroad/moc_utilities.cc deleted file mode 100644 index c35509e9a..000000000 --- a/starpilot/ui/qt/offroad/moc_utilities.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'utilities.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "utilities.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'utilities.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotUtilitiesPanel_t { - QByteArrayData data[1]; - char stringdata0[24]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotUtilitiesPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotUtilitiesPanel_t qt_meta_stringdata_StarPilotUtilitiesPanel = { - { -QT_MOC_LITERAL(0, 0, 23) // "StarPilotUtilitiesPanel" - - }, - "StarPilotUtilitiesPanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotUtilitiesPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotUtilitiesPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotUtilitiesPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotUtilitiesPanel.data, - qt_meta_data_StarPilotUtilitiesPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotUtilitiesPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotUtilitiesPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotUtilitiesPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotUtilitiesPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_vehicle_settings.cc b/starpilot/ui/qt/offroad/moc_vehicle_settings.cc deleted file mode 100644 index 496a53f43..000000000 --- a/starpilot/ui/qt/offroad/moc_vehicle_settings.cc +++ /dev/null @@ -1,134 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'vehicle_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "vehicle_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'vehicle_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotVehiclesPanel_t { - QByteArrayData data[3]; - char stringdata0[37]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotVehiclesPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotVehiclesPanel_t qt_meta_stringdata_StarPilotVehiclesPanel = { - { -QT_MOC_LITERAL(0, 0, 22), // "StarPilotVehiclesPanel" -QT_MOC_LITERAL(1, 23, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 36, 0) // "" - - }, - "StarPilotVehiclesPanel\0openSubPanel\0" - "" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotVehiclesPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotVehiclesPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotVehiclesPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotVehiclesPanel::openSubPanel)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotVehiclesPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotVehiclesPanel.data, - qt_meta_data_StarPilotVehiclesPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotVehiclesPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotVehiclesPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotVehiclesPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotVehiclesPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotVehiclesPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_visual_settings.cc b/starpilot/ui/qt/offroad/moc_visual_settings.cc deleted file mode 100644 index b65ed4b10..000000000 --- a/starpilot/ui/qt/offroad/moc_visual_settings.cc +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'visual_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "visual_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'visual_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotVisualsPanel_t { - QByteArrayData data[4]; - char stringdata0[52]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotVisualsPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotVisualsPanel_t qt_meta_stringdata_StarPilotVisualsPanel = { - { -QT_MOC_LITERAL(0, 0, 21), // "StarPilotVisualsPanel" -QT_MOC_LITERAL(1, 22, 12), // "openSubPanel" -QT_MOC_LITERAL(2, 35, 0), // "" -QT_MOC_LITERAL(3, 36, 15) // "openSubSubPanel" - - }, - "StarPilotVisualsPanel\0openSubPanel\0\0" - "openSubSubPanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotVisualsPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 24, 2, 0x06 /* Public */, - 3, 0, 25, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - QMetaType::Void, - - 0 // eod -}; - -void StarPilotVisualsPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->openSubPanel(); break; - case 1: _t->openSubSubPanel(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotVisualsPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotVisualsPanel::openSubPanel)) { - *result = 0; - return; - } - } - { - using _t = void (StarPilotVisualsPanel::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotVisualsPanel::openSubSubPanel)) { - *result = 1; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotVisualsPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotVisualsPanel.data, - qt_meta_data_StarPilotVisualsPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotVisualsPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotVisualsPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotVisualsPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotVisualsPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void StarPilotVisualsPanel::openSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} - -// SIGNAL 1 -void StarPilotVisualsPanel::openSubSubPanel() -{ - QMetaObject::activate(this, &staticMetaObject, 1, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/moc_wheel_settings.cc b/starpilot/ui/qt/offroad/moc_wheel_settings.cc deleted file mode 100644 index 9f76e7b46..000000000 --- a/starpilot/ui/qt/offroad/moc_wheel_settings.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'wheel_settings.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "wheel_settings.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'wheel_settings.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotWheelPanel_t { - QByteArrayData data[1]; - char stringdata0[20]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotWheelPanel_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotWheelPanel_t qt_meta_stringdata_StarPilotWheelPanel = { - { -QT_MOC_LITERAL(0, 0, 19) // "StarPilotWheelPanel" - - }, - "StarPilotWheelPanel" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotWheelPanel[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotWheelPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotWheelPanel::staticMetaObject = { { - &StarPilotListWidget::staticMetaObject, - qt_meta_stringdata_StarPilotWheelPanel.data, - qt_meta_data_StarPilotWheelPanel, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotWheelPanel::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotWheelPanel::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotWheelPanel.stringdata0)) - return static_cast(this); - return StarPilotListWidget::qt_metacast(_clname); -} - -int StarPilotWheelPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotListWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/offroad/model_settings.cc b/starpilot/ui/qt/offroad/model_settings.cc deleted file mode 100644 index 6839a60d2..000000000 --- a/starpilot/ui/qt/offroad/model_settings.cc +++ /dev/null @@ -1,858 +0,0 @@ -#include "starpilot/ui/qt/offroad/model_settings.h" -#include "starpilot/ui/qt/offroad/expandable_multi_option_dialog.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#include "system/hardware/hw.h" - -namespace { - -QString paramDefaultValue(const Params ¶ms, const char *key) { - return QString::fromStdString(const_cast(params).getKeyDefaultValue(key).value_or("")).trimmed(); -} - -QString builtinDefaultModelKey(const Params ¶ms) { - QString key = paramDefaultValue(params, "Model"); - if (key.isEmpty()) { - key = paramDefaultValue(params, "DrivingModel"); - } - return key.isEmpty() ? QStringLiteral("rdf43") : key; -} - -QString builtinDefaultModelName(const Params ¶ms) { - QString name = paramDefaultValue(params, "DrivingModelName"); - return name.isEmpty() ? QStringLiteral("Regret Driven Framework V4") : name; -} - -QStringList builtinDefaultModelAliases(const QString &defaultKey) { - QString canonical = defaultKey.trimmed(); - if (canonical.isEmpty()) { - canonical = QStringLiteral("rdf43"); - } - - QStringList aliases{canonical}; - - if (canonical == QStringLiteral("rdf43")) { - aliases.append(QStringLiteral("rdf")); - } - - if (canonical.endsWith("2")) { - aliases.append(canonical.left(canonical.size() - 1)); - } else { - aliases.append(canonical + "2"); - } - - if (canonical.endsWith("_default")) { - aliases.append(canonical.left(canonical.size() - QStringLiteral("_default").size())); - } - - aliases.removeAll(""); - aliases.removeDuplicates(); - return aliases; -} - -bool isBuiltinDefaultModel(const Params ¶ms, const QString &key) { - return builtinDefaultModelAliases(builtinDefaultModelKey(params)).contains(key.trimmed()); -} - -QString canonicalModelKey(const Params ¶ms, const QString &key) { - const QString trimmedKey = key.trimmed(); - return isBuiltinDefaultModel(params, trimmedKey) ? builtinDefaultModelKey(params) : trimmedKey; -} - -void ensureDefaultModelVisible(const Params ¶ms, const QString &fallbackSeries, - QMap &modelFileToNameMap, - QMap &modelFileToNameMapProcessed, - QMap &modelSeriesMap, - QMap &modelReleasedDates) { - const QString defaultKey = builtinDefaultModelKey(params); - QString displayName = builtinDefaultModelName(params); - QString series = fallbackSeries; - QString releasedDate; - - for (const QString &alias : builtinDefaultModelAliases(defaultKey)) { - if (!modelFileToNameMap.contains(alias)) { - continue; - } - - displayName = modelFileToNameMap.value(alias, displayName); - if (series == fallbackSeries && modelSeriesMap.contains(alias)) { - series = modelSeriesMap.value(alias); - } - if (releasedDate.isEmpty() && modelReleasedDates.contains(alias)) { - releasedDate = modelReleasedDates.value(alias); - } - - if (alias != defaultKey) { - modelFileToNameMap.remove(alias); - modelFileToNameMapProcessed.remove(alias); - modelSeriesMap.remove(alias); - modelReleasedDates.remove(alias); - } - } - - modelFileToNameMap.insert(defaultKey, displayName); - modelFileToNameMapProcessed.insert(defaultKey, cleanModelName(displayName)); - modelSeriesMap.insert(defaultKey, series); - if (!releasedDate.isEmpty()) { - modelReleasedDates.insert(defaultKey, releasedDate); - } -} - -} // namespace - -StarPilotModelPanel::StarPilotModelPanel(StarPilotSettingsWindow *parent) : StarPilotListWidget(parent), - allModelsDownloaded(false), - allModelsDownloading(false), - cancellingDownload(false), - finalizingDownload(false), - forceOpenDescriptions(false), - modelDownloading(false), - noModelsDownloaded(true), - started(false), - tinygradUpdate(false), - updatingTinygrad(false), - tuningLevel(0), - parent(parent) { - if (Hardware::PC()) { - modelDir.setPath(QString::fromStdString(Path::comma_home() + "/starpilot/data/models/")); - } - modelDir.mkpath("."); - - QStackedLayout *modelLayout = new QStackedLayout(); - addItem(modelLayout); - - StarPilotListWidget *modelList = new StarPilotListWidget(this); - - ScrollView *modelPanel = new ScrollView(modelList, this); - - modelLayout->addWidget(modelPanel); - - StarPilotListWidget *modelLabelsList = new StarPilotListWidget(this); - - ScrollView *modelLabelsPanel = new ScrollView(modelLabelsList, this); - - modelLayout->addWidget(modelLabelsPanel); - - const std::vector> modelToggles { - {"AutomaticallyDownloadModels", tr("Automatically Download New Models"), tr("Automatically download new driving models as they become available."), ""}, - {"DeleteModel", tr("Delete Driving Models"), tr("Delete driving models from the device."), ""}, - {"DownloadModel", tr("Download Driving Models"), tr("Download driving models to the device."), ""}, - {"ModelRandomizer", tr("Model Randomizer"), tr("Driving models are chosen at random each drive and feedback prompts are used to find the model that best suits your needs."), ""}, - {"RecoveryPower", tr("Recovery Power"), tr("Adjust the strength of planplus lane recovery corrections (0.5 to 2.0)."), ""}, - {"ManageBlacklistedModels", tr("Manage Model Blacklist"), tr("Add or remove models from the Model Randomizer's blacklist list."), ""}, - {"ManageScores", tr("Manage Model Ratings"), tr("Reset or view the saved ratings for the driving models."), ""}, - {"SelectModel", tr("Select Driving Model"), tr("Select the active driving model."), ""}, - }; - - StarPilotParamValueButtonControl *recoveryPowerToggle = nullptr; - - for (const auto &[param, title, desc, icon] : modelToggles) { - AbstractControl *modelToggle; - - if (param == "DeleteModel") { - deleteModelButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DELETE ALL")}); - QObject::connect(deleteModelButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QMap deletableModelsMap = getDeletableModelDisplayNames(); - noModelsDownloaded = deletableModelsMap.isEmpty(); - - if (noModelsDownloaded) { - return; - } - - if (id == 0) { - // Group deletable models by series and keep a lookup for selected names - QMap deletableSeriesToModels; - QMap displayNameToKey; - QMap deletableFileToNameMap; - for (auto it = deletableModelsMap.constBegin(); it != deletableModelsMap.constEnd(); ++it) { - const QString &modelKey = it.key(); - const QString &displayName = it.value(); - QString series = modelSeriesMap.value(modelKey, tr("Custom Series")); - deletableSeriesToModels[series].append(displayName); - displayNameToKey.insert(displayName, modelKey); - deletableFileToNameMap.insert(modelKey, displayName); - } - - // Sort models within each series - for (QString &series : deletableSeriesToModels.keys()) { - QStringList &models = deletableSeriesToModels[series]; - models.removeDuplicates(); - std::sort(models.begin(), models.end()); - } - - QString savedSortMode = QString::fromStdString(params.get("ModelSortMode")); - if (savedSortMode.isEmpty()) savedSortMode = "alphabetical"; - - QString modelToDelete = ExpandableMultiOptionDialog::getSelection(tr("Select a driving model to delete"), deletableSeriesToModels, "", this, - QStringList(), QStringList(), QMap(), - deletableFileToNameMap, savedSortMode); - if (!modelToDelete.isEmpty()) { - QString modelKey = displayNameToKey.value(modelToDelete); - if (modelKey.isEmpty()) { - QString processedName = cleanModelName(modelToDelete); - for (auto it = deletableModelsMap.constBegin(); it != deletableModelsMap.constEnd(); ++it) { - if (cleanModelName(it.value()) == processedName) { - modelKey = it.key(); - break; - } - } - } - - if (!modelKey.isEmpty() && ConfirmationDialog::confirm(tr("Are you sure you want to delete the \"%1\" model?").arg(modelToDelete), tr("Delete"), this)) { - for (const QString &file : modelDir.entryList(QDir::Files)) { - QString base = QFileInfo(file).baseName(); - if (base.startsWith(modelKey)) { - QFile::remove(modelDir.filePath(file)); - } - } - - allModelsDownloaded = false; - noModelsDownloaded = getDeletableModelDisplayNames().isEmpty(); - deleteModelButton->setEnabled(!(allModelsDownloading || modelDownloading || noModelsDownloaded)); - } - } - } else if (id == 1) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to delete all of your downloaded driving models?"), tr("Delete"), this)) { - const QList deletableKeys = deletableModelsMap.keys(); - for (const QString &file : modelDir.entryList(QDir::Files)) { - QString base = QFileInfo(file).baseName(); - for (const QString &modelKey : deletableKeys) { - if (base.startsWith(modelKey)) { - QFile::remove(modelDir.filePath(file)); - break; - } - } - } - - allModelsDownloaded = false; - noModelsDownloaded = true; - deleteModelButton->setEnabled(false); - } - } - }); - modelToggle = deleteModelButton; - } else if (param == "DownloadModel") { - downloadModelButton = new StarPilotButtonsControl(title, desc, icon, {tr("DOWNLOAD"), tr("DOWNLOAD ALL")}); - QObject::connect(downloadModelButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - if (id == 0) { - if (modelDownloading) { - params_memory.putBool("CancelModelDownload", true); - - cancellingDownload = true; - } else { - QMap downloadableSeriesToModels; - QStringList downloadableModelNames; - - for (auto it = modelFileToNameMap.constBegin(); it != modelFileToNameMap.constEnd(); ++it) { - const QString &modelKey = it.key(); - const QString &modelName = it.value(); - if (modelName.isEmpty() || isModelInstalled(modelKey)) { - continue; - } - - QString series = modelSeriesMap.value(modelKey, tr("Custom Series")); - downloadableSeriesToModels[series].append(modelName); - if (!downloadableModelNames.contains(modelName)) { - downloadableModelNames.append(modelName); - } - } - - allModelsDownloaded = downloadableModelNames.isEmpty(); - if (allModelsDownloaded) { - return; - } - - for (QString &series : downloadableSeriesToModels.keys()) { - QStringList &models = downloadableSeriesToModels[series]; - models.removeDuplicates(); - std::sort(models.begin(), models.end()); - } - - QStringList userFavorites = QString::fromStdString(params.get("UserFavorites")).split(","); - userFavorites.removeAll(""); - - QStringList communityFavorites = QString::fromStdString(params.get("CommunityFavorites")).split(","); - communityFavorites.removeAll(""); - - QString savedSortMode = QString::fromStdString(params.get("ModelSortMode")); - if (savedSortMode.isEmpty()) savedSortMode = "alphabetical"; - - ExpandableMultiOptionDialog dialog( - tr("Select a driving model to download"), - downloadableSeriesToModels, - "", - this, - userFavorites, - communityFavorites, - modelReleasedDates, - modelFileToNameMap, - savedSortMode); - - int dialogResult = dialog.exec(); - - QString sortMode = dialog.getCurrentSortMode(); - QStringList newUserFavs = dialog.getUserFavorites(); - params.put("ModelSortMode", sortMode.toStdString()); - params.put("UserFavorites", newUserFavs.join(",").toStdString()); - userFavorites = newUserFavs; - - if (dialogResult == QDialog::Accepted) { - QString modelToDownload = dialog.selection; - if (!modelToDownload.isEmpty()) { - QString modelKey = modelFileToNameMap.key(modelToDownload); - params_memory.put("ModelToDownload", modelKey.toStdString()); - // Also persist the version for this downloaded model if known - { - QFile vf(modelDir.filePath(".model_versions.json")); - if (vf.open(QIODevice::ReadOnly)) { - auto doc = QJsonDocument::fromJson(vf.readAll()); - if (doc.isObject()) { - auto obj = doc.object(); - if (obj.contains(modelKey)) { - const std::string version = obj.value(modelKey).toString().toStdString(); - params.put("ModelVersion", version); - params.put("DrivingModelVersion", version); - } - } - } - } - params_memory.put("ModelDownloadProgress", "Downloading..."); - - downloadModelButton->setText(0, tr("CANCEL")); - - downloadModelButton->setValue("Downloading..."); - - downloadModelButton->setVisibleButton(1, false); - - modelDownloading = true; - } - } - } - } else if (id == 1) { - if (allModelsDownloading) { - params_memory.putBool("CancelModelDownload", true); - - cancellingDownload = true; - } else { - params_memory.putBool("DownloadAllModels", true); - params_memory.put("ModelDownloadProgress", "Downloading..."); - - downloadModelButton->setText(1, tr("CANCEL")); - - downloadModelButton->setValue("Downloading..."); - - downloadModelButton->setVisibleButton(0, false); - - allModelsDownloading = true; - } - } - }); - modelToggle = downloadModelButton; - } else if (param == "ManageBlacklistedModels") { - StarPilotButtonsControl *blacklistBtn = new StarPilotButtonsControl(title, desc, icon, {tr("ADD"), tr("REMOVE"), tr("REMOVE ALL")}); - QObject::connect(blacklistBtn, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList blacklistedModels = QString::fromStdString(params.get("BlacklistedModels")).split(","); - blacklistedModels.removeAll(""); - - if (id == 0) { - QStringList blacklistableModels; - for (const QString &model : modelFileToNameMapProcessed.keys()) { - if (!blacklistedModels.contains(model)) { - blacklistableModels.append(modelFileToNameMapProcessed.value(model)); - } - } - - if (blacklistableModels.size() <= 1) { - ConfirmationDialog::alert(tr("There are no more models to blacklist! The only available model is \"%1\"!").arg(blacklistableModels.first()), this); - } else { - // Group blacklistable models by series - QMap blacklistableSeriesToModels; - for (const QString &modelName : blacklistableModels) { - QString modelKey = modelFileToNameMapProcessed.key(modelName); - QString series = modelSeriesMap.value(modelKey, "Custom Series"); - blacklistableSeriesToModels[series].append(modelName); - } - - // Sort models within each series - for (QString &series : blacklistableSeriesToModels.keys()) { - blacklistableSeriesToModels[series].sort(); - } - - QString modelToBlacklist = ExpandableMultiOptionDialog::getSelection(tr("Select a model to add to the blacklist"), blacklistableSeriesToModels, "", this); - if (!modelToBlacklist.isEmpty()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to add the \"%1\" model to the blacklist?").arg(modelToBlacklist), tr("Add"), this)) { - blacklistedModels.append(modelFileToNameMapProcessed.key(modelToBlacklist)); - - params.put("BlacklistedModels", blacklistedModels.join(",").toStdString()); - } - } - } - } else if (id == 1) { - QStringList whitelistableModels; - for (const QString &model : blacklistedModels) { - QString modelName = modelFileToNameMapProcessed.value(model); - whitelistableModels.append(modelName); - } - - // Group whitelistable models by series - QMap whitelistableSeriesToModels; - for (const QString &modelName : whitelistableModels) { - QString modelKey = modelFileToNameMapProcessed.key(modelName); - QString series = modelSeriesMap.value(modelKey, "Custom Series"); - whitelistableSeriesToModels[series].append(modelName); - } - - // Sort models within each series - for (QString &series : whitelistableSeriesToModels.keys()) { - whitelistableSeriesToModels[series].sort(); - } - - QString modelToWhitelist = ExpandableMultiOptionDialog::getSelection(tr("Select a model to remove from the blacklist"), whitelistableSeriesToModels, "", this); - if (!modelToWhitelist.isEmpty()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to remove the \"%1\" model from the blacklist?").arg(modelToWhitelist), tr("Remove"), this)) { - blacklistedModels.removeAll(modelFileToNameMapProcessed.key(modelToWhitelist)); - - params.put("BlacklistedModels", blacklistedModels.join(",").toStdString()); - } - } - } else if (id == 2) { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to remove all of your blacklisted models?"), this)) { - params.remove("BlacklistedModels"); - } - } - }); - modelToggle = blacklistBtn; - } else if (param == "ManageScores") { - StarPilotButtonsControl *manageScoresBtn = new StarPilotButtonsControl(title, desc, icon, {tr("RESET"), tr("VIEW")}); - QObject::connect(manageScoresBtn, &StarPilotButtonsControl::buttonClicked, [this, modelLayout, modelLabelsList, modelLabelsPanel](int id) { - if (id == 0) { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to reset all of your model drives and scores?"), this)) { - params.remove("ModelDrivesAndScores"); - } - } else if (id == 1) { - openSubPanel(); - - updateModelLabels(modelLabelsList); - - modelLayout->setCurrentWidget(modelLabelsPanel); - } - }); - modelToggle = manageScoresBtn; - } else if (param == "SelectModel") { - selectModelButton = new ButtonControl(title, tr("SELECT"), desc); - QObject::connect(selectModelButton, &ButtonControl::clicked, [this]() { - // Group models by series for the enhanced dialog - QMap seriesToModels; - QMap installedModelFileToNameMap; - QMap installedReleasedDates; - - // Add all available models by series - for (const QString &modelKey : modelFileToNameMap.keys()) { - if (!isModelInstalled(modelKey)) { - continue; - } - - QString modelName = modelFileToNameMap.value(modelKey); - installedModelFileToNameMap.insert(modelKey, modelName); - if (modelReleasedDates.contains(modelKey)) { - installedReleasedDates.insert(modelKey, modelReleasedDates.value(modelKey)); - } - - QString series = modelSeriesMap.value(modelKey, "Custom Series"); - seriesToModels[series].append(modelName); - } - - // Sort models alphabetically within each series - for (QString &series : seriesToModels.keys()) { - seriesToModels[series].sort(); - } - - // Add default model to the beginning of its series - const QString defaultKey = builtinDefaultModelKey(params); - const QString defaultName = modelFileToNameMap.value(defaultKey, builtinDefaultModelName(params)); - const QString defaultSeries = modelSeriesMap.value(defaultKey, tr("Custom Series")); - if (seriesToModels.contains(defaultSeries) && seriesToModels[defaultSeries].contains(defaultName)) { - seriesToModels[defaultSeries].removeAll(defaultName); - seriesToModels[defaultSeries].prepend(defaultName); - } - - // Prepare favorites and dates for the enhanced dialog - QStringList userFavs = QString::fromStdString(params.get("UserFavorites")).split(","); - userFavs.removeAll(""); - - QStringList communityFavs = QString::fromStdString(params.get("CommunityFavorites")).split(","); - communityFavs.removeAll(""); - - // Create dialog instance to access sort mode and favorites after selection - QString savedSortMode = QString::fromStdString(params.get("ModelSortMode")); - if (savedSortMode.isEmpty()) savedSortMode = "alphabetical"; - - ExpandableMultiOptionDialog dialog(tr("Select a model - 🗺️ = Navigation | 📡 = Radar | 👀 = VOACC"), - seriesToModels, currentModel, this, - userFavs, communityFavs, installedReleasedDates, installedModelFileToNameMap, savedSortMode); - - int dialogResult = dialog.exec(); - - // Persist sort mode and user favorites even if no selection was made - QString sortMode = dialog.getCurrentSortMode(); - QStringList newUserFavs = dialog.getUserFavorites(); - params.put("ModelSortMode", sortMode.toStdString()); - params.put("UserFavorites", newUserFavs.join(",").toStdString()); - - if (dialogResult == QDialog::Accepted) { - QString modelToSelect = dialog.selection; - if (!modelToSelect.isEmpty()) { - currentModel = modelToSelect; - - QString modelKey = modelFileToNameMap.key(modelToSelect); - params.put("Model", modelKey.toStdString()); - params.put("DrivingModel", modelKey.toStdString()); - params.put("DrivingModelName", modelToSelect.toStdString()); - // Sync ModelVersion with the selected model if known - { - QFile vf(modelDir.filePath(".model_versions.json")); - if (vf.open(QIODevice::ReadOnly)) { - auto doc = QJsonDocument::fromJson(vf.readAll()); - if (doc.isObject()) { - auto obj = doc.object(); - if (obj.contains(modelKey)) { - const std::string version = obj.value(modelKey).toString().toStdString(); - params.put("ModelVersion", version); - params.put("DrivingModelVersion", version); - } - } - } - } - - updateStarPilotToggles(); - - if (started) { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - } - selectModelButton->setValue(modelToSelect); - - noModelsDownloaded = getDeletableModelDisplayNames().isEmpty(); - deleteModelButton->setEnabled(!(allModelsDownloading || modelDownloading || noModelsDownloaded)); - } - } - }); - modelToggle = selectModelButton; - - } else if (param == "RecoveryPower") { - std::vector recoveryPowerButton{"Reset"}; - modelToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0.5, 2.0, QString(), std::map(), 0.1, false, {}, recoveryPowerButton, false, false); - recoveryPowerToggle = static_cast(modelToggle); - } else { - modelToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = modelToggle; - - modelList->addItem(modelToggle); - - QObject::connect(modelToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - QObject::connect(static_cast(toggles["ModelRandomizer"]), &ToggleControl::toggleFlipped, [this](bool state) { - updateToggles(); - - if (state && !allModelsDownloaded) { - if (StarPilotConfirmationDialog::yesorno(tr("The \"Model Randomizer\" only works with downloaded models. Do you want to download all the driving models?"), this)) { - params_memory.putBool("DownloadAllModels", true); - params_memory.put("ModelDownloadProgress", "Downloading..."); - - downloadModelButton->setValue("Downloading..."); - - allModelsDownloading = true; - } - } - }); - - if (recoveryPowerToggle) { - QObject::connect(recoveryPowerToggle, &StarPilotParamValueButtonControl::buttonClicked, [this, recoveryPowerToggle]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset your Recovery Power to the default of 1.0?"), tr("Reset"), this)) { - params.putFloat("RecoveryPower", 1.0); - recoveryPowerToggle->refresh(); - updateStarPilotToggles(); - } - }); - } - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [modelLayout, modelPanel] {modelLayout->setCurrentWidget(modelPanel);}); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotModelPanel::updateState); -} - -bool StarPilotModelPanel::isModelInstalled(const QString &key) const { - if (key.isEmpty()) { - return false; - } - - if (isBuiltinDefaultModel(params, key)) { - return true; - } - - bool has_combined_tg = false; - - for (const QString &file : modelDir.entryList(QDir::Files)) { - QFileInfo fi(modelDir.filePath(file)); - const QString base = fi.baseName(); - const QString ext = fi.suffix(); - - if (!(base.startsWith(key) || base.startsWith(key + "_"))) continue; - if (ext == "pkl" && base == key + "_driving_tinygrad") { - has_combined_tg = true; - } - } - - return has_combined_tg; -} - -QMap StarPilotModelPanel::getDeletableModelDisplayNames() { - QMap deletable; - - const QString defaultKey = builtinDefaultModelKey(params); - const QString defaultName = modelFileToNameMap.value(defaultKey, builtinDefaultModelName(params)); - const QString processedDefault = cleanModelName(defaultName); - QString processedCurrent = cleanModelName(currentModel); - - for (auto it = modelFileToNameMap.constBegin(); it != modelFileToNameMap.constEnd(); ++it) { - const QString &modelKey = it.key(); - const QString &displayName = it.value(); - if (displayName.isEmpty()) { - continue; - } - - if (!isModelInstalled(modelKey)) { - continue; - } - - QString processedName = cleanModelName(displayName); - if (!processedCurrent.isEmpty() && processedName == processedCurrent) { - continue; - } - - if (!processedDefault.isEmpty() && processedName == processedDefault) { - continue; - } - - deletable.insert(modelKey, displayName); - } - - return deletable; -} - -void StarPilotModelPanel::showEvent(QShowEvent *event) { - StarPilotUIState &fs = *starpilotUIState(); - UIState &s = *uiState(); - - starpilotToggleLevels = parent->starpilotToggleLevels; - tuningLevel = parent->tuningLevel; - - allModelsDownloading = params_memory.getBool("DownloadAllModels"); - modelDownloading = !params_memory.get("ModelToDownload").empty(); - - QStringList availableModels = QString::fromStdString(params.get("AvailableModels")).split(","); - availableModelNames = QString::fromStdString(params.get("AvailableModelNames")).split(","); - availableModelSeries = QString::fromStdString(params.get("AvailableModelSeries")).split(","); - QStringList releasedDatesParam = QString::fromStdString(params.get("ModelReleasedDates")).split(","); - QStringList communityFavsParam = QString::fromStdString(params.get("CommunityFavorites")).split(","); - QStringList userFavsParam = QString::fromStdString(params.get("UserFavorites")).split(","); - - // Build a simple model->version map for quick lookups elsewhere - { - QStringList versionList = QString::fromStdString(params.get("ModelVersions")).split(","); - QJsonObject versionObj; - int verCount = qMin(availableModels.size(), versionList.size()); - for (int i = 0; i < verCount; ++i) { - const QString modelKey = canonicalModelKey(params, availableModels[i]); - if (!modelKey.isEmpty()) { - versionObj.insert(modelKey, versionList[i]); - } - } - QFile out(modelDir.filePath(".model_versions.json")); - if (out.open(QIODevice::WriteOnly)) { - out.write(QJsonDocument(versionObj).toJson()); - out.close(); - } - } - - modelFileToNameMap.clear(); - modelFileToNameMapProcessed.clear(); - modelSeriesMap.clear(); - modelReleasedDates.clear(); - int size = qMin(availableModels.size(), availableModelNames.size()); - for (int i = 0; i < size; ++i) { - const QString modelKey = canonicalModelKey(params, availableModels[i]); - const QString modelName = availableModelNames[i].trimmed(); - if (modelKey.isEmpty() || modelName.isEmpty()) { - continue; - } - - QString series; - if (i < availableModelSeries.size()) { - series = availableModelSeries[i].trimmed(); - } - if (series.isEmpty()) { - series = tr("Custom Series"); - } - - modelFileToNameMap.insert(modelKey, modelName); - modelFileToNameMapProcessed.insert(modelKey, cleanModelName(modelName)); - modelSeriesMap.insert(modelKey, series); - - if (i < releasedDatesParam.size()) { - const QString released = releasedDatesParam[i].trimmed(); - if (!released.isEmpty()) { - this->modelReleasedDates.insert(modelKey, released); - } - } - } - - ensureDefaultModelVisible(params, tr("Custom Series"), modelFileToNameMap, modelFileToNameMapProcessed, modelSeriesMap, modelReleasedDates); - - allModelsDownloaded = true; - for (auto it = modelFileToNameMap.constBegin(); it != modelFileToNameMap.constEnd(); ++it) { - if (it.value().isEmpty()) { - continue; - } - if (!isModelInstalled(it.key())) { - allModelsDownloaded = false; - break; - } - } - - QString modelKey = canonicalModelKey(params, QString::fromStdString(params.get("Model"))); - if (modelKey.isEmpty()) { - modelKey = canonicalModelKey(params, QString::fromStdString(params.get("DrivingModel"))); - } - if (!isModelInstalled(modelKey)) { - modelKey = builtinDefaultModelKey(params); - } - currentModel = modelFileToNameMap.value(modelKey, builtinDefaultModelName(params)); - selectModelButton->setValue(currentModel); - - noModelsDownloaded = getDeletableModelDisplayNames().isEmpty(); - - bool parked = !s.scene.started || fs.starpilot_scene.parked || parent->isFrogsGoMoo; - - deleteModelButton->setEnabled(!(allModelsDownloading || modelDownloading || noModelsDownloaded)); - - downloadModelButton->setEnabledButtons(0, !allModelsDownloaded && !allModelsDownloading && !cancellingDownload && fs.starpilot_scene.online && parked); - downloadModelButton->setEnabledButtons(1, !allModelsDownloaded && !modelDownloading && !cancellingDownload && fs.starpilot_scene.online && parked); - - downloadModelButton->setValue(fs.starpilot_scene.online ? (parked ? "" : "Not parked") : tr("Offline...")); - - started = s.scene.started; - - updateToggles(); -} - -void StarPilotModelPanel::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible() || finalizingDownload) { - return; - } - - bool parked = !started || fs.starpilot_scene.parked || parent->isFrogsGoMoo; - - if (allModelsDownloading || modelDownloading) { - QString progress = QString::fromStdString(params_memory.get("ModelDownloadProgress")); - bool downloadFailed = progress.contains(QRegularExpression("cancelled|exists|failed|offline", QRegularExpression::CaseInsensitiveOption)); - - if (progress != "Downloading...") { - downloadModelButton->setValue(progress); - } - - if (progress == "All models downloaded!" && allModelsDownloading || progress == "Downloaded!" && modelDownloading || downloadFailed) { - finalizingDownload = true; - - QTimer::singleShot(2500, [this, progress]() { - allModelsDownloaded = progress == "All models downloaded!"; - allModelsDownloading = false; - cancellingDownload = false; - finalizingDownload = false; - modelDownloading = false; - noModelsDownloaded = false; - - params_memory.remove("CancelModelDownload"); - params_memory.remove("DownloadAllModels"); - params_memory.remove("ModelDownloadProgress"); - params_memory.remove("ModelToDownload"); - - downloadModelButton->setEnabled(true); - downloadModelButton->setValue(""); - }); - } - } else { - downloadModelButton->setValue(fs.starpilot_scene.online ? (parked ? "" : "Not parked") : tr("Offline...")); - } - - deleteModelButton->setEnabled(!(allModelsDownloading || modelDownloading || noModelsDownloaded)); - - downloadModelButton->setText(0, modelDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - downloadModelButton->setText(1, allModelsDownloading ? tr("CANCEL") : tr("DOWNLOAD ALL")); - - downloadModelButton->setEnabledButtons(0, !allModelsDownloaded && !allModelsDownloading && !cancellingDownload && fs.starpilot_scene.online && parked); - downloadModelButton->setEnabledButtons(1, !allModelsDownloaded && !modelDownloading && !cancellingDownload && fs.starpilot_scene.online && parked); - - downloadModelButton->setVisibleButton(0, !allModelsDownloading); - downloadModelButton->setVisibleButton(1, !modelDownloading); - - started = s.scene.started; - - parent->keepScreenOn = allModelsDownloading || modelDownloading; -} - -void StarPilotModelPanel::updateModelLabels(StarPilotListWidget *labelsList) { - labelsList->clear(); - - QJsonObject modelDrivesAndScores = QJsonDocument::fromJson(QString::fromStdString(params.get("ModelDrivesAndScores")).toUtf8()).object(); - - for (const QString &modelName : availableModelNames) { - QJsonObject modelData = modelDrivesAndScores.value(cleanModelName(modelName)).toObject(); - - int drives = modelData.value("Drives").toInt(0); - int score = modelData.value("Score").toInt(0); - - QString drivesDisplay = drives == 1 ? QString("%1 Drive").arg(drives) : drives > 0 ? QString("%1 Drives").arg(drives) : "N/A"; - QString scoreDisplay = drives > 0 ? QString("Score: %1%").arg(score) : "N/A"; - - QString labelTitle = cleanModelName(modelName); - QString labelText = QString("%1 (%2)").arg(scoreDisplay, drivesDisplay); - - LabelControl *labelControl = new LabelControl(labelTitle, labelText, "", this); - labelsList->addItem(labelControl); - } -} - -void StarPilotModelPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - bool setVisible = showAllToggles || tuningLevel >= starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "ManageBlacklistedModels" || key == "ManageScores") { - setVisible &= params.getBool("ModelRandomizer"); - } else if (key == "SelectModel") { - setVisible &= !params.getBool("ModelRandomizer"); - } else if (key == "RecoveryPower") { - setVisible &= (tuningLevel == 3); // Only visible in developer tuning level - } - } - - toggle->setVisible(setVisible); - } - - update(); -} diff --git a/starpilot/ui/qt/offroad/model_settings.h b/starpilot/ui/qt/offroad/model_settings.h deleted file mode 100644 index 7526cd543..000000000 --- a/starpilot/ui/qt/offroad/model_settings.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotModelPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotModelPanel(StarPilotSettingsWindow *parent); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateModelLabels(StarPilotListWidget *labelsList); - void updateState(const UIState &s, const StarPilotUIState &fs); - void updateToggles(); - bool isModelInstalled(const QString &key) const; - QMap getDeletableModelDisplayNames(); - - bool allModelsDownloaded; - bool allModelsDownloading; - bool cancellingDownload; - bool finalizingDownload; - bool forceOpenDescriptions; - bool modelDownloading; - bool noModelsDownloaded; - bool started; - bool tinygradUpdate; - bool updatingTinygrad; - - int tuningLevel; - - std::map toggles; - - ButtonControl *selectModelButton; - - StarPilotButtonsControl *deleteModelButton; - StarPilotButtonsControl *downloadModelButton; - StarPilotButtonsControl *updateTinygradButton; - - StarPilotSettingsWindow *parent; - - Params params; - Params params_memory{"", true}; - - QDir modelDir{"/data/models/"}; - - QJsonObject starpilotToggleLevels; - - QMap modelFileToNameMap; - QMap modelFileToNameMapProcessed; - QMap modelReleasedDates; - QMap modelSeriesMap; - - QString currentModel; - - - QStringList availableModelNames; - QStringList availableModelSeries; -}; diff --git a/starpilot/ui/qt/offroad/navigation_settings.cc b/starpilot/ui/qt/offroad/navigation_settings.cc deleted file mode 100644 index c323cd6f8..000000000 --- a/starpilot/ui/qt/offroad/navigation_settings.cc +++ /dev/null @@ -1,330 +0,0 @@ -#include "starpilot/ui/qt/offroad/navigation_settings.h" - -StarPilotNavigationPanel::StarPilotNavigationPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - networkManager = new QNetworkAccessManager(this); - - primelessLayout = new QStackedLayout(); - addItem(primelessLayout); - - StarPilotListWidget *settingsList = new StarPilotListWidget(this); - ipLabel = new LabelControl(tr("Manage Your Settings At"), tr("Offline...")); - settingsList->addItem(ipLabel); - - publicMapboxKeyControl = new StarPilotButtonsControl(tr("Public Mapbox Key"), tr("Manage your Public Mapbox Key."), "", {tr("ADD"), tr("TEST")}); - QObject::connect(publicMapboxKeyControl, &StarPilotButtonsControl::buttonClicked, [this](int id) { - if (id == 0) { - if (mapboxPublicKeySet) { - if (StarPilotConfirmationDialog::yesorno(tr("Remove your Public Mapbox Key?"), this)) { - params.remove("MapboxPublicKey"); - - updateButtons(); - } - } else { - int minKeyLength = 80; - QString key = InputDialog::getText(tr("Enter your Public Mapbox Key"), this, "", false, minKeyLength).trimmed(); - if (!key.isEmpty()) { - if (!key.startsWith("pk.")) { - key = "pk." + key; - } - params.put("MapboxPublicKey", key.toStdString()); - updateButtons(); - } - } - } else { - publicMapboxKeyControl->setValue(tr("Testing...")); - - QString key = QString::fromStdString(params.get("MapboxPublicKey")); - QString url = QString("https://api.mapbox.com/geocoding/v5/mapbox.places/mapbox.json?access_token=%1").arg(key); - - QNetworkRequest request(url); - QNetworkReply *reply = networkManager->get(request); - connect(reply, &QNetworkReply::finished, [=]() { - publicMapboxKeyControl->setValue(""); - - QString message; - if (reply->error() == QNetworkReply::NoError) { - message = tr("Key is valid!"); - } else if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 401) { - message = tr("Key is invalid!"); - } else { - message = tr("An error occurred: %1").arg(reply->errorString()); - } - ConfirmationDialog::alert(message, this); - reply->deleteLater(); - }); - } - }); - settingsList->addItem(publicMapboxKeyControl); - - secretMapboxKeyControl = new StarPilotButtonsControl(tr("Secret Mapbox Key"), tr("Manage your Secret Mapbox Key."), "", {tr("ADD"), tr("TEST")}); - QObject::connect(secretMapboxKeyControl, &StarPilotButtonsControl::buttonClicked, [this](int id) { - if (id == 0) { - if (mapboxSecretKeySet) { - if (StarPilotConfirmationDialog::yesorno(tr("Remove your Secret Mapbox Key?"), this)) { - params.remove("MapboxSecretKey"); - - updateButtons(); - } - } else { - int minKeyLength = 80; - QString key = InputDialog::getText(tr("Enter your Secret Mapbox Key"), this, "", false, minKeyLength).trimmed(); - if (!key.isEmpty()) { - if (!key.startsWith("sk.")) { - key = "sk." + key; - } - params.put("MapboxSecretKey", key.toStdString()); - updateButtons(); - } - } - } else { - secretMapboxKeyControl->setValue(tr("Testing...")); - - QString key = QString::fromStdString(params.get("MapboxSecretKey")); - QString url = QString("https://api.mapbox.com/directions/v5/mapbox/driving/-73.989,40.733;-74,40.733?access_token=%1").arg(key); - - QNetworkRequest request(url); - QNetworkReply *reply = networkManager->get(request); - connect(reply, &QNetworkReply::finished, [=]() { - secretMapboxKeyControl->setValue(""); - - QString message; - if (reply->error() == QNetworkReply::NoError) { - message = tr("Key is valid!"); - } else if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 401) { - message = tr("Key is invalid!"); - } else { - message = tr("An error occurred: %1").arg(reply->errorString()); - } - ConfirmationDialog::alert(message, this); - reply->deleteLater(); - }); - } - }); - settingsList->addItem(secretMapboxKeyControl); - - setupButton = new ButtonControl(tr("Mapbox Setup Instructions"), tr("VIEW"), tr("Instructions on how to set up Mapbox for \"Primeless Navigation\"."), this); - QObject::connect(setupButton, &ButtonControl::clicked, [this]() { - openSubPanel(); - - updateStep(); - - primelessLayout->setCurrentIndex(1); - }); - settingsList->addItem(setupButton); - - std::vector filterButtonNames{tr("CANCEL"), tr("Manually Update Speed Limits")}; - updateSpeedLimitsToggle = new StarPilotButtonControl("SpeedLimitFiller", tr("Speed Limit Filler"), - tr("Automatically collect missing or incorrect speed limits while you drive using speeds limits sourced from your dashboard (if supported), " - "Mapbox, and \"Navigate on openpilot\".

" - "When you're parked and connected to Wi-Fi, StarPilot will automatically process this data into a file " - "to be used with the \"Speed Limit Filler\" tool in \"The Galaxy\".

" - "You can download this file from \"The Galaxy\" in the \"Download Speed Limits\" menu.

" - "Need a step-by-step guide? Visit #speed-limit-filler in the StarPilot Discord!"), - "", filterButtonNames); - QObject::connect(updateSpeedLimitsToggle, &StarPilotButtonControl::buttonClicked, [this](int id) { - if (id == 0) { - if (StarPilotConfirmationDialog::yesorno(tr("Cancel the speed-limit update?"), this)) { - updatingLimits = false; - - updateSpeedLimitsToggle->setEnabledButton(0, false); - updateSpeedLimitsToggle->setValue(tr("Cancelled...")); - - params_memory.remove("UpdateSpeedLimits"); - - QTimer::singleShot(2500, [this]() { - updateSpeedLimitsToggle->clearCheckedButtons(); - updateSpeedLimitsToggle->setEnabledButton(0, true); - updateSpeedLimitsToggle->setValue(""); - updateSpeedLimitsToggle->setVisibleButton(0, false); - updateSpeedLimitsToggle->setVisibleButton(1, true); - - params_memory.remove("UpdateSpeedLimitsStatus"); - }); - } - } else if (id == 1) { - QJsonObject overpassRequests = QJsonDocument::fromJson(QString::fromStdString(params.get("OverpassRequests")).toUtf8()).object(); - - int totalRequests = overpassRequests.value("total_requests").toInt(0); - int maxRequests = overpassRequests.value("max_requests").toInt(10000); - int savedDay = overpassRequests.value("day").toInt(QDate::currentDate().day()); - - int currentDay = QDate::currentDate().day(); - - if (savedDay != currentDay) { - totalRequests = 0; - } - - if (totalRequests >= maxRequests) { - QTime now = QTime::currentTime(); - - int secondsUntilMidnight = (24 * 3600) - (now.hour() * 3600 + now.minute() * 60 + now.second()); - int hours = secondsUntilMidnight / 3600; - int minutes = (secondsUntilMidnight % 3600) / 60; - - ConfirmationDialog::alert(QString(tr("You've hit today's request limit.\n\nIt will reset in %1 hours and %2 minutes.")).arg(hours).arg(minutes), this); - - updateSpeedLimitsToggle->clearCheckedButtons(); - return; - } - - updateSpeedLimitsToggle->setVisibleButton(0, true); - updateSpeedLimitsToggle->setVisibleButton(1, false); - - if (StarPilotConfirmationDialog::yesorno(tr("This process takes a while. It's recommended to start when you're done driving and connected to stable Wi-Fi. Continue?"), this)) { - updatingLimits = true; - - updateSpeedLimitsToggle->setValue("Calculating..."); - - params_memory.put("UpdateSpeedLimitsStatus", "Calculating..."); - params_memory.putBool("UpdateSpeedLimits", true); - } else { - updateSpeedLimitsToggle->setVisibleButton(0, false); - updateSpeedLimitsToggle->setVisibleButton(1, true); - - updateSpeedLimitsToggle->clearCheckedButtons(); - } - } - }); - updateSpeedLimitsToggle->setVisibleButton(0, false); - settingsList->addItem(updateSpeedLimitsToggle); - - ScrollView *settingsPanel = new ScrollView(settingsList, this); - primelessLayout->addWidget(settingsPanel); - - imageLabel = new QLabel(this); - - ScrollView *instructionsPanel = new ScrollView(imageLabel, this); - primelessLayout->addWidget(instructionsPanel); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [this]() { - primelessLayout->setCurrentIndex(0); - - if (forceOpenDescriptions) { - publicMapboxKeyControl->showDescription(); - secretMapboxKeyControl->showDescription(); - setupButton->showDescription(); - updateSpeedLimitsToggle->showDescription(); - } - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotNavigationPanel::updateState); -} - -void StarPilotNavigationPanel::showEvent(QShowEvent *event) { - if (forceOpenDescriptions) { - publicMapboxKeyControl->showDescription(); - secretMapboxKeyControl->showDescription(); - setupButton->showDescription(); - updateSpeedLimitsToggle->showDescription(); - } - - UIState &s = *uiState(); - - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - QString ipAddress = fs.wifi->getIp4Address(); - ipLabel->setText(ipAddress.isEmpty() ? tr("Offline...") : QString("%1:8082").arg(ipAddress)); - - updateButtons(); - - updatingLimits = !params_memory.get("UpdateSpeedLimitsStatus").empty() && QString::fromStdString(params_memory.get("UpdateSpeedLimitsStatus")) != "Completed!"; - - bool parked = !s.scene.started || starpilot_scene.parked || parent->isFrogsGoMoo; - - updateSpeedLimitsToggle->setVisibleButton(0, updatingLimits); - updateSpeedLimitsToggle->setVisibleButton(1, !updatingLimits); - - if (updatingLimits) { - updateSpeedLimitsToggle->setValue(QString::fromStdString(params_memory.get("UpdateSpeedLimitsStatus"))); - } else { - updateSpeedLimitsToggle->setEnabledButton(1, starpilot_scene.online && util::system_time_valid() && parked); - updateSpeedLimitsToggle->setValue(starpilot_scene.online ? (parked ? "" : "Not parked") : tr("Offline...")); - updateSpeedLimitsToggle->setVisible(parent->showAllTogglesEnabled() || parent->tuningLevel >= parent->starpilotToggleLevels["SpeedLimitFiller"].toDouble()); - } -} - -void StarPilotNavigationPanel::hideEvent(QHideEvent *event) { - primelessLayout->setCurrentIndex(0); -} - -void StarPilotNavigationPanel::mousePressEvent(QMouseEvent *event) { - if (primelessLayout->currentIndex() == 1) { - closeSubPanel(); - - primelessLayout->setCurrentIndex(0); - - if (forceOpenDescriptions) { - publicMapboxKeyControl->showDescription(); - secretMapboxKeyControl->showDescription(); - setupButton->showDescription(); - updateSpeedLimitsToggle->showDescription(); - } - } -} - -void StarPilotNavigationPanel::updateButtons() { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - mapboxPublicKeySet = QString::fromStdString(params.get("MapboxPublicKey")).startsWith("pk"); - mapboxSecretKeySet = QString::fromStdString(params.get("MapboxSecretKey")).startsWith("sk"); - - publicMapboxKeyControl->setText(0, mapboxPublicKeySet ? tr("REMOVE") : tr("ADD")); - publicMapboxKeyControl->setVisibleButton(1, mapboxPublicKeySet && starpilot_scene.online); - secretMapboxKeyControl->setText(0, mapboxSecretKeySet ? tr("REMOVE") : tr("ADD")); - secretMapboxKeyControl->setVisibleButton(1, mapboxSecretKeySet && starpilot_scene.online); -} - -void StarPilotNavigationPanel::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible() || s.sm->frame % (UI_FREQ / 2) != 0) { - return; - } - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - updateButtons(); - updateStep(); - - bool parked = !s.scene.started || starpilot_scene.parked || parent->isFrogsGoMoo; - - if (updatingLimits) { - if (QString::fromStdString(params_memory.get("UpdateSpeedLimitsStatus")) == "Completed!") { - updatingLimits = false; - - updateSpeedLimitsToggle->setValue(tr("Completed!")); - - QTimer::singleShot(2500, [this]() { - updateSpeedLimitsToggle->clearCheckedButtons(); - updateSpeedLimitsToggle->setValue(""); - updateSpeedLimitsToggle->setVisibleButton(0, false); - updateSpeedLimitsToggle->setVisibleButton(1, true); - - params_memory.remove("UpdateSpeedLimitsStatus"); - }); - } else { - updateSpeedLimitsToggle->setValue(QString::fromStdString(params_memory.get("UpdateSpeedLimitsStatus"))); - } - } else { - updateSpeedLimitsToggle->setEnabledButton(1, starpilot_scene.online && util::system_time_valid() && parked); - updateSpeedLimitsToggle->setValue(starpilot_scene.online ? (parked ? "" : "Not parked") : tr("Offline...")); - } - - parent->keepScreenOn = primelessLayout->currentIndex() == 1 || updatingLimits; -} - -void StarPilotNavigationPanel::updateStep() { - QString currentStep; - if (mapboxPublicKeySet) { - currentStep = "../../starpilot/navigation/navigation_training/public_key_set.png"; - } else { - currentStep = "../../starpilot/navigation/navigation_training/no_keys_set.png"; - } - - QPixmap pixmap; - pixmap.load(currentStep); - imageLabel->setPixmap(pixmap.scaledToWidth(1500, Qt::SmoothTransformation)); - - update(); -} diff --git a/starpilot/ui/qt/offroad/navigation_settings.h b/starpilot/ui/qt/offroad/navigation_settings.h deleted file mode 100644 index f08160aa6..000000000 --- a/starpilot/ui/qt/offroad/navigation_settings.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotNavigationPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotNavigationPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void closeSubPanel(); - void openSubPanel(); - -protected: - void hideEvent(QHideEvent *event); - void showEvent(QShowEvent *event) override; - -private: - void mousePressEvent(QMouseEvent *event); - void updateButtons(); - void updateState(const UIState &s, const StarPilotUIState &fs); - void updateStep(); - - bool forceOpenDescriptions; - bool mapboxPublicKeySet; - bool mapboxSecretKeySet; - bool updatingLimits; - - StarPilotButtonsControl *publicMapboxKeyControl; - StarPilotButtonsControl *secretMapboxKeyControl; - ButtonControl *setupButton; - - StarPilotButtonControl *updateSpeedLimitsToggle; - - StarPilotSettingsWindow *parent; - - LabelControl *ipLabel; - - Params params; - Params params_memory{"", true}; - - QLabel *imageLabel; - - QNetworkAccessManager *networkManager; - - QStackedLayout *primelessLayout; -}; diff --git a/starpilot/ui/qt/offroad/sounds_settings.cc b/starpilot/ui/qt/offroad/sounds_settings.cc deleted file mode 100644 index 08052a384..000000000 --- a/starpilot/ui/qt/offroad/sounds_settings.cc +++ /dev/null @@ -1,241 +0,0 @@ -#include "starpilot/ui/qt/offroad/sounds_settings.h" - -StarPilotSoundsPanel::StarPilotSoundsPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *soundsLayout = new QStackedLayout(); - addItem(soundsLayout); - - StarPilotListWidget *soundsList = new StarPilotListWidget(this); - - ScrollView *soundsPanel = new ScrollView(soundsList, this); - - soundsLayout->addWidget(soundsPanel); - - StarPilotListWidget *alertVolumeControlList = new StarPilotListWidget(this); - StarPilotListWidget *customAlertsList = new StarPilotListWidget(this); - - ScrollView *alertVolumeControlPanel = new ScrollView(alertVolumeControlList, this); - ScrollView *customAlertsPanel = new ScrollView(customAlertsList, this); - - soundsLayout->addWidget(alertVolumeControlPanel); - soundsLayout->addWidget(customAlertsPanel); - - const std::vector> soundsToggles { - {"AlertVolumeControl", tr("Alert Volume Controller"), tr("Set how loud each type of openpilot alert is to keep routine prompts from becoming distracting."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"SwitchbackModeCooldown", tr("Switchback Mode Cooldown"), tr("Set the minimum time between repeated steering-limit and minimum-steer-speed alerts while \"Switchback Mode\" is active.

Useful on winding roads where \"Turn Exceeds Steering Limit\" and \"Steer Unavailable Under\" can repeat frequently. Set to Off to disable the cooldown even when the mode is on."), ""}, - {"BelowSteerSpeedVolume", tr("Min Steer Speed Alert Volume"), tr("Set the volume for the \"Steer Unavailable Under\" alert shown below the car's minimum steering speed.

Set to Muted to silence only this alert."), ""}, - {"DisengageVolume", tr("Disengage Volume"), tr("Set the volume for alerts when openpilot disengages.

Examples include: \"Cruise Fault: Restart the Car\", \"Parking Brake Engaged\", \"Pedal Pressed\"."), ""}, - {"EngageVolume", tr("Engage Volume"), tr("Set the volume for the chime when openpilot engages, such as after pressing the \"RESUME\" or \"SET\" steering wheel buttons."), ""}, - {"PromptVolume", tr("Prompt Volume"), tr("Set the volume for prompts that need attention.

Examples include: \"Car Detected in Blindspot\", \"Steering Temporarily Unavailable\", \"Turn Exceeds Steering Limit\"."), ""}, - {"PromptDistractedVolume", tr("Prompt Distracted Volume"), tr("Set the volume for prompts when openpilot detects driver distraction or unresponsiveness.

Examples include: \"Pay Attention\", \"Touch Steering Wheel\"."), ""}, - {"RefuseVolume", tr("Refuse Volume"), tr("Set the volume for alerts when openpilot refuses to engage.

Examples include: \"Brake Hold Active\", \"Door Open\", \"Seatbelt Unlatched\"."), ""}, - {"WarningSoftVolume", tr("Warning Soft Volume"), tr("Set the volume for softer warnings about potential risks.

Examples include: \"BRAKE! Risk of Collision\", \"Steering Temporarily Unavailable\"."), ""}, - {"WarningImmediateVolume", tr("Warning Immediate Volume"), tr("Set the volume for the loudest warnings that require urgent attention.

Examples include: \"DISENGAGE IMMEDIATELY — Driver Distracted\", \"DISENGAGE IMMEDIATELY — Driver Unresponsive\"."), ""}, - - {"CustomAlerts", tr("StarPilot Alerts"), tr("Optional StarPilot alerts that highlight driving events in a more noticeable way."), "../../starpilot/assets/toggle_icons/icon_green_light.png"}, - {"GoatScream", tr("Goat Scream"), tr("Play the infamous \"Goat Scream\" when the steering controller reaches its limit. Based on the \"Turn Exceeds Steering Limit\" event."), ""}, - {"GoatScreamCriticalAlerts", tr("Goat Scream Critical Alerts"), tr("Play the infamous \"Goat Scream\" for full-screen critical alerts that require immediate takeover.

Examples include: \"TAKE CONTROL IMMEDIATELY\" and \"Stock AEB: Risk of Collision\"."), ""}, - {"GreenLightAlert", tr("Green Light Alert"), tr("Play an alert when the model predicts a red light has turned green.

Disclaimer: openpilot does not explicitly detect traffic lights. This alert is based on end-to-end model predictions from camera input and may trigger even when the light has not changed."), ""}, - {"LeadDepartingAlert", tr("Lead Departing Alert"), tr("Play an alert when the lead vehicle departs from a stop."), ""}, - {"LoudBlindspotAlert", tr("Loud \"Car Detected in Blindspot\" Alert"), tr("Play a louder alert if a vehicle is in the blind spot when attempting to change lanes. Based on the \"Car Detected in Blindspot\" event."), ""}, - {"LoudBlindspotAlertWhenDisengaged", tr("Blind Spot Alert When Disengaged"), tr("Play the loud blind spot alert while lateral control is off or paused.

Useful when steering pauses on turn signal, since the lane-change state machine is inactive then."), ""}, - {"SpeedLimitChangedAlert", tr("Speed Limit Changed Alert"), tr("Play an alert when the posted speed limit changes."), ""} - }; - - for (const auto &[param, title, desc, icon] : soundsToggles) { - AbstractControl *soundsToggle; - - if (param == "AlertVolumeControl") { - StarPilotManageControl *alertVolumeControlToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(alertVolumeControlToggle, &StarPilotManageControl::manageButtonClicked, [soundsLayout, alertVolumeControlPanel]() { - soundsLayout->setCurrentWidget(alertVolumeControlPanel); - }); - soundsToggle = alertVolumeControlToggle; - } else if (alertCooldownKeys.contains(param)) { - std::map cooldownLabels; - for (int i = 0; i <= 30; ++i) { - cooldownLabels[i] = i == 0 ? tr("Off") : i == 1 ? tr("1 minute") : QString::number(i) + tr(" minutes"); - } - soundsToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 30, QString(), cooldownLabels, 1); - } else if (alertVolumeControlKeys.contains(param)) { - std::map volumeLabels; - for (int i = 0; i <= 101; ++i) { - volumeLabels[i] = i == 0 ? tr("Muted") : i == 101 ? tr("Auto") : QString::number(i) + "%"; - } - std::vector alertButton{tr("Test")}; - if (param == "WarningImmediateVolume" || param == "WarningSoftVolume") { - soundsToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 25, 101, QString(), volumeLabels, 1, true, {}, alertButton, false, false); - } else { - soundsToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 0, 101, QString(), volumeLabels, 1, true, {}, alertButton, false, false); - } - - } else if (param == "CustomAlerts") { - StarPilotManageControl *customAlertsToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(customAlertsToggle, &StarPilotManageControl::manageButtonClicked, [soundsLayout, customAlertsPanel]() { - soundsLayout->setCurrentWidget(customAlertsPanel); - }); - soundsToggle = customAlertsToggle; - - } else { - soundsToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = soundsToggle; - - if (alertCooldownKeys.contains(param) || alertVolumeControlKeys.contains(param)) { - alertVolumeControlList->addItem(soundsToggle); - } else if (customAlertsKeys.contains(param)) { - customAlertsList->addItem(soundsToggle); - } else { - soundsList->addItem(soundsToggle); - - parentKeys.insert(param); - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(soundsToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(soundsToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(soundsToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - for (const QString &key : alertVolumeControlKeys) { - StarPilotParamValueButtonControl *toggle = static_cast(toggles[key]); - QObject::connect(toggle, &StarPilotParamValueButtonControl::buttonClicked, [key, toggle, this]() { - toggle->updateParam(); - testSound(key); - }); - } - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [soundsLayout, soundsPanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - soundsLayout->setCurrentWidget(soundsPanel); - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotSoundsPanel::updateState); - - for (auto &[key, toggle] : toggles) { - if (alertCooldownKeys.contains(key) || alertVolumeControlKeys.contains(key)) { - toggle->setVisible(true); - } - } - - initializeSoundPlayer(); - - updateToggles(); -} - -void StarPilotSoundsPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void StarPilotSoundsPanel::initializeSoundPlayer() { - QString program = R"( -import numpy as np -import sounddevice as sd -import sys -import wave - -while True: - try: - line = sys.stdin.readline() - if not line: - break - path, volume = line.strip().split('|') - - sound_file = wave.open(path, 'rb') - audio = np.frombuffer(sound_file.readframes(sound_file.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0 - - sd.play(audio * float(volume), sound_file.getframerate()) - sd.wait() - except Exception: - pass -)"; - - soundPlayerProcess = new QProcess(this); - soundPlayerProcess->start("python3", QStringList{"-u", "-c", program}); -} - -void StarPilotSoundsPanel::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - started = s.scene.started; -} - -void StarPilotSoundsPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "LoudBlindspotAlert") { - setVisible &= parent->hasBSM; - } - - else if (key == "LoudBlindspotAlertWhenDisengaged") { - setVisible &= parent->hasBSM && params.getBool("LoudBlindspotAlert"); - } - - else if (key == "SpeedLimitChangedAlert") { - setVisible &= params.getBool("ShowSpeedLimits") || (parent->hasOpenpilotLongitudinal && params.getBool("SpeedLimitController")); - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (alertCooldownKeys.contains(key) || alertVolumeControlKeys.contains(key)) { - toggles["AlertVolumeControl"]->setVisible(true); - } else if (customAlertsKeys.contains(key)) { - toggles["CustomAlerts"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} - -void StarPilotSoundsPanel::testSound(const QString &key) { - QString baseName = QString(key).remove("Volume"); - - if (started) { - updateStarPilotToggles(); - - util::sleep_for(UI_FREQ); - - QString camelCaseAlert = baseName == "BelowSteerSpeed" ? "belowSteerSpeed" : QString(baseName).replace(0, 1, baseName[0].toLower()); - params_memory.put("TestAlert", camelCaseAlert.toStdString()); - } else { - QString previewBaseName = baseName == "BelowSteerSpeed" ? "Prompt" : baseName; - QString snakeCaseAlert = QString(previewBaseName).replace(QRegularExpression("([A-Z])"), "_\\1").toLower().mid(1); - QString stockPath = "../../selfdrive/assets/sounds/" + snakeCaseAlert + ".wav"; - QString themePath = "../../starpilot/assets/active_theme/sounds/" + snakeCaseAlert + ".wav"; - - float volume = params.getFloat(key.toStdString()) / 100.0f; - - soundPlayerProcess->write(((QFile::exists(themePath) ? themePath : stockPath) + "|" + QString::number(volume) + "\n").toUtf8()); - } -} diff --git a/starpilot/ui/qt/offroad/sounds_settings.h b/starpilot/ui/qt/offroad/sounds_settings.h deleted file mode 100644 index f8d448e4d..000000000 --- a/starpilot/ui/qt/offroad/sounds_settings.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotSoundsPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotSoundsPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void initializeSoundPlayer(); - void testSound(const QString &key); - void updateState(const UIState &s); - void updateToggles(); - - bool forceOpenDescriptions; - bool started; - - std::map toggles; - - QSet alertCooldownKeys {"SwitchbackModeCooldown"}; - QSet alertVolumeControlKeys {"BelowSteerSpeedVolume", "DisengageVolume", "EngageVolume", "PromptDistractedVolume", "PromptVolume", "RefuseVolume", "WarningImmediateVolume", "WarningSoftVolume"}; - QSet customAlertsKeys {"GoatScream", "GoatScreamCriticalAlerts", "GreenLightAlert", "LeadDepartingAlert", "LoudBlindspotAlert", "LoudBlindspotAlertWhenDisengaged", "SpeedLimitChangedAlert"}; - - QSet parentKeys; - - StarPilotSettingsWindow *parent; - - Params params; - Params params_memory{"", true}; - - QProcess *soundPlayerProcess; -}; diff --git a/starpilot/ui/qt/offroad/starpilot_settings.cc b/starpilot/ui/qt/offroad/starpilot_settings.cc deleted file mode 100644 index 119a4df09..000000000 --- a/starpilot/ui/qt/offroad/starpilot_settings.cc +++ /dev/null @@ -1,482 +0,0 @@ -#include "starpilot/ui/qt/offroad/data_settings.h" -#include "starpilot/ui/qt/offroad/device_settings.h" -#include "starpilot/ui/qt/offroad/starpilot_settings.h" -#include "starpilot/ui/qt/offroad/lateral_settings.h" -#include "starpilot/ui/qt/offroad/longitudinal_settings.h" -#include "starpilot/ui/qt/offroad/maps_settings.h" -#include "starpilot/ui/qt/offroad/model_settings.h" -#include "starpilot/ui/qt/offroad/navigation_settings.h" -#include "starpilot/ui/qt/offroad/sounds_settings.h" -#include "starpilot/ui/qt/offroad/theme_settings.h" -#include "starpilot/ui/qt/offroad/utilities.h" -#include "starpilot/ui/qt/offroad/vehicle_settings.h" -#include "starpilot/ui/qt/offroad/visual_settings.h" -#include "starpilot/ui/qt/offroad/wheel_settings.h" -#include "system/hardware/hw.h" - -#include - -bool nnffLogFileExists(const QString &carFingerprint) { - static QStringList models; - static QMap substitutes; - - if (models.isEmpty()) { - QFileInfoList fileInfoList = QDir(QStringLiteral("../../starpilot/assets/nnff_models")).entryInfoList(QDir::Files | QDir::NoDotAndDotDot); - for (const QFileInfo &fileInfo : fileInfoList) { - models.append(fileInfo.completeBaseName()); - } - - QFile sub_file("../../opendbc/car/torque_data/substitute.toml"); - if (sub_file.open(QIODevice::ReadOnly)) { - QTextStream in(&sub_file); - while (!in.atEnd()) { - QString line = in.readLine().trimmed(); - if (line.startsWith("#") || line.startsWith("legend") || !line.contains("=")) { - continue; - } - - QStringList parts = line.split("="); - if (parts.size() == 2) { - QString key = parts[0].trimmed().remove('"'); - QString value = parts[1].trimmed().remove('"'); - if (!key.isEmpty() && !value.isEmpty()) { - substitutes[key] = value; - } - } - } - } - } - - QStringList fingerprintsToCheck; - fingerprintsToCheck.append(carFingerprint); - if (substitutes.contains(carFingerprint)) { - fingerprintsToCheck.append(substitutes.value(carFingerprint)); - } - - for (const QString &fingerprint : fingerprintsToCheck) { - for (const QString &match : models) { - if (match.startsWith(fingerprint)) { - std::cout << "NNFF model found for fingerprint: " << fingerprint.toStdString() << std::endl; - return true; - } - } - } - - return false; -} - -void StarPilotSettingsWindow::createPanelButtons(StarPilotListWidget *list) { - StarPilotDataPanel *starpilotDataPanel = new StarPilotDataPanel(this, !shownDescriptions.value("StarPilotDataPanel").toBool(false)); - StarPilotDevicePanel *starpilotDevicePanel = new StarPilotDevicePanel(this, !shownDescriptions.value("StarPilotDevicePanel").toBool(false)); - StarPilotLateralPanel *starpilotLateralPanel = new StarPilotLateralPanel(this, !shownDescriptions.value("StarPilotLateralPanel").toBool(false)); - StarPilotLongitudinalPanel *starpilotLongitudinalPanel = new StarPilotLongitudinalPanel(this, !shownDescriptions.value("StarPilotLongitudinalPanel").toBool(false)); - StarPilotMapsPanel *starpilotMapsPanel = new StarPilotMapsPanel(this, !shownDescriptions.value("StarPilotMapsPanel").toBool(false)); - StarPilotModelPanel *starpilotModelPanel = new StarPilotModelPanel(this); - StarPilotNavigationPanel *starpilotNavigationPanel = new StarPilotNavigationPanel(this, !shownDescriptions.value("StarPilotNavigationPanel").toBool(false)); - StarPilotSoundsPanel *starpilotSoundsPanel = new StarPilotSoundsPanel(this, !shownDescriptions.value("StarPilotSoundsPanel").toBool(false)); - StarPilotThemesPanel *starpilotThemesPanel = new StarPilotThemesPanel(this, !shownDescriptions.value("StarPilotThemesPanel").toBool(false)); - StarPilotUtilitiesPanel *starpilotUtilitiesPanel = new StarPilotUtilitiesPanel(this, !shownDescriptions.value("StarPilotUtilitiesPanel").toBool(false)); - StarPilotVehiclesPanel *starpilotVehiclesPanel = new StarPilotVehiclesPanel(this, !shownDescriptions.value("StarPilotVehiclesPanel").toBool(false)); - StarPilotVisualsPanel *starpilotVisualsPanel = new StarPilotVisualsPanel(this, !shownDescriptions.value("StarPilotVisualsPanel").toBool(false)); - StarPilotWheelPanel *starpilotWheelPanel = new StarPilotWheelPanel(this, !shownDescriptions.value("StarPilotWheelPanel").toBool(false)); - - std::vector>> panelButtons = { - {{tr("MANAGE"), starpilotSoundsPanel}}, - {{tr("DRIVING MODEL"), starpilotModelPanel}, {tr("GAS / BRAKE"), starpilotLongitudinalPanel}, {tr("STEERING"), starpilotLateralPanel}}, - {{tr("MAP DATA"), starpilotMapsPanel}, {tr("NAVIGATION"), starpilotNavigationPanel}}, - {{tr("DATA"), starpilotDataPanel}, {tr("DEVICE CONTROLS"), starpilotDevicePanel}, {tr("UTILITIES"), starpilotUtilitiesPanel}}, - {{tr("APPEARANCE"), starpilotVisualsPanel}, {tr("THEME"), starpilotThemesPanel}}, - {{tr("VEHICLE SETTINGS"), starpilotVehiclesPanel}, {tr("WHEEL CONTROLS"), starpilotWheelPanel}} - }; - - std::vector> panelInfo = { - {tr("Alerts and Sounds"), tr("Adjust alert volumes and enable custom notifications."), "../../starpilot/assets/toggle_icons/icon_sound.png"}, - {tr("Driving Controls"), tr("Fine-tune custom StarPilot acceleration, braking, and steering controls."), "../../starpilot/assets/toggle_icons/icon_steering.png"}, - {tr("Navigation"), tr("Download map data for the \"Speed Limit Controller\"."), "../../starpilot/assets/toggle_icons/icon_navigate.png"}, - {tr("System Settings"), tr("Manage backups, device settings, screen options, storage, and tools to keep StarPilot running smoothly."), "../../starpilot/assets/toggle_icons/icon_system.png"}, - {tr("Theme and Appearance"), tr("Customize the look of the driving screen and interface, including themes!"), "../../starpilot/assets/toggle_icons/icon_display.png"}, - {tr("Vehicle Settings"), tr("Configure car-specific options and steering wheel button mappings."), "../../starpilot/assets/toggle_icons/icon_vehicle.png"} - }; - - for (size_t i = 0; i < panelInfo.size(); ++i) { - const QString &title = std::get<0>(panelInfo[i]); - const QString &description = std::get<1>(panelInfo[i]); - const QString &icon = std::get<2>(panelInfo[i]); - - const std::vector> &widgetLabels = panelButtons[i]; - - std::vector labels; - std::vector widgets; - - for (size_t j = 0; j < widgetLabels.size(); ++j) { - labels.push_back(std::get<0>(widgetLabels[j])); - - QWidget *panel = std::get<1>(widgetLabels[j]); - panel->setContentsMargins(50, 25, 50, 25); - - ScrollView *panelFrame = new ScrollView(panel, this); - mainLayout->addWidget(panelFrame); - widgets.push_back(panelFrame); - } - - StarPilotButtonsControl *panelButton = new StarPilotButtonsControl(title, description, icon, labels); - if (title == tr("Alerts and Sounds")) soundPanelButtons = panelButton; - if (title == tr("Driving Controls")) drivingPanelButtons = panelButton; - if (title == tr("Navigation")) navigationPanelButtons = panelButton; - if (title == tr("System Settings")) systemPanelButtons = panelButton; - if (title == tr("Theme and Appearance")) themePanelButtons = panelButton; - if (title == tr("Vehicle Settings")) vehiclePanelButtons = panelButton; - - if (forceOpenDescriptions) { - panelButton->showDescription(); - } - - QObject::connect(panelButton, &StarPilotButtonsControl::buttonClicked, [widgets, this](int id) { - mainLayout->setCurrentWidget(widgets[id]); - - panelOpen = true; - - openPanel(); - - ScrollView *panelFrame = qobject_cast(widgets[id]); - if (panelFrame) { - QWidget *panel = panelFrame->widget(); - QString className = panel->metaObject()->className(); - - if (!shownDescriptions.value(className).toBool(false)) { - shownDescriptions.insert(className, true); - params.putNonBlocking("ShownToggleDescriptions", QJsonDocument(shownDescriptions).toJson(QJsonDocument::Compact).toStdString()); - } - } - }); - - list->addItem(panelButton); - } - - QObject::connect(starpilotDataPanel, &StarPilotDataPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotDevicePanel, &StarPilotDevicePanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotLateralPanel, &StarPilotLateralPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotLongitudinalPanel, &StarPilotLongitudinalPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotLongitudinalPanel, &StarPilotLongitudinalPanel::openSubSubPanel, this, &StarPilotSettingsWindow::openSubSubPanel); - QObject::connect(starpilotLongitudinalPanel, &StarPilotLongitudinalPanel::openSubSubSubPanel, this, &StarPilotSettingsWindow::openSubSubSubPanel); - QObject::connect(starpilotMapsPanel, &StarPilotMapsPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotModelPanel, &StarPilotModelPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotNavigationPanel, &StarPilotNavigationPanel::closeSubPanel, this, &StarPilotSettingsWindow::closeSubPanel); - QObject::connect(starpilotNavigationPanel, &StarPilotNavigationPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotSoundsPanel, &StarPilotSoundsPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotThemesPanel, &StarPilotThemesPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotVehiclesPanel, &StarPilotVehiclesPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotVisualsPanel, &StarPilotVisualsPanel::openSubPanel, this, &StarPilotSettingsWindow::openSubPanel); - QObject::connect(starpilotVisualsPanel, &StarPilotVisualsPanel::openSubSubPanel, this, &StarPilotSettingsWindow::openSubSubPanel); -} - -StarPilotSettingsWindow::StarPilotSettingsWindow(SettingsWindow *parent) : QFrame(parent) { - shownDescriptions = QJsonDocument::fromJson(QString::fromStdString(params.get("ShownToggleDescriptions")).toUtf8()).object(); - - QString className = this->metaObject()->className(); - QString legacyClassName = className; - legacyClassName.replace("StarPilot", "FrogPilot"); - - bool alreadyShown = shownDescriptions.value(className).toBool(false); - bool legacyShown = legacyClassName != className && shownDescriptions.value(legacyClassName).toBool(false); - if (legacyShown && !alreadyShown) { - shownDescriptions.insert(className, true); - params.putNonBlocking("ShownToggleDescriptions", QJsonDocument(shownDescriptions).toJson(QJsonDocument::Compact).toStdString()); - } else if (!alreadyShown) { - forceOpenDescriptions = true; - } - - mainLayout = new QStackedLayout(this); - - QWidget *starpilotWidget = new QWidget(this); - QVBoxLayout *starpilotLayout = new QVBoxLayout(starpilotWidget); - starpilotLayout->setContentsMargins(50, 25, 50, 25); - starpilotWidget->setLayout(starpilotLayout); - - starpilotPanel = new ScrollView(starpilotWidget, this); - mainLayout->addWidget(starpilotPanel); - starpilotPanel->setWidget(starpilotWidget); - - StarPilotListWidget *list = new StarPilotListWidget(this); - starpilotLayout->addWidget(list); - - std::vector togglePresets{tr("Minimal"), tr("Standard"), tr("Advanced"), tr("Developer")}; - togglePreset = new StarPilotButtonsControl(tr("Tuning Level"), - tr("Choose your tuning level. Lower levels keep it simple; higher levels unlock more toggles for finer control.\n\n" - "Minimal - Ideal for those who prefer simplicity or ease of use\n" - "Standard - Recommended for most users for a balanced experience\n" - "Advanced - Fine-tuning for experienced users\n" - "Developer - Highly customizable settings for seasoned enthusiasts"), - "../../starpilot/assets/toggle_icons/icon_tuning.png", togglePresets, true); - QObject::connect(togglePreset, &StarPilotButtonsControl::buttonClicked, [this](int id) { - tuningLevel = id; - - params.putIntNonBlocking("TuningLevel", tuningLevel); - - updateVariables(); - - emit tuningLevelChanged(tuningLevel); - - if (id == 3) { - ConfirmationDialog::alert(tr("WARNING: These settings are risky and can drastically change how openpilot drives. Only change if you fully understand what they do!"), this); - } - }); - togglePreset->setCheckedButton(params.getInt("TuningLevel")); - if (forceOpenDescriptions) { - togglePreset->showDescription(); - } - list->addItem(togglePreset, true); - - createPanelButtons(list); - - QObject::connect(parent, &SettingsWindow::closePanel, this, &StarPilotSettingsWindow::closePanel); - QObject::connect(parent, &SettingsWindow::closeSubPanel, this, &StarPilotSettingsWindow::closeSubPanel); - QObject::connect(parent, &SettingsWindow::closeSubSubPanel, this, &StarPilotSettingsWindow::closeSubSubPanel); - QObject::connect(parent, &SettingsWindow::closeSubSubSubPanel, this, &StarPilotSettingsWindow::closeSubSubSubPanel); - QObject::connect(parent, &SettingsWindow::updateMetric, this, &StarPilotSettingsWindow::updateMetric); - QObject::connect(parent, &SettingsWindow::updateTuningLevel, this, &StarPilotSettingsWindow::updateTuningLevel); - QObject::connect(uiState(), &UIState::offroadTransition, this, &StarPilotSettingsWindow::updateVariables); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotSettingsWindow::updateState); - - std::vector keys = params.allKeys(); - for (std::vector::const_iterator it = keys.begin(); it != keys.end(); ++it) { - const std::string &key = *it; - starpilotToggleLevels[QString::fromStdString(key)] = params.getTuningLevel(key); - } - tuningLevel = params.getInt("TuningLevel"); - - closeSubPanel(); - updateMetric(params.getBool("IsMetric"), true); - updateVariables(); -} - -void StarPilotSettingsWindow::updateTuningLevel() { - tuningLevel = params.getInt("TuningLevel"); - togglePreset->setCheckedButton(params.getInt("TuningLevel")); - - updateVariables(); - - emit tuningLevelChanged(tuningLevel); -} - -bool StarPilotSettingsWindow::showAllTogglesEnabled() { - return params.getBool("ShowAllToggles"); -} - -void StarPilotSettingsWindow::showEvent(QShowEvent *event) { - static bool alertShown = false; - - QString className = this->metaObject()->className(); - if (!shownDescriptions.value(className).toBool(false)) { - shownDescriptions.insert(className, true); - params.putNonBlocking("ShownToggleDescriptions", QJsonDocument(shownDescriptions).toJson(QJsonDocument::Compact).toStdString()); - } - - if (forceOpenDescriptions) { - togglePreset->showDescription(); - - drivingPanelButtons->showDescription(); - navigationPanelButtons->showDescription(); - soundPanelButtons->showDescription(); - systemPanelButtons->showDescription(); - themePanelButtons->showDescription(); - vehiclePanelButtons->showDescription(); - - if (!alertShown) { - ConfirmationDialog::alert(tr("All toggle descriptions are currently expanded. You can tap a toggle's name to open or close its description at any time!"), this); - alertShown = true; - } - } -} - -void StarPilotSettingsWindow::hideEvent(QHideEvent *event) { - closePanel(); -} - -void StarPilotSettingsWindow::closePanel() { - if (forceOpenDescriptions) { - togglePreset->showDescription(); - - drivingPanelButtons->showDescription(); - navigationPanelButtons->showDescription(); - soundPanelButtons->showDescription(); - systemPanelButtons->showDescription(); - themePanelButtons->showDescription(); - vehiclePanelButtons->showDescription(); - } - - mainLayout->setCurrentWidget(starpilotPanel); - - panelOpen = false; -} - -void StarPilotSettingsWindow::updateState() { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - starpilot_scene.starpilot_panel_active = panelOpen && keepScreenOn; -} - -void StarPilotSettingsWindow::updateVariables() { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const bool showAllToggles = showAllTogglesEnabled(); - - auto applyDesktopVehicleFallback = [&]() { - QString fallbackMake = starpilot_toggles.value("car_make").toString(); - QString fallbackModel = starpilot_toggles.value("car_model").toString(); - if (fallbackMake.isEmpty()) { - fallbackMake = "gm"; - } - if (fallbackModel.isEmpty()) { - fallbackModel = "CHEVROLET_BOLT_ACC_2022_2023"; - } - - carMake = fallbackMake.toStdString(); - std::string fallbackFingerprint = fallbackModel.toStdString(); - - hasPedal = starpilot_toggles.value("has_pedal").toBool(true); - hasModeStarButtons = starpilot_toggles.contains("has_canfd_media_buttons") && starpilot_toggles.value("has_canfd_media_buttons").toBool(); - hasSDSU = starpilot_toggles.value("has_sdsu").toBool(); - hasZSS = starpilot_toggles.value("has_zss").toBool(); - isBolt = fallbackFingerprint.rfind("CHEVROLET_BOLT", 0) == 0; - isGM = carMake == "gm"; - isHKG = carMake == "hyundai"; - isHKGCanFd = isHKG && hasModeStarButtons; - isJeep = fallbackFingerprint.rfind("JEEP_", 0) == 0; - isSubaru = carMake == "subaru"; - isToyota = carMake == "toyota"; - isVolt = fallbackFingerprint.rfind("CHEVROLET_VOLT", 0) == 0; - canUsePedal = hasPedal || isBolt; - canUseSDSU = hasSDSU; - }; - - isFrogsGoMoo = ::isFrogsGoMoo(); - - std::string carParams = params.get("CarParamsPersistent"); - if (!carParams.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(carParams.data(), carParams.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - cereal::CarParams::SafetyModel safetyModel = CP.getSafetyConfigs()[0].getSafetyModel(); - - std::string carFingerprint = CP.getCarFingerprint(); - carMake = CP.getBrand(); - - friction = CP.getLateralTuning().getTorque().getFriction(); - hasAlphaLongitudinal = CP.getAlphaLongitudinalAvailable(); - hasBSM = CP.getEnableBsm(); - hasDashSpeedLimits = carMake == "ford" || carMake == "hyundai" || carMake == "toyota" || carMake == "honda"; - hasNNFFLog = nnffLogFileExists(QString::fromStdString(carFingerprint)); - hasOpenpilotLongitudinal = hasLongitudinalControl(CP); - hasPCMCruise = CP.getPcmCruise(); - hasPedal = CP.getEnableGasInterceptorDEPRECATED(); - hasRadar = !CP.getRadarUnavailable(); - hasSDSU = starpilot_toggles.value("has_sdsu").toBool(); - hasSNG = CP.getAutoResumeSng(); - hasZSS = starpilot_toggles.value("has_zss").toBool(); - isAngleCar = CP.getSteerControlType() == cereal::CarParams::SteerControlType::ANGLE; - isBolt = carFingerprint.rfind("CHEVROLET_BOLT", 0) == 0; - isGM = carMake == "gm"; - isHKG = carMake == "hyundai"; - isHKGCanFd = isHKG && safetyModel == cereal::CarParams::SafetyModel::HYUNDAI_CANFD; - isJeep = carMake == "chrysler" && carFingerprint.rfind("JEEP_", 0) == 0; - isSubaru = carMake == "subaru"; - isTorqueCar = CP.getLateralTuning().which() == cereal::CarParams::LateralTuning::TORQUE; - isToyota = carMake == "toyota"; - isTSK = CP.getSecOcRequired(); - isVolt = carFingerprint.rfind("CHEVROLET_VOLT", 0) == 0; - latAccelFactor = CP.getLateralTuning().getTorque().getLatAccelFactor(); - hasModeStarButtons = starpilot_toggles.contains("has_canfd_media_buttons") ? starpilot_toggles.value("has_canfd_media_buttons").toBool() : isHKGCanFd; - lkasAllowedForAOL = starpilot_toggles.value("lkas_allowed_for_aol").toBool(); - longitudinalActuatorDelay = CP.getLongitudinalActuatorDelay(); - startAccel = CP.getStartAccel(); - steerActuatorDelay = CP.getSteerActuatorDelay(); - // Keep Qt stock-sync aligned with selfdrive/controls/lib/latcontrol_torque.py::KP. - steerKp = 0.6f; - steerRatio = CP.getSteerRatio(); - stopAccel = CP.getStopAccel(); - stoppingDecelRate = CP.getStoppingDecelRate(); - vEgoStarting = CP.getVEgoStarting(); - vEgoStopping = CP.getVEgoStopping(); - - float currentDelayStock = params.getFloat("SteerDelayStock"); - float currentFrictionStock = params.getFloat("SteerFrictionStock"); - float currentKPStock = params.getFloat("SteerKPStock"); - float currentLatAccelStock = params.getFloat("SteerLatAccelStock"); - float currentLongDelayStock = params.getFloat("LongitudinalActuatorDelayStock"); - float currentStartAccelStock = params.getFloat("StartAccelStock"); - float currentSteerRatioStock = params.getFloat("SteerRatioStock"); - float currentStopAccelStock = params.getFloat("StopAccelStock"); - float currentStoppingDecelRateStock = params.getFloat("StoppingDecelRateStock"); - float currentVEgoStartingStock = params.getFloat("VEgoStartingStock"); - float currentVEgoStoppingStock = params.getFloat("VEgoStoppingStock"); - - auto nearlyEqual = [](float a, float b) { - return std::fabs(a - b) <= 1e-6f; - }; - - auto syncStockParam = [&](const char *key, const char *stockKey, float currentStock, float liveValue) { - if (nearlyEqual(currentStock, liveValue) || nearlyEqual(liveValue, 0.0f)) { - return; - } - - float currentValue = params.getFloat(key); - bool shouldUpdateLiveValue = nearlyEqual(currentValue, currentStock) || nearlyEqual(currentValue, 0.0f); - if (shouldUpdateLiveValue) { - params.putFloatNonBlocking(key, liveValue); - } - - params.putFloatNonBlocking(stockKey, liveValue); - }; - - syncStockParam("SteerDelay", "SteerDelayStock", currentDelayStock, steerActuatorDelay); - syncStockParam("SteerFriction", "SteerFrictionStock", currentFrictionStock, friction); - syncStockParam("SteerKP", "SteerKPStock", currentKPStock, steerKp); - syncStockParam("SteerLatAccel", "SteerLatAccelStock", currentLatAccelStock, latAccelFactor); - syncStockParam("LongitudinalActuatorDelay", "LongitudinalActuatorDelayStock", currentLongDelayStock, longitudinalActuatorDelay); - syncStockParam("StartAccel", "StartAccelStock", currentStartAccelStock, startAccel); - syncStockParam("SteerRatio", "SteerRatioStock", currentSteerRatioStock, steerRatio); - syncStockParam("StopAccel", "StopAccelStock", currentStopAccelStock, stopAccel); - syncStockParam("StoppingDecelRate", "StoppingDecelRateStock", currentStoppingDecelRateStock, stoppingDecelRate); - syncStockParam("VEgoStarting", "VEgoStartingStock", currentVEgoStartingStock, vEgoStarting); - syncStockParam("VEgoStopping", "VEgoStoppingStock", currentVEgoStoppingStock, vEgoStopping); - - if (Hardware::PC() && (carMake == "mock" || carFingerprint == "MOCK")) { - applyDesktopVehicleFallback(); - } - } else if (Hardware::PC()) { - applyDesktopVehicleFallback(); - } - - std::string starpilotCarParams = params.get("StarPilotCarParamsPersistent"); - if (!starpilotCarParams.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader fpcmsg(aligned_buf.align(starpilotCarParams.data(), starpilotCarParams.size())); - cereal::StarPilotCarParams::Reader FPCP = fpcmsg.getRoot(); - - canUsePedal = FPCP.getCanUsePedal(); - canUseSDSU = FPCP.getCanUseSDSU(); - openpilotLongitudinalControlDisabled = FPCP.getOpenpilotLongitudinalControlDisabled(); - } - - std::string liveTorqueParameters = params.get("LiveTorqueParameters"); - if (!liveTorqueParameters.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader reader(aligned_buf.align(liveTorqueParameters.data(), liveTorqueParameters.size())); - cereal::Event::Reader event = reader.getRoot(); - cereal::LiveTorqueParametersData::Reader LTP = event.getLiveTorqueParameters(); - - hasAutoTune = LTP.getUseParams(); - } - - drivingPanelButtons->setVisibleButton(0, showAllToggles || tuningLevel >= starpilotToggleLevels.value("DrivingModel").toDouble()); - drivingPanelButtons->setVisibleButton(1, showAllToggles || hasOpenpilotLongitudinal); - - systemPanelButtons->setVisibleButton(1, showAllToggles || tuningLevel >= starpilotToggleLevels.value("DeviceManagement").toDouble() || tuningLevel >= starpilotToggleLevels.value("ScreenManagement").toDouble()); - - vehiclePanelButtons->setVisibleButton(1, showAllToggles || tuningLevel >= starpilotToggleLevels.value("WheelControls").toDouble()); - - update(); -} diff --git a/starpilot/ui/qt/offroad/starpilot_settings.h b/starpilot/ui/qt/offroad/starpilot_settings.h deleted file mode 100644 index a7e27109b..000000000 --- a/starpilot/ui/qt/offroad/starpilot_settings.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/offroad/settings.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -#include "starpilot/ui/starpilot_ui.h" -#include "starpilot/ui/qt/widgets/starpilot_controls.h" - -class QNetworkAccessManager; - -class StarPilotSettingsWindow : public QFrame { - Q_OBJECT - -public: - explicit StarPilotSettingsWindow(SettingsWindow *parent); - - void updateVariables(); - bool showAllTogglesEnabled(); - - bool canUsePedal = false; - bool canUseSDSU = false; - bool forceOpenDescriptions = false; - bool hasAlphaLongitudinal = false; - bool hasAutoTune = true; - bool hasBSM = true; - bool hasDashSpeedLimits = true; - bool hasNNFFLog = true; - bool hasOpenpilotLongitudinal = true; - bool hasPCMCruise = false; - bool hasPedal = false; - bool hasRadar = true; - bool hasSDSU = false; - bool hasSNG = false; - bool hasModeStarButtons = false; - bool hasZSS = false; - bool isAngleCar = false; - bool isBolt = false; - bool isFrogsGoMoo = false; - bool isGM = true; - bool isHKG = true; - bool isHKGCanFd = true; - bool isJeep = false; - bool isSubaru = false; - bool isTorqueCar = false; - bool isToyota = true; - bool isTSK = false; - bool isVolt = true; - bool keepScreenOn = false; - bool lkasAllowedForAOL = false; - bool openpilotLongitudinalControlDisabled = false; - - float friction; - float latAccelFactor; - float longitudinalActuatorDelay; - float startAccel; - float steerActuatorDelay; - float steerKp; - float steerRatio; - float stopAccel; - float stoppingDecelRate; - float vEgoStarting; - float vEgoStopping; - - int tuningLevel; - - QJsonObject starpilotToggleLevels; - -signals: - void closeSubPanel(); - void closeSubSubPanel(); - void closeSubSubSubPanel(); - void openPanel(); - void openSubPanel(); - void openSubSubPanel(); - void openSubSubSubPanel(); - void tuningLevelChanged(int level); - void updateMetric(bool metric, bool bootRun=false); - -private: - void closePanel(); - void createPanelButtons(StarPilotListWidget *list); - void hideEvent(QHideEvent *event) override; - void showEvent(QShowEvent *event) override; - void updateState(); - void updateTuningLevel(); - - bool panelOpen; - - std::string carMake; - - StarPilotButtonsControl *drivingPanelButtons; - StarPilotButtonsControl *navigationPanelButtons; - StarPilotButtonsControl *soundPanelButtons; - StarPilotButtonsControl *systemPanelButtons; - StarPilotButtonsControl *themePanelButtons; - StarPilotButtonsControl *togglePreset; - StarPilotButtonsControl *vehiclePanelButtons; - - Params params; - - QJsonObject shownDescriptions; - - QStackedLayout *mainLayout; - - ScrollView *starpilotPanel; -}; diff --git a/starpilot/ui/qt/offroad/theme_settings.cc b/starpilot/ui/qt/offroad/theme_settings.cc deleted file mode 100644 index 9d2654c3c..000000000 --- a/starpilot/ui/qt/offroad/theme_settings.cc +++ /dev/null @@ -1,951 +0,0 @@ -#include "starpilot/ui/qt/offroad/theme_settings.h" -#include "system/hardware/hw.h" - -bool isUserCreatedTheme(const QString &themeName) { - return themeName.endsWith("-user_created"); -} - -void updateAssetParam(const QString &assetParam, Params ¶ms, const QString &value, bool add) { - QStringList assets = QString::fromStdString(params.get(assetParam.toStdString())).split(",", QString::SkipEmptyParts); - if (add) { - if (!assets.contains(value)) { - assets.append(value); - } - } else { - assets.removeAll(value); - } - assets.sort(); - - params.put(assetParam.toStdString(), assets.join(",").toStdString()); -} - -void deleteThemeAsset(QDir &directory, const QString &subFolder, const QString &assetParam, const QString &themeToDelete, Params ¶ms) { - bool useFiles = subFolder.isEmpty(); - - QString baseName = themeToDelete.toLower(); - baseName.replace("(", "-").replace(")", "").replace(" ", "-"); - baseName.remove(QRegularExpression("[^a-z0-9\\-]")); - while (baseName.endsWith("-")) { - baseName.chop(1); - } - - QString baseUnderscore = baseName; - baseUnderscore.replace("-", "_"); - - QStringList candidateNames = { - baseName, - baseName + "-user-created", - baseUnderscore, - baseUnderscore + "-user_created" - }; - - if (useFiles) { - QStringList files = directory.entryList(QDir::Files); - for (QString &file : files) { - QString normalizedFile = QFileInfo(file).baseName().toLower(); - normalizedFile.replace("_", "-"); - normalizedFile.remove(QRegularExpression("[^a-z0-9\\-~]")); - - if (candidateNames.contains(normalizedFile)) { - QFile::remove(directory.filePath(file)); - break; - } - } - } else { - for (QString &candidate : candidateNames) { - QString fullSubPath = QDir(candidate).filePath(subFolder); - QDir targetDir(directory.filePath(fullSubPath)); - - if (targetDir.exists()) { - targetDir.removeRecursively(); - break; - } - } - } - - updateAssetParam(assetParam, params, themeToDelete, true); -} - -void downloadThemeAsset(const QString &input, const std::string ¶mKey, const QString &assetParam, Params ¶ms, Params ¶ms_memory) { - if (paramKey == "BootLogoToDownload") { - params_memory.put(paramKey, input.trimmed().toStdString()); - return; - } - - QString output = input; - output.replace(" - by: ", "~"); - int tilde = output.indexOf("~"); - if (tilde >= 0) { - output = output.left(tilde).toLower() + "~" + output.mid(tilde + 1); - } else { - output = output.toLower(); - } - output.remove("(").remove(")"); - output.replace(" ", input.contains("(") ? "-" : "_"); - - params_memory.put(paramKey, output.toStdString()); -} - -QStringList getHolidayThemes() { - return QStringList() - << "New Year's" - << "Valentine's Day" - << "St. Patrick's Day" - << "World Frog Day" - << "April Fools" - << "Easter" - << "May the Fourth" - << "Cinco de Mayo" - << "Stitch Day" - << "Fourth of July" - << "Halloween" - << "Thanksgiving" - << "Christmas"; -} - -QStringList getThemeList(const bool &randomThemes, const QDir &themePacksDirectory, const QString &subFolder, const QString &assetParam, Params ¶ms) { - bool useFiles = subFolder.isEmpty(); - - QString currentAsset = randomThemes ? "" : QString::fromStdString(params.get(assetParam.toStdString())); - - QStringList themeList; - for (const QFileInfo &entry : themePacksDirectory.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { - if (entry.baseName() == currentAsset) { - continue; - } - - if (useFiles && entry.isDir()) { - continue; - } - - if (!useFiles) { - QString targetPath = QDir(entry.filePath()).filePath(subFolder); - if (!QFileInfo(targetPath).exists()) { - continue; - } - } - - QString baseName = entry.baseName(); - bool userCreated = isUserCreatedTheme(baseName); - if (userCreated) { - baseName = baseName.replace("-user_created", ""); - } - - int tildeIdx = baseName.indexOf("~"); - QString creator; - if (tildeIdx >= 0) { - creator = baseName.mid(tildeIdx + 1); - baseName = baseName.left(tildeIdx); - } - - QStringList parts = baseName.split(baseName.contains("-") ? "-" : "_", QString::SkipEmptyParts); - for (QString &part : parts) { - part[0] = part[0].toUpper(); - } - - QString displayName; - if (userCreated) { - displayName = parts.join(" "); - } else { - displayName = (parts.size() <= 1 || useFiles || !baseName.contains("-")) ? parts.join(" ") : QString("%1 (%2)").arg(parts[0], parts.mid(1).join(" ")); - } - - if (userCreated) { - displayName += " 🌟"; - } - if (!creator.isEmpty()) { - displayName += " - by: " + creator; - } - - themeList.append(displayName); - } - - return themeList; -} - -QString getThemeName(const std::string ¶mKey, Params ¶ms) { - QString value = QString::fromStdString(params.get(paramKey)); - - QString baseName = value; - - int tildeIdx = baseName.indexOf("~"); - QString creator; - if (tildeIdx >= 0) { - creator = baseName.mid(tildeIdx + 1); - baseName = baseName.left(tildeIdx); - } - - QStringList parts = baseName.split(baseName.contains("-") ? "-" : "_", QString::SkipEmptyParts); - for (QString &part : parts) { - part[0] = part[0].toUpper(); - } - - QString displayName; - if (baseName.contains("-") && parts.size() > 1) { - displayName = QString("%1 (%2)").arg(parts[0], parts.mid(1).join(" ")); - } else { - displayName = parts.join(" "); - } - - if (isUserCreatedTheme(value)) { - displayName = displayName.split(" (")[0] + " 🌟"; - } - if (!creator.isEmpty()) { - displayName += " - by: " + creator; - } - - return displayName; -} - -QString storeThemeName(const QString &input, const std::string ¶mKey, Params ¶ms) { - QString output = input.toLower().remove("(").remove(")").remove("'").remove("."); - output.replace(" ", input.contains("(") ? "-" : "_"); - output.replace("_🌟", "-user_created"); - output = output.trimmed(); - - params.put(paramKey, output.toStdString()); - - return getThemeName(paramKey, params); -} - -StarPilotThemesPanel::StarPilotThemesPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - if (Hardware::PC()) { - const QString themesRoot = QString::fromStdString(Path::comma_home() + "/starpilot/data/themes/"); - bootLogosDirectory.setPath(themesRoot + "bootlogos/"); - themePacksDirectory.setPath(themesRoot + "theme_packs/"); - wheelsDirectory.setPath(themesRoot + "steering_wheels/"); - } - - QDir().mkpath(bootLogosDirectory.path()); - QDir().mkpath(themePacksDirectory.path()); - QDir().mkpath(wheelsDirectory.path()); - - QStackedLayout *themesLayout = new QStackedLayout(); - addItem(themesLayout); - - StarPilotListWidget *themesList = new StarPilotListWidget(this); - - ScrollView *themesPanel = new ScrollView(themesList, this); - - themesLayout->addWidget(themesPanel); - - StarPilotListWidget *customThemesList = new StarPilotListWidget(this); - - ScrollView *customThemesPanel = new ScrollView(customThemesList, this); - - themesLayout->addWidget(customThemesPanel); - - const std::vector> themeToggles { - {"CustomThemes", tr("Custom Themes"), tr("The overall look and feel of openpilot. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), "../../starpilot/assets/toggle_icons/icon_frog.png"}, - {"BootLogo", tr("Boot Logo"), tr("The boot logo shown while the device starts."), ""}, - {"ColorScheme", tr("Color Scheme"), tr("The color scheme used throughout openpilot. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"DistanceIconPack", tr("Distance Button"), tr("The distance button icons shown on the driving screen. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"IconPack", tr("Icon Pack"), tr("The icon style used across openpilot. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"SignalAnimation", tr("Turn Signal"), tr("Themed turn-signal animations. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"SoundPack", tr("Sound Pack"), tr("The sound pack used by openpilot. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"WheelIcon", tr("Steering Wheel"), tr("The steering-wheel icon shown at the top-right of the driving screen. Use the \"Theme Maker\" in \"The Galaxy\" to create and share your own themes!"), ""}, - {"DownloadStatusLabel", tr("Download Status"), "", ""}, - - {"HolidayThemes", tr("Holiday Themes"), tr("Themes based on U.S. holidays. Minor holidays last one day; major holidays (Christmas, Easter, Halloween) run for a full week."), "../../starpilot/assets/toggle_icons/icon_calendar.png"}, - {"RainbowPath", tr("Rainbow Path"), tr("Color the driving path like a Mario Kart–style \"Rainbow Road\"."), "../../starpilot/assets/toggle_icons/icon_rainbow.png"}, - {"RandomEvents", tr("Random Events"), tr("Occasional on-screen effects triggered by driving conditions. These are purely a visual and don't impact how openpilot drives!"), "../../starpilot/assets/toggle_icons/icon_random.png"}, - {"RandomThemes", tr("Random Themes"), tr("Pick a random theme between each drive from the themes you have downloaded. Great for variety without changing settings while driving."), "../../starpilot/assets/toggle_icons/icon_random_themes.png"}, - {"StartupAlert", tr("Startup Alert"), tr("Customize the \"Startup Alert\" message shown at the start of each drive."), "../../starpilot/assets/toggle_icons/icon_message.png"} - }; - - for (const auto &[param, title, desc, icon] : themeToggles) { - AbstractControl *themeToggle; - - if (param == "CustomThemes") { - StarPilotManageControl *personalizeOpenpilotToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(personalizeOpenpilotToggle, &StarPilotManageControl::manageButtonClicked, [customThemesPanel, themesLayout]() { - themesLayout->setCurrentWidget(customThemesPanel); - }); - themeToggle = personalizeOpenpilotToggle; - } else if (param == "BootLogo") { - manageBootLogosButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageBootLogosButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - // Show all downloaded boot logos, including the currently selected one. - QStringList bootLogos = getThemeList(true, QDir(bootLogosDirectory.path()), "", "BootLogo", params); - - if (id == 0) { - QString bootLogoToDelete = MultiOptionDialog::getSelection(tr("Select a boot logo to delete"), bootLogos, "", this); - if (!bootLogoToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" boot logo?").arg(bootLogoToDelete), tr("Delete"), this)) { - bootLogosDownloaded = false; - - deleteThemeAsset(bootLogosDirectory, "", "DownloadableBootLogos", bootLogoToDelete, params); - } - } else if (id == 1) { - if (bootLogoDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - bootLogoDownloading = false; - cancellingDownload = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableBootLogos = QString::fromStdString(params.get("DownloadableBootLogos")).split(","); - bootLogoToDownload = MultiOptionDialog::getSelection(tr("Select a boot logo to download"), downloadableBootLogos, "", this); - if (!bootLogoToDownload.isEmpty()) { - manageBootLogosButton->setValue(storeThemeName(bootLogoToDownload, "BootLogo", params)); - - bootLogoDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(bootLogoToDownload, "BootLogoToDownload", "DownloadableBootLogos", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - QString bootLogoToSelect = MultiOptionDialog::getSelection(tr("Select a boot logo"), bootLogos, getThemeName("BootLogo", params), this); - if (!bootLogoToSelect.isEmpty()) { - manageBootLogosButton->setValue(storeThemeName(bootLogoToSelect, "BootLogo", params)); - } - } - }); - manageBootLogosButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageBootLogosButton; - } else if (param == "ColorScheme") { - manageColorSchemeButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageColorSchemeButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList colorSchemes = getThemeList(randomThemes, QDir(themePacksDirectory.path()), "colors", "ColorScheme", params); - - if (id == 0) { - QString colorSchemeToDelete = MultiOptionDialog::getSelection(tr("Select a color scheme to delete"), colorSchemes, "", this); - if (!colorSchemeToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" color scheme?").arg(colorSchemeToDelete), tr("Delete"), this)) { - colorsDownloaded = false; - - deleteThemeAsset(themePacksDirectory, "colors", "DownloadableColors", colorSchemeToDelete, params); - } - } else if (id == 1) { - if (colorDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - colorDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableColorSchemes = QString::fromStdString(params.get("DownloadableColors")).split(","); - colorSchemeToDownload = MultiOptionDialog::getSelection(tr("Select a color scheme to download"), downloadableColorSchemes, "", this); - if (!colorSchemeToDownload.isEmpty()) { - colorDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(colorSchemeToDownload, "ColorToDownload", "DownloadableColors", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - colorSchemes.append("Stock"); - colorSchemes.append(getHolidayThemes()); - colorSchemes.sort(); - - QString colorSchemeToSelect = MultiOptionDialog::getSelection(tr("Select a color scheme"), colorSchemes, getThemeName("ColorScheme", params), this); - if (!colorSchemeToSelect.isEmpty()) { - manageColorSchemeButton->setValue(storeThemeName(colorSchemeToSelect, "ColorScheme", params)); - } - } - }); - manageColorSchemeButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageColorSchemeButton; - } else if (param == "DistanceIconPack") { - manageDistanceIconPackButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageDistanceIconPackButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList distanceIconPacks = getThemeList(randomThemes, QDir(themePacksDirectory.path()), "distance_icons", "DistanceIconPack", params); - - if (id == 0) { - QString distanceIconPackToDelete = MultiOptionDialog::getSelection(tr("Select a distance icon pack to delete"), distanceIconPacks, "", this); - if (!distanceIconPackToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" distance icon pack?").arg(distanceIconPackToDelete), tr("Delete"), this)) { - distanceIconsDownloaded = false; - - deleteThemeAsset(themePacksDirectory, "distance_icons", "DownloadableDistanceIcons", distanceIconPackToDelete, params); - } - } else if (id == 1) { - if (distanceIconDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - distanceIconDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableDistanceIconPacks = QString::fromStdString(params.get("DownloadableDistanceIcons")).split(","); - distanceIconPackToDownload = MultiOptionDialog::getSelection(tr("Select a distance icon pack to download"), downloadableDistanceIconPacks, "", this); - if (!distanceIconPackToDownload.isEmpty()) { - distanceIconDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(distanceIconPackToDownload, "DistanceIconToDownload", "DownloadableDistanceIcons", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - distanceIconPacks.append("Stock"); - distanceIconPacks.append(getHolidayThemes()); - distanceIconPacks.sort(); - - QString distanceIconPackToSelect = MultiOptionDialog::getSelection(tr("Select a distance icon pack"), distanceIconPacks, getThemeName("DistanceIconPack", params), this); - if (!distanceIconPackToSelect.isEmpty()) { - manageDistanceIconPackButton->setValue(storeThemeName(distanceIconPackToSelect, "DistanceIconPack", params)); - } - } - }); - manageDistanceIconPackButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageDistanceIconPackButton; - } else if (param == "IconPack") { - manageIconPackButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageIconPackButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList iconPacks = getThemeList(randomThemes, QDir(themePacksDirectory.path()), "icons", "IconPack", params); - - if (id == 0) { - QString iconPackToDelete = MultiOptionDialog::getSelection(tr("Select an icon pack to delete"), iconPacks, "", this); - if (!iconPackToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" icon pack?").arg(iconPackToDelete), tr("Delete"), this)) { - iconsDownloaded = false; - - deleteThemeAsset(themePacksDirectory, "icons", "DownloadableIcons", iconPackToDelete, params); - } - } else if (id == 1) { - if (iconDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - iconDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableIconPacks = QString::fromStdString(params.get("DownloadableIcons")).split(","); - iconPackToDownload = MultiOptionDialog::getSelection(tr("Select an icon pack to download"), downloadableIconPacks, "", this); - if (!iconPackToDownload.isEmpty()) { - iconDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(iconPackToDownload, "IconToDownload", "DownloadableIcons", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - iconPacks.append("Stock"); - iconPacks.append(getHolidayThemes()); - iconPacks.sort(); - - QString iconPackToSelect = MultiOptionDialog::getSelection(tr("Select an icon pack"), iconPacks, getThemeName("IconPack", params), this); - if (!iconPackToSelect.isEmpty()) { - manageIconPackButton->setValue(storeThemeName(iconPackToSelect, "IconPack", params)); - } - } - }); - manageIconPackButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageIconPackButton; - } else if (param == "SignalAnimation") { - manageSignalAnimationButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageSignalAnimationButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList signalAnimations = getThemeList(randomThemes, QDir(themePacksDirectory.path()), "signals", "SignalAnimation", params); - - if (id == 0) { - QString signalAnimationToDelete = MultiOptionDialog::getSelection(tr("Select a signal animation to delete"), signalAnimations, "", this); - if (!signalAnimationToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" signal animation?").arg(signalAnimationToDelete), tr("Delete"), this)) { - signalsDownloaded = false; - - deleteThemeAsset(themePacksDirectory, "signals", "DownloadableSignals", signalAnimationToDelete, params); - } - } else if (id == 1) { - if (signalDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - signalDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableSignalAnimations = QString::fromStdString(params.get("DownloadableSignals")).split(","); - signalAnimationToDownload = MultiOptionDialog::getSelection(tr("Select a signal animation to download"), downloadableSignalAnimations, "", this); - if (!signalAnimationToDownload.isEmpty()) { - signalDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(signalAnimationToDownload, "SignalToDownload", "DownloadableSignals", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - signalAnimations.append("None"); - signalAnimations.append(getHolidayThemes()); - signalAnimations.sort(); - - QString signalAnimationToSelect = MultiOptionDialog::getSelection(tr("Select a signal animation"), signalAnimations, getThemeName("SignalAnimation", params), this); - if (!signalAnimationToSelect.isEmpty()) { - manageSignalAnimationButton->setValue(storeThemeName(signalAnimationToSelect, "SignalAnimation", params)); - } - } - }); - manageSignalAnimationButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageSignalAnimationButton; - } else if (param == "SoundPack") { - manageSoundPackButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageSoundPackButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList soundPacks = getThemeList(randomThemes, QDir(themePacksDirectory.path()), "sounds", "SoundPack", params); - - if (id == 0) { - QString soundPackToDelete = MultiOptionDialog::getSelection(tr("Select a sound pack to delete"), soundPacks, "", this); - if (!soundPackToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" sound pack?").arg(soundPackToDelete), tr("Delete"), this)) { - soundsDownloaded = false; - - deleteThemeAsset(themePacksDirectory, "sounds", "DownloadableSounds", soundPackToDelete, params); - } - } else if (id == 1) { - if (soundDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - soundDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableSoundPacks = QString::fromStdString(params.get("DownloadableSounds")).split(","); - soundPackToDownload = MultiOptionDialog::getSelection(tr("Select a sound pack to download"), downloadableSoundPacks, "", this); - if (!soundPackToDownload.isEmpty()) { - soundDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(soundPackToDownload, "SoundToDownload", "DownloadableSounds", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - soundPacks.append("Stock"); - soundPacks.append(getHolidayThemes()); - soundPacks.sort(); - - QString soundPackToSelect = MultiOptionDialog::getSelection(tr("Select a sound pack"), soundPacks, getThemeName("SoundPack", params), this); - if (!soundPackToSelect.isEmpty()) { - manageSoundPackButton->setValue(storeThemeName(soundPackToSelect, "SoundPack", params)); - } - } - }); - manageSoundPackButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageSoundPackButton; - } else if (param == "WheelIcon") { - manageWheelIconsButton = new StarPilotButtonsControl(title, desc, icon, {tr("DELETE"), tr("DOWNLOAD"), tr("SELECT")}); - QObject::connect(manageWheelIconsButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - QStringList wheelIcons = getThemeList(randomThemes, QDir(wheelsDirectory.path()), "", "WheelIcon", params); - - if (id == 0) { - QString wheelIconToDelete = MultiOptionDialog::getSelection(tr("Select a steering wheel to delete"), wheelIcons, "", this); - if (!wheelIconToDelete.isEmpty() && ConfirmationDialog::confirm(tr("Delete the \"%1\" steering wheel?").arg(wheelIconToDelete), tr("Delete"), this)) { - wheelsDownloaded = false; - - deleteThemeAsset(wheelsDirectory, "", "DownloadableWheels", wheelIconToDelete, params); - } - } else if (id == 1) { - if (wheelDownloading) { - cancellingDownload = true; - - params_memory.putBool("CancelThemeDownload", true); - - QTimer::singleShot(2500, [this]() { - cancellingDownload = false; - wheelDownloading = false; - themeDownloading = false; - - params_memory.putBool("CancelThemeDownload", false); - }); - } else { - QStringList downloadableWheels = QString::fromStdString(params.get("DownloadableWheels")).split(","); - wheelToDownload = MultiOptionDialog::getSelection(tr("Select a steering wheel to download"), downloadableWheels, "", this); - if (!wheelToDownload.isEmpty()) { - wheelDownloading = true; - themeDownloading = true; - - params_memory.put("ThemeDownloadProgress", "Downloading..."); - - downloadThemeAsset(wheelToDownload, "WheelToDownload", "DownloadableWheels", params, params_memory); - - downloadStatusLabel->setText(tr("Downloading...")); - } - } - } else if (id == 2) { - wheelIcons.append("None"); - wheelIcons.append("Stock"); - wheelIcons.append(getHolidayThemes()); - wheelIcons.sort(); - - QString steeringWheelToSelect = MultiOptionDialog::getSelection(tr("Select a steering wheel"), wheelIcons, getThemeName("WheelIcon", params), this); - if (!steeringWheelToSelect.isEmpty()) { - manageWheelIconsButton->setValue(storeThemeName(steeringWheelToSelect, "WheelIcon", params)); - } - } - }); - manageWheelIconsButton->setValue(getThemeName(param.toStdString(), params)); - themeToggle = manageWheelIconsButton; - } else if (param == "DownloadStatusLabel") { - downloadStatusLabel = new LabelControl(title, tr("Idle")); - themeToggle = downloadStatusLabel; - - } else if (param == "RandomThemes") { - std::vector randomThemesToggles{"RandomThemesHolidays"}; - std::vector randomThemesToggleNames{tr("Include Holiday Themes")}; - themeToggle = new StarPilotButtonToggleControl(param, title, desc, icon, randomThemesToggles, randomThemesToggleNames); - - } else if (param == "StartupAlert") { - StarPilotButtonsControl *startupAlertButton = new StarPilotButtonsControl(title, desc, icon, {tr("STOCK"), tr("STARPILOT"), tr("CUSTOM"), tr("CLEAR")}, true); - - QString currentTop = QString::fromStdString(params.get("StartupMessageTop")); - QString currentBottom = QString::fromStdString(params.get("StartupMessageBottom")); - - QString stockTop = "Be ready to take over at any time"; - QString stockBottom = "Always keep hands on wheel and eyes on road"; - - QString starpilotTop = "Hop in and buckle up!"; - QString starpilotBottom = "Human-tested, frog-approved 🐸"; - - if (currentTop == stockTop && currentBottom == stockBottom) { - startupAlertButton->setCheckedButton(0); - } else if (currentTop == starpilotTop && currentBottom == starpilotBottom) { - startupAlertButton->setCheckedButton(1); - } else if (!currentTop.isEmpty() || !currentBottom.isEmpty()) { - startupAlertButton->setCheckedButton(2); - } - - QObject::connect(startupAlertButton, &StarPilotButtonsControl::buttonClicked, [=](int id) { - int maxLengthTop = 35; - int maxLengthBottom = 45; - - if (id == 0) { - params.put("StartupMessageTop", stockTop.toStdString()); - params.put("StartupMessageBottom", stockBottom.toStdString()); - } else if (id == 1) { - params.put("StartupMessageTop", starpilotTop.toStdString()); - params.put("StartupMessageBottom", starpilotBottom.toStdString()); - } else if (id == 2) { - QString currentTop = QString::fromStdString(params.get("StartupMessageTop")); - QString newTop = InputDialog::getText(tr("Enter the text for the top half"), this, tr("Characters: 0/%1").arg(maxLengthTop), false, 1, currentTop, maxLengthTop).trimmed(); - if (!newTop.isEmpty()) { - params.put("StartupMessageTop", newTop.toStdString()); - - QString currentBottom = QString::fromStdString(params.get("StartupMessageBottom")); - QString newBottom = InputDialog::getText(tr("Enter the text for the bottom half"), this, tr("Characters: 0/%1").arg(maxLengthBottom), false, 1, currentBottom, maxLengthBottom).trimmed(); - if (!newBottom.isEmpty()) { - params.put("StartupMessageBottom", newBottom.toStdString()); - } - } - } else if (id == 3) { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your startup message?"), this)) { - params.remove("StartupMessageTop"); - params.remove("StartupMessageBottom"); - - startupAlertButton->clearCheckedButtons(); - } - } - }); - themeToggle = startupAlertButton; - - } else { - themeToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = themeToggle; - - if (customThemeKeys.contains(param)) { - customThemesList->addItem(themeToggle); - } else { - themesList->addItem(themeToggle); - - if (param == "CustomThemes") { - parentKeys.insert(param); - } - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(themeToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(themeToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(themeToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(static_cast(toggles["CustomThemes"]), &ToggleControl::toggleFlipped, this, &StarPilotThemesPanel::updateToggles); - QObject::connect(static_cast(toggles["RandomThemes"]), &ToggleControl::toggleFlipped, [this](bool state) { - if (state) { - ConfirmationDialog::alert(tr("\"Random Themes\" only works with downloaded themes, so make sure you download the themes you want it to use!"), this); - - manageColorSchemeButton->setValue(""); - manageColorSchemeButton->setVisibleButton(2, false); - - manageDistanceIconPackButton->setValue(""); - manageDistanceIconPackButton->setVisibleButton(2, false); - - manageIconPackButton->setValue(""); - manageIconPackButton->setVisibleButton(2, false); - - manageSignalAnimationButton->setValue(""); - manageSignalAnimationButton->setVisibleButton(2, false); - - manageSoundPackButton->setValue(""); - manageSoundPackButton->setVisibleButton(2, false); - - manageWheelIconsButton->setValue(""); - manageWheelIconsButton->setVisibleButton(2, false); - } else { - manageColorSchemeButton->setValue(getThemeName("ColorScheme", params)); - manageColorSchemeButton->setVisibleButton(2, true); - - manageDistanceIconPackButton->setValue(getThemeName("DistanceIconPack", params)); - manageDistanceIconPackButton->setVisibleButton(2, true); - - manageIconPackButton->setValue(getThemeName("IconPack", params)); - manageIconPackButton->setVisibleButton(2, true); - - manageSignalAnimationButton->setValue(getThemeName("SignalAnimation", params)); - manageSignalAnimationButton->setVisibleButton(2, true); - - manageSoundPackButton->setValue(getThemeName("SoundPack", params)); - manageSoundPackButton->setVisibleButton(2, true); - - manageWheelIconsButton->setValue(getThemeName("WheelIcon", params)); - manageWheelIconsButton->setVisibleButton(2, true); - } - - randomThemes = state; - }); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [themesLayout, themesPanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - themesLayout->setCurrentWidget(themesPanel); - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotThemesPanel::updateState); -} - -void StarPilotThemesPanel::showEvent(QShowEvent *event) { - bootLogosDownloaded = params.get("DownloadableBootLogos").empty(); - colorsDownloaded = params.get("DownloadableColors").empty(); - distanceIconsDownloaded = params.get("DownloadableDistanceIcons").empty(); - iconsDownloaded = params.get("DownloadableIcons").empty(); - signalsDownloaded = params.get("DownloadableSignals").empty(); - soundsDownloaded = params.get("DownloadableSounds").empty(); - wheelsDownloaded = params.get("DownloadableWheels").empty(); - - if (params.getBool("RandomThemes")) { - manageColorSchemeButton->setValue(""); - manageColorSchemeButton->setVisibleButton(2, false); - - manageDistanceIconPackButton->setValue(""); - manageDistanceIconPackButton->setVisibleButton(2, false); - - manageIconPackButton->setValue(""); - manageIconPackButton->setVisibleButton(2, false); - - manageSignalAnimationButton->setValue(""); - manageSignalAnimationButton->setVisibleButton(2, false); - - manageSoundPackButton->setValue(""); - manageSoundPackButton->setVisibleButton(2, false); - - manageWheelIconsButton->setValue(""); - manageWheelIconsButton->setVisibleButton(2, false); - - randomThemes = true; - } - - updateToggles(); -} - -void StarPilotThemesPanel::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible() || finalizingDownload) { - return; - } - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - - if (themeDownloading) { - QString progress = QString::fromStdString(params_memory.get("ThemeDownloadProgress")); - bool downloadFailed = progress.contains(QRegularExpression("cancelled|exists|failed|offline", QRegularExpression::CaseInsensitiveOption)); - - if (progress != "Downloading...") { - static const QMap progressTranslations = { - {"Download cancelled...", tr("Download cancelled...")}, - {"Download failed...", tr("Download failed...")}, - {"Downloaded!", tr("Downloaded!")}, - {"GitHub and GitLab are offline...", tr("GitHub and GitLab are offline...")}, - {"Repository unavailable", tr("Repository unavailable")}, - {"Unpacking theme...", tr("Unpacking theme...")}, - {"Verifying authenticity...", tr("Verifying authenticity...")} - }; - - if (progressTranslations.contains(progress)) { - downloadStatusLabel->setText(progressTranslations[progress]); - } else if (progress.endsWith("%")) { - downloadStatusLabel->setText(progress); - } else { - downloadStatusLabel->setText(tr("Idle")); - } - } - - if (progress == "Downloaded!" || downloadFailed) { - finalizingDownload = true; - - QTimer::singleShot(2500, [this]() { - bootLogoDownloading = false; - colorDownloading = false; - distanceIconDownloading = false; - finalizingDownload = false; - iconDownloading = false; - signalDownloading = false; - soundDownloading = false; - themeDownloading = false; - wheelDownloading = false; - - bootLogosDownloaded = params.get("DownloadableBootLogos").empty(); - colorsDownloaded = params.get("DownloadableColors").empty(); - distanceIconsDownloaded = params.get("DownloadableDistanceIcons").empty(); - iconsDownloaded = params.get("DownloadableIcons").empty(); - signalsDownloaded = params.get("DownloadableSignals").empty(); - soundsDownloaded = params.get("DownloadableSounds").empty(); - wheelsDownloaded = params.get("DownloadableWheels").empty(); - - params_memory.remove("CancelThemeDownload"); - params_memory.remove("ThemeDownloadProgress"); - - downloadStatusLabel->setText(tr("Idle")); - }); - } - } - - bool parked = !s.scene.started || starpilot_scene.parked || parent->isFrogsGoMoo; - - manageBootLogosButton->setText(1, bootLogoDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageBootLogosButton->setEnabledButtons(0, !themeDownloading); - manageBootLogosButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || bootLogoDownloading) && !cancellingDownload && !finalizingDownload && !bootLogosDownloaded && parked); - manageBootLogosButton->setEnabledButtons(2, !themeDownloading); - - manageColorSchemeButton->setText(1, colorDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageColorSchemeButton->setEnabledButtons(0, !themeDownloading); - manageColorSchemeButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || colorDownloading) && !cancellingDownload && !finalizingDownload && !colorsDownloaded && parked); - manageColorSchemeButton->setEnabledButtons(2, !themeDownloading); - - manageDistanceIconPackButton->setText(1, distanceIconDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageDistanceIconPackButton->setEnabledButtons(0, !themeDownloading); - manageDistanceIconPackButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || distanceIconDownloading) && !cancellingDownload && !finalizingDownload && !distanceIconsDownloaded && parked); - manageDistanceIconPackButton->setEnabledButtons(2, !themeDownloading); - - manageIconPackButton->setText(1, iconDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageIconPackButton->setEnabledButtons(0, !themeDownloading); - manageIconPackButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || iconDownloading) && !cancellingDownload && !finalizingDownload && !iconsDownloaded && parked); - manageIconPackButton->setEnabledButtons(2, !themeDownloading); - - manageSignalAnimationButton->setText(1, signalDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageSignalAnimationButton->setEnabledButtons(0, !themeDownloading); - manageSignalAnimationButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || signalDownloading) && !cancellingDownload && !finalizingDownload && !signalsDownloaded && parked); - manageSignalAnimationButton->setEnabledButtons(2, !themeDownloading); - - manageSoundPackButton->setText(1, soundDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageSoundPackButton->setEnabledButtons(0, !themeDownloading); - manageSoundPackButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || soundDownloading) && !cancellingDownload && !finalizingDownload && !soundsDownloaded && parked); - manageSoundPackButton->setEnabledButtons(2, !themeDownloading); - - manageWheelIconsButton->setText(1, wheelDownloading ? tr("CANCEL") : tr("DOWNLOAD")); - manageWheelIconsButton->setEnabledButtons(0, !themeDownloading); - manageWheelIconsButton->setEnabledButtons(1, starpilot_scene.online && (!themeDownloading || wheelDownloading) && !cancellingDownload && !finalizingDownload && !wheelsDownloaded && parked); - manageWheelIconsButton->setEnabledButtons(2, !themeDownloading); - - parent->keepScreenOn = themeDownloading; -} - -void StarPilotThemesPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "DistanceIconPack") { - setVisible &= params.getBool("QOLVisuals") && params.getBool("OnroadDistanceButton"); - } - - else if (key == "RandomThemes") { - setVisible &= params.getBool("CustomThemes"); - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (customThemeKeys.contains(key)) { - toggles["CustomThemes"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/theme_settings.h b/starpilot/ui/qt/offroad/theme_settings.h deleted file mode 100644 index 966a56b93..000000000 --- a/starpilot/ui/qt/offroad/theme_settings.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotThemesPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotThemesPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -protected: - void showEvent(QShowEvent *event) override; - -signals: - void openSubPanel(); - -private: - void updateState(const UIState &s, const StarPilotUIState &fs); - void updateToggles(); - - bool bootLogoDownloading = false; - bool bootLogosDownloaded = false; - bool cancellingDownload = false; - bool colorDownloading = false; - bool colorsDownloaded = false; - bool distanceIconDownloading = false; - bool distanceIconsDownloaded = false; - bool finalizingDownload = false; - bool forceOpenDescriptions = false; - bool iconDownloading = false; - bool iconsDownloaded = false; - bool randomThemes = false; - bool signalDownloading = false; - bool signalsDownloaded = false; - bool soundDownloading = false; - bool soundsDownloaded = false; - bool themeDownloading = false; - bool wheelDownloading = false; - bool wheelsDownloaded = false; - - std::map toggles; - - QSet customThemeKeys = {"BootLogo", "ColorScheme", "DistanceIconPack", "DownloadStatusLabel", "IconPack", "SignalAnimation", "SoundPack", "WheelIcon"}; - - QSet parentKeys; - - StarPilotButtonsControl *manageBootLogosButton; - StarPilotButtonsControl *manageColorSchemeButton; - StarPilotButtonsControl *manageDistanceIconPackButton; - StarPilotButtonsControl *manageIconPackButton; - StarPilotButtonsControl *manageSignalAnimationButton; - StarPilotButtonsControl *manageSoundPackButton; - StarPilotButtonsControl *manageWheelIconsButton; - - StarPilotSettingsWindow *parent; - - LabelControl *downloadStatusLabel; - - QDir bootLogosDirectory{"/data/themes/bootlogos/"}; - QDir themePacksDirectory{"/data/themes/theme_packs/"}; - QDir wheelsDirectory{"/data/themes/steering_wheels/"}; - - QString bootLogoToDownload; - QString colorSchemeToDownload; - QString distanceIconPackToDownload; - QString iconPackToDownload; - QString signalAnimationToDownload; - QString soundPackToDownload; - QString wheelToDownload; - - Params params; - Params params_memory{"", true}; -}; diff --git a/starpilot/ui/qt/offroad/utilities.cc b/starpilot/ui/qt/offroad/utilities.cc deleted file mode 100644 index e40e3557b..000000000 --- a/starpilot/ui/qt/offroad/utilities.cc +++ /dev/null @@ -1,192 +0,0 @@ -#include "starpilot/ui/qt/offroad/utilities.h" - -StarPilotUtilitiesPanel::StarPilotUtilitiesPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - ParamControl *debugModeToggle = new ParamControl("DebugMode", tr("Debug Mode"), tr("Use all of StarPilot's developer metrics on your next drive to diagnose issues and improve bug reports."), ""); - if (forceOpenDescriptions) { - debugModeToggle->showDescription(); - } - addItem(debugModeToggle); - - ButtonControl *flashPandaButton = new ButtonControl(tr("Flash Panda"), tr("FLASH"), tr("Flash the latest, official firmware onto your Panda device to restore core functionality, fix bugs, or ensure you have the most up-to-date software.")); - QObject::connect(flashPandaButton, &ButtonControl::clicked, [parent, flashPandaButton, this]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to flash the Panda firmware?"), tr("Flash"), this)) { - std::thread([parent, flashPandaButton, this]() { - parent->keepScreenOn = true; - - flashPandaButton->setEnabled(false); - flashPandaButton->setValue(tr("Flashing...")); - - params_memory.putBool("FlashPanda", true); - while (params_memory.getBool("FlashPanda")) { - util::sleep_for(UI_FREQ); - } - - flashPandaButton->setValue(tr("Flashed!")); - - util::sleep_for(2500); - - flashPandaButton->setValue(tr("Rebooting...")); - - util::sleep_for(2500); - - Hardware::reboot(); - }).detach(); - } - }); - if (forceOpenDescriptions) { - flashPandaButton->showDescription(); - } - addItem(flashPandaButton); - - StarPilotButtonsControl *forceStartedButton = new StarPilotButtonsControl(tr("Force Drive State"), tr("Force openpilot to be offroad or onroad."), "", {tr("OFFROAD"), tr("ONROAD"), tr("OFF")}, true); - QObject::connect(forceStartedButton, &StarPilotButtonsControl::buttonClicked, [this](int id) { - if (id == 0) { - params.putBool("ForceOffroad", true); - params.putBool("ForceOnroad", false); - - updateStarPilotToggles(); - } else if (id == 1) { - params.put("CarParams", params.get("CarParamsPersistent")); - params.put("StarPilotCarParams", params.get("StarPilotCarParamsPersistent")); - - params.putBool("ForceOffroad", false); - params.putBool("ForceOnroad", true); - - updateStarPilotToggles(); - } else if (id == 2) { - params.putBool("ForceOffroad", false); - params.putBool("ForceOnroad", false); - - updateStarPilotToggles(); - } - }); - forceStartedButton->setCheckedButton(2); - if (forceOpenDescriptions) { - forceStartedButton->showDescription(); - } - addItem(forceStartedButton); - - ButtonControl *reportIssueButton = new ButtonControl(tr("Report a Bug or an Issue"), tr("REPORT"), tr("Send a bug report so we can help fix the problem!")); - QObject::connect(reportIssueButton, &ButtonControl::clicked, [this]() { - if (!starpilotUIState()->starpilot_scene.online) { - ConfirmationDialog::alert(tr("Please connect to the internet before sending a report!"), this); - return; - } - - QStringList report_messages = { - tr("Acceleration feels harsh or jerky"), - tr("An alert was unclear and I'm not sure what it meant"), - tr("Braking is too sudden or uncomfortable"), - tr("I'm not sure if this is normal or a bug:"), - tr("My steering wheel buttons aren't working"), - tr("openpilot disengages when I don't expect it"), - tr("openpilot feels sluggish or slow to respond"), - tr("Something else (please describe)") - }; - - if (QFile::exists("/data/error_logs/error.txt")) { - report_messages.prepend(tr("I saw an alert that said \"openpilot crashed\"")); - } - - QString selected_issue = MultiOptionDialog::getSelection(tr("What's going on?"), report_messages, "", this); - if (selected_issue.isEmpty()) { - return; - } - - if (selected_issue.contains("crashed") || selected_issue.contains("not sure") || selected_issue.contains("Something else")) { - QString extra_input = InputDialog::getText(tr("Please describe what's happening"), this, tr("Send Report"), false, 10, "", 300).trimmed(); - if (extra_input.isEmpty()) { - return; - } - selected_issue += " — " + extra_input; - } - - QString discord_user = InputDialog::getText(tr("What's your Discord username?"), this, tr("Send Report"), false, -1, QString::fromStdString(params.get("DiscordUsername"))).trimmed(); - - QJsonObject reportData; - reportData["DiscordUser"] = discord_user; - reportData["Issue"] = selected_issue; - - params.putNonBlocking("DiscordUsername", discord_user.toStdString()); - params_memory.put("IssueReported", QJsonDocument(reportData).toJson(QJsonDocument::Compact).toStdString()); - - ConfirmationDialog::alert(tr("Report Sent! Thanks for letting us know!"), this); - }); - if (forceOpenDescriptions) { - reportIssueButton->showDescription(); - } - addItem(reportIssueButton); - reportIssueButton->setVisible(true); - - ButtonControl *resetTogglesButton = new ButtonControl(tr("Reset Toggles to Default"), tr("RESET"), tr("Reset all toggles to their default values.")); - QObject::connect(resetTogglesButton, &ButtonControl::clicked, [parent, resetTogglesButton, this]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset all toggles to their default values?"), tr("Reset"), this)) { - std::thread([parent, resetTogglesButton, this]() { - parent->keepScreenOn = true; - - resetTogglesButton->setEnabled(false); - resetTogglesButton->setValue(tr("Resetting...")); - - std::vector all_keys = params.allKeys(); - for (const std::string &key : all_keys) { - if (excluded_keys.count(key)) { - continue; - } - std::optional default_value = params.getKeyDefaultValue(key); - if (default_value.has_value()) { - params.put(key, default_value.value()); - } - } - - updateStarPilotToggles(); - - resetTogglesButton->setValue(tr("Reset!")); - - util::sleep_for(2500); - - resetTogglesButton->setValue(""); - }).detach(); - } - }); - if (forceOpenDescriptions) { - resetTogglesButton->showDescription(); - } - addItem(resetTogglesButton); - - ButtonControl *resetTogglesButtonStock = new ButtonControl(tr("Reset Toggles to Stock openpilot"), tr("RESET"), tr("Reset all toggles to match stock openpilot.")); - QObject::connect(resetTogglesButtonStock, &ButtonControl::clicked, [parent, resetTogglesButtonStock, this]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset all toggles to match stock openpilot?"), tr("Reset"), this)) { - std::thread([parent, resetTogglesButtonStock, this]() { - parent->keepScreenOn = true; - - resetTogglesButtonStock->setEnabled(false); - resetTogglesButtonStock->setValue(tr("Resetting...")); - - std::vector all_keys = params.allKeys(); - for (const std::string &key : all_keys) { - if (excluded_keys.count(key)) { - continue; - } - std::optional stock_value = params.getStockValue(key); - if (stock_value.has_value()) { - params.put(key, stock_value.value()); - } - } - - updateStarPilotToggles(); - - resetTogglesButtonStock->setValue(tr("Reset!")); - - util::sleep_for(2500); - - resetTogglesButtonStock->setValue(""); - }).detach(); - } - }); - if (forceOpenDescriptions) { - resetTogglesButtonStock->showDescription(); - } - addItem(resetTogglesButtonStock); -} diff --git a/starpilot/ui/qt/offroad/utilities.h b/starpilot/ui/qt/offroad/utilities.h deleted file mode 100644 index 09e83d9af..000000000 --- a/starpilot/ui/qt/offroad/utilities.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotUtilitiesPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotUtilitiesPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -private: - bool forceOpenDescriptions; - - StarPilotSettingsWindow *parent; - - Params params; - Params params_memory{"", true}; - - std::set excluded_keys = { - "AvailableModels", "AvailableModelNames", "AvailableModelArtifactFormats", "StarPilotStats", - "GithubSshKeys", "GithubUsername", "MapBoxRequests", - "ModelDrivesAndScores", "ModelManifestVersion", "OverpassRequests", "SpeedLimits", - "SpeedLimitsFiltered", "UpdaterAvailableBranches", - }; -}; diff --git a/starpilot/ui/qt/offroad/vehicle_settings.cc b/starpilot/ui/qt/offroad/vehicle_settings.cc deleted file mode 100644 index 2eedb78a5..000000000 --- a/starpilot/ui/qt/offroad/vehicle_settings.cc +++ /dev/null @@ -1,497 +0,0 @@ -#include - -#include "starpilot/ui/qt/offroad/vehicle_settings.h" -#include "system/hardware/hw.h" - -QStringList getCarNames(const QString &carMake, QMap &carModels) { - static const QHash makeToFolder = { - {"acura", "honda"}, - {"audi", "volkswagen"}, - {"buick", "gm"}, - {"cadillac", "gm"}, - {"chevrolet", "gm"}, - {"chrysler", "chrysler"}, - {"cupra", "volkswagen"}, - {"dodge", "chrysler"}, - {"ford", "ford"}, - {"genesis", "hyundai"}, - {"gmc", "gm"}, - {"holden", "gm"}, - {"honda", "honda"}, - {"hyundai", "hyundai"}, - {"jeep", "chrysler"}, - {"kia", "hyundai"}, - {"lexus", "toyota"}, - {"lincoln", "ford"}, - {"man", "volkswagen"}, - {"mazda", "mazda"}, - {"nissan", "nissan"}, - {"peugeot", "psa"}, - {"ram", "chrysler"}, - {"rivian", "rivian"}, - {"seat", "volkswagen"}, - {"škoda", "volkswagen"}, - {"subaru", "subaru"}, - {"tesla", "tesla"}, - {"toyota", "toyota"}, - {"volkswagen", "volkswagen"} - }; - - QStringList carNames; - - const QString folder = makeToFolder.value(carMake.toLower()); - if (folder.isEmpty()) { - return carNames; - } - - QFile file(QString("../../opendbc/car/%1/values.py").arg(folder)); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - return carNames; - } - - QString content = file.readAll(); - file.close(); - - static const QRegularExpression commentRe("#[^\\n]*"); - static const QRegularExpression footnoteRe("footnotes=\\[[^\\]]*\\],\\s*"); - content.remove(commentRe).remove(footnoteRe); - - static const QRegularExpression platformRe("(\\w+)\\s*=\\s*\\w+\\s*\\("); - QRegularExpressionMatchIterator platformIt = platformRe.globalMatch(content); - - QVector> platforms; - while (platformIt.hasNext()) { - QRegularExpressionMatch match = platformIt.next(); - platforms.append({match.capturedStart(), match.captured(1)}); - } - platforms.append({content.length(), QString()}); - - static const QRegularExpression carNameRe("CarDocs\\w*\\s*\\(\\s*\"([^\"]+)\""); - const QString lowerMake = carMake.toLower(); - - for (int i = 0; i < platforms.size() - 1; ++i) { - int start = platforms[i].first; - int end = platforms[i + 1].first; - const QString &platformName = platforms[i].second; - - QRegularExpressionMatchIterator carIt = carNameRe.globalMatch( - content.mid(start, end - start) - ); - - while (carIt.hasNext()) { - QString carName = carIt.next().captured(1); - if (carName.startsWith(carMake, Qt::CaseInsensitive)) { - carModels[carName] = platformName; - carNames.append(carName); - } - } - } - - carNames.sort(Qt::CaseInsensitive); - return carNames; -} - -StarPilotVehiclesPanel::StarPilotVehiclesPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *vehiclesLayout = new QStackedLayout(); - addItem(vehiclesLayout); - - StarPilotListWidget *settingsList = new StarPilotListWidget(this); - - ScrollView *vehiclesPanel = new ScrollView(settingsList, this); - - vehiclesLayout->addWidget(vehiclesPanel); - - QStringList makes = { - "Acura", "Audi", "Buick", "Cadillac", "Chevrolet", "Chrysler", "CUPRA", - "Dodge", "Ford", "Genesis", "GMC", "Holden", "Honda", "Hyundai", "Jeep", - "Kia", "Lexus", "Lincoln", "MAN", "Mazda", "Nissan", "Peugeot", "Ram", - "Rivian", "SEAT", "Škoda", "Subaru", "Tesla", "Toyota", "Volkswagen" - }; - - ButtonControl *selectMakeButton = new ButtonControl(tr("Car Make"), tr("SELECT")); - QObject::connect(selectMakeButton, &ButtonControl::clicked, [makes, selectMakeButton, this]() { - QString makeSelection = MultiOptionDialog::getSelection(tr("Choose your car make"), makes, "", this); - if (!makeSelection.isEmpty()) { - params.put("CarMake", makeSelection.toStdString()); - selectMakeButton->setValue(makeSelection); - } - }); - settingsList->addItem(selectMakeButton); - - ButtonControl *selectModelButton = new ButtonControl(tr("Car Model"), tr("SELECT")); - QObject::connect(selectModelButton, &ButtonControl::clicked, [selectModelButton, this]() { - QString modelSelection = MultiOptionDialog::getSelection(tr("Choose your car model"), getCarNames(QString::fromStdString(params.get("CarMake")).toLower(), carModels), "", this); - if (!modelSelection.isEmpty()) { - params.put("CarModel", carModels.value(modelSelection).toStdString()); - params.put("CarModelName", modelSelection.toStdString()); - selectModelButton->setValue(modelSelection); - } - }); - settingsList->addItem(selectModelButton); - - forceFingerprint = new ParamControl("ForceFingerprint", tr("Disable Automatic Fingerprint Detection"), tr("Force the selected fingerprint and prevent it from ever changing."), ""); - settingsList->addItem(forceFingerprint); - - disableOpenpilotLong = new ParamControl("DisableOpenpilotLongitudinal", tr("Disable openpilot Longitudinal Control"), tr("Disable openpilot longitudinal and use the car's stock ACC instead."), ""); - QObject::connect(disableOpenpilotLong, &ToggleControl::toggleFlipped, [parent, this](bool state) { - if (state) { - if (StarPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely disable openpilot longitudinal control?"), this)) { - if (started) { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - } - } else { - params.putBool("DisableOpenpilotLongitudinal", false); - disableOpenpilotLong->refresh(); - } - } - - parent->updateVariables(); - updateToggles(); - }); - settingsList->addItem(disableOpenpilotLong); - - StarPilotListWidget *chryslerList = new StarPilotListWidget(this); - StarPilotListWidget *gmList = new StarPilotListWidget(this); - StarPilotListWidget *hkgList = new StarPilotListWidget(this); - StarPilotListWidget *subaruList = new StarPilotListWidget(this); - StarPilotListWidget *toyotaList = new StarPilotListWidget(this); - StarPilotListWidget *vehicleInfoList = new StarPilotListWidget(this); - - ScrollView *chryslerPanel = new ScrollView(chryslerList, this); - ScrollView *gmPanel = new ScrollView(gmList, this); - ScrollView *hkgPanel = new ScrollView(hkgList, this); - ScrollView *subaruPanel = new ScrollView(subaruList, this); - ScrollView *toyotaPanel = new ScrollView(toyotaList, this); - ScrollView *vehicleInfoPanel = new ScrollView(vehicleInfoList, this); - - vehiclesLayout->addWidget(chryslerPanel); - vehiclesLayout->addWidget(gmPanel); - vehiclesLayout->addWidget(hkgPanel); - vehiclesLayout->addWidget(subaruPanel); - vehiclesLayout->addWidget(toyotaPanel); - vehiclesLayout->addWidget(vehicleInfoPanel); - - std::vector> vehicleToggles { - {"ChryslerToggles", tr("Chrysler/Jeep Settings"), tr("StarPilot features for Chrysler and Jeep vehicles."), ""}, - {"JeepBrakeHold", tr("Brake Hold"), tr("Hold the brakes after Jeep ACC times out at a stop, then send resume when traffic moves again."), ""}, - - {"GMToggles", tr("General Motors Settings"), tr("StarPilot features for General Motors vehicles."), ""}, - {"GMPedalLongitudinal", tr("Use Pedal For Longitudinal"), tr("Use the pedal interceptor for full longitudinal control on supported GM vehicles."), ""}, - {"GMDashSpoofOffsets", tr("Apply Offsets To Dash Spoof"), tr("On GM pedal-long cars, add the configured set-speed offset to the spoofed dash set speed so it matches the on-screen set speed."), ""}, - {"IgnoreIgnitionLine", tr("Use CAN Ignition Only"), tr("Use CAN ignition only and ignore the physical ignition line in Panda firmware.

Requires a Panda flash. Use this only on vehicles with reliable CAN ignition when the harness box reports false ignition."), ""}, - {"LongPitch", tr("Smooth Pedal Response on Hills"), tr("Smoothen acceleration and braking when driving downhill/uphill."), ""}, - {"RemoteStartBootsComma", tr("Remote Start Boots comma"), tr("Use the remote-start GM panda firmware at boot.

Required for GM remote-start startup signal behavior."), ""}, - {"RemapCancelToDistance", tr("Remap Cancel Button"), tr("On pedal-interceptor Bolts, treat the steering-wheel CANCEL button as an extra mappable button."), ""}, - {"VoltSNG", tr("Stop-and-Go Hack"), tr("Force stop-and-go on the 2017 Chevy Volt."), ""}, - - {"HKGToggles", tr("Hyundai/Kia/Genesis Settings"), tr("StarPilot features for Hyundai/Kia/Genesis vehicles."), ""}, - {"HKGRemoteStartBootsComma", tr("EV Remote Climate"), tr("Use the remote-climate Hyundai/Kia/Genesis CAN-FD panda firmware at boot.

Required for EV remote-climate startup signal behavior."), ""}, - - {"SubaruToggles", tr("Subaru Settings"), tr("StarPilot features for Subaru vehicles."), ""}, - {"SubaruSNG", tr("Stop and Go"), tr("Stop and go for supported Subaru vehicles."), ""}, - {"SubaruSNGManualParkingBrake", tr("Stop and Go for Manual Parking Brake"), tr("Use the manual-parking-brake Subaru stop-and-go strategy.

Enable this for supported Subaru Global models with a manual handbrake. Keep it off on models with an electric parking brake."), ""}, - - {"ToyotaToggles", tr("Toyota/Lexus Settings"), tr("StarPilot features for Lexus and Toyota vehicles."), ""}, - {"ToyotaDoors", tr("Automatically Lock/Unlock Doors"), tr("Automatically lock/unlock doors when shifting in and out of drive."), ""}, - {"ClusterOffset", tr("Dashboard Speed Offset"), tr("The speed offset openpilot uses to match the speed on the dashboard display."), ""}, - {"LockDoorsTimer", tr("Lock Doors On Ignition Off After"), tr("Automatically lock the doors on ignition off when no one is detected in the front seats."), ""}, - {"SNGHack", tr("Stop-and-Go Hack"), tr("Force stop-and-go on Lexus/Toyota vehicles without stock stop-and-go functionality."), ""}, - - {"VehicleInfo", tr("Vehicle Info"), tr("Information about your vehicle in regards to openpilot support and functionality."), ""}, - {"HardwareDetected", tr("3rd Party Hardware Detected"), tr("Detected 3rd party hardware."), ""}, - {"BlindSpotSupport", tr("Blind Spot Support"), tr("Does openpilot use the vehicle's blind spot data?"), ""}, - {"PedalSupport", tr("comma Pedal Support"), tr("Does your vehicle support the \"comma pedal\"?"), ""}, - {"OpenpilotLongitudinal", tr("openpilot Longitudinal Support"), tr("Can openpilot control the vehicle's acceleration and braking?"), ""}, - {"RadarSupport", tr("Radar Support"), tr("Does openpilot use the vehicle's radar data alongside the device's camera for tracking lead vehicles?"), ""}, - {"SDSUSupport", tr("SDSU Support"), tr("Does your vehicle support \"SDSUs\"?"), ""}, - {"SNGSupport", tr("Stop-and-Go Support"), tr("Does your vehicle support stop-and-go driving?"), ""} - }; - - for (const auto &[param, title, desc, icon] : vehicleToggles) { - AbstractControl *vehicleToggle; - - if (param == "ChryslerToggles") { - ButtonControl *chryslerButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(chryslerButton, &ButtonControl::clicked, [vehiclesLayout, chryslerPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(chryslerPanel); - }); - vehicleToggle = chryslerButton; - - } else if (param == "GMToggles") { - ButtonControl *gmButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(gmButton, &ButtonControl::clicked, [vehiclesLayout, gmPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(gmPanel); - }); - vehicleToggle = gmButton; - - } else if (param == "HKGToggles") { - ButtonControl *hkgButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(hkgButton, &ButtonControl::clicked, [vehiclesLayout, hkgPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(hkgPanel); - }); - vehicleToggle = hkgButton; - - } else if (param == "SubaruToggles") { - ButtonControl *subaruButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(subaruButton, &ButtonControl::clicked, [vehiclesLayout, subaruPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(subaruPanel); - }); - vehicleToggle = subaruButton; - - } else if (param == "ToyotaToggles") { - ButtonControl *toyotaButton = new ButtonControl(title, tr("MANAGE"), desc); - QObject::connect(toyotaButton, &ButtonControl::clicked, [vehiclesLayout, toyotaPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(toyotaPanel); - }); - vehicleToggle = toyotaButton; - } else if (param == "ToyotaDoors") { - std::vector lockToggles{"LockDoors", "UnlockDoors"}; - std::vector lockToggleNames{tr("Lock"), tr("Unlock")}; - vehicleToggle = new StarPilotButtonToggleControl(param, title, desc, icon, lockToggles, lockToggleNames); - } else if (param == "LockDoorsTimer") { - std::map autoLockLabels; - for (int i = 0; i <= 300; ++i) { - autoLockLabels[i] = i == 0 ? tr("Never") : QString::number(i) + tr(" seconds"); - } - vehicleToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 300, QString(), autoLockLabels, 5); - } else if (param == "ClusterOffset") { - std::vector clusterOffsetButton{"Reset"}; - StarPilotParamValueButtonControl *clusterOffsetToggle = new StarPilotParamValueButtonControl(param, title, desc, icon, 1.000, 1.050, "x", std::map(), 0.001, false, {}, clusterOffsetButton, false, false); - QObject::connect(clusterOffsetToggle, &StarPilotParamValueButtonControl::buttonClicked, [clusterOffsetToggle, this]() { - params.putFloat("ClusterOffset", std::stof(params.getKeyDefaultValue("ClusterOffset").value())); - clusterOffsetToggle->refresh(); - }); - vehicleToggle = clusterOffsetToggle; - - } else if (param == "VehicleInfo") { - ButtonControl *VehicleInfoButton = new ButtonControl(title, tr("VIEW"), desc); - QObject::connect(VehicleInfoButton, &ButtonControl::clicked, [vehiclesLayout, vehicleInfoPanel, this]() { - openDescriptions(forceOpenDescriptions, toggles); - vehiclesLayout->setCurrentWidget(vehicleInfoPanel); - }); - vehicleToggle = VehicleInfoButton; - } else if (vehicleInfoKeys.contains(param)) { - vehicleToggle = new LabelControl(title, "", desc); - - } else { - vehicleToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = vehicleToggle; - - if (chryslerKeys.contains(param)) { - chryslerList->addItem(vehicleToggle); - } else if (gmKeys.contains(param)) { - gmList->addItem(vehicleToggle); - } else if (hkgKeys.contains(param)) { - hkgList->addItem(vehicleToggle); - } else if (subaruKeys.contains(param)) { - subaruList->addItem(vehicleToggle); - } else if (toyotaKeys.contains(param)) { - toyotaList->addItem(vehicleToggle); - } else if (vehicleInfoKeys.contains(param)) { - vehicleInfoList->addItem(vehicleToggle); - } else { - settingsList->addItem(vehicleToggle); - - parentKeys.insert(param); - } - - if (ButtonControl *buttonControl = qobject_cast(vehicleToggle)) { - QObject::connect(buttonControl, &ButtonControl::clicked, this, &StarPilotVehiclesPanel::openSubPanel); - } - - QObject::connect(vehicleToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(vehicleToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - static_cast(toggles["LockDoorsTimer"])->setWarning("Warning: openpilot can't detect if keys are still inside the car, so ensure you have a spare key to prevent accidental lockouts!"); - - QSet rebootKeys = {"RemapCancelToDistance"}; - for (const QString &key : rebootKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, [key, this](bool state) { - if (started) { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - } - }); - } - - auto connectPandaFlashToggle = [parent, this](const QString &key, const QString &prompt) { - ParamControl *toggle = static_cast(toggles[key]); - QObject::connect(toggle, &ToggleControl::toggleFlipped, [parent, key, prompt, toggle, this](bool state) { - if (!StarPilotConfirmationDialog::yesorno(prompt, this)) { - params.putBool(key.toStdString(), !state); - toggle->refresh(); - return; - } - - std::thread([parent, this]() { - parent->keepScreenOn = true; - params_memory.putBool("FlashPanda", true); - while (params_memory.getBool("FlashPanda")) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - Hardware::reboot(); - }).detach(); - }); - }; - - connectPandaFlashToggle("IgnoreIgnitionLine", tr("CAN Ignition Only requires a Panda firmware update. Flash the Panda now?")); - connectPandaFlashToggle("HKGRemoteStartBootsComma", tr("EV Remote Climate requires a Panda firmware update. Flash the Panda now?")); - connectPandaFlashToggle("RemoteStartBootsComma", tr("Remote Start requires a Panda firmware update. Flash the Panda now?")); - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(uiState(), &UIState::offroadTransition, [selectMakeButton, selectModelButton, this]() { - std::thread([selectMakeButton, selectModelButton, this]() { - selectMakeButton->setValue(QString::fromStdString(params.get("CarMake", true))); - selectModelButton->setValue(QString::fromStdString(params.get(params.get("CarModelName").empty() ? "CarModel" : "CarModelName", true))); - }).detach(); - }); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [vehiclesLayout, vehiclesPanel, this] { - if (forceOpenDescriptions) { - openDescriptions(forceOpenDescriptions, toggles); - disableOpenpilotLong->showDescription(); - forceFingerprint->showDescription(); - } - vehiclesLayout->setCurrentWidget(vehiclesPanel); - }); - QObject::connect(uiState(), &UIState::uiUpdate, this, &StarPilotVehiclesPanel::updateState); -} - -void StarPilotVehiclesPanel::showEvent(QShowEvent *event) { - if (forceOpenDescriptions) { - disableOpenpilotLong->showDescription(); - forceFingerprint->showDescription(); - } - - QStringList detected; - if (parent->hasPedal) detected << "comma Pedal"; - if (parent->hasSDSU) detected << "SDSU"; - if (parent->hasZSS) detected << "ZSS"; - static_cast(toggles["HardwareDetected"])->setText(detected.isEmpty() ? tr("None") : detected.join(", ")); - - static_cast(toggles["BlindSpotSupport"])->setText(parent->hasBSM ? tr("Yes") : tr("No")); - static_cast(toggles["OpenpilotLongitudinal"])->setText(parent->hasOpenpilotLongitudinal ? tr("Yes") : tr("No")); - static_cast(toggles["PedalSupport"])->setText(parent->canUsePedal ? tr("Yes") : tr("No")); - static_cast(toggles["RadarSupport"])->setText(parent->hasRadar ? tr("Yes") : tr("No")); - static_cast(toggles["SDSUSupport"])->setText(parent->canUseSDSU ? tr("Yes") : tr("No")); - static_cast(toggles["SNGSupport"])->setText(parent->hasSNG ? tr("Yes") : tr("No")); - - updateToggles(); -} - -void StarPilotVehiclesPanel::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - started = s.scene.started; -} - -void StarPilotVehiclesPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (chryslerKeys.contains(key)) { - setVisible &= parent->isJeep; - } else if (gmKeys.contains(key)) { - setVisible &= parent->isGM; - } else if (hkgKeys.contains(key)) { - setVisible &= parent->isHKGCanFd && parent->hasOpenpilotLongitudinal; - } else if (subaruKeys.contains(key)) { - setVisible &= parent->isSubaru; - } else if (toyotaKeys.contains(key)) { - setVisible &= parent->isToyota; - } else if (vehicleInfoKeys.contains(key)) { - setVisible = true; - } - - if (longitudinalKeys.contains(key)) { - setVisible &= parent->hasOpenpilotLongitudinal; - } - - if (key == "SNGHack") { - setVisible &= !parent->hasSNG; - } - - else if (key == "GMPedalLongitudinal") { - setVisible &= parent->hasPedal || (Hardware::PC() && parent->canUsePedal); - } - - else if (key == "GMDashSpoofOffsets") { - setVisible &= parent->hasPedal || (Hardware::PC() && parent->canUsePedal); - } - - else if (key == "RemapCancelToDistance") { - setVisible &= parent->isBolt && (parent->hasPedal || (Hardware::PC() && parent->canUsePedal)); - } - - else if (key == "SubaruSNG") { - setVisible &= parent->hasSNG; - } - - else if (key == "SubaruSNGManualParkingBrake") { - setVisible &= parent->hasSNG && params.getBool("SubaruSNG"); - } - - else if (key == "VoltSNG") { - setVisible &= parent->isVolt && !parent->hasSNG; - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (chryslerKeys.contains(key)) { - toggles["ChryslerToggles"]->setVisible(true); - } else if (gmKeys.contains(key)) { - toggles["GMToggles"]->setVisible(true); - } else if (hkgKeys.contains(key)) { - toggles["HKGToggles"]->setVisible(true); - } else if (subaruKeys.contains(key)) { - toggles["SubaruToggles"]->setVisible(true); - } else if (toyotaKeys.contains(key)) { - toggles["ToyotaToggles"]->setVisible(true); - } else if (vehicleInfoKeys.contains(key)) { - toggles["VehicleInfo"]->setVisible(true); - } - } - } - - disableOpenpilotLong->setVisible(showAllToggles || ((parent->hasOpenpilotLongitudinal || parent->openpilotLongitudinalControlDisabled) && !parent->hasAlphaLongitudinal && parent->tuningLevel >= parent->starpilotToggleLevels["DisableOpenpilotLongitudinal"].toDouble())); - forceFingerprint->setVisible(showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels["ForceFingerprint"].toDouble()); - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/vehicle_settings.h b/starpilot/ui/qt/offroad/vehicle_settings.h deleted file mode 100644 index 3ebb7f802..000000000 --- a/starpilot/ui/qt/offroad/vehicle_settings.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotVehiclesPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotVehiclesPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateState(const UIState &s); - void updateToggles(); - - bool forceOpenDescriptions; - bool started; - - std::map toggles; - - QSet chryslerKeys = {"JeepBrakeHold"}; - QSet gmKeys = {"GMPedalLongitudinal", "GMDashSpoofOffsets", "IgnoreIgnitionLine", "LongPitch", "RemoteStartBootsComma", "RemapCancelToDistance", "VoltSNG"}; - QSet hkgKeys = {"HKGRemoteStartBootsComma"}; - QSet longitudinalKeys = {"GMDashSpoofOffsets", "LongPitch", "RemapCancelToDistance", "SNGHack", "VoltSNG"}; - QSet subaruKeys = {"SubaruSNG", "SubaruSNGManualParkingBrake"}; - QSet toyotaKeys = {"ClusterOffset", "LockDoorsTimer", "SNGHack", "ToyotaDoors"}; - QSet vehicleInfoKeys = {"BlindSpotSupport", "HardwareDetected", "OpenpilotLongitudinal", "PedalSupport", "RadarSupport", "SDSUSupport", "SNGSupport"}; - - QSet parentKeys; - - StarPilotSettingsWindow *parent; - - ParamControl *disableOpenpilotLong; - ParamControl *forceFingerprint; - - Params params; - Params params_memory{"", true}; - - QMap carModels; -}; diff --git a/starpilot/ui/qt/offroad/visual_settings.cc b/starpilot/ui/qt/offroad/visual_settings.cc deleted file mode 100644 index af9b20ab4..000000000 --- a/starpilot/ui/qt/offroad/visual_settings.cc +++ /dev/null @@ -1,353 +0,0 @@ -#include "starpilot/ui/qt/offroad/visual_settings.h" - -StarPilotVisualsPanel::StarPilotVisualsPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - QStackedLayout *visualsLayout = new QStackedLayout(); - addItem(visualsLayout); - - StarPilotListWidget *visualsList = new StarPilotListWidget(this); - - ScrollView *visualsPanel = new ScrollView(visualsList, this); - - visualsLayout->addWidget(visualsPanel); - - StarPilotListWidget *advancedCustomList = new StarPilotListWidget(this); - StarPilotListWidget *customUIList = new StarPilotListWidget(this); - StarPilotListWidget *modelUIList = new StarPilotListWidget(this); - StarPilotListWidget *navigationUIList = new StarPilotListWidget(this); - StarPilotListWidget *qualityOfLifeList = new StarPilotListWidget(this); - - ScrollView *advancedCustomPanel = new ScrollView(advancedCustomList, this); - ScrollView *customUIPanel = new ScrollView(customUIList, this); - ScrollView *modelUIPanel = new ScrollView(modelUIList, this); - ScrollView *navigationUIPanel = new ScrollView(navigationUIList, this); - ScrollView *qualityOfLifePanel = new ScrollView(qualityOfLifeList, this); - - visualsLayout->addWidget(advancedCustomPanel); - visualsLayout->addWidget(customUIPanel); - visualsLayout->addWidget(modelUIPanel); - visualsLayout->addWidget(navigationUIPanel); - visualsLayout->addWidget(qualityOfLifePanel); - - const std::vector> visualToggles { - {"AdvancedCustomUI", tr("Advanced UI Controls"), tr("Advanced visual changes to fine-tune how the driving screen looks."), "../../starpilot/assets/toggle_icons/icon_advanced_device.png"}, - {"HideSpeed", tr("Hide Current Speed"), tr("Hide the current speed from the driving screen."), ""}, - {"HideLeadMarker", tr("Hide Lead Marker"), tr("Hide the lead-vehicle marker from the driving screen."), ""}, - {"HideMaxSpeed", tr("Hide Max Speed"), tr("Hide the max speed from the driving screen."), ""}, - {"HideAlerts", tr("Hide Non-Critical Alerts"), tr("Hide non-critical alerts from the driving screen."), ""}, - {"HideChangingLanesBanner", tr("Hide Changing Lanes Banner"), tr("Hide the 'Changing Lanes' banner from the driving screen."), ""}, - {"HideDistanceProfileBanner", tr("Hide Distance Profile Banner"), tr("Hide the driving personality banner when changing distance profiles."), ""}, - {"HideDMIcon", tr("Hide Driver Monitoring Icon"), tr("Hide the driver monitoring icon from the driving screen."), ""}, - {"HideTurningBanner", tr("Hide Turning Banner"), tr("Hide the 'Turning Left/Right' banner from the driving screen."), ""}, - {"HideSpeedLimit", tr("Hide Speed Limits"), tr("Hide posted speed limits from the driving screen."), ""}, - {"HideSteeringWheel", tr("Hide Steering Wheel"), tr("Hide the steering-wheel button from the top-right of the driving screen."), ""}, - {"WheelSpeed", tr("Use Wheel Speed"), tr("Use the vehicle's wheel speed instead of the cluster speed. This is purely a visual change and doesn't impact how openpilot drives!"), ""}, - - {"CustomUI", tr("Driving Screen Widgets"), tr("Custom StarPilot widgets for the driving screen."), "../assets/icons/calibration.png"}, - {"AccelerationPath", tr("Acceleration Path"), tr("Color the driving path by planned acceleration and braking."), ""}, - {"AdjacentPath", tr("Adjacent Lanes"), tr("Show the driving paths for the left and right lanes."), ""}, - {"BlindSpotPath", tr("Blind Spot Path"), tr("Show a red path when a vehicle is in that lane's blind spot."), ""}, - {"Compass", tr("Compass"), tr("Show the current driving direction with a simple on-screen compass."), ""}, - {"OnroadDistanceButton", tr("Driving Personality Button"), tr("Control and view the current driving personality via a driving screen widget."), ""}, - {"PedalsOnUI", tr("Gas / Brake Pedal Indicators"), tr("On-screen gas and brake indicators.

Dynamic: Opacity changes according to how much openpilot is accelerating or braking
Static: Full when active, dim when not"), ""}, - {"RotatingWheel", tr("Rotating Steering Wheel"), tr("Rotate the driving screen wheel with the physical steering wheel."), ""}, - - {"ModelUI", tr("Model UI"), tr("Model visualizations for the driving path, lane lines, path edges, and road edges."), "../../starpilot/assets/toggle_icons/icon_road.png"}, - {"DynamicPathWidth", tr("Dynamic Path Width"), tr("Change the path width based on engagement.

Fully Engaged: 100%
Always On Lateral: 75%
Disengaged: 50%"), ""}, - {"LaneLinesWidth", tr("Lane Lines Width"), tr("Set the lane-line thickness.

Default matches the MUTCD lane-line width standard of 4 inches."), ""}, - {"PathEdgeWidth", tr("Path Edges Width"), tr("Set the driving-path edge width that represents different driving modes and statuses.

Default is 20% of the total path width.

Color Guide:

- Light Blue: Always On Lateral
- Green: Default
- Orange: Experimental Mode
- Red: Traffic Mode
- Yellow: Conditional Experimental Mode overridden"), ""}, - {"PathWidth", tr("Path Width"), tr("Set the driving-path width.

Default (6.1 feet) matches the width of a 2019 Lexus ES 350."), ""}, - {"RoadEdgesWidth", tr("Road Edges Width"), tr("Set the road-edge thickness.

Default matches half of the MUTCD lane-line width standard of 4 inches."), ""}, - - {"NavigationUI", tr("Navigation Widgets"), tr("Speed limits, and other navigation widgets."), "../../starpilot/assets/toggle_icons/icon_map.png"}, - {"ClearNavOnOffroad", tr("Clear Route When Offroad"), tr("Clear the active navigation destination when the device goes offroad."), ""}, - {"RoadNameUI", tr("Road Name"), tr("Display the road name at the bottom of the driving screen using data from \"OpenStreetMap (OSM)\"."), ""}, - {"ShowSpeedLimits", tr("Show Speed Limits"), tr("Show speed limits in the top-left corner of the driving screen. Uses data from the car's dashboard (if supported) and \"OpenStreetMap (OSM)\"."), ""}, - {"SLCMapboxFiller", tr("Show Speed Limits from Mapbox"), tr("Use Mapbox speed-limit data when no other source is available."), ""}, - {"UseVienna", tr("Use Vienna-Style Speed Signs"), tr("Show Vienna-style (EU) speed-limit signs instead of MUTCD (US)."), ""}, - - {"QOLVisuals", tr("Quality of Life"), tr("Miscellaneous visual changes to fine-tune how the driving screen looks."), "../../starpilot/assets/toggle_icons/icon_quality_of_life.png"}, - {"CameraView", tr("Camera View"), tr("Select the active camera view. This is purely a visual change and doesn't impact how openpilot drives!"), ""}, - {"DriverCamera", tr("Show Driver Camera When In Reverse"), tr("Show the driver camera feed when the vehicle is in reverse."), ""}, - {"StoppedTimer", tr("Stopped Timer"), tr("Show a timer when stopped in place of the current speed to indicate how long the vehicle has been stopped."), ""}, - {"StockConfidenceBallWidget", tr("Stock Confidence Ball Widget"), tr("Use the original moving confidence ball on the small comma 4 UI instead of the fixed confidence, CEM/CCM, and personality sidebar."), ""}, - - {"DisableWideRoad", tr("Disable Wide Road Camera"), QString("%1

%2").arg(tr("Only enable this if the wide camera is broken or for development!")).arg(tr("Disabling the wide camera may degrade driving performance and cause instability.

Requires a reboot to take effect.")), "../../starpilot/assets/toggle_icons/icon_advanced_device.png"} - }; - - for (const auto &[param, title, desc, icon] : visualToggles) { - AbstractControl *visualToggle; - - if (param == "AdvancedCustomUI") { - StarPilotManageControl *advancedCustomUIToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(advancedCustomUIToggle, &StarPilotManageControl::manageButtonClicked, [visualsLayout, advancedCustomPanel]() { - visualsLayout->setCurrentWidget(advancedCustomPanel); - }); - visualToggle = advancedCustomUIToggle; - - } else if (param == "CustomUI") { - StarPilotManageControl *customUIToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(customUIToggle, &StarPilotManageControl::manageButtonClicked, [visualsLayout, customUIPanel]() { - visualsLayout->setCurrentWidget(customUIPanel); - }); - visualToggle = customUIToggle; - } else if (param == "PedalsOnUI") { - std::vector pedalsToggles{"DynamicPedalsOnUI", "StaticPedalsOnUI"}; - std::vector pedalsToggleNames{tr("Dynamic"), tr("Static")}; - StarPilotButtonToggleControl *pedalsToggle = new StarPilotButtonToggleControl(param, title, desc, icon, pedalsToggles, pedalsToggleNames, true); - QObject::connect(pedalsToggle, &StarPilotButtonToggleControl::buttonClicked, [this](int id) { - if (id == 0) { - params.putBool("StaticPedalsOnUI", false); - } else if (id == 1) { - params.putBool("DynamicPedalsOnUI", false); - } - }); - visualToggle = pedalsToggle; - - } else if (param == "ModelUI") { - StarPilotManageControl *modelUIToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(modelUIToggle, &StarPilotManageControl::manageButtonClicked, [visualsLayout, modelUIPanel]() { - visualsLayout->setCurrentWidget(modelUIPanel); - }); - visualToggle = modelUIToggle; - } else if (param == "LaneLinesWidth" || param == "RoadEdgesWidth") { - visualToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 24, tr(" inches")); - } else if (param == "PathEdgeWidth") { - std::map pathEdgeLabels; - for (int i = 0; i <= 100; ++i) { - pathEdgeLabels[i] = i == 0 ? tr("Off") : QString::number(i) + "%"; - } - visualToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 100, QString(), pathEdgeLabels); - } else if (param == "PathWidth") { - visualToggle = new StarPilotParamValueControl(param, title, desc, icon, 0, 10, tr(" feet"), std::map(), 0.1); - - } else if (param == "NavigationUI") { - StarPilotManageControl *navigationUIToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(navigationUIToggle, &StarPilotManageControl::manageButtonClicked, [visualsLayout, navigationUIPanel]() { - visualsLayout->setCurrentWidget(navigationUIPanel); - }); - visualToggle = navigationUIToggle; - - } else if (param == "QOLVisuals") { - StarPilotManageControl *qolToggle = new StarPilotManageControl(param, title, desc, icon); - QObject::connect(qolToggle, &StarPilotManageControl::manageButtonClicked, [visualsLayout, qualityOfLifePanel]() { - visualsLayout->setCurrentWidget(qualityOfLifePanel); - }); - visualToggle = qolToggle; - } else if (param == "CameraView") { - std::vector cameraOptions{tr("Auto"), tr("Driver"), tr("Standard"), tr("Wide"), tr("None")}; - ButtonParamControl *cameraSelection = new ButtonParamControl(param, title, desc, icon, cameraOptions); - visualToggle = cameraSelection; - - } else { - visualToggle = new ParamControl(param, title, desc, icon); - } - - toggles[param] = visualToggle; - - if (advancedCustomOnroadUIKeys.contains(param)) { - advancedCustomList->addItem(visualToggle); - } else if (customOnroadUIKeys.contains(param)) { - customUIList->addItem(visualToggle); - } else if (modelUIKeys.contains(param)) { - modelUIList->addItem(visualToggle); - } else if (navigationUIKeys.contains(param)) { - navigationUIList->addItem(visualToggle); - } else if (qualityOfLifeKeys.contains(param)) { - qualityOfLifeList->addItem(visualToggle); - } else { - visualsList->addItem(visualToggle); - - parentKeys.insert(param); - } - - if (StarPilotManageControl *frogPilotManageToggle = qobject_cast(visualToggle)) { - QObject::connect(frogPilotManageToggle, &StarPilotManageControl::manageButtonClicked, [this]() { - emit openSubPanel(); - openDescriptions(forceOpenDescriptions, toggles); - }); - } - - QObject::connect(visualToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(visualToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - if (ToggleControl *toggle = qobject_cast(visualToggle)) { - QObject::connect(toggle, &ToggleControl::toggleFlipped, this, []() { - updateStarPilotToggles(); - }); - } - } - - QSet forceUpdateKeys = {"HideLeadMarker", "ShowSpeedLimits"}; - for (const QString &key : forceUpdateKeys) { - QObject::connect(static_cast(toggles[key]), &ToggleControl::toggleFlipped, this, &StarPilotVisualsPanel::updateToggles); - } - - static_cast(toggles["DisableWideRoad"])->setConfirmation(true, false); - QObject::connect(static_cast(toggles["DisableWideRoad"]), &ToggleControl::toggleFlipped, [this](bool state) { - if (StarPilotConfirmationDialog::toggleReboot(this)) { - Hardware::reboot(); - } - }); - - openDescriptions(forceOpenDescriptions, toggles); - - QObject::connect(parent, &StarPilotSettingsWindow::closeSubPanel, [visualsLayout, visualsPanel, this] { - openDescriptions(forceOpenDescriptions, toggles); - visualsLayout->setCurrentWidget(visualsPanel); - }); - QObject::connect(parent, &StarPilotSettingsWindow::closeSubSubPanel, [this]() { - openDescriptions(forceOpenDescriptions, toggles); - }); - QObject::connect(parent, &StarPilotSettingsWindow::updateMetric, this, &StarPilotVisualsPanel::updateMetric); -} - -void StarPilotVisualsPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void StarPilotVisualsPanel::updateMetric(bool metric, bool bootRun) { - static bool previousMetric; - if (metric != previousMetric && !bootRun) { - double distanceConversion = metric ? FOOT_TO_METER : METER_TO_FOOT; - double smallDistanceConversion = metric ? INCH_TO_CM : CM_TO_INCH; - - params.putIntNonBlocking("LaneLinesWidth", params.getInt("LaneLinesWidth") * smallDistanceConversion); - params.putIntNonBlocking("RoadEdgesWidth", params.getInt("RoadEdgesWidth") * smallDistanceConversion); - - params.putFloatNonBlocking("PathWidth", params.getFloat("PathWidth") * distanceConversion); - } - previousMetric = metric; - - static std::map imperialDistanceLabels; - static std::map imperialSmallDistanceLabels; - static std::map metricDistanceLabels; - static std::map metricSmallDistanceLabels; - - static bool labelsInitialized = false; - if (!labelsInitialized) { - for (int i = 0; i <= 10; ++i) { - imperialDistanceLabels[i] = i == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" foot") : QString::number(i) + tr(" feet"); - } - - for (int i = 0; i <= 24; ++i) { - imperialSmallDistanceLabels[i] = i == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" inch") : QString::number(i) + tr(" inches"); - } - - for (float i = 0.0f; i <= 3.0f; i += 0.1f) { - metricDistanceLabels[i] = i == 0.0f ? tr("Off") : i == 1.0 ? QString::number(i) + tr(" meter") : QString::number(i, 'f', 1) + tr(" meters"); - } - - for (int i = 0; i <= 60; ++i) { - metricSmallDistanceLabels[i] = i == 0 ? tr("Off") : i == 1 ? QString::number(i) + tr(" centimeter") : QString::number(i) + tr(" centimeters"); - } - - labelsInitialized = true; - } - - StarPilotParamValueControl *laneLinesWidthToggle = static_cast(toggles["LaneLinesWidth"]); - StarPilotParamValueControl *pathWidthToggle = static_cast(toggles["PathWidth"]); - StarPilotParamValueControl *roadEdgesWidthToggle = static_cast(toggles["RoadEdgesWidth"]); - - if (metric) { - laneLinesWidthToggle->setDescription(tr("Set the lane-line thickness.

Default matches the MUTCD lane-line width standard of 10 centimeters.")); - pathWidthToggle->setDescription(tr("Set the driving-path width.

Default (1.9 meters) matches the width of a 2019 Lexus ES 350.")); - roadEdgesWidthToggle->setDescription(tr("Set the road-edge thickness.

Default matches half of the MUTCD lane-line width standard of 10 centimeters.")); - - laneLinesWidthToggle->updateControl(0, 60, metricSmallDistanceLabels); - roadEdgesWidthToggle->updateControl(0, 60, metricSmallDistanceLabels); - - pathWidthToggle->updateControl(0, 3, metricDistanceLabels); - } else { - laneLinesWidthToggle->setDescription(tr("Set the lane-line thickness.

Default matches the MUTCD lane-line width standard of 4 inches.")); - pathWidthToggle->setDescription(tr("Set the driving-path width.

Default (6.1 feet) matches the width of a 2019 Lexus ES 350.")); - roadEdgesWidthToggle->setDescription(tr("Set the road-edge thickness.

Default matches half of the MUTCD lane-line width standard of 4 inches.")); - - laneLinesWidthToggle->updateControl(0, 24, imperialSmallDistanceLabels); - roadEdgesWidthToggle->updateControl(0, 24, imperialSmallDistanceLabels); - - pathWidthToggle->updateControl(0, 10, imperialDistanceLabels); - } -} - -void StarPilotVisualsPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - toggle->setVisible(showAllToggles); - } - } - - for (auto &[key, toggle] : toggles) { - if (parentKeys.contains(key)) { - continue; - } - - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles) { - if (key == "AccelerationPath") { - setVisible &= parent->hasOpenpilotLongitudinal; - } - - else if (key == "BlindSpotPath") { - setVisible &= parent->hasBSM; - } - - else if (key == "HideLeadMarker") { - setVisible &= parent->hasOpenpilotLongitudinal; - } - - else if (key == "HideSpeedLimit") { - setVisible &= parent->hasOpenpilotLongitudinal && params.getBool("SpeedLimitController"); - } - - else if (key == "OnroadDistanceButton") { - setVisible &= parent->hasOpenpilotLongitudinal; - } - - else if (key == "PedalsOnUI") { - setVisible &= parent->hasOpenpilotLongitudinal; - } - - else if (key == "ShowSpeedLimits") { - setVisible &= !params.getBool("SpeedLimitController") || !parent->hasOpenpilotLongitudinal; - } - - else if (key == "SLCMapboxFiller") { - setVisible &= params.getBool("ShowSpeedLimits"); - setVisible &= !params.getBool("SpeedLimitController") || !parent->hasOpenpilotLongitudinal; - setVisible &= !params.get("MapboxSecretKey").empty(); - } - - else if (key == "UseVienna") { - setVisible &= params.getBool("ShowSpeedLimits") || params.getBool("SpeedLimitController"); - } - } - - toggle->setVisible(setVisible); - - if (setVisible) { - if (advancedCustomOnroadUIKeys.contains(key)) { - toggles["AdvancedCustomUI"]->setVisible(true); - } else if (customOnroadUIKeys.contains(key)) { - toggles["CustomUI"]->setVisible(true); - } else if (modelUIKeys.contains(key)) { - toggles["ModelUI"]->setVisible(true); - } else if (navigationUIKeys.contains(key)) { - toggles["NavigationUI"]->setVisible(true); - } else if (qualityOfLifeKeys.contains(key)) { - toggles["QOLVisuals"]->setVisible(true); - } - } - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/visual_settings.h b/starpilot/ui/qt/offroad/visual_settings.h deleted file mode 100644 index 615b05bb3..000000000 --- a/starpilot/ui/qt/offroad/visual_settings.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotVisualsPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotVisualsPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -signals: - void openSubPanel(); - void openSubSubPanel(); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateMetric(bool metric, bool bootRun); - void updateToggles(); - - bool forceOpenDescriptions; - - std::map toggles; - - QSet advancedCustomOnroadUIKeys = {"HideAlerts", "HideChangingLanesBanner", "HideDistanceProfileBanner", "HideDMIcon", "HideLeadMarker", "HideMaxSpeed", "HideSpeed", "HideSpeedLimit", "HideSteeringWheel", "HideTurningBanner", "WheelSpeed"}; - QSet customOnroadUIKeys = {"AccelerationPath", "AdjacentPath", "BlindSpotPath", "Compass", "OnroadDistanceButton", "PedalsOnUI", "RotatingWheel"}; - QSet modelUIKeys = {"DynamicPathWidth", "LaneLinesWidth", "PathEdgeWidth", "PathWidth", "RoadEdgesWidth"}; - QSet navigationUIKeys = {"RoadNameUI", "ShowSpeedLimits", "SLCMapboxFiller", "UseVienna"}; - QSet qualityOfLifeKeys = {"CameraView", "DriverCamera", "StoppedTimer", "StockConfidenceBallWidget"}; - - QSet parentKeys; - - StarPilotSettingsWindow *parent; - - Params params; -}; diff --git a/starpilot/ui/qt/offroad/wheel_settings.cc b/starpilot/ui/qt/offroad/wheel_settings.cc deleted file mode 100644 index 4cd05de82..000000000 --- a/starpilot/ui/qt/offroad/wheel_settings.cc +++ /dev/null @@ -1,188 +0,0 @@ -#include "starpilot/ui/qt/offroad/wheel_settings.h" - -namespace { - -QMap getWheelFunctionsMap() { - return { - {0, QObject::tr("No Action")}, - {3, QObject::tr("Pause Steering")}, - {7, QObject::tr("Toggle \"Switchback Mode\" On/Off")}, - {8, QObject::tr("Create Bookmark")}, - {11, QObject::tr("Favorite #1")}, - {12, QObject::tr("Favorite #2")}, - {13, QObject::tr("Favorite #3")}, - }; -} - -QMap getLongitudinalWheelFunctionsMap() { - return { - {1, QObject::tr("Change \"Personality Profile\"")}, - {2, QObject::tr("Force openpilot to Coast")}, - {4, QObject::tr("Pause Acceleration/Braking")}, - {5, QObject::tr("Toggle \"Experimental Mode\" On/Off")}, - {6, QObject::tr("Toggle \"Traffic Mode\" On/Off")}, - }; -} - -QMap getMergedWheelFunctionsMap() { - QMap functionsMap = getWheelFunctionsMap(); - const QMap longitudinalFunctionsMap = getLongitudinalWheelFunctionsMap(); - for (auto it = longitudinalFunctionsMap.constBegin(); it != longitudinalFunctionsMap.constEnd(); ++it) { - functionsMap[it.key()] = it.value(); - } - return functionsMap; -} - -QMap getMainCruiseFunctionsMap() { - return { - {0, QObject::tr("No Action")}, - {9, QObject::tr("Toggle Always On Lateral")}, - {10, QObject::tr("Adopt Current Speed Limit")}, - {11, QObject::tr("Favorite #1")}, - {12, QObject::tr("Favorite #2")}, - {13, QObject::tr("Favorite #3")}, - }; -} - -QString getWheelFunctionLabel(Params ¶ms, const QString &key) { - QMap functionsMap; - if (key == "MainCruiseButtonControl") { - functionsMap = getMainCruiseFunctionsMap(); - } else { - functionsMap = getMergedWheelFunctionsMap(); - if (key == "LKASButtonControl") { - functionsMap[9] = QObject::tr("Toggle Always On Lateral"); - } - } - return functionsMap.value(params.getInt(key.toStdString()), QObject::tr("No Action")); -} - -} // namespace - -StarPilotWheelPanel::StarPilotWheelPanel(StarPilotSettingsWindow *parent, bool forceOpen) : StarPilotListWidget(parent), parent(parent) { - forceOpenDescriptions = forceOpen; - - ParamControl *nostalgiaModeToggle = new ParamControl( - "NostalgiaMode", - tr("Nostalgia Mode"), - tr("Use the left paddle to pause openpilot acceleration and braking while Always On Lateral stays active on supported Hyundai CAN-FD cars."), - "../../starpilot/assets/toggle_icons/icon_mute.png" - ); - toggles["NostalgiaMode"] = nostalgiaModeToggle; - addItem(nostalgiaModeToggle); - QObject::connect(nostalgiaModeToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(nostalgiaModeToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - - const std::vector> wheelToggles { - {"CancelButtonControl", tr("Cancel Button"), tr("Action performed when the remapped \"Cancel\" button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"DistanceButtonControl", tr("Distance Button"), tr("Action performed when the \"Distance\" button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"LongCancelButtonControl", tr("Cancel Button (Long Press)"), tr("Action performed when the remapped \"Cancel\" button is pressed for more than 0.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"LongDistanceButtonControl", tr("Distance Button (Long Press)"), tr("Action performed when the \"Distance\" button is pressed for more than 0.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"VeryLongCancelButtonControl", tr("Cancel Button (Very Long Press)"), tr("Action performed when the remapped \"Cancel\" button is pressed for more than 2.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"VeryLongDistanceButtonControl", tr("Distance Button (Very Long Press)"), tr("Action performed when the \"Distance\" button is pressed for more than 2.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"LKASButtonControl", tr("LKAS Button"), tr("Action performed when the \"LKAS\" button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"MainCruiseButtonControl", tr("CC Main Button"), tr("Action performed when the cruise control main button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"ModeButtonControl", tr("Mode Button"), tr("Action performed when the \"Mode\" button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"LongModeButtonControl", tr("Mode Button (Long Press)"), tr("Action performed when the \"Mode\" button is pressed for more than 0.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"VeryLongModeButtonControl", tr("Mode Button (Very Long Press)"), tr("Action performed when the \"Mode\" button is pressed for more than 2.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"StarButtonControl", tr("Star Button"), tr("Action performed when the \"Star\" button is pressed."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"LongStarButtonControl", tr("Star Button (Long Press)"), tr("Action performed when the \"Star\" button is pressed for more than 0.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"}, - {"VeryLongStarButtonControl", tr("Star Button (Very Long Press)"), tr("Action performed when the \"Star\" button is pressed for more than 2.5 seconds."), "../../starpilot/assets/toggle_icons/icon_mute.png"} - }; - - for (const auto &[param, title, desc, icon] : wheelToggles) { - ButtonControl *wheelToggle = new ButtonControl(title, tr("SELECT"), desc); - QObject::connect(wheelToggle, &ButtonControl::clicked, [key = param, parent, wheelToggle, this]() { - QMap functionsMap; - if (key == "MainCruiseButtonControl") { - functionsMap = getMainCruiseFunctionsMap(); - } else { - functionsMap = getWheelFunctionsMap(); - if (parent->hasOpenpilotLongitudinal) { - const QMap longitudinalFunctionsMap = getLongitudinalWheelFunctionsMap(); - for (auto it = longitudinalFunctionsMap.constBegin(); it != longitudinalFunctionsMap.constEnd(); ++it) { - functionsMap[it.key()] = it.value(); - } - } - if (key == "LKASButtonControl") { - functionsMap[9] = tr("Toggle Always On Lateral"); - } - } - - QString selection = MultiOptionDialog::getSelection(tr("Select a function to assign to this button"), functionsMap.values(), functionsMap[params.getInt(key.toStdString())], this); - if (!selection.isEmpty()) { - params.putInt(key.toStdString(), functionsMap.key(selection)); - wheelToggle->setValue(selection); - updateStarPilotToggles(); - } - }); - wheelToggle->setValue(getWheelFunctionLabel(params, param)); - - toggles[param] = wheelToggle; - - addItem(wheelToggle); - - QObject::connect(wheelToggle, &AbstractControl::hideDescriptionEvent, [this]() { - update(); - }); - QObject::connect(wheelToggle, &AbstractControl::showDescriptionEvent, [this]() { - update(); - }); - } - - openDescriptions(forceOpenDescriptions, toggles); -} - -void StarPilotWheelPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void StarPilotWheelPanel::updateToggles() { - const bool showAllToggles = parent->showAllTogglesEnabled(); - - for (auto &[key, toggle] : toggles) { - bool setVisible = showAllToggles || parent->tuningLevel >= parent->starpilotToggleLevels[key].toDouble(); - - if (!showAllToggles && key == "LKASButtonControl") { - setVisible &= !parent->isSubaru; - } - - if (!showAllToggles && ( - key == "CancelButtonControl" || - key == "LongCancelButtonControl" || - key == "VeryLongCancelButtonControl")) { - setVisible &= parent->isBolt; - setVisible &= parent->hasPedal; - setVisible &= params.getBool("RemapCancelToDistance"); - } - - if (!showAllToggles && key == "NostalgiaMode") { - setVisible &= parent->isHKGCanFd; - setVisible &= parent->hasOpenpilotLongitudinal; - } - - if (!showAllToggles && ( - key == "ModeButtonControl" || - key == "LongModeButtonControl" || - key == "VeryLongModeButtonControl" || - key == "StarButtonControl" || - key == "LongStarButtonControl" || - key == "VeryLongStarButtonControl")) { - setVisible &= parent->hasModeStarButtons; - } - - if (ButtonControl *wheelToggle = qobject_cast(toggle)) { - wheelToggle->setValue(getWheelFunctionLabel(params, key)); - } - - toggle->setVisible(setVisible); - } - - openDescriptions(forceOpenDescriptions, toggles); - - update(); -} diff --git a/starpilot/ui/qt/offroad/wheel_settings.h b/starpilot/ui/qt/offroad/wheel_settings.h deleted file mode 100644 index a8995bcd1..000000000 --- a/starpilot/ui/qt/offroad/wheel_settings.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "starpilot/ui/qt/offroad/starpilot_settings.h" - -class StarPilotWheelPanel : public StarPilotListWidget { - Q_OBJECT - -public: - explicit StarPilotWheelPanel(StarPilotSettingsWindow *parent, bool forceOpen = false); - -protected: - void showEvent(QShowEvent *event) override; - -private: - void updateToggles(); - - bool forceOpenDescriptions; - - std::map toggles; - - StarPilotSettingsWindow *parent; - - Params params; -}; diff --git a/starpilot/ui/qt/onroad/moc_starpilot_annotated_camera.cc b/starpilot/ui/qt/onroad/moc_starpilot_annotated_camera.cc deleted file mode 100644 index f48e05851..000000000 --- a/starpilot/ui/qt/onroad/moc_starpilot_annotated_camera.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_annotated_camera.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_annotated_camera.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_annotated_camera.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotAnnotatedCameraWidget_t { - QByteArrayData data[1]; - char stringdata0[31]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotAnnotatedCameraWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotAnnotatedCameraWidget_t qt_meta_stringdata_StarPilotAnnotatedCameraWidget = { - { -QT_MOC_LITERAL(0, 0, 30) // "StarPilotAnnotatedCameraWidget" - - }, - "StarPilotAnnotatedCameraWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotAnnotatedCameraWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotAnnotatedCameraWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotAnnotatedCameraWidget::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_StarPilotAnnotatedCameraWidget.data, - qt_meta_data_StarPilotAnnotatedCameraWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotAnnotatedCameraWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotAnnotatedCameraWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotAnnotatedCameraWidget.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int StarPilotAnnotatedCameraWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/onroad/moc_starpilot_buttons.cc b/starpilot/ui/qt/onroad/moc_starpilot_buttons.cc deleted file mode 100644 index 1ef1dcc5a..000000000 --- a/starpilot/ui/qt/onroad/moc_starpilot_buttons.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_buttons.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_buttons.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_buttons.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DrivingPersonalityButton_t { - QByteArrayData data[1]; - char stringdata0[25]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DrivingPersonalityButton_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DrivingPersonalityButton_t qt_meta_stringdata_DrivingPersonalityButton = { - { -QT_MOC_LITERAL(0, 0, 24) // "DrivingPersonalityButton" - - }, - "DrivingPersonalityButton" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DrivingPersonalityButton[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void DrivingPersonalityButton::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject DrivingPersonalityButton::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_DrivingPersonalityButton.data, - qt_meta_data_DrivingPersonalityButton, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DrivingPersonalityButton::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DrivingPersonalityButton::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DrivingPersonalityButton.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int DrivingPersonalityButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/onroad/moc_starpilot_onroad.cc b/starpilot/ui/qt/onroad/moc_starpilot_onroad.cc deleted file mode 100644 index e37db6a17..000000000 --- a/starpilot/ui/qt/onroad/moc_starpilot_onroad.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_onroad.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_onroad.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_onroad.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotOnroadWindow_t { - QByteArrayData data[1]; - char stringdata0[22]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotOnroadWindow_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotOnroadWindow_t qt_meta_stringdata_StarPilotOnroadWindow = { - { -QT_MOC_LITERAL(0, 0, 21) // "StarPilotOnroadWindow" - - }, - "StarPilotOnroadWindow" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotOnroadWindow[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotOnroadWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotOnroadWindow::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_StarPilotOnroadWindow.data, - qt_meta_data_StarPilotOnroadWindow, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotOnroadWindow::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotOnroadWindow::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotOnroadWindow.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int StarPilotOnroadWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/onroad/starpilot_annotated_camera.cc b/starpilot/ui/qt/onroad/starpilot_annotated_camera.cc deleted file mode 100644 index 9aaf00ae9..000000000 --- a/starpilot/ui/qt/onroad/starpilot_annotated_camera.cc +++ /dev/null @@ -1,1297 +0,0 @@ -#include - -#include "starpilot/ui/qt/onroad/starpilot_annotated_camera.h" - -StarPilotAnnotatedCameraWidget::StarPilotAnnotatedCameraWidget(QWidget *parent) : QWidget(parent) { - animationTimer = new QTimer(this); - - QSize iconSize(img_size / 4, img_size / 4); - - brakePedalImg = loadPixmap("../../starpilot/assets/other_images/brake_pedal.png", {btn_size, btn_size}); - curveSpeedIcon = loadPixmap("../../starpilot/assets/other_images/curve_speed.png", {btn_size, btn_size}); - curveSpeedIconFlipped = curveSpeedIcon.transformed(QTransform().scale(-1, 1)); - dashboardIcon = loadPixmap("../../starpilot/assets/other_images/dashboard_icon.png", {btn_size / 2, btn_size / 2}).scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - gasPedalImg = loadPixmap("../../starpilot/assets/other_images/gas_pedal.png", {btn_size, btn_size}); - mapboxIcon = loadPixmap("../../starpilot/assets/other_images/mapbox_icon.png", {btn_size / 2, btn_size / 2}).scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - mapDataIcon = loadPixmap("../../starpilot/assets/other_images/offline_maps_icon.png", {btn_size / 2, btn_size / 2}).scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - nextMapsIcon = loadPixmap("../../starpilot/assets/other_images/next_maps_icon.png", {btn_size / 2, btn_size / 2}).scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - pausedIcon = loadPixmap("../../starpilot/assets/other_images/paused_icon.png", {widget_size, widget_size}); - speedIcon = loadPixmap("../../starpilot/assets/other_images/speed_icon.png", {widget_size, widget_size}); - forceStopDashImg = loadPixmap("../../starpilot/assets/other_images/force_stop_dash.png", {btn_size, btn_size}); - forceStopImg = loadPixmap("../../starpilot/assets/other_images/force_stop.png", {btn_size, btn_size}); - stopSignImg = loadPixmap("../../starpilot/assets/other_images/stop_sign.png", {btn_size, btn_size}); - turnIcon = loadPixmap("../../starpilot/assets/other_images/turn_icon.png", {widget_size, widget_size}); - visionIcon = loadPixmap("../../starpilot/assets/other_images/speed_icon.png", {btn_size / 2, btn_size / 2}).scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - loadGif("../../starpilot/assets/other_images/curve_icon.gif", cemCurveIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/lead_icon.gif", cemLeadIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/speed_icon.gif", cemSpeedIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/light_icon.gif", cemStopIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/turn_icon.gif", cemTurnIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/chill_mode_icon.gif", chillModeIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/experimental_mode_icon.gif", experimentalModeIcon, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/weather_clear_day.gif", weatherClearDay, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/weather_clear_night.gif", weatherClearNight, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/weather_low_visibility.gif", weatherLowVisibility, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/weather_rain.gif", weatherRain, QSize(widget_size, widget_size), this); - loadGif("../../starpilot/assets/other_images/weather_snow.gif", weatherSnow, QSize(widget_size, widget_size), this); - - QObject::connect(animationTimer, &QTimer::timeout, [this] { - animationFrameIndex = (animationFrameIndex + 1) % totalFrames; - }); - QObject::connect(starpilotUIState(), &StarPilotUIState::themeUpdated, this, &StarPilotAnnotatedCameraWidget::updateSignals); - QObject::connect(uiState(), &UIState::offroadTransition, [this] { - standstillTimer.invalidate(); - - QJsonObject stats = QJsonDocument::fromJson(QString::fromStdString(params.get("StarPilotStats")).toUtf8()).object(); - stats["FrogHops"] = stats.value("FrogHops").toInt(0) + frogHopCount; - params.putNonBlocking("StarPilotStats", QJsonDocument(stats).toJson(QJsonDocument::Compact).toStdString()); - - frogHopCount = 0; - }); -} - -void StarPilotAnnotatedCameraWidget::showEvent(QShowEvent *event) { - updateSignals(); -} - -void StarPilotAnnotatedCameraWidget::updateSignals() { - QVector().swap(blindspotImages); - QVector().swap(blindspotImagesRight); - QVector().swap(signalImages); - QVector().swap(signalImagesRight); - - bool isGif = false; - - QFileInfoList files = QDir("../../starpilot/assets/active_theme/signals/").entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); - for (const QFileInfo &fileInfo : files) { - QString fileName = fileInfo.fileName(); - QString filePath = fileInfo.absoluteFilePath(); - - if (fileName.endsWith(".gif", Qt::CaseInsensitive)) { - isGif = true; - - QMovie movie(filePath); - movie.setCacheMode(QMovie::CacheNone); - movie.start(); - - int frameCount = movie.frameCount(); - signalImages.reserve(frameCount); - signalImagesRight.reserve(frameCount); - - for (int i = 0; i < frameCount; ++i) { - movie.jumpToFrame(i); - - QPixmap frame = movie.currentPixmap(); - signalImages.append(frame); - signalImagesRight.append(frame.transformed(QTransform().scale(-1, 1))); - } - - movie.stop(); - } else if (fileName.endsWith(".png", Qt::CaseInsensitive)) { - QPixmap img(filePath); - if (fileName.contains("blindspot", Qt::CaseInsensitive)) { - blindspotImages.append(img); - blindspotImagesRight.append(img.transformed(QTransform().scale(-1, 1))); - } else { - signalImages.append(img); - signalImagesRight.append(img.transformed(QTransform().scale(-1, 1))); - } - } else { - QStringList parts = fileName.split('_'); - if (parts.size() == 2) { - signalStyle = parts[0]; - signalAnimationLength = parts[1].toInt(); - } - } - } - - if (!signalImages.isEmpty()) { - QPixmap &firstImage = signalImages.front(); - signalHeight = firstImage.height(); - signalWidth = firstImage.width(); - totalFrames = signalImages.size(); - - if (isGif && signalStyle == "traditional") { - signalMovement = (width() + signalWidth * 2) / totalFrames; - signalStyle = "traditional_gif"; - } else { - signalMovement = 0; - } - } else { - signalAnimationLength = 0; - signalHeight = 0; - signalMovement = 0; - signalWidth = 0; - totalFrames = 0; - - signalStyle = "None"; - } -} - -void StarPilotAnnotatedCameraWidget::updateState(const UIState &s, const StarPilotUIState &fs) { - const UIScene &scene = s.scene; - - const SubMaster &sm = *(s.sm); - const SubMaster &fpsm = *(fs.sm); - - const cereal::CarState::Reader &carState = sm["carState"].getCarState(); - const cereal::StarPilotCarState::Reader &starpilotCarState = fpsm["starpilotCarState"].getStarpilotCarState(); - const cereal::StarPilotPlan::Reader &starpilotPlan = fpsm["starpilotPlan"].getStarpilotPlan(); - const cereal::StarPilotSelfdriveState::Reader &starpilotSelfdriveState = fpsm["starpilotSelfdriveState"].getStarpilotSelfdriveState(); - const cereal::MapdOut::Reader &mapdOut = fpsm["mapdOut"].getMapdOut(); - const cereal::ModelDataV2::Reader &modelV2 = sm["modelV2"].getModelV2(); - const cereal::SelfdriveState::Reader &selfdriveState = sm["selfdriveState"].getSelfdriveState(); - - // Cache toggle lookups once per frame — avoids 30+ QJsonObject tree-walks in paint code - const bool cachedUseSiMetrics = starpilot_toggles.value("use_si_metrics").toBool(); - cachedAdjacentPathMetrics = starpilot_toggles.value("adjacent_path_metrics").toBool(); - cachedBlindSpotPath = starpilot_toggles.value("blind_spot_path").toBool(); - cachedCemStatus = starpilot_toggles.value("cem_status").toBool(); - cachedColorScheme = starpilot_toggles.value("color_scheme").toString(); - cachedCompass = starpilot_toggles.value("compass").toBool(); - cachedCscStatus = starpilot_toggles.value("csc_status").toBool(); - cachedDynamicPedalsOnUi = starpilot_toggles.value("dynamic_pedals_on_ui").toBool(); - cachedHideSpeedLimit = starpilot_toggles.value("hide_speed_limit").toBool(); - cachedLaneDetectionWidth = starpilot_toggles.value("lane_detection_width").toDouble(); - cachedOpenpilotLongitudinal = starpilot_toggles.value("openpilot_longitudinal").toBool(); - cachedPathEdgesColor = starpilot_toggles.value("path_edges_color").toString(); - cachedPedalsOnUi = starpilot_toggles.value("pedals_on_ui").toBool(); - cachedRadarTracks = starpilot_toggles.value("radar_tracks").toBool(); - cachedRoadNameUi = starpilot_toggles.value("road_name_ui").toBool(); - cachedShowSpeedLimitOffset = starpilot_toggles.value("show_speed_limit_offset").toBool(); - cachedShowSpeedLimits = starpilot_toggles.value("show_speed_limits").toBool(); - cachedShowStoppingPoint = starpilot_toggles.value("show_stopping_point").toBool(); - cachedShowStoppingPointMetrics = starpilot_toggles.value("show_stopping_point_metrics").toBool(); - cachedSignalIcons = starpilot_toggles.value("signal_icons").toString(); - cachedSimpleMode = starpilot_toggles.value("simple_mode").toBool(); - cachedSpeedLimitController = starpilot_toggles.value("speed_limit_controller").toBool(); - cachedSpeedLimitSources = starpilot_toggles.value("speed_limit_sources").toBool(); - cachedSlcAbbreviatedSources = starpilot_toggles.value("slc_abbreviated_sources").toBool(); - cachedSlcActiveSourcesOnly = starpilot_toggles.value("slc_active_sources_only").toBool(); - cachedSpeedLimitVienna = starpilot_toggles.value("speed_limit_vienna").toBool(); - cachedStaticPedalsOnUi = starpilot_toggles.value("static_pedals_on_ui").toBool(); - cachedStoppedTimer = starpilot_toggles.value("stopped_timer").toBool(); - - if (scene.is_metric || cachedUseSiMetrics) { - leadDistanceUnit = tr(" meters"); - leadSpeedUnit = cachedUseSiMetrics ? tr(" m/s") : tr(" km/h"); - speedUnit = scene.is_metric ? tr("km/h") : tr("mph"); - - distanceConversion = 1.0f; - speedConversion = scene.is_metric ? MS_TO_KPH : MS_TO_MPH; - speedConversionMetrics = cachedUseSiMetrics ? 1.0f : MS_TO_KPH; - } else { - leadDistanceUnit = tr(" feet"); - leadSpeedUnit = tr(" mph"); - speedUnit = tr("mph"); - - distanceConversion = METER_TO_FOOT; - speedConversion = MS_TO_MPH; - speedConversionMetrics = MS_TO_MPH; - } - - accelerationEgo = carState.getAEgo(); - blindspotLeft = carState.getLeftBlindspot(); - blindspotRight = carState.getRightBlindspot(); - blinkerLeft = carState.getLeftBlinker(); - blinkerRight = carState.getRightBlinker(); - brakeLights = starpilotCarState.getBrakeLights(); - cscControllingSpeed = starpilotPlan.getCscControllingSpeed(); - cscSpeed = starpilotPlan.getCscSpeed(); - cscTraining = starpilotPlan.getCscTraining(); - dashboardSpeedLimit = starpilotCarState.getDashboardSpeedLimit(); - desiredFollowDistance = starpilotPlan.getDesiredFollowDistance(); - experimentalMode = selfdriveState.getExperimentalMode(); - forceCoast = starpilotCarState.getForceCoast(); - forcingStop = starpilotPlan.getForcingStop(); - forcingStopLength = starpilotPlan.getForcingStopLength(); - stopSignConfirmed = starpilotPlan.getStopSignConfirmed(); - laneWidthLeft = starpilotPlan.getLaneWidthLeft(); - laneWidthRight = starpilotPlan.getLaneWidthRight(); - lateralPaused = starpilotCarState.getPauseLateral(); - longitudinalPaused = starpilotCarState.getPauseLongitudinal(); - mapSpeedLimit = starpilotPlan.getSlcMapSpeedLimit(); - mapboxSpeedLimit = starpilotPlan.getSlcMapboxSpeedLimit(); - nextSpeedLimit = starpilotPlan.getSlcNextSpeedLimit(); - redLight = starpilotPlan.getRedLight(); - roadCurvature = starpilotPlan.getRoadCurvature(); - roadName = QString::fromStdString(mapdOut.getRoadName()); - slcOverriddenSpeed = starpilotPlan.getSlcOverriddenSpeed(); - speedLimit = slcOverriddenSpeed != 0 ? slcOverriddenSpeed : starpilotPlan.getSlcSpeedLimit(); - speedLimitChanged = starpilotPlan.getSpeedLimitChanged(); - unconfirmedSpeedLimitValid = starpilotPlan.getUnconfirmedSlcSpeedLimit() > 1; - speedLimitSource = starpilotPlan.getSlcSpeedLimitSource(); - stoppingDistance = modelV2.getPosition().getX().size() > 33 - 1 ? modelV2.getPosition().getX()[33 - 1] : 0.0; - unconfirmedSpeedLimit = starpilotPlan.getUnconfirmedSlcSpeedLimit(); - visionSpeedLimit = params.getBool("VisionSpeedLimitDetection") ? params_memory.getFloat("VisionSpeedLimit") : 0.0; - weatherDaytime = starpilotPlan.getWeatherDaytime(); - weatherId = starpilotPlan.getWeatherId(); - - hideBottomIcons = selfdriveState.getAlertSize() != cereal::SelfdriveState::AlertSize::NONE; - hideBottomIcons |= starpilotSelfdriveState.getAlertSize() != cereal::StarPilotSelfdriveState::AlertSize::NONE; - hideBottomIcons |= signalStyle.startsWith("traditional") && (blinkerLeft || blinkerRight); - - if (slcOverriddenSpeed == 0 && !cachedShowSpeedLimitOffset) { - speedLimit += starpilotPlan.getSlcSpeedLimitOffset(); - } - speedLimit *= (scene.is_metric ? MS_TO_KPH : MS_TO_MPH); - float speedLimitOffset = starpilotPlan.getSlcSpeedLimitOffset() * speedConversion; - speedLimitOffsetStr = (speedLimitOffset != 0) ? QString::number(speedLimitOffset, 'f', 0).prepend((speedLimitOffset > 0) ? "+" : "-") : "–"; - - static int lastFrameIndex; - if (lastFrameIndex > animationFrameIndex && cachedSignalIcons == "frog") { - frogHopCount++; - } - lastFrameIndex = animationFrameIndex; - - if ((blinkerLeft || blinkerRight) && signalStyle != "None") { - if (!animationTimer->isActive()) { - animationTimer->start(signalAnimationLength); - } - } else if (animationTimer->isActive()) { - animationFrameIndex = 0; - animationTimer->stop(); - } - - if (cscTraining) { - if (!glowTimer.isValid()) { - glowTimer.start(); - } - } else { - glowTimer.invalidate(); - } - - if (speedLimitChanged && unconfirmedSpeedLimitValid) { - if (!pendingLimitTimer.isValid()) { - pendingLimitTimer.start(); - } - } else { - pendingLimitTimer.invalidate(); - } - - if (starpilot_scene.standstill && cachedStoppedTimer) { - if (!standstillTimer.isValid()) { - standstillTimer.start(); - } else { - standstillDuration = starpilot_scene.started_timer / UI_FREQ < 60 ? 0 : standstillTimer.elapsed() / 1000; - } - } else { - standstillDuration = 0; - standstillTimer.invalidate(); - } -} - -void StarPilotAnnotatedCameraWidget::mousePressEvent(QMouseEvent *mouseEvent) { - if (starpilot_toggles.value("simple_mode").toBool()) { - mouseEvent->ignore(); - return; - } - - if (speedLimitChanged && speedLimitRect.contains(mouseEvent->pos())) { - params_memory.putBool("SpeedLimitAccepted", true); - mouseEvent->accept(); - return; - } - - mouseEvent->ignore(); -} - -void StarPilotAnnotatedCameraWidget::paintStarPilotWidgets(QPainter &p, UIState &s, bool hideCameraOverlays) { - if (cachedSimpleMode) { - cemStatusPosition = QPoint(0, 0); - compassPosition = QPoint(0, 0); - lateralPausedPosition = QPoint(0, 0); - speedLimitHeight = 0; - return; - } - - if (!hideBottomIcons && cachedCemStatus) { - paintCEMStatus(p); - } else { - cemStatusPosition.setX(0); - cemStatusPosition.setY(0); - } - - if (!hideBottomIcons && cachedCompass) { - paintCompass(p); - } else { - compassPosition.setX(0); - compassPosition.setY(0); - } - - if (forcingStop) { - paintForceStop(p); - } else if (!speedLimitChanged && !(signalStyle == "static" && blinkerLeft) && cachedCscStatus) { - if (cscTraining) { - paintCurveSpeedControlTraining(p); - } else if (isCruiseSet && cscControllingSpeed) { - paintCurveSpeedControl(p); - } - } - - if (!hideBottomIcons && lateralPaused) { - paintLateralPaused(p); - } else { - lateralPausedPosition.setX(0); - lateralPausedPosition.setY(0); - } - - if (!hideBottomIcons && (forceCoast || longitudinalPaused)) { - paintLongitudinalPaused(p); - } - - if (cachedPedalsOnUi) { - paintPedalIcons(p); - } - - if (!hideCameraOverlays && cachedRadarTracks) { - paintRadarTracks(p); - } - - if (cachedRoadNameUi) { - paintRoadName(p); - } - - bool hideSpeedLimit = !(speedLimitChanged && unconfirmedSpeedLimitValid) && cachedHideSpeedLimit; - if (!hideSpeedLimit && (cachedShowSpeedLimits || cachedSpeedLimitController)) { - paintSpeedLimit(p); - } else { - speedLimitHeight = 0; - } - - if (cachedSpeedLimitSources) { - paintSpeedLimitSources(p); - } - - if (standstillDuration != 0) { - paintStandstillTimer(p); - } - - if (!hideCameraOverlays && track_vertices.length() >= 1 && redLight && cachedShowStoppingPoint) { - paintStoppingPoint(p); - } - - if ((blinkerLeft || blinkerRight) && signalStyle != "None" && (standstillDuration == 0 || signalStyle != "static")) { - paintTurnSignals(p); - } - - if (!hideBottomIcons) { - paintWeather(p); - } -} - -void StarPilotAnnotatedCameraWidget::paintAdjacentPaths(QPainter &p) { - std::function paintPath = [&](const QPolygonF &path, bool isLeft, bool isBlindSpot, float laneWidth) { - if (laneWidth == 0.0f) { - return; - } - - p.save(); - - QLinearGradient gradient(0, height(), 0, 0); - if (isBlindSpot && cachedBlindSpotPath) { - gradient.setColorAt(0.0f, QColor::fromHslF(0.0f, 0.75f, 0.5f, 0.4f)); - gradient.setColorAt(0.5f, QColor::fromHslF(0.0f, 0.75f, 0.5f, 0.35f)); - gradient.setColorAt(1.0f, QColor::fromHslF(0.0f, 0.75f, 0.5f, 0.0f)); - } else { - float ratio = std::clamp(laneWidth / cachedLaneDetectionWidth, 0.0, 1.0); - float hue = (ratio * ratio) * (120.0f / 360.0f); - - gradient.setColorAt(0.0f, QColor::fromHslF(hue, 0.75f, 0.5f, 0.4f)); - gradient.setColorAt(0.5f, QColor::fromHslF(hue, 0.75f, 0.5f, 0.35f)); - gradient.setColorAt(1.0f, QColor::fromHslF(hue, 0.75f, 0.5f, 0.0f)); - } - - p.setBrush(gradient); - p.drawPolygon(path); - - if (cachedAdjacentPathMetrics) { - QString text; - if (isBlindSpot && cachedBlindSpotPath) { - text = tr("Vehicle in blind spot"); - } else { - text = QString::number(laneWidth * distanceConversion, 'f', 2) + leadDistanceUnit; - } - - int midIndex = path.size() / 2; - QPointF anchorPoint = isLeft ? path[midIndex / 2] : path[midIndex + (path.size() - midIndex) / 2]; - - p.setFont(InterFont(45, QFont::DemiBold)); - QFontMetrics metrics(p.font()); - - int textXPosition = isLeft ? anchorPoint.x() - metrics.horizontalAdvance(text) : anchorPoint.x(); - int textYPosition = anchorPoint.y() - metrics.height() / 2 + metrics.ascent(); - - QPainterPath textPath; - textPath.addText(textXPosition, textYPosition, p.font(), text); - p.strokePath(textPath, QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - - p.setPen(whiteColor()); - p.drawText(textXPosition, textYPosition, text); - } - - p.restore(); - }; - - paintPath(track_adjacent_vertices[0], true, blindspotLeft, laneWidthLeft); - paintPath(track_adjacent_vertices[1], false, blindspotRight, laneWidthRight); -} - -void StarPilotAnnotatedCameraWidget::paintBlindSpotPath(QPainter &p) { - p.save(); - - QLinearGradient bs(0, height(), 0, 0); - bs.setColorAt(0.0f, QColor::fromHslF(0 / 360.0f, 0.75f, 0.5f, 0.4f)); - bs.setColorAt(0.5f, QColor::fromHslF(0 / 360.0f, 0.75f, 0.5f, 0.35f)); - bs.setColorAt(1.0f, QColor::fromHslF(0 / 360.0f, 0.75f, 0.5f, 0.0f)); - p.setBrush(bs); - - if (track_adjacent_vertices[0].boundingRect().width() > 0 && blindspotLeft) { - p.drawPolygon(track_adjacent_vertices[0]); - } - if (track_adjacent_vertices[1].boundingRect().width() > 0 && blindspotRight) { - p.drawPolygon(track_adjacent_vertices[1]); - } - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintCEMStatus(QPainter &p) { - if (dmIconPosition == QPoint(0, 0)) { - return; - } - - p.save(); - - cemStatusPosition.setX(dmIconPosition.x() + (rightHandDM ? -img_size - widget_size : widget_size)); - cemStatusPosition.setY(dmIconPosition.y() - widget_size / 2); - - QRect cemWidget(cemStatusPosition, QSize(widget_size, widget_size)); - const bool conditionalExperimentalMode = starpilot_toggles.value("conditional_experimental_mode").toBool(); - const bool conditionalChillMode = starpilot_toggles.value("conditional_chill_mode").toBool(); - const bool manualOverride = - (conditionalExperimentalMode && starpilot_scene.conditional_status == 1) || - (conditionalChillMode && (starpilot_scene.conditional_status == 1 || starpilot_scene.conditional_status == 2)); - - p.setBrush(blackColor(166)); - if (manualOverride) { - p.setPen(QPen(QColor(bg_colors[STATUS_CEM_DISABLED]), 10)); - } else if (experimentalMode) { - p.setPen(QPen(QColor(bg_colors[STATUS_EXPERIMENTAL_MODE_ENABLED]), 10)); - } else { - p.setPen(QPen(blackColor(), 10)); - } - p.drawRoundedRect(cemWidget, 24, 24); - - QSharedPointer icon = chillModeIcon; - if (conditionalChillMode && !conditionalExperimentalMode) { - if (starpilot_scene.conditional_status == 1) { - icon = experimentalModeIcon; - } else if (starpilot_scene.conditional_status == 2) { - icon = chillModeIcon; - } else if (starpilot_scene.conditional_status == 4) { - icon = cemLeadIcon; - } else if (starpilot_scene.conditional_status == 6) { - icon = cemSpeedIcon; - } else { - icon = experimentalMode ? experimentalModeIcon : chillModeIcon; - } - } else if (experimentalMode) { - if (starpilot_scene.conditional_status == 1) { - icon = chillModeIcon; - } else if (starpilot_scene.conditional_status == 2) { - icon = experimentalModeIcon; - } else if (starpilot_scene.conditional_status == 3) { - icon = cemCurveIcon; - } else if (starpilot_scene.conditional_status == 4) { - icon = cemLeadIcon; - } else if (starpilot_scene.conditional_status == 5) { - icon = cemTurnIcon; - } else if (starpilot_scene.conditional_status == 6 || starpilot_scene.conditional_status == 7) { - icon = cemSpeedIcon; - } else if (starpilot_scene.conditional_status == 8) { - icon = cemStopIcon; - } else { - icon = experimentalModeIcon; - } - } - p.drawPixmap(cemWidget, icon->currentPixmap()); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintCompass(QPainter &p) { - if (dmIconPosition == QPoint(0, 0)) { - return; - } - - p.save(); - - constexpr double PIXELS_PER_DEGREE = 2.5; - - constexpr int BASE_RIBBON_WIDTH = static_cast(360 * PIXELS_PER_DEGREE); - constexpr int BORDER_WIDTH = 10; - constexpr int MARGIN = 5; - constexpr int TRIANGLE_SIZE = 40; - - static QPixmap compassRibbon = [&]() { - QPixmap ribbon(BASE_RIBBON_WIDTH * 2, widget_size); - ribbon.fill(Qt::transparent); - - QPainter ribbonPainter(&ribbon); - ribbonPainter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); - - QFont font = InterFont(65, QFont::Bold); - ribbonPainter.setFont(font); - QFontMetrics fm(font); - - QMap directionLabels = {{0, "N"}, {45, "NE"}, {90, "E"}, {135, "SE"}, {180, "S"}, {225, "SW"}, {270, "W"}, {315, "NW"}, {360, "N"}}; - - for (int cycle = 0; cycle < 2; ++cycle) { - int xOffset = cycle * 360; - - for (int degree = 0; degree < 360; ++degree) { - int x = qRound((xOffset + degree) * PIXELS_PER_DEGREE); - - if (directionLabels.contains(degree)) { - QString label = directionLabels[degree]; - ribbonPainter.setPen(whiteColor()); - ribbonPainter.drawText(x - fm.horizontalAdvance(label) / 2, fm.ascent(), label); - } - - int notchHeight = (degree % 45 == 0) ? 35 : (degree % 15 == 0) ? 25 : 15; - int notchWidth = (degree % 45 == 0) ? 5 : (degree % 15 == 0) ? 4 : 3; - - ribbonPainter.setPen(QPen(whiteColor(), notchWidth)); - ribbonPainter.drawLine(x, widget_size - notchHeight - MARGIN, x, widget_size); - } - } - - return ribbon; - }(); - - compassPosition.rx() = rightHandDM ? UI_BORDER_SIZE + widget_size / 2 : width() - UI_BORDER_SIZE - btn_size; - compassPosition.ry() = dmIconPosition.y() - widget_size / 2; - - QRect compassWidget(compassPosition, QSize(widget_size, widget_size)); - - p.setBrush(blackColor(166)); - p.setPen(QPen(blackColor(), BORDER_WIDTH)); - p.drawRoundedRect(compassWidget, 24, 24); - - QPainterPath clipPath; - clipPath.addRoundedRect(compassWidget.adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN), 24, 24); - p.setClipPath(clipPath); - - double rawBearing = QJsonDocument::fromJson(QByteArray::fromStdString(params_memory.get("LastGPSPosition"))).object().value("bearing").toDouble(0.0); - int bearing = qRound(fmod(rawBearing + 360.0, 360.0)); - int offset = qRound(bearing * PIXELS_PER_DEGREE) % BASE_RIBBON_WIDTH; - int drawX = compassWidget.center().x() - offset; - - p.drawPixmap(drawX - BASE_RIBBON_WIDTH, compassWidget.top() + MARGIN, compassRibbon); - p.drawPixmap(drawX, compassWidget.top() + MARGIN, compassRibbon); - - int triangleX = compassWidget.center().x(); - int triangleY = compassWidget.bottom() - TRIANGLE_SIZE; - QPolygon triangle({ - QPoint(triangleX, triangleY - TRIANGLE_SIZE), - QPoint(triangleX - TRIANGLE_SIZE / 1.5, triangleY), - QPoint(triangleX + TRIANGLE_SIZE / 1.5, triangleY) - }); - - p.setBrush(whiteColor()); - p.setPen(Qt::NoPen); - p.drawPolygon(triangle); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintCurveSpeedControl(QPainter &p) { - p.save(); - - QRect curveSpeedRect(QPoint(setSpeedRect.right() + UI_BORDER_SIZE, setSpeedRect.top()), QSize(defaultSize.width() * 1.25, defaultSize.width() * 1.25)); - - QPixmap &curveSpeedImage = roadCurvature < 0 ? curveSpeedIcon : curveSpeedIconFlipped; - QSize curveSpeedSize = curveSpeedImage.size(); - QPoint curveSpeedPoint = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, curveSpeedSize, curveSpeedRect).topLeft(); - - p.setOpacity(1.0); - - QRect cscRect(curveSpeedRect.topLeft() + QPoint(0, curveSpeedRect.height() + 10), QSize(curveSpeedRect.width(), 100)); - p.setBrush(blueColor(166)); - p.setFont(InterFont(45, QFont::Bold)); - p.setPen(QPen(blueColor(), 10)); - p.drawRoundedRect(cscRect, 24, 24); - p.setPen(QPen(whiteColor(), 6)); - p.drawText(cscRect.adjusted(20, 0, 0, 0), Qt::AlignVCenter | Qt::AlignLeft, QString::number(std::nearbyint(fmin(speed, cscSpeed * speedConversion))) + speedUnit); - p.drawPixmap(curveSpeedPoint, curveSpeedImage); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintCurveSpeedControlTraining(QPainter &p) { - p.save(); - - qreal phase = (glowTimer.elapsed() % 2000) / 2000.0 * 2 * M_PI; - qreal alphaFactor = 0.5 + 0.5 * sin(phase); - - QColor glowColor = blueColor(); - glowColor.setAlphaF(0.3 + 0.7 * alphaFactor); - - int glowWidth = 8 + static_cast(2 * alphaFactor); - - QRect curveSpeedRect(QPoint(setSpeedRect.right() + UI_BORDER_SIZE, setSpeedRect.top()), QSize(defaultSize.width() * 1.25, defaultSize.width() * 1.25)); - - QPixmap &curveSpeedImage = roadCurvature < 0 ? curveSpeedIcon : curveSpeedIconFlipped; - QSize curveSpeedSize = curveSpeedImage.size(); - QPoint curveSpeedPoint = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, curveSpeedSize, curveSpeedRect).topLeft(); - - p.setOpacity(1.0); - - p.setBrush(blackColor(166)); - p.setPen(QPen(glowColor, glowWidth)); - p.drawRoundedRect(curveSpeedRect, 24, 24); - p.drawPixmap(curveSpeedPoint, curveSpeedImage); - p.setBrush(blackColor(166)); - p.setFont(InterFont(35, QFont::Bold)); - p.setPen(QPen(blackColor(), 10)); - - QRect textRect(curveSpeedRect.topLeft() + QPoint(0, curveSpeedRect.height() + 10), QSize(curveSpeedRect.width(), 50)); - p.drawRoundedRect(textRect, 24, 24); - p.setPen(QPen(whiteColor(), 6)); - p.drawText(textRect.adjusted(20, 0, 0, 0), Qt::AlignVCenter | Qt::AlignLeft, "Training..."); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintLateralPaused(QPainter &p) { - if (dmIconPosition == QPoint(0, 0)) { - return; - } - - p.save(); - - if (cemStatusPosition != QPoint(0, 0)) { - lateralPausedPosition = cemStatusPosition; - } else { - lateralPausedPosition.rx() = dmIconPosition.x(); - lateralPausedPosition.ry() = dmIconPosition.y() - widget_size / 2; - } - lateralPausedPosition.rx() += rightHandDM ? -UI_BORDER_SIZE - widget_size - UI_BORDER_SIZE : UI_BORDER_SIZE + widget_size + UI_BORDER_SIZE; - - QRect lateralWidget(lateralPausedPosition, QSize(widget_size, widget_size)); - - p.setBrush(blackColor(166)); - p.setPen(QPen(QColor(bg_colors[STATUS_TRAFFIC_MODE_ENABLED]), 10)); - p.drawRoundedRect(lateralWidget, 24, 24); - - p.setOpacity(0.5); - p.drawPixmap(lateralWidget, turnIcon); - p.setOpacity(0.75); - p.drawPixmap(lateralWidget, pausedIcon); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintLeadMetrics(QPainter &p, bool adjacent, QPointF *chevron, const cereal::RadarState::LeadData::Reader &lead_data) { - float leadDistance = lead_data.getDRel() + (adjacent ? std::abs(lead_data.getYRel()) : 0.0f); - float leadSpeed = std::max(lead_data.getVLead(), 0.0f); - - QString distanceString = QString::number(qRound(leadDistance * distanceConversion)); - QString speedString = QString::number(qRound(leadSpeed * speedConversionMetrics)); - - QVector textLines; - textLines.reserve(3); - if (adjacent) { - textLines.append(QString("%1 %2").arg(distanceString, leadDistanceUnit)); - textLines.append(QString("%1 %2").arg(speedString, leadSpeedUnit)); - } else { - if (cachedOpenpilotLongitudinal) { - int desiredDistance = std::max(0, qRound(desiredFollowDistance * distanceConversion)); - textLines.append(QString("%1 %2 (%3)").arg(distanceString, leadDistanceUnit, tr("Desired: %1").arg(desiredDistance))); - } else { - textLines.append(QString("%1 %2").arg(distanceString, leadDistanceUnit)); - } - textLines.append(QString("%1 %2").arg(speedString, leadSpeedUnit)); - - float timeGap = leadDistance / std::max(speed / speedConversion, 1.0f); - textLines.append(QString("%1 %2").arg(QString::number(timeGap, 'f', 2), tr("seconds"))); - } - - p.setFont(InterFont(45, QFont::DemiBold)); - p.setPen(whiteColor()); - - QFontMetrics metrics(p.font()); - int lineHeight = metrics.lineSpacing(); - - int maxTextWidth = 0; - for (QString &line : textLines) { - maxTextWidth = std::max(maxTextWidth, metrics.horizontalAdvance(line)); - } - - int centerX = (chevron[2].x() + chevron[0].x()) / 2; - int startY = chevron[0].y() + lineHeight + 5; - - int xMargin = maxTextWidth * 0.1; - int yMargin = lineHeight * 0.1; - - QRect textRect(centerX - maxTextWidth / 2, startY - lineHeight, maxTextWidth, textLines.size() * lineHeight); - textRect.adjust(-xMargin, -yMargin, xMargin, yMargin); - - if (adjacent) { - if (textRect.intersects(adjacentLeadTextRect) || textRect.intersects(leadTextRect)) { - return; - } - adjacentLeadTextRect = textRect; - } else { - leadTextRect = textRect; - } - - for (int i = 0; i < textLines.size(); ++i) { - int lineX = centerX - metrics.horizontalAdvance(textLines[i]) / 2; - int lineY = startY + (i * lineHeight); - - QPainterPath path; - path.addText(lineX, lineY, p.font(), textLines[i]); - p.strokePath(path, QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - - p.setPen(whiteColor()); - p.drawText(lineX, lineY, textLines[i]); - } -} - -void StarPilotAnnotatedCameraWidget::paintLongitudinalPaused(QPainter &p) { - if (dmIconPosition == QPoint(0, 0)) { - return; - } - - p.save(); - - QPoint longitudinalIconPosition; - if (lateralPausedPosition != QPoint(0, 0)) { - longitudinalIconPosition = lateralPausedPosition; - } else if (cemStatusPosition != QPoint(0, 0)) { - longitudinalIconPosition = cemStatusPosition; - } else { - longitudinalIconPosition.rx() = dmIconPosition.x(); - longitudinalIconPosition.ry() = dmIconPosition.y() - widget_size / 2; - } - longitudinalIconPosition.rx() += rightHandDM ? -UI_BORDER_SIZE - widget_size - UI_BORDER_SIZE : UI_BORDER_SIZE + widget_size + UI_BORDER_SIZE; - - QRect longitudinalWidget(longitudinalIconPosition, QSize(widget_size, widget_size)); - - p.setBrush(blackColor(166)); - p.setPen(QPen(QColor(bg_colors[STATUS_TRAFFIC_MODE_ENABLED]), 10)); - p.drawRoundedRect(longitudinalWidget, 24, 24); - - p.setOpacity(0.5); - p.drawPixmap(longitudinalWidget, speedIcon); - p.setOpacity(0.75); - p.drawPixmap(longitudinalWidget, pausedIcon); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintPathEdges(QPainter &p, int height) { - p.save(); - - QLinearGradient gradient(0, height, 0, 0); - - std::function setPathEdgeColors = [&gradient](const QColor &baseColor) { - gradient.setColorAt(0.0f, QColor(baseColor.red(), baseColor.green(), baseColor.blue(), 255.0f * 0.4f)); - gradient.setColorAt(0.5f, QColor(baseColor.red(), baseColor.green(), baseColor.blue(), 255.0f * 0.35f)); - gradient.setColorAt(1.0f, QColor(baseColor.red(), baseColor.green(), baseColor.blue(), 255.0f * 0.0f)); - }; - const bool conditionalExperimentalMode = starpilot_toggles.value("conditional_experimental_mode").toBool(); - const bool conditionalChillMode = starpilot_toggles.value("conditional_chill_mode").toBool(); - const bool highlightOverride = - (conditionalExperimentalMode && starpilot_scene.conditional_status == 1) || - (conditionalChillMode && (starpilot_scene.conditional_status == 1 || starpilot_scene.conditional_status == 2)); - - if (starpilot_scene.switchback_mode_enabled) { - setPathEdgeColors(bg_colors[STATUS_SWITCHBACK_MODE_ENABLED]); - } else if (starpilot_scene.always_on_lateral_active) { - setPathEdgeColors(bg_colors[STATUS_ALWAYS_ON_LATERAL_ACTIVE]); - } else if (highlightOverride) { - setPathEdgeColors(bg_colors[STATUS_CEM_DISABLED]); - } else if (experimentalMode) { - setPathEdgeColors(bg_colors[STATUS_EXPERIMENTAL_MODE_ENABLED]); - } else if (starpilot_scene.traffic_mode_enabled) { - setPathEdgeColors(bg_colors[STATUS_TRAFFIC_MODE_ENABLED]); - } else if (cachedColorScheme != "stock") { - setPathEdgeColors(QColor(cachedPathEdgesColor)); - } else { - gradient.setColorAt(0.0f, QColor::fromHslF(148.0f / 360.0f, 0.94f, 0.41f, 0.4f)); - gradient.setColorAt(0.5f, QColor::fromHslF(112.0f / 360.0f, 1.0f, 0.54f, 0.35f)); - gradient.setColorAt(1.0f, QColor::fromHslF(112.0f / 360.0f, 1.0f, 0.54f, 0.0f)); - } - - p.setBrush(gradient); - - QPainterPath path; - path.addPolygon(track_vertices); - path.addPolygon(track_edge_vertices); - p.drawPath(path); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintPedalIcons(QPainter &p) { - p.save(); - - float brakeOpacity = 1.0f; - float gasOpacity = 1.0f; - - if (cachedDynamicPedalsOnUi) { - brakeOpacity = starpilot_scene.standstill ? 1.0f : accelerationEgo < -0.25f ? std::max(0.25f, std::abs(accelerationEgo)) : 0.25f; - gasOpacity = std::max(0.25f, accelerationEgo); - } else if (cachedStaticPedalsOnUi) { - brakeOpacity = starpilot_scene.standstill || brakeLights || accelerationEgo < -0.25f ? 1.0f : 0.25f; - gasOpacity = accelerationEgo > 0.25 ? 1.0f : 0.25f; - } - - int startX = experimentalButtonPosition.x(); - int startY = experimentalButtonPosition.y() + btn_size + UI_BORDER_SIZE; - - p.setOpacity(brakeOpacity); - p.drawPixmap(startX, startY, brakePedalImg); - - p.setOpacity(gasOpacity); - p.drawPixmap(startX + btn_size / 2, startY, gasPedalImg); - - p.restore(); -} - - -void StarPilotAnnotatedCameraWidget::paintRainbowPath(QPainter &p, QLinearGradient &bg, float lin_grad_point) { - p.save(); - - static float hueOffset = 0.0f; - if (speed > 0) { - hueOffset += speed / speedConversion * 0.02f; - - if (hueOffset >= 360.0f) { - hueOffset = fmodf(hueOffset, 360.0f); - } - } - - float alpha = util::map_val(lin_grad_point, 0.0f, 1.0f, 0.5f, 0.1f); - float pathHue = fmodf(lin_grad_point * 120.0f + hueOffset, 360.0f); - - bg.setColorAt(lin_grad_point, QColor::fromHslF(pathHue / 360.0f, 1.0f, 0.5f, alpha)); - bg.setSpread(QGradient::RepeatSpread); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintRadarTracks(QPainter &p) { - if (radar_tracks.empty()) { - return; - } - - p.save(); - - int diameter = 25; - - float radius = diameter / 2.0f; - float track_x = p.viewport().width() - diameter; - float track_y = p.viewport().height() - diameter; - - p.setBrush(redColor()); - - for (const QPointF &track : radar_tracks) { - float x = std::clamp(static_cast(track.x()), 0.0f, track_x); - float y = std::clamp(static_cast(track.y()), 0.0f, track_y); - - p.drawEllipse(QPointF(x + radius, y + radius), radius, radius); - } - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintRoadName(QPainter &p) { - if (roadName.isEmpty()) { - return; - } - - p.save(); - - QFont font = InterFont(40, QFont::DemiBold); - - int textWidth = QFontMetrics(font).horizontalAdvance(roadName); - - QSize size(textWidth + 100, 50); - QRect roadNameRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignHCenter | Qt::AlignBottom, size, rect().adjusted(0, 0, 0, -5)); - - p.setBrush(blackColor(166)); - p.setOpacity(1.0); - p.setPen(QPen(blackColor(), 10)); - p.drawRoundedRect(roadNameRect, 24, 24); - - p.setFont(font); - p.setPen(QPen(whiteColor(), 6)); - p.drawText(roadNameRect, Qt::AlignCenter, roadName); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintSpeedLimit(QPainter &p) { - if (setSpeedRect.isEmpty()) { - return; - } - - p.save(); - - bool isFlashingPending = speedLimitChanged && unconfirmedSpeedLimitValid; - bool flashOn = isFlashingPending && (pendingLimitTimer.elapsed() % 1000 < 500); - QString displaySpeedLimitStr = isFlashingPending - ? QString::number(std::nearbyint(unconfirmedSpeedLimit * speedConversion)) - : ((speedLimit > 1) ? QString::number(std::nearbyint(speedLimit)) : "–"); - QString speedLimitStr = displaySpeedLimitStr; - - bool hasUsSpeedLimit = !cachedSpeedLimitVienna; - bool hasEuSpeedLimit = !hasUsSpeedLimit; - - int euSignSize = 176; - int usSignHeight = 186; - int signMargin = 12; - - if (hasUsSpeedLimit) { - speedLimitHeight = usSignHeight + signMargin; - } else if (hasEuSpeedLimit) { - speedLimitHeight = euSignSize + signMargin; - } - - QRect signRect; - if (hasUsSpeedLimit) { - signRect = QRect(setSpeedRect.x() + signMargin, setSpeedRect.bottom() - speedLimitHeight, setSpeedRect.width() - 2 * signMargin, usSignHeight); - } else if (hasEuSpeedLimit) { - signRect = QRect(setSpeedRect.x() + signMargin, setSpeedRect.bottom() - speedLimitHeight, setSpeedRect.width() - 2 * signMargin, euSignSize); - } - speedLimitRect = signRect; - - if (hasUsSpeedLimit) { - QColor borderColor = flashOn ? redColor() : blackColor(); - QColor textColor = flashOn ? redColor() : blackColor(); - - p.setPen(Qt::NoPen); - p.setBrush(whiteColor()); - p.drawRoundedRect(signRect, 24, 24); - p.setPen(QPen(borderColor, 6)); - p.drawRoundedRect(signRect.adjusted(9, 9, -9, -9), 16, 16); - - p.setOpacity(slcOverriddenSpeed == 0 ? 1.0 : 0.25); - p.setPen(textColor); - if (isFlashingPending) { - p.setFont(InterFont(28, QFont::DemiBold)); - p.drawText(signRect.adjusted(0, 22, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("PENDING")); - p.setFont(InterFont(70, QFont::Bold)); - p.drawText(signRect.adjusted(0, 51, 0, 0), Qt::AlignTop | Qt::AlignHCenter, speedLimitStr); - } else if (slcOverriddenSpeed == 0 && cachedShowSpeedLimitOffset) { - p.setFont(InterFont(28, QFont::DemiBold)); - p.drawText(signRect.adjusted(0, 22, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("LIMIT")); - p.setFont(InterFont(70, QFont::Bold)); - p.drawText(signRect.adjusted(0, 51, 0, 0), Qt::AlignTop | Qt::AlignHCenter, speedLimitStr); - p.setFont(InterFont(50, QFont::DemiBold)); - p.drawText(signRect.adjusted(0, 120, 0, 0), Qt::AlignTop | Qt::AlignHCenter, speedLimitOffsetStr); - } else { - p.setFont(InterFont(28, QFont::DemiBold)); - p.drawText(signRect.adjusted(0, 22, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("SPEED")); - p.drawText(signRect.adjusted(0, 51, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("LIMIT")); - p.setFont(InterFont(70, QFont::Bold)); - p.drawText(signRect.adjusted(0, 85, 0, 0), Qt::AlignTop | Qt::AlignHCenter, speedLimitStr); - } - } - - if (hasEuSpeedLimit) { - QColor textColor = flashOn ? redColor() : blackColor(); - - p.setPen(Qt::NoPen); - p.setBrush(whiteColor()); - p.drawEllipse(signRect); - p.setPen(QPen(Qt::red, 20)); - p.drawEllipse(signRect.adjusted(16, 16, -16, -16)); - - p.setOpacity(slcOverriddenSpeed == 0 ? 1.0 : 0.25); - p.setPen(textColor); - if (isFlashingPending) { - p.setFont(InterFont((speedLimitStr.size() >= 3) ? 60 : 70, QFont::Bold)); - p.drawText(signRect, Qt::AlignCenter, speedLimitStr); - } else if (cachedShowSpeedLimitOffset) { - p.setFont(InterFont((speedLimitStr.size() >= 3) ? 60 : 70, QFont::Bold)); - p.drawText(signRect.adjusted(0, -25, 0, 0), Qt::AlignCenter, speedLimitStr); - p.setFont(InterFont(40, QFont::DemiBold)); - p.drawText(signRect.adjusted(0, 100, 0, 0), Qt::AlignTop | Qt::AlignHCenter, speedLimitOffsetStr); - } else { - p.setFont(InterFont((speedLimitStr.size() >= 3) ? 60 : 70, QFont::Bold)); - p.drawText(signRect, Qt::AlignCenter, speedLimitStr); - } - } - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintSpeedLimitSources(QPainter &p) { - p.save(); - - const bool abbreviated = cachedSlcAbbreviatedSources; - const bool activeOnly = cachedSlcActiveSourcesOnly; - - std::function drawSource = - [&](QRect &rect, QPixmap &icon, const QString &title, const QString &abbrev, double speedLimitValue) { - bool isActive = QString::fromUtf8(speedLimitSource.c_str()) == title && speedLimitValue != 0; - - if (isActive) { - p.setBrush(redColor(166)); - p.setFont(InterFont(35, QFont::Bold)); - p.setPen(QPen(redColor(), 10)); - } else { - p.setBrush(blackColor(166)); - p.setFont(InterFont(35, QFont::DemiBold)); - p.setPen(QPen(blackColor(), 10)); - } - - QString fullText; - if (abbreviated) { - if (speedLimitValue != 0) { - fullText = abbrev + "-" + QString::number(std::nearbyint(speedLimitValue)); - } else { - fullText = abbrev + "-X"; - } - } else { - QString speedText = (speedLimitValue != 0) - ? QString::number(std::nearbyint(speedLimitValue)) + speedUnit - : "N/A"; - fullText = tr(title.toUtf8().constData()) + " - " + speedText; - } - - p.setOpacity(1.0); - p.drawRoundedRect(rect, 24, 24); - - QRect textRect; - if (abbreviated) { - textRect = QRect(rect.x() + 20, rect.y(), rect.width() - 40, rect.height()); - } else { - QSize size(img_size / 4, img_size / 4); - QRect iconRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignLeft | Qt::AlignVCenter, size, rect.adjusted(20, 0, 0, 0)); - p.drawPixmap(iconRect, icon); - textRect = QRect(iconRect.right() + 10, rect.y(), rect.width() - iconRect.width() - 30, rect.height()); - } - - p.setPen(QPen(whiteColor(), 6)); - - if (isActive) { - QFontMetrics fm(p.font()); - int textYPosition = textRect.y() + (textRect.height() - fm.height()) / 2 + fm.ascent(); - QPainterPath path; - path.addText(textRect.x(), textYPosition, p.font(), fullText); - p.strokePath(path, QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - p.drawText(textRect.x(), textYPosition, fullText); - } else { - p.drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, fullText); - } - }; - - struct SrcEntry { QPixmap *icon; QString title; QString abbrev; double value; }; - std::vector sources = { - {&dashboardIcon, "Dashboard", "Dash", dashboardSpeedLimit * speedConversion}, - {&mapDataIcon, "Map Data", "MapD", mapSpeedLimit * speedConversion}, - {&visionIcon, "Vision", "Vision", visionSpeedLimit * speedConversion}, - {&mapboxIcon, "Mapbox", "MapB", mapboxSpeedLimit * speedConversion}, - {&nextMapsIcon, "Upcoming", "Next", nextSpeedLimit * speedConversion}, - }; - - const int signMargin = 12; - const int rectH = 60; - const int gap = UI_BORDER_SIZE / 2; - const int xPos = abbreviated ? speedLimitRect.x() : speedLimitRect.x() - signMargin; - int yPos = speedLimitRect.y() + speedLimitRect.height() + UI_BORDER_SIZE; - - int rectW = abbreviated ? speedLimitRect.width() : 450; - if (abbreviated) { - // Pre-compute the widest label across all visible rows so every box is the same width. - QFontMetrics fm(InterFont(35, QFont::DemiBold)); - for (auto &s : sources) { - if (activeOnly && s.value == 0) continue; - QString label = s.value != 0 - ? s.abbrev + "-" + QString::number(std::nearbyint(s.value)) - : s.abbrev + "-na"; - int needed = fm.horizontalAdvance(label) + 40; - if (needed > rectW) rectW = needed; - } - } - - for (auto &s : sources) { - if (activeOnly && s.value == 0) continue; - QRect rect(xPos, yPos, rectW, rectH); - drawSource(rect, *s.icon, s.title, s.abbrev, s.value); - yPos += rectH + gap; - } - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintStandstillTimer(QPainter &p) { - p.save(); - - float transition = 0.0f; - - QColor startColor, endColor; - if (standstillDuration < 60) { - startColor = endColor = bg_colors[STATUS_ENGAGED]; - } else if (standstillDuration < 150) { - startColor = bg_colors[STATUS_ENGAGED]; - endColor = bg_colors[STATUS_CEM_DISABLED]; - transition = (standstillDuration - 60) / 90.0f; - } else if (standstillDuration < 300) { - startColor = bg_colors[STATUS_CEM_DISABLED]; - endColor = bg_colors[STATUS_TRAFFIC_MODE_ENABLED]; - transition = (standstillDuration - 150) / 150.0f; - } else { - startColor = endColor = bg_colors[STATUS_TRAFFIC_MODE_ENABLED]; - } - - QColor blendedColor( - startColor.red() + transition * (endColor.red() - startColor.red()), - startColor.green() + transition * (endColor.green() - startColor.green()), - startColor.blue() + transition * (endColor.blue() - startColor.blue()) - ); - - std::function drawText = [&](const QString &text, int y, const QFont &font, const QColor &color) { - p.setFont(font); - p.setPen(color); - - QRect standstillRect = p.fontMetrics().boundingRect(text); - standstillRect.moveCenter({rect().center().x(), y - standstillRect.height() / 2}); - p.drawText(standstillRect.x(), standstillRect.bottom(), text); - }; - - int minutes = standstillDuration / 60; - QString minuteStr = minutes == 1 ? tr("1 minute") : tr("%1 minutes").arg(minutes); - drawText(minuteStr, 210, InterFont(176, QFont::Bold), blendedColor); - - int seconds = standstillDuration % 60; - QString secondStr = seconds == 1 ? tr("1 second") : tr("%1 seconds").arg(seconds); - drawText(secondStr, 290, InterFont(66), whiteColor()); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintForceStop(QPainter &p) { - p.save(); - - QRect forceStopRect(QPoint(setSpeedRect.right() + UI_BORDER_SIZE, setSpeedRect.top()), QSize(defaultSize.width() * 1.25, defaultSize.width() * 1.25)); - - p.setOpacity(1.0); - - QRect cscRect(forceStopRect.topLeft() + QPoint(0, forceStopRect.height() + 10), QSize(forceStopRect.width(), 100)); - p.setBrush(redColor(166)); - p.setFont(InterFont(45, QFont::Bold)); - p.setPen(QPen(QColor(255, 150, 150), 10)); - p.drawRoundedRect(cscRect, 24, 24); - p.setPen(QPen(whiteColor(), 6)); - p.drawText(cscRect.adjusted(20, 0, 0, 0), Qt::AlignVCenter | Qt::AlignLeft, - QString::number(std::nearbyint(forcingStopLength * distanceConversion)) + leadDistanceUnit); - - QPixmap &activeIcon = stopSignConfirmed ? forceStopDashImg : forceStopImg; - QSize imgSize = activeIcon.size(); - QPoint imgPoint(forceStopRect.x() + (forceStopRect.width() - imgSize.width()) / 2, - forceStopRect.y() + (forceStopRect.height() - imgSize.height()) / 2); - p.drawPixmap(imgPoint, activeIcon); - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintStoppingPoint(QPainter &p) { - p.save(); - - QPointF centerPoint = (track_vertices.first() + track_vertices.last()) / 2.0f; - QPointF stopSignPosition = centerPoint - QPointF(stopSignImg.width() / 2.0f, stopSignImg.height()); - p.drawPixmap(stopSignPosition, stopSignImg); - - if (cachedShowStoppingPointMetrics) { - float distance = stoppingDistance * distanceConversion; - QString distanceText = QString::number(std::nearbyint(distance)) + leadDistanceUnit; - - QFont font = InterFont(45, QFont::DemiBold); - QFontMetrics fm(font); - - QPointF textPosition(centerPoint.x() - fm.horizontalAdvance(distanceText) / 2.0f, centerPoint.y() - stopSignImg.height() - fm.ascent()); - - QPainterPath path; - path.addText(textPosition, font, distanceText); - p.strokePath(path, QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - - p.setFont(font); - p.setPen(whiteColor()); - p.drawText(textPosition, distanceText); - } - - p.restore(); -} - -void StarPilotAnnotatedCameraWidget::paintTurnSignals(QPainter &p) { - int frameIndex = qBound(0, animationFrameIndex, totalFrames - 1); - - bool blindspotActive = blinkerLeft ? blindspotLeft : blindspotRight; - - int signalXPosition = 0; - int signalYPosition = 0; - - if (signalStyle == "static") { - signalXPosition = blinkerLeft ? (rect().center().x() * 0.75) - signalWidth : rect().center().x() * 1.25; - signalYPosition = signalHeight / 2; - } else { - if (signalStyle == "traditional_gif") { - signalXPosition = blinkerLeft ? width() - (frameIndex * signalMovement) + signalWidth : (frameIndex * signalMovement) - signalWidth; - } else { - signalXPosition = blinkerLeft ? width() - ((frameIndex + 1) * signalWidth) : frameIndex * signalWidth; - } - signalYPosition = height() - signalHeight - alertHeight; - } - - if (blinkerLeft) { - QPixmap &imgToDraw = (blindspotActive && !blindspotImages.empty()) ? blindspotImages[0] : signalImages[frameIndex]; - p.drawPixmap(signalXPosition, signalYPosition, signalWidth, signalHeight, imgToDraw); - } else { - QPixmap &imgToDraw = (blindspotActive && !blindspotImagesRight.empty()) ? blindspotImagesRight[0] : signalImagesRight[frameIndex]; - p.drawPixmap(signalXPosition, signalYPosition, signalWidth, signalHeight, imgToDraw); - } -} - -void StarPilotAnnotatedCameraWidget::paintWeather(QPainter &p) { - if (weatherId == 0) { - return; - } - - p.save(); - - QPoint weatherIconPosition; - if (compassPosition != QPoint(0, 0)) { - weatherIconPosition = compassPosition; - weatherIconPosition.rx() += (rightHandDM ? UI_BORDER_SIZE + widget_size + UI_BORDER_SIZE : -UI_BORDER_SIZE - widget_size - UI_BORDER_SIZE); - } else { - weatherIconPosition.rx() = rightHandDM ? UI_BORDER_SIZE + widget_size / 2 : width() - UI_BORDER_SIZE - btn_size; - weatherIconPosition.ry() = dmIconPosition.y() - widget_size / 2; - } - - QRect weatherRect(weatherIconPosition, QSize(widget_size, widget_size)); - - p.setBrush(blackColor(166)); - p.setPen(QPen(blackColor(), 10)); - p.drawRoundedRect(weatherRect, 24, 24); - - QSharedPointer icon = weatherDaytime ? weatherClearDay : weatherClearNight; - if ((weatherId >= 200 && weatherId <= 232) || (weatherId >= 300 && weatherId <= 321) || (weatherId >= 500 && weatherId <= 531)) { - icon = weatherRain; - } else if (weatherId >= 600 && weatherId <= 622) { - icon = weatherSnow; - } else if (weatherId >= 701 && weatherId <= 762) { - icon = weatherLowVisibility; - } - - p.drawPixmap(weatherRect, icon->currentPixmap()); - - p.restore(); -} diff --git a/starpilot/ui/qt/onroad/starpilot_annotated_camera.h b/starpilot/ui/qt/onroad/starpilot_annotated_camera.h deleted file mode 100644 index 4d779c301..000000000 --- a/starpilot/ui/qt/onroad/starpilot_annotated_camera.h +++ /dev/null @@ -1,216 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -const int widget_size = img_size + (UI_BORDER_SIZE / 2); - -class StarPilotAnnotatedCameraWidget : public QWidget { - Q_OBJECT - -public: - explicit StarPilotAnnotatedCameraWidget(QWidget *parent = 0); - - void mousePressEvent(QMouseEvent *mouseEvent) override; - void paintAdjacentPaths(QPainter &p); - void paintBlindSpotPath(QPainter &p); - void paintStarPilotWidgets(QPainter &p, UIState &s, bool hideCameraOverlays = false); - void paintLeadMetrics(QPainter &p, bool adjacent, QPointF *chevron, const cereal::RadarState::LeadData::Reader &lead_data); - void paintPathEdges(QPainter &p, int height); - void paintRainbowPath(QPainter &p, QLinearGradient &bg, float lin_grad_point); - void updateState(const UIState &s, const StarPilotUIState &fs); - - bool hideBottomIcons; - bool isCruiseSet; - bool rightHandDM; - - int alertHeight; - int speedLimitHeight; - int standstillDuration; - - float speed; - - std::vector radar_tracks; - - StarPilotUIScene starpilot_scene; - - QColor blueColor(int alpha = 255) { return QColor(0, 0, 255, alpha); } - QColor purpleColor(int alpha = 255) { return QColor(128, 0, 128, alpha); } - QColor whiteColor(int alpha = 255) { return QColor(255, 255, 255, alpha); } - - QJsonObject starpilot_toggles; - - QPoint dmIconPosition; - QPoint experimentalButtonPosition; - - QPolygonF track_adjacent_vertices[2]; - QPolygonF track_edge_vertices; - QPolygonF track_vertices; - - QRect adjacentLeadTextRect; - QRect leadTextRect; - QRect setSpeedRect; - - QSize defaultSize; - - QString signalStyle; - -protected: - void showEvent(QShowEvent *event) override; - -private: - void paintCEMStatus(QPainter &p); - void paintCompass(QPainter &p); - void paintCurveSpeedControl(QPainter &p); - void paintCurveSpeedControlTraining(QPainter &p); - void paintLateralPaused(QPainter &p); - void paintLongitudinalPaused(QPainter &p); - void paintPedalIcons(QPainter &p); - void paintRadarTracks(QPainter &p); - void paintRoadName(QPainter &p); - void paintSpeedLimit(QPainter &p); - void paintSpeedLimitSources(QPainter &p); - void paintStandstillTimer(QPainter &p); - void paintForceStop(QPainter &p); - void paintStoppingPoint(QPainter &p); - void paintTurnSignals(QPainter &p); - void paintWeather(QPainter &p); - void updateSignals(); - - bool blindspotLeft; - bool blindspotRight; - bool blinkerLeft; - bool blinkerRight; - bool brakeLights; - bool cscControllingSpeed; - bool forcingStop; - bool stopSignConfirmed; - bool cscTraining; - bool experimentalMode; - bool forceCoast; - bool lateralPaused; - bool longitudinalPaused; - bool redLight; - bool speedLimitChanged; - bool unconfirmedSpeedLimitValid = false; - bool weatherDaytime; - - // Cached toggle values — refreshed once per updateState(), used in paint code - bool cachedAdjacentPathMetrics = false; - bool cachedBlindSpotPath = false; - bool cachedCemStatus = false; - bool cachedCompass = false; - bool cachedCscStatus = false; - bool cachedDynamicPedalsOnUi = false; - bool cachedHideSpeedLimit = false; - bool cachedOpenpilotLongitudinal = false; - bool cachedPedalsOnUi = false; - bool cachedRadarTracks = false; - bool cachedRoadNameUi = false; - bool cachedShowSpeedLimitOffset = false; - bool cachedShowSpeedLimits = false; - bool cachedShowStoppingPoint = false; - bool cachedShowStoppingPointMetrics = false; - bool cachedSimpleMode = false; - bool cachedSpeedLimitController = false; - bool cachedSpeedLimitSources = false; - bool cachedSlcAbbreviatedSources = false; - bool cachedSlcActiveSourcesOnly = false; - bool cachedSpeedLimitVienna = false; - bool cachedStaticPedalsOnUi = false; - bool cachedStoppedTimer = false; - double cachedLaneDetectionWidth = 3.7; - QString cachedColorScheme; - QString cachedPathEdgesColor; - QString cachedSignalIcons; - - int animationFrameIndex; - int desiredFollowDistance; - int frogHopCount; - int signalAnimationLength; - int signalHeight; - int signalMovement; - int signalWidth; - int totalFrames; - int weatherId; - - float accelerationEgo; - float cscSpeed; - float forcingStopLength; - float dashboardSpeedLimit; - float distanceConversion; - float laneWidthLeft; - float laneWidthRight; - float mapSpeedLimit; - float mapboxSpeedLimit; - float nextSpeedLimit; - float roadCurvature; - float setSpeed; - float slcOverriddenSpeed; - float speedConversion; - float speedConversionMetrics; - float speedLimit; - float stoppingDistance; - float unconfirmedSpeedLimit; - float visionSpeedLimit; - - std::string speedLimitSource; - - Params params; - Params params_memory{"", true}; - - QColor blackColor(int alpha = 255) { return QColor(0, 0, 0, alpha); } - QColor redColor(int alpha = 255) { return QColor(201, 34, 49, alpha); } - - QElapsedTimer glowTimer; - QElapsedTimer pendingLimitTimer; - QElapsedTimer standstillTimer; - - QPixmap brakePedalImg; - QPixmap curveSpeedIcon; - QPixmap curveSpeedIconFlipped; - QPixmap dashboardIcon; - QPixmap gasPedalImg; - QPixmap mapboxIcon; - QPixmap mapDataIcon; - QPixmap nextMapsIcon; - QPixmap pausedIcon; - QPixmap speedIcon; - QPixmap forceStopDashImg; - QPixmap forceStopImg; - QPixmap stopSignImg; - QPixmap turnIcon; - QPixmap visionIcon; - - QPoint cemStatusPosition; - QPoint compassPosition; - QPoint lateralPausedPosition; - - QRect speedLimitRect; - - QSharedPointer cemCurveIcon; - QSharedPointer cemLeadIcon; - QSharedPointer cemSpeedIcon; - QSharedPointer cemStopIcon; - QSharedPointer cemTurnIcon; - QSharedPointer chillModeIcon; - QSharedPointer experimentalModeIcon; - QSharedPointer weatherClearDay; - QSharedPointer weatherClearNight; - QSharedPointer weatherLowVisibility; - QSharedPointer weatherRain; - QSharedPointer weatherSnow; - - QString leadDistanceUnit; - QString leadSpeedUnit; - QString roadName; - QString speedLimitOffsetStr; - QString speedUnit; - - QTimer *animationTimer; - - QVector blindspotImages; - QVector blindspotImagesRight; - QVector signalImages; - QVector signalImagesRight; -}; diff --git a/starpilot/ui/qt/onroad/starpilot_buttons.cc b/starpilot/ui/qt/onroad/starpilot_buttons.cc deleted file mode 100644 index e69415de5..000000000 --- a/starpilot/ui/qt/onroad/starpilot_buttons.cc +++ /dev/null @@ -1,241 +0,0 @@ -#include "starpilot/ui/qt/onroad/starpilot_buttons.h" - -#include -#include -#include -#include -#include -#include - -namespace { -constexpr int favorite_btn_size = btn_size; -constexpr int favorite_indicator_size = 22; -constexpr int favorite_slots_count = 3; -const QString favorite_action_decrease = "__starpilot_favorite_action__:distance_decrease"; -const QString favorite_action_increase = "__starpilot_favorite_action__:distance_increase"; -const std::string favorite_action_decel_counter = "FavoriteVirtualDecelCruiseCounter"; -const std::string favorite_action_accel_counter = "FavoriteVirtualAccelCruiseCounter"; - -QJsonArray parseFavoriteSlots(const std::string &raw_slots) { - QJsonParseError error; - const QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(raw_slots), &error); - if (error.error != QJsonParseError::NoError || !doc.isArray()) { - return QJsonArray(); - } - return doc.array(); -} -} // namespace - -DrivingPersonalityButton::DrivingPersonalityButton(QWidget *parent) : QPushButton(parent) { - setFixedSize(btn_size + UI_BORDER_SIZE, btn_size); - - QObject::connect(starpilotUIState(), &StarPilotUIState::themeUpdated, this, &DrivingPersonalityButton::updateTheme); - QObject::connect(this, &QPushButton::pressed, [this] {params_memory.putBool("OnroadDistanceButtonPressed", true);}); - QObject::connect(this, &QPushButton::released, [this] {params_memory.putBool("OnroadDistanceButtonPressed", false);}); -} - -void DrivingPersonalityButton::showEvent(QShowEvent *event) { - updateTheme(); -} - -void DrivingPersonalityButton::updateTheme() { - for (QMap>>::iterator it = icon_map.begin(); it != icon_map.end(); ++it) { - QSharedPointer &movie = it.value().second; - if (!movie.isNull()) { - QObject::disconnect(movie.data(), nullptr, this, nullptr); - movie->stop(); - } - } - - icon_map.clear(); - - QPixmap traffic_img, aggressive_img, standard_img, relaxed_img; - QSharedPointer traffic_gif, aggressive_gif, standard_gif, relaxed_gif; - - loadImage("../../starpilot/assets/active_theme/distance_icons/traffic", traffic_img, traffic_gif, QSize(btn_size, btn_size), this); - loadImage("../../starpilot/assets/active_theme/distance_icons/aggressive", aggressive_img, aggressive_gif, QSize(btn_size, btn_size), this); - loadImage("../../starpilot/assets/active_theme/distance_icons/standard", standard_img, standard_gif, QSize(btn_size, btn_size), this); - loadImage("../../starpilot/assets/active_theme/distance_icons/relaxed", relaxed_img, relaxed_gif, QSize(btn_size, btn_size), this); - - icon_map.insert(0, qMakePair(traffic_img, traffic_gif)); - icon_map.insert(1, qMakePair(aggressive_img, aggressive_gif)); - icon_map.insert(2, qMakePair(standard_img, standard_gif)); - icon_map.insert(3, qMakePair(relaxed_img, relaxed_gif)); - - theme_updated = true; -} - -void DrivingPersonalityButton::updateState(const UIState &s, const StarPilotUIState &fs) { - const UIScene &scene = s.scene; - - const SubMaster &fpsm = *(fs.sm); - - const cereal::StarPilotCarState::Reader &starpilotCarState = fpsm["starpilotCarState"].getStarpilotCarState(); - - bool new_traffic_mode_active = starpilotCarState.getTrafficModeEnabled(); - - int new_personality = static_cast(scene.personality) + 1; - - bool state_changed = (traffic_mode_active != new_traffic_mode_active) || - (personality != new_personality && !new_traffic_mode_active); - - if (!state_changed && !theme_updated) { - return; - } - - traffic_mode_active = new_traffic_mode_active; - - personality = new_personality; - - theme_updated = false; - - QPair> icon = icon_map.value(traffic_mode_active ? 0 : personality); - currentImg = icon.first; - currentGif = icon.second.data(); -} - -void DrivingPersonalityButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - drawIcon(p, rect().center() + QPoint(UI_BORDER_SIZE / 2, 0), currentGif ? currentGif->currentPixmap() : currentImg, Qt::transparent, 1.0); -} - -FavoriteButton::FavoriteButton(int slot_index, QWidget *parent) : QPushButton(parent), slot_index(slot_index) { - setFixedSize(favorite_btn_size, favorite_btn_size); - QObject::connect(this, &QPushButton::clicked, this, &FavoriteButton::toggleFavorite); -} - -FavoriteSlotState FavoriteButton::currentSlot() { - FavoriteSlotState next_slot; - if (slot_index < 0 || slot_index >= favorite_slots_count) { - return next_slot; - } - - const QJsonArray favorite_slots = parseFavoriteSlots(params.get("StarPilotFavoriteSlots")); - if (slot_index >= favorite_slots.size() || !favorite_slots.at(slot_index).isObject()) { - return next_slot; - } - - const QJsonObject slot_obj = favorite_slots.at(slot_index).toObject(); - next_slot.enabled = slot_obj.value("enabled").toBool(false); - next_slot.show_onroad = slot_obj.value("show_onroad").toBool(false); - next_slot.key = slot_obj.value("key").toString().trimmed(); - next_slot.label = slot_obj.value("label").toString().trimmed(); - next_slot.action = next_slot.key == favorite_action_decrease || next_slot.key == favorite_action_increase; - - if (!next_slot.action && - (next_slot.key.isEmpty() || !params.checkKey(next_slot.key.toStdString()) || params.getKeyType(next_slot.key.toStdString()) != ParamKeyType::BOOL)) { - next_slot.enabled = false; - next_slot.show_onroad = false; - next_slot.key.clear(); - next_slot.label.clear(); - return next_slot; - } - - if (next_slot.label.isEmpty() && next_slot.action) { - next_slot.label = next_slot.key == favorite_action_increase ? "Distance + / RES" : "Distance - / SET"; - } else if (next_slot.label.isEmpty()) { - next_slot.label = next_slot.key; - } - next_slot.value = !next_slot.action && params.getBool(next_slot.key.toStdString()); - return next_slot; -} - -void FavoriteButton::updateState() { - const FavoriteSlotState next_slot = currentSlot(); - const bool changed = next_slot.enabled != slot.enabled || - next_slot.show_onroad != slot.show_onroad || - next_slot.action != slot.action || - next_slot.value != slot.value || - next_slot.key != slot.key || - next_slot.label != slot.label; - slot = next_slot; - setVisible(shouldShow()); - if (changed) { - update(); - } -} - -bool FavoriteButton::shouldShow() const { - return slot.enabled && slot.show_onroad && !slot.key.isEmpty(); -} - -void FavoriteButton::toggleFavorite() { - slot = currentSlot(); - if (!slot.enabled || slot.key.isEmpty()) { - return; - } - - if (slot.action) { - const std::string counter_key = slot.key == favorite_action_increase ? favorite_action_accel_counter : favorite_action_decel_counter; - params_memory.putInt(counter_key, params_memory.getInt(counter_key) + 1); - update(); - return; - } - - const bool next_value = !params.getBool(slot.key.toStdString()); - params.putBool(slot.key.toStdString(), next_value); - params_memory.putBool("StarPilotTogglesUpdated", true); - slot.value = next_value; - update(); -} - -QFont FavoriteButton::fittedLabelFont(QPainter &p, const QString &label, const QRect &text_rect) const { - QFont font = p.font(); - font.setWeight(QFont::DemiBold); - font.setLetterSpacing(QFont::AbsoluteSpacing, 0); - - for (int font_size = 28; font_size >= 18; --font_size) { - font.setPixelSize(font_size); - const QFontMetrics metrics(font); - const QRect bounds = metrics.boundingRect(text_rect, Qt::AlignCenter | Qt::TextWordWrap, label); - if (bounds.width() <= text_rect.width() && bounds.height() <= text_rect.height()) { - return font; - } - } - - font.setPixelSize(18); - return font; -} - -void FavoriteButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - const QRectF bg_rect = rect().adjusted(0, 0, -1, -1); - QPainterPath bg_path; - bg_path.addRoundedRect(bg_rect, 12, 12); - p.fillPath(bg_path, QColor(0, 0, 0, isDown() ? 190 : 166)); - p.setPen(QPen(QColor(255, 255, 255, isDown() ? 130 : 95), 2)); - p.drawPath(bg_path); - - const QColor indicator_color = slot.action ? QColor(139, 108, 197) : (slot.value ? QColor(48, 255, 156) : QColor(135, 135, 135)); - const int indicator_x = width() - 20 - favorite_indicator_size; - const int indicator_y = 20; - p.setPen(Qt::NoPen); - p.setBrush(indicator_color); - p.drawEllipse(indicator_x, indicator_y, favorite_indicator_size, favorite_indicator_size); - if (slot.action) { - QFont action_font = p.font(); - action_font.setPixelSize(20); - action_font.setWeight(QFont::DemiBold); - p.setFont(action_font); - p.setPen(QColor(255, 255, 255, 230)); - p.drawText(QRect(indicator_x, indicator_y - 1, favorite_indicator_size, favorite_indicator_size), Qt::AlignCenter, slot.key == favorite_action_increase ? "+" : "-"); - } - - QFont slot_font = p.font(); - slot_font.setPixelSize(20); - slot_font.setWeight(QFont::DemiBold); - slot_font.setLetterSpacing(QFont::AbsoluteSpacing, 0); - p.setFont(slot_font); - p.setPen(QColor(255, 255, 255, 175)); - p.drawText(QRect(18, 14, 54, 32), Qt::AlignLeft | Qt::AlignVCenter, QString("#%1").arg(slot_index + 1)); - - const QString label = slot.label.isEmpty() ? QStringLiteral("Favorite") : slot.label; - const QRect text_rect(14, 50, width() - 28, height() - 64); - p.setFont(fittedLabelFont(p, label, text_rect)); - p.setPen(QColor(255, 255, 255, 245)); - p.drawText(text_rect, Qt::AlignCenter | Qt::TextWordWrap, label); -} diff --git a/starpilot/ui/qt/onroad/starpilot_buttons.h b/starpilot/ui/qt/onroad/starpilot_buttons.h deleted file mode 100644 index f6bacd9c8..000000000 --- a/starpilot/ui/qt/onroad/starpilot_buttons.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/qt/onroad/buttons.h" - -struct FavoriteSlotState { - bool enabled = false; - bool show_onroad = false; - bool action = false; - bool value = false; - QString key; - QString label; -}; - -class DrivingPersonalityButton : public QPushButton { - Q_OBJECT - -public: - explicit DrivingPersonalityButton(QWidget *parent = 0); - - void updateState(const UIState &s, const StarPilotUIState &fs); - -private: - void paintEvent(QPaintEvent *event) override; - void showEvent(QShowEvent *event) override; - void updateTheme(); - - bool theme_updated; - bool traffic_mode_active; - - int personality; - - Params params_memory{"", true}; - - QMap>> icon_map; - - QMovie *currentGif; - - QPixmap currentImg; -}; - -class FavoriteButton : public QPushButton { -public: - explicit FavoriteButton(int slot_index, QWidget *parent = 0); - - void updateState(); - bool shouldShow() const; - -private: - void paintEvent(QPaintEvent *event) override; - void toggleFavorite(); - - FavoriteSlotState currentSlot(); - QFont fittedLabelFont(QPainter &p, const QString &label, const QRect &text_rect) const; - - int slot_index; - FavoriteSlotState slot; - - Params params; - Params params_memory{"", true}; -}; diff --git a/starpilot/ui/qt/onroad/starpilot_onroad.cc b/starpilot/ui/qt/onroad/starpilot_onroad.cc deleted file mode 100644 index 745ca155b..000000000 --- a/starpilot/ui/qt/onroad/starpilot_onroad.cc +++ /dev/null @@ -1,155 +0,0 @@ -#include "starpilot/ui/qt/onroad/starpilot_onroad.h" - -StarPilotOnroadWindow::StarPilotOnroadWindow(QWidget *parent) : QWidget(parent) { - signalTimer = new QTimer(this); - QObject::connect(signalTimer, &QTimer::timeout, [this] { - flickerActive = !flickerActive; - }); -} - -void StarPilotOnroadWindow::resizeEvent(QResizeEvent *event) { - rect = QWidget::rect(); - marginRegion = QRegion(rect) - QRegion(rect.marginsRemoved(QMargins(UI_BORDER_SIZE, UI_BORDER_SIZE, UI_BORDER_SIZE, UI_BORDER_SIZE))); - - steeringGradient = QLinearGradient(rect.topLeft(), rect.bottomLeft()); - QColor bottomGreen = bg_colors[STATUS_ENGAGED].lighter(120); - bottomGreen.setAlpha(bg_colors[STATUS_ENGAGED].alpha()); - steeringGradient.setColorAt(0.0, bg_colors[STATUS_TRAFFIC_MODE_ENABLED]); - steeringGradient.setColorAt(0.25, bg_colors[STATUS_EXPERIMENTAL_MODE_ENABLED]); - steeringGradient.setColorAt(0.5, bg_colors[STATUS_CEM_DISABLED]); - steeringGradient.setColorAt(0.75, bg_colors[STATUS_ENGAGED]); - steeringGradient.setColorAt(1.0, bottomGreen); -} - -void StarPilotOnroadWindow::updateState(const UIState &s, const StarPilotUIState &fs) { - const SubMaster &sm = *(s.sm); - const SubMaster &fpsm = *(fs.sm); - - const cereal::CarState::Reader &carState = sm["carState"].getCarState(); - const cereal::CarControl::Reader &carControl = fpsm["carControl"].getCarControl(); - - blindSpotLeft = carState.getLeftBlindspot(); - blindSpotRight = carState.getRightBlindspot(); - torque = -carControl.getActuators().getTorque(); - turnSignalLeft = carState.getLeftBlinker(); - turnSignalRight = carState.getRightBlinker(); - - showBlindspot = (blindSpotLeft || blindSpotRight) && starpilot_toggles.value("blind_spot_metrics").toBool(); - showFPS = starpilot_toggles.value("show_fps").toBool(); - showSignal = (turnSignalLeft || turnSignalRight) && starpilot_toggles.value("signal_metrics").toBool(); - showSteering = starpilot_toggles.value("steering_metrics").toBool(); - - if (showSteering) { - float absTorque = std::abs(torque); - smoothedSteer = 0.25f * absTorque + 0.75f * smoothedSteer; - if (std::abs(smoothedSteer - absTorque) < 0.01f) { - smoothedSteer = absTorque; - } - } - - if (showBlindspot || showSignal) { - std::function getBorderColor = [&](bool blindSpot, bool turnSignal) { - if (turnSignal && showSignal) { - if (blindSpot) { - return flickerActive ? bg_colors[STATUS_TRAFFIC_MODE_ENABLED] : bg_colors[STATUS_CEM_DISABLED]; - } else { - return flickerActive ? bg_colors[STATUS_CEM_DISABLED] : bg; - } - } else if (blindSpot && showBlindspot) { - return bg_colors[STATUS_TRAFFIC_MODE_ENABLED]; - } else { - return bg; - } - }; - - leftBorderColor = getBorderColor(blindSpotLeft, turnSignalLeft); - rightBorderColor = getBorderColor(blindSpotRight, turnSignalRight); - - int interval = showBlindspot ? 250 : 500; - if (!signalTimer->isActive() || signalTimer->interval() != interval) { - signalTimer->start(interval); - } - } else if (signalTimer->isActive()) { - signalTimer->stop(); - } - - if (showFPS) { - static float avgFPS = 0.0f; - static float maxFPS = 0.0f; - static float minFPS = 99.9f; - - if (avgFPS == 0.0f) { - avgFPS = fps; - } - - static float alpha = 1.0f / (UI_FREQ * 60.0f); - avgFPS = alpha * fps + (1.0f - alpha) * avgFPS; - - minFPS = std::min(minFPS, fps); - maxFPS = std::max(maxFPS, fps); - - fpsDisplayString = QString("FPS: %1 | Min: %2 | Max: %3 | Avg: %4") - .arg(qRound(fps)) - .arg(qRound(minFPS)) - .arg(qRound(maxFPS)) - .arg(qRound(avgFPS)); - } - - if (showBlindspot || showSignal || showSteering || showFPS) { - update(); - } -} - -void StarPilotOnroadWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - - p.setClipRegion(marginRegion); - p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); - - if (showSteering) { - paintSteeringTorqueBorder(p); - } - - if (showBlindspot || showSignal) { - paintTurnSignalBorder(p); - } - - if (showFPS) { - paintFPS(p); - } -} - -void StarPilotOnroadWindow::paintFPS(QPainter &p) { - p.save(); - - p.setFont(InterFont(28, QFont::DemiBold)); - p.setPen(Qt::white); - - int xPos = (rect.width() - p.fontMetrics().horizontalAdvance(fpsDisplayString)) / 2; - int yPos = rect.bottom() - 5; - - p.drawText(xPos, yPos, fpsDisplayString); - - p.restore(); -} - -void StarPilotOnroadWindow::paintSteeringTorqueBorder(QPainter &p) { - p.save(); - - int visibleHeight = rect.height() * smoothedSteer; - int xPos = (torque < 0) ? rect.x() : (rect.x() + rect.width() - UI_BORDER_SIZE); - int yPos = rect.y() + rect.height() - visibleHeight; - - p.fillRect(QRect(xPos, yPos, UI_BORDER_SIZE, visibleHeight), steeringGradient); - - p.restore(); -} - -void StarPilotOnroadWindow::paintTurnSignalBorder(QPainter &p) { - p.save(); - - p.fillRect(rect.x(), rect.y(), rect.width() / 2, rect.height(), leftBorderColor); - p.fillRect(rect.x() + rect.width() / 2, rect.y(), rect.width() / 2, rect.height(), rightBorderColor); - - p.restore(); -} diff --git a/starpilot/ui/qt/onroad/starpilot_onroad.h b/starpilot/ui/qt/onroad/starpilot_onroad.h deleted file mode 100644 index 541f09d89..000000000 --- a/starpilot/ui/qt/onroad/starpilot_onroad.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -class StarPilotOnroadWindow : public QWidget { - Q_OBJECT - -public: - StarPilotOnroadWindow(QWidget* parent = 0); - - void updateState(const UIState &s, const StarPilotUIState &fs); - - float fps; - - StarPilotUIScene starpilot_scene; - - QColor bg; - - QJsonObject starpilot_toggles; - -private: - void paintEvent(QPaintEvent *event); - void paintFPS(QPainter &p); - void paintSteeringTorqueBorder(QPainter &p); - void paintTurnSignalBorder(QPainter &p); - void resizeEvent(QResizeEvent *event); - - bool blindSpotLeft; - bool blindSpotRight; - bool flickerActive; - bool showBlindspot; - bool showFPS; - bool showSignal; - bool showSteering; - bool turnSignalLeft; - bool turnSignalRight; - - float smoothedSteer; - float torque; - - QColor leftBorderColor; - QColor rightBorderColor; - - QRect rect; - QLinearGradient steeringGradient; - - QRegion marginRegion; - - QString fpsDisplayString; - - QTimer *signalTimer; -}; diff --git a/starpilot/ui/qt/widgets/developer_sidebar.cc b/starpilot/ui/qt/widgets/developer_sidebar.cc deleted file mode 100644 index 91f112000..000000000 --- a/starpilot/ui/qt/widgets/developer_sidebar.cc +++ /dev/null @@ -1,338 +0,0 @@ -#include "starpilot/ui/qt/widgets/developer_sidebar.h" - -#include -#include - -#include -#include -#include -#include - -namespace { - -const QColor LOCKED_VALUE_COLOR = QColor(34, 197, 94); -const QColor AUTO_TUNE_COLOR = QColor(59, 130, 246); -const QColor FLM_OVERRIDE_COLOR = QColor(239, 68, 68); - -bool settingChanged(float value, float reference) { - return std::round(value * 100.0f) != std::round(reference * 100.0f); -} - -bool toggleBool(const QJsonObject &toggles, const QString &key, bool fallback = false) { - return toggles.contains(key) ? toggles.value(key).toBool(fallback) : fallback; -} - -float toggleFloat(const QJsonObject &toggles, const QString &key, float fallback = 0.0f) { - return toggles.contains(key) ? static_cast(toggles.value(key).toDouble(fallback)) : fallback; -} - -float resolveEffectiveTorqueValue(bool customEnabled, float customValue, - bool liveEnabled, float liveValue, - float stockValue, float configuredValue) { - if (customEnabled) { - return customValue; - } - if (liveEnabled) { - return liveValue; - } - return stockValue != 0.0f ? stockValue : configuredValue; -} - -QSet readFlmGenericParamKeys(Params ¶ms) { - QSet keys; - const std::string raw = params.get("FLMTrialBaseline"); - if (raw.empty()) { - return keys; - } - - QJsonParseError error; - const QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(raw), &error); - if (error.error != QJsonParseError::NoError || !doc.isObject()) { - return keys; - } - - const QJsonObject appliedParams = doc.object().value("appliedGenericParams").toObject(); - for (const QString &key : appliedParams.keys()) { - keys.insert(key); - } - return keys; -} - -bool flmChanged(const QSet &keys, std::initializer_list names) { - for (const char *name : names) { - if (keys.contains(QString::fromUtf8(name))) { - return true; - } - } - return false; -} - -QColor tuningColor(bool autoTune, bool flm) { - if (flm) { - return FLM_OVERRIDE_COLOR; - } - return autoTune ? AUTO_TUNE_COLOR : LOCKED_VALUE_COLOR; -} - -} // namespace - -void DeveloperSidebar::drawMetric(QPainter &p, const QPair &label, QColor c, int y) { - const QRect rect = {12, y, 275, 126}; - - p.setPen(Qt::NoPen); - p.setBrush(QBrush(c)); - p.setClipRect(rect.x() + rect.width() - 4 - 18, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); - p.drawRoundedRect(QRect(rect.x() + rect.width() - 4 - 100, rect.y() + 4, 100, 118), 18, 18); - p.setClipping(false); - - QPen pen = QPen(QColor(0xff, 0xff, 0xff, 0x55)); - pen.setWidth(2); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRoundedRect(rect, 20, 20); - - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setFont(InterFont(35, QFont::DemiBold)); - if (label.second.isEmpty()) { - p.drawText(rect.adjusted(8, 8, -22, -8), Qt::AlignCenter | Qt::TextWordWrap, label.first); - } else { - p.drawText(rect.adjusted(8, 8, -22, -8), Qt::AlignCenter, label.first + "\n" + label.second); - } -} - -DeveloperSidebar::DeveloperSidebar(QWidget *parent) : QFrame(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - setFixedWidth(300); - - QObject::connect(starpilotUIState(), &StarPilotUIState::themeUpdated, this, &DeveloperSidebar::updateToggles); - QObject::connect(uiState(), &UIState::offroadTransition, this, &DeveloperSidebar::resetVariables); - QObject::connect(uiState(), &UIState::uiUpdate, this, &DeveloperSidebar::updateState); -} - -void DeveloperSidebar::showEvent(QShowEvent *event) { - updateToggles(); -} - -void DeveloperSidebar::updateToggles() { - StarPilotUIState &fs = *starpilotUIState(); - StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - - metricAssignments.clear(); - for (int i = 1; i <= 7; ++i) { - QString key = QString("developer_sidebar_metric%1").arg(i); - int metricId = starpilot_toggles.value(key).toInt(); - metricAssignments.push_back(metricId); - } - - metricColor = QColor(starpilot_toggles.value("sidebar_color1").toString()); -} - -void DeveloperSidebar::resetVariables() { - lateralEngagementTime = 0; - longitudinalEngagementTime = 0; - maxAcceleration = 0; - totalEngagementTime = 0; -} - -void DeveloperSidebar::updateState(const UIState &s, const StarPilotUIState &fs) { - if (!isVisible()) { - return; - } - - const SubMaster &sm = *(s.sm); - - const StarPilotUIScene &starpilot_scene = fs.starpilot_scene; - const QJsonObject &starpilot_toggles = starpilot_scene.starpilot_toggles; - const SubMaster &fpsm = *(fs.sm); - - const cereal::CarControl::Reader &carControl = fpsm["carControl"].getCarControl(); - const cereal::CarState::Reader &carState = sm["carState"].getCarState(); - const cereal::StarPilotPlan::Reader &starpilotPlan = fpsm["starpilotPlan"].getStarpilotPlan(); - const cereal::LiveDelayData::Reader &liveDelay = fpsm["liveDelay"].getLiveDelay(); - const cereal::LiveParametersData::Reader &liveParameters = fpsm["liveParameters"].getLiveParameters(); - const cereal::LiveTorqueParametersData::Reader &liveTorqueParameters = fpsm["liveTorqueParameters"].getLiveTorqueParameters(); - const bool forceAutoTuneOff = toggleBool(starpilot_toggles, "force_auto_tune_off", params.getBool("ForceAutoTuneOff")); - const bool forceAutoTune = toggleBool(starpilot_toggles, "force_auto_tune", params.getBool("ForceAutoTune")); - const bool usingLiveTorqueTune = !forceAutoTuneOff && (liveTorqueParameters.getUseParams() || forceAutoTune); - - const bool is_metric = s.scene.is_metric; - const bool use_si = starpilot_toggles.value("use_si_metrics").toBool(); - - const QString accelerationUnit = (is_metric || use_si) ? tr(" m/s²") : tr(" ft/s²"); - const float accelerationConversion = (is_metric || use_si) ? 1.0f : METER_TO_FOOT; - - double acceleration = carState.getAEgo() * accelerationConversion; - if (!carState.getGasPressed()) { - maxAcceleration = std::max(maxAcceleration, acceleration); - } - - lateralEngagementTime += carControl.getLatActive() && !starpilot_scene.reverse && !starpilot_scene.standstill ? 1 : 0; - longitudinalEngagementTime += carControl.getLongActive() && !starpilot_scene.reverse && !starpilot_scene.standstill ? 1 : 0; - totalEngagementTime += !(starpilot_scene.reverse || starpilot_scene.standstill) || totalEngagementTime == 0 ? 1 : 0; - - static int maxSteerAngle = 0; - int currentSteerAngle = fabs(carState.getSteeringAngleDeg()); - - static int maxTorque = 0; - int currentTorque = fabs(carControl.getActuators().getTorque() * 100); - - static QElapsedTimer torqueTimer; - - if (currentTorque >= 50) { - maxSteerAngle = std::max(maxSteerAngle, currentSteerAngle); - maxTorque = std::max(maxTorque, currentTorque); - - torqueTimer.start(); - } else if (torqueTimer.elapsed() >= 10000) { - maxTorque = 0; - maxSteerAngle = 0; - - torqueTimer.invalidate(); - } - - QString steerLabel = QString::number(currentSteerAngle) + "°"; - QString torqueLabel = QString::number(currentTorque) + "%"; - - if (currentTorque >= 50 || torqueTimer.isValid()) { - steerLabel += QString(" - (%1°)").arg(maxSteerAngle); - torqueLabel += QString(" - (%1%)").arg(maxTorque); - } - - const float frictionStock = params.getFloat("SteerFrictionStock"); - const float frictionConfigured = params.getFloat("SteerFriction"); - const float latAccelStock = params.getFloat("SteerLatAccelStock"); - const float latAccelConfigured = params.getFloat("SteerLatAccel"); - const float steerRatioStock = params.getFloat("SteerRatioStock"); - const float steerRatioConfigured = params.getFloat("SteerRatio"); - - const float customFriction = toggleFloat(starpilot_toggles, "friction", frictionConfigured); - const float customLatAccel = toggleFloat(starpilot_toggles, "latAccelFactor", latAccelConfigured); - const bool useCustomFriction = toggleBool(starpilot_toggles, "use_custom_friction", - forceAutoTuneOff || (settingChanged(frictionConfigured, frictionStock) && !forceAutoTune)); - const bool useCustomLatAccel = toggleBool(starpilot_toggles, "use_custom_latAccelFactor", - forceAutoTuneOff || (settingChanged(latAccelConfigured, latAccelStock) && !forceAutoTune)); - - const float displayedFriction = resolveEffectiveTorqueValue( - useCustomFriction, - customFriction, - usingLiveTorqueTune, - liveTorqueParameters.getFrictionCoefficientFiltered(), - frictionStock, - frictionConfigured - ); - const float displayedLatAccel = resolveEffectiveTorqueValue( - useCustomLatAccel, - customLatAccel, - usingLiveTorqueTune, - liveTorqueParameters.getLatAccelFactorFiltered(), - latAccelStock, - latAccelConfigured - ); - - const bool cachedUseAutoDelay = params.get("UseAutoSteerDelay").empty() ? true : params.getBool("UseAutoSteerDelay"); - const bool useAutoSteerDelay = toggleBool(starpilot_toggles, "use_auto_steer_delay", cachedUseAutoDelay); - const bool useCustomDelay = toggleBool(starpilot_toggles, "use_custom_steerActuatorDelay", !useAutoSteerDelay); - const float customDelay = toggleFloat(starpilot_toggles, "steerActuatorDelay", params.getFloat("SteerDelay")); - const float displayedDelay = useCustomDelay ? customDelay : liveDelay.getLateralDelay(); - - const bool useCustomSteerRatio = toggleBool(starpilot_toggles, "use_custom_steerRatio", - forceAutoTuneOff || (settingChanged(steerRatioConfigured, steerRatioStock) && !forceAutoTune)); - const QSet flmGenericParamKeys = params.getBool("FLMTrialApplied") ? readFlmGenericParamKeys(params) : QSet(); - const bool forceAutoTuneFlm = flmChanged(flmGenericParamKeys, {"ForceAutoTune", "ForceAutoTuneOff"}); - const QColor delayColor = tuningColor(!useCustomDelay, flmChanged(flmGenericParamKeys, {"SteerDelay", "UseAutoSteerDelay"})); - const QColor frictionColor = tuningColor( - usingLiveTorqueTune && !useCustomFriction, - flmChanged(flmGenericParamKeys, {"SteerFriction"}) || (forceAutoTuneFlm && (usingLiveTorqueTune || useCustomFriction)) - ); - const QColor latAccelColor = tuningColor( - usingLiveTorqueTune && !useCustomLatAccel, - flmChanged(flmGenericParamKeys, {"SteerLatAccel"}) || (forceAutoTuneFlm && (usingLiveTorqueTune || useCustomLatAccel)) - ); - const QColor steerRatioColor = tuningColor( - !useCustomSteerRatio, - flmChanged(flmGenericParamKeys, {"SteerRatio"}) || (forceAutoTuneFlm && useCustomSteerRatio) - ); - - accelerationStatus = ItemStatus(QPair(tr("ACCEL"), QString::number(acceleration, 'f', 2) + accelerationUnit), metricColor); - accelerationJerkStatus = ItemStatus(QPair(tr("ACCEL JERK"), QString::number(starpilotPlan.getAccelerationJerk())), metricColor); - actuatorAccelerationStatus = ItemStatus(QPair(tr("ACT ACCEL"), QString::number(carControl.getActuators().getAccel() * accelerationConversion, 'f', 2) + accelerationUnit), metricColor); - dangerFactorStatus = ItemStatus(QPair(tr("DANGER %"), QString::number(starpilotPlan.getDangerFactor() * 100.0f, 'f', 2) + "%"), metricColor); - dangerJerkStatus = ItemStatus(QPair(tr("DANGER JERK"), QString::number(starpilotPlan.getDangerJerk())), metricColor); - delayStatus = ItemStatus(QPair(tr("STEER DELAY"), QString::number(displayedDelay, 'f', 5)), delayColor); - frictionStatus = ItemStatus(QPair(tr("FRICTION"), QString::number(displayedFriction, 'f', 5)), frictionColor); - latAccelStatus = ItemStatus(QPair(tr("LAT ACCEL"), QString::number(displayedLatAccel, 'f', 5)), latAccelColor); - lateralEngagementStatus = ItemStatus(QPair(tr("LATERAL %"), QString::number((lateralEngagementTime / totalEngagementTime) * 100.0f, 'f', 2) + "%"), metricColor); - longitudinalEngagementStatus = ItemStatus(QPair(tr("LONG %"), QString::number((longitudinalEngagementTime / totalEngagementTime) * 100.0f, 'f', 2) + "%"), metricColor); - maxAccelerationStatus = ItemStatus(QPair(tr("MAX ACCEL"), QString::number(maxAcceleration, 'f', 2) + accelerationUnit), metricColor); - speedJerkStatus = ItemStatus(QPair(tr("SPEED JERK"), QString::number(starpilotPlan.getSpeedJerk())), metricColor); - steerAngleStatus = ItemStatus(QPair(tr("STEER ANGLE"), steerLabel), metricColor); - steerRatioStatus = ItemStatus(QPair(tr("STEER RATIO"), QString::number(liveParameters.getSteerRatio(), 'f', 5)), steerRatioColor); - stiffnessFactorStatus = ItemStatus(QPair(tr("STEER STIFF"), QString::number(liveParameters.getStiffnessFactor(), 'f', 5)), AUTO_TUNE_COLOR); - torqueStatus = ItemStatus(QPair(tr("TORQUE %"), torqueLabel), metricColor); - - QString modelName = starpilot_toggles.value("model_name").toString(); - modelName.remove(QRegularExpression("\\(.*\\)")); - modelName.remove(QRegularExpression("[^a-zA-Z0-9 \\-\\.:]")); - modelNameStatus = ItemStatus(QPair(modelName.trimmed(), ""), metricColor); - - update(); -} - -void DeveloperSidebar::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(57, 57, 57)); - - QMap metricMap; - metricMap.insert(1, &accelerationStatus); - metricMap.insert(2, &maxAccelerationStatus); - metricMap.insert(3, &delayStatus); - metricMap.insert(4, &frictionStatus); - metricMap.insert(5, &latAccelStatus); - metricMap.insert(6, &steerRatioStatus); - metricMap.insert(7, &stiffnessFactorStatus); - metricMap.insert(8, &lateralEngagementStatus); - metricMap.insert(9, &longitudinalEngagementStatus); - metricMap.insert(10, &steerAngleStatus); - metricMap.insert(11, &torqueStatus); - metricMap.insert(12, &actuatorAccelerationStatus); - metricMap.insert(13, &dangerFactorStatus); - metricMap.insert(14, &accelerationJerkStatus); - metricMap.insert(15, &dangerJerkStatus); - metricMap.insert(16, &speedJerkStatus); - metricMap.insert(17, &modelNameStatus); - - int count = 0; - for (size_t i = 0; i < metricAssignments.size(); ++i) { - if (metricAssignments[i] > 0 && metricMap.contains(metricAssignments[i])) { - count++; - } - } - if (count == 0) { - return; - } - - int metricHeight = 126; - int spacing = (height() - (count * metricHeight)) / (count + 1); - int y = spacing; - - for (size_t i = 0; i < metricAssignments.size(); ++i) { - int metricId = metricAssignments[i]; - - if (metricId == 0) { - continue; - } - - if (!metricMap.contains(metricId)) { - continue; - } - - ItemStatus *status = metricMap[metricId]; - drawMetric(p, status->first, status->second, y); - y += metricHeight + spacing; - } -} diff --git a/starpilot/ui/qt/widgets/developer_sidebar.h b/starpilot/ui/qt/widgets/developer_sidebar.h deleted file mode 100644 index bb588ecc8..000000000 --- a/starpilot/ui/qt/widgets/developer_sidebar.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/sidebar.h" - -class DeveloperSidebar : public QFrame { - Q_OBJECT - -public: - explicit DeveloperSidebar(QWidget* parent = 0); - -private: - void drawMetric(QPainter &p, const QPair &label, QColor c, int y); - void paintEvent(QPaintEvent *event) override; - void resetVariables(); - void showEvent(QShowEvent *event); - void updateState(const UIState &s, const StarPilotUIState &fs); - void updateToggles(); - - double lateralEngagementTime; - double longitudinalEngagementTime; - double maxAcceleration; - double totalEngagementTime; - - std::vector metricAssignments; - - QColor metricColor; - Params params; - - ItemStatus accelerationJerkStatus; - ItemStatus accelerationStatus; - ItemStatus actuatorAccelerationStatus; - ItemStatus dangerFactorStatus; - ItemStatus dangerJerkStatus; - ItemStatus delayStatus; - ItemStatus frictionStatus; - ItemStatus latAccelStatus; - ItemStatus lateralEngagementStatus; - ItemStatus longitudinalEngagementStatus; - ItemStatus maxAccelerationStatus; - ItemStatus modelNameStatus; - ItemStatus speedJerkStatus; - ItemStatus steerAngleStatus; - ItemStatus steerRatioStatus; - ItemStatus stiffnessFactorStatus; - ItemStatus torqueStatus; -}; diff --git a/starpilot/ui/qt/widgets/drive_stats.cc b/starpilot/ui/qt/widgets/drive_stats.cc deleted file mode 100644 index aaa5032fe..000000000 --- a/starpilot/ui/qt/widgets/drive_stats.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "selfdrive/ui/qt/request_repeater.h" - -#include "starpilot/ui/qt/widgets/drive_stats.h" - -static QLabel *newLabel(const QString &text, const QString &type) { - QLabel *label = new QLabel(text); - label->setProperty("type", type); - return label; -} - -DriveStats::DriveStats(QWidget *parent) : QFrame(parent) { - isMetric = params.getBool("IsMetric"); - konik = useKonikServer(); - - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 25, 50, 20); - - addStatsLayouts(konik ? tr("ALL TIME (KONIK)") : tr("ALL TIME"), all); - addStatsLayouts(konik ? tr("PAST WEEK (KONIK)") : tr("PAST WEEK"), week); - addStatsLayouts(tr("STARPILOT"), frogPilot, true); - - std::optional dongleId = getDongleId(); - if (dongleId.has_value()) { - QString url = CommaApi::BASE_URL + "/v1.1/devices/" + dongleId.value() + "/stats"; - RequestRepeater *repeater = new RequestRepeater(this, url, "ApiCache_DriveStats", 30); - QObject::connect(repeater, &RequestRepeater::requestDone, this, &DriveStats::parseResponse); - } - - setStyleSheet(R"( - DriveStats { - background-color: #333333; - border-radius: 10px; - } - - QLabel[type="starpilot_title"] { font-size: 50px; font-weight: 500; color: #178643; } - QLabel[type="number"] { font-size: 65px; font-weight: 400; } - QLabel[type="title"] { font-size: 50px; font-weight: 500; } - QLabel[type="unit"] { font-size: 50px; font-weight: 300; color: #A0A0A0; } - )"); -} - -void DriveStats::showEvent(QShowEvent *event) { - isMetric = params.getBool("IsMetric"); - - updateStats(); -} - -void DriveStats::addStatsLayouts(const QString &title, StatsLabels &labels, bool StarPilot) { - QGridLayout *grid_layout = new QGridLayout; - grid_layout->setVerticalSpacing(10); - grid_layout->setContentsMargins(0, 10, 0, 10); - - int row = 0; - grid_layout->addWidget(newLabel(title, StarPilot ? "starpilot_title" : "title"), row++, 0, 1, 3); - grid_layout->addItem(new QSpacerItem(0, 10), row++, 0, 1, 1); - - grid_layout->addWidget(labels.routes = newLabel("0", "number"), row, 0, Qt::AlignLeft); - grid_layout->addWidget(labels.distance = newLabel("0", "number"), row, 1, Qt::AlignLeft); - grid_layout->addWidget(labels.hours = newLabel("0", "number"), row, 2, Qt::AlignLeft); - - grid_layout->addWidget(newLabel(tr("Drives"), "unit"), row + 1, 0, Qt::AlignLeft); - grid_layout->addWidget(labels.distance_unit = newLabel(isMetric ? tr("KM") : tr("Miles"), "unit"), row + 1, 1, Qt::AlignLeft); - grid_layout->addWidget(newLabel(tr("Hours"), "unit"), row + 1, 2, Qt::AlignLeft); - - QVBoxLayout *main_layout = static_cast(layout()); - main_layout->addLayout(grid_layout); - main_layout->addStretch(1); -} - -void DriveStats::parseResponse(const QString &response, bool success) { - if (!success) { - return; - } - - QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8()); - if (doc.isNull()) { - qDebug() << "JSON Parse failed on getting past drives statistics"; - return; - } - stats = doc; - updateStats(); -} - -void DriveStats::updateStatsForLabel(const QJsonObject &obj, StatsLabels &labels) { - labels.distance->setText(QString::number(int(obj["distance"].toDouble() * (isMetric ? MILE_TO_KM : 1)))); - labels.distance_unit->setText(isMetric ? tr("KM") : tr("Miles")); - labels.hours->setText(QString::number((int)(obj["minutes"].toDouble() / 60))); - labels.routes->setText(QString::number((int)obj["routes"].toDouble())); -} - -void DriveStats::updateStarPilotStatsForLabel(StatsLabels &labels) { - QJsonObject starpilot_stats = QJsonDocument::fromJson(QByteArray::fromStdString(params.get("StarPilotStats"))).object(); - - labels.distance->setText(QString::number(int(starpilot_stats.value("StarPilotMeters").toDouble() * (isMetric ? 0.001 : METER_TO_MILE)))); - labels.distance_unit->setText(isMetric ? tr("KM") : tr("Miles")); - labels.hours->setText(QString::number(int(starpilot_stats.value("StarPilotSeconds").toDouble() / (60 * 60)))); - labels.routes->setText(QString::number(starpilot_stats.value("StarPilotDrives").toInt())); -} - -void DriveStats::updateStats() { - QJsonObject json = stats.object(); - - updateStatsForLabel(json["all"].toObject(), all); - updateStatsForLabel(json["week"].toObject(), week); - updateStarPilotStatsForLabel(frogPilot); - - params.putIntNonBlocking(konik ? "KonikMinutes" : "openpilotMinutes", json["all"].toObject()["minutes"].toDouble()); -} diff --git a/starpilot/ui/qt/widgets/drive_stats.h b/starpilot/ui/qt/widgets/drive_stats.h deleted file mode 100644 index 9daba33aa..000000000 --- a/starpilot/ui/qt/widgets/drive_stats.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include "selfdrive/ui/ui.h" - -struct StatsLabels { - QLabel *distance; - QLabel *distance_unit; - QLabel *hours; - QLabel *routes; -}; - -class DriveStats : public QFrame { - Q_OBJECT - -public: - explicit DriveStats(QWidget *parent = 0); - -private: - void addStatsLayouts(const QString &title, StatsLabels &labels, bool StarPilot = false); - void showEvent(QShowEvent *event) override; - void updateStarPilotStatsForLabel(StatsLabels &labels); - void updateStats(); - void updateStatsForLabel(const QJsonObject &obj, StatsLabels &labels); - - bool isMetric; - bool konik; - - Params params; - - QJsonDocument stats; - - StatsLabels all; - StatsLabels frogPilot; - StatsLabels week; - -private slots: - void parseResponse(const QString &response, bool success); -}; diff --git a/starpilot/ui/qt/widgets/drive_summary.cc b/starpilot/ui/qt/widgets/drive_summary.cc deleted file mode 100644 index c1844f139..000000000 --- a/starpilot/ui/qt/widgets/drive_summary.cc +++ /dev/null @@ -1,225 +0,0 @@ -#include "selfdrive/ui/qt/widgets/scrollview.h" - -#include "starpilot/ui/qt/widgets/drive_summary.h" - -StarPilotDriveSummary::StarPilotDriveSummary(QWidget *parent, bool randomEvents) : QFrame(parent), displayRandomEvents(randomEvents) { - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setContentsMargins(20, 20, 20, 20); - mainLayout->setSpacing(15); - - titleLabel = new QLabel(randomEvents ? tr("Random Events Summary") : tr("Drive Summary"), this); - titleLabel->setAlignment(Qt::AlignCenter); - titleLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - titleLabel->setStyleSheet(R"( - QLabel { - background-color: #444444; - border-radius: 12px; - color: #FFFFFF; - font-size: 50px; - font-weight: bold; - padding: 12px 28px; - } - )"); - titleLabel->setMaximumHeight(titleLabel->sizeHint().height()); - - mainLayout->addWidget(titleLabel); - mainLayout->addSpacing(10); - - QWidget *containerWidget = new QWidget(this); - QVBoxLayout *listLayout = new QVBoxLayout(containerWidget); - listLayout->setAlignment(Qt::AlignTop); - listLayout->setSpacing(20); - - if (displayRandomEvents) { - randomEventsMap.insert("accel30", tr("UwUs")); - randomEventsMap.insert("accel35", tr("Loch Ness Encounters")); - randomEventsMap.insert("accel40", tr("Visits to 1955")); - randomEventsMap.insert("dejaVuCurve", tr("Deja Vu Moments")); - randomEventsMap.insert("firefoxSteerSaturated", tr("Internet Explorer Weeeeeeees")); - randomEventsMap.insert("hal9000", tr("HAL 9000 Denials")); - randomEventsMap.insert("openpilotCrashedRandomEvent", tr("openpilot Crashes")); - randomEventsMap.insert("thisIsFineSteerSaturated", tr("This Is Fine Moments")); - randomEventsMap.insert("toBeContinued", tr("To Be Continued Moments")); - randomEventsMap.insert("vCruise69", tr("Noices")); - randomEventsMap.insert("yourFrogTriedToKillMe", tr("Attempted Frog Murders")); - randomEventsMap.insert("youveGotMail", tr("Total Mail Received")); - } else { - listLayout->addWidget(createStatBox(tr("% of Drive With openpilot Engaged"), &engagementValue, this)); - listLayout->addWidget(createStatBox(tr("Drive Distance"), &frogPilotMetersValue, this)); - listLayout->addWidget(createStatBox(tr("Drive Time"), &trackedTimeValue, this)); - listLayout->addWidget(createStatBox(tr("% of Drive In \"Experimental Mode\""), &experimentalModeTimeValue, this)); - } - - if (displayRandomEvents) { - eventsListLayout = listLayout; - mainLayout->addWidget(new ScrollView(containerWidget, this), 1); - } else { - mainLayout->addWidget(containerWidget, 1); - } - - setLayout(mainLayout); - - setStyleSheet(R"( - QFrame { - background-color: #333333; - } - )"); - - QObject::connect(device(), &Device::interactiveTimeout, [this]() { - emit panelClosed(); - }); - QObject::connect(uiState(), &UIState::offroadTransition, [this](bool offroad) { - if (!offroad) { - previousStats = QJsonDocument::fromJson(QString::fromStdString(params.get("StarPilotStats")).toUtf8()).object(); - } - }); -} - -void StarPilotDriveSummary::mousePressEvent(QMouseEvent *e) { - emit panelClosed(); -} - -void StarPilotDriveSummary::showEvent(QShowEvent *event) { - bool isMetric = params.getBool("IsMetric"); - - QJsonObject currentStats = QJsonDocument::fromJson(QString::fromStdString(params.get("StarPilotStats")).toUtf8()).object(); - - if (displayRandomEvents) { - QJsonObject currentRandomEvents = currentStats.value("RandomEvents").toObject(); - QJsonObject previousRandomEvents = previousStats.value("RandomEvents").toObject(); - - QList> eventsList; - for (QMap::const_iterator it = randomEventsMap.constBegin(); it != randomEventsMap.constEnd(); ++it) { - int currentValue = currentRandomEvents.value(it.key()).toInt(); - int previousValue = previousRandomEvents.value(it.key()).toInt(); - int diffValue = currentValue - previousValue; - - if (diffValue > 0) { - eventsList.append(qMakePair(it.value(), diffValue)); - } - } - - std::sort(eventsList.begin(), eventsList.end(), [](const QPair &a, const QPair &b) { - if (a.second != b.second) { - return a.second > b.second; - } else { - return a.first.localeAwareCompare(b.first) < 0; - } - }); - - QLayoutItem *child; - while ((child = eventsListLayout->takeAt(0)) != nullptr) { - if (QWidget *widget = child->widget()) { - widget->deleteLater(); - } - delete child; - } - randomEventLabels.clear(); - - if (eventsList.isEmpty()) { - eventsListLayout->setAlignment(Qt::AlignCenter); - - QLabel *noEventsLabel = new QLabel(tr("No Random Events Played!"), this); - noEventsLabel->setAlignment(Qt::AlignCenter); - noEventsLabel->setStyleSheet(R"( - QLabel { - font-size: 50px; - font-weight: bold; - color: #FFFFFF; - } - )"); - eventsListLayout->addWidget(noEventsLabel); - } else { - eventsListLayout->setAlignment(Qt::AlignTop); - - for (QList>::const_iterator it = eventsList.constBegin(); it != eventsList.constEnd(); ++it) { - QLabel *valueLabel = nullptr; - eventsListLayout->addWidget(createStatBox(it->first, &valueLabel, this)); - randomEventLabels.insert(it->first, valueLabel); - valueLabel->setText(QLocale().toString(it->second)); - } - } - } else { - std::function diffDouble = [currentStats, this](const QString &key) -> double { - return currentStats.value(key).toDouble() - previousStats.value(key).toDouble(); - }; - - std::function formatDistance = [&](double meters) { - double value; - QString unit; - if (isMetric) { - value = meters / 1000.0; - unit = (qRound(value) == 1) ? tr(" kilometer") : tr(" kilometers"); - } else { - value = meters * METER_TO_MILE; - unit = (qRound(value) == 1) ? tr(" mile") : tr(" miles"); - } - return QLocale().toString(qRound(value)) + unit; - }; - - std::function formatTime = [&](int seconds) { - static int secondsInDay = 60 * 60 * 24; - static int secondsInHour = 60 * 60; - - int days = seconds / secondsInDay; - int hours = (seconds % secondsInDay) / secondsInHour; - int minutes = (seconds % secondsInHour) / 60; - - QString result; - if (days > 0) result += QLocale().toString(days) + (days == 1 ? tr(" day ") : tr(" days ")); - if (hours > 0 || days > 0) result += QLocale().toString(hours) + (hours == 1 ? tr(" hour ") : tr(" hours ")); - result += QLocale().toString(minutes) + (minutes == 1 ? tr(" minute") : tr(" minutes")); - return result.trimmed(); - }; - - int engagedTime = diffDouble("AOLTime") + diffDouble("LongitudinalTime"); - int experimentalTime = diffDouble("ExperimentalModeTime"); - int trackedTime = diffDouble("TrackedTime"); - - engagementValue->setText(QLocale().toString((trackedTime > 0) ? (engagedTime * 100 / trackedTime) : 0) + "%"); - experimentalModeTimeValue->setText(QLocale().toString((trackedTime > 0) ? (experimentalTime * 100 / trackedTime) : 0) + "%"); - frogPilotMetersValue->setText(formatDistance(diffDouble("StarPilotMeters"))); - trackedTimeValue->setText(formatTime(trackedTime)); - } -} - -void StarPilotDriveSummary::hideEvent(QHideEvent *event) { - emit panelClosed(); -} - -QWidget *StarPilotDriveSummary::createStatBox(const QString &title, QLabel **valueLabel, QWidget *parent) { - QWidget *box = new QWidget(parent); - - QVBoxLayout *layout = new QVBoxLayout(box); - layout->setAlignment(Qt::AlignCenter); - layout->setContentsMargins(10, 10, 10, 10); - layout->setSpacing(8); - - QLabel *statTitleLabel = new QLabel(title, box); - statTitleLabel->setAlignment(Qt::AlignCenter); - statTitleLabel->setStyleSheet(R"( - QLabel { - color: #AAAAAA; - font-size: 40px; - font-weight: bold; - } - )"); - - QLabel *value = new QLabel("-", box); - value->setAlignment(Qt::AlignCenter); - value->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - value->setStyleSheet(R"( - QLabel { - color: #FFFFFF; - font-size: 75px; - font-weight: bold; - } - )"); - - *valueLabel = value; - - layout->addWidget(statTitleLabel); - layout->addWidget(value); - - return box; -} diff --git a/starpilot/ui/qt/widgets/drive_summary.h b/starpilot/ui/qt/widgets/drive_summary.h deleted file mode 100644 index ca0b36e3e..000000000 --- a/starpilot/ui/qt/widgets/drive_summary.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include "selfdrive/ui/ui.h" - -class StarPilotDriveSummary : public QFrame { - Q_OBJECT - -public: - explicit StarPilotDriveSummary(QWidget *parent = nullptr, bool random_events = false); - -signals: - void panelClosed(); - -protected: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void mousePressEvent(QMouseEvent *e); - -private: - QWidget *createStatBox(const QString &title, QLabel **valueLabel, QWidget *parent); - - bool displayRandomEvents; - - Params params; - - QJsonObject previousStats; - - QLabel *experimentalModeTimeValue; - QLabel *frogPilotMetersValue; - QLabel *engagementValue; - QLabel *titleLabel; - QLabel *trackedTimeValue; - - QMap randomEventLabels; - - QMap randomEventsMap; - - QVBoxLayout *eventsListLayout; -}; diff --git a/starpilot/ui/qt/widgets/moc_developer_sidebar.cc b/starpilot/ui/qt/widgets/moc_developer_sidebar.cc deleted file mode 100644 index 0527ac9b6..000000000 --- a/starpilot/ui/qt/widgets/moc_developer_sidebar.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'developer_sidebar.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "developer_sidebar.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'developer_sidebar.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DeveloperSidebar_t { - QByteArrayData data[1]; - char stringdata0[17]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DeveloperSidebar_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DeveloperSidebar_t qt_meta_stringdata_DeveloperSidebar = { - { -QT_MOC_LITERAL(0, 0, 16) // "DeveloperSidebar" - - }, - "DeveloperSidebar" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DeveloperSidebar[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void DeveloperSidebar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject DeveloperSidebar::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_DeveloperSidebar.data, - qt_meta_data_DeveloperSidebar, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DeveloperSidebar::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DeveloperSidebar::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DeveloperSidebar.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int DeveloperSidebar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/widgets/moc_drive_stats.cc b/starpilot/ui/qt/widgets/moc_drive_stats.cc deleted file mode 100644 index 7a4891266..000000000 --- a/starpilot/ui/qt/widgets/moc_drive_stats.cc +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'drive_stats.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "drive_stats.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'drive_stats.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_DriveStats_t { - QByteArrayData data[5]; - char stringdata0[43]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_DriveStats_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_DriveStats_t qt_meta_stringdata_DriveStats = { - { -QT_MOC_LITERAL(0, 0, 10), // "DriveStats" -QT_MOC_LITERAL(1, 11, 13), // "parseResponse" -QT_MOC_LITERAL(2, 25, 0), // "" -QT_MOC_LITERAL(3, 26, 8), // "response" -QT_MOC_LITERAL(4, 35, 7) // "success" - - }, - "DriveStats\0parseResponse\0\0response\0" - "success" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_DriveStats[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 2, 19, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, QMetaType::QString, QMetaType::Bool, 3, 4, - - 0 // eod -}; - -void DriveStats::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->parseResponse((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; - default: ; - } - } -} - -QT_INIT_METAOBJECT const QMetaObject DriveStats::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_DriveStats.data, - qt_meta_data_DriveStats, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *DriveStats::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *DriveStats::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_DriveStats.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int DriveStats::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/widgets/moc_drive_summary.cc b/starpilot/ui/qt/widgets/moc_drive_summary.cc deleted file mode 100644 index 052e9ef38..000000000 --- a/starpilot/ui/qt/widgets/moc_drive_summary.cc +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'drive_summary.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "drive_summary.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'drive_summary.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotDriveSummary_t { - QByteArrayData data[3]; - char stringdata0[35]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotDriveSummary_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotDriveSummary_t qt_meta_stringdata_StarPilotDriveSummary = { - { -QT_MOC_LITERAL(0, 0, 21), // "StarPilotDriveSummary" -QT_MOC_LITERAL(1, 22, 11), // "panelClosed" -QT_MOC_LITERAL(2, 34, 0) // "" - - }, - "StarPilotDriveSummary\0panelClosed\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotDriveSummary[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotDriveSummary::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->panelClosed(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotDriveSummary::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotDriveSummary::panelClosed)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotDriveSummary::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_StarPilotDriveSummary.data, - qt_meta_data_StarPilotDriveSummary, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotDriveSummary::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotDriveSummary::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotDriveSummary.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int StarPilotDriveSummary::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotDriveSummary::panelClosed() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/widgets/moc_navigation_functions.cc b/starpilot/ui/qt/widgets/moc_navigation_functions.cc deleted file mode 100644 index 7613f70e5..000000000 --- a/starpilot/ui/qt/widgets/moc_navigation_functions.cc +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'navigation_functions.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "navigation_functions.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'navigation_functions.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_MapSelectionControl_t { - QByteArrayData data[1]; - char stringdata0[20]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_MapSelectionControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_MapSelectionControl_t qt_meta_stringdata_MapSelectionControl = { - { -QT_MOC_LITERAL(0, 0, 19) // "MapSelectionControl" - - }, - "MapSelectionControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_MapSelectionControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void MapSelectionControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject MapSelectionControl::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_MapSelectionControl.data, - qt_meta_data_MapSelectionControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *MapSelectionControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *MapSelectionControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_MapSelectionControl.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int MapSelectionControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/widgets/moc_starpilot_controls.cc b/starpilot/ui/qt/widgets/moc_starpilot_controls.cc deleted file mode 100644 index 1551ecad8..000000000 --- a/starpilot/ui/qt/widgets/moc_starpilot_controls.cc +++ /dev/null @@ -1,876 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'starpilot_controls.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "starpilot_controls.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'starpilot_controls.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_StarPilotConfirmationDialog_t { - QByteArrayData data[1]; - char stringdata0[28]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotConfirmationDialog_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotConfirmationDialog_t qt_meta_stringdata_StarPilotConfirmationDialog = { - { -QT_MOC_LITERAL(0, 0, 27) // "StarPilotConfirmationDialog" - - }, - "StarPilotConfirmationDialog" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotConfirmationDialog[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotConfirmationDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotConfirmationDialog::staticMetaObject = { { - &ConfirmationDialog::staticMetaObject, - qt_meta_stringdata_StarPilotConfirmationDialog.data, - qt_meta_data_StarPilotConfirmationDialog, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotConfirmationDialog::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotConfirmationDialog::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotConfirmationDialog.stringdata0)) - return static_cast(this); - return ConfirmationDialog::qt_metacast(_clname); -} - -int StarPilotConfirmationDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ConfirmationDialog::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_StarPilotListWidget_t { - QByteArrayData data[1]; - char stringdata0[20]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotListWidget_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotListWidget_t qt_meta_stringdata_StarPilotListWidget = { - { -QT_MOC_LITERAL(0, 0, 19) // "StarPilotListWidget" - - }, - "StarPilotListWidget" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotListWidget[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotListWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotListWidget::staticMetaObject = { { - &QWidget::staticMetaObject, - qt_meta_stringdata_StarPilotListWidget.data, - qt_meta_data_StarPilotListWidget, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotListWidget::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotListWidget::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotListWidget.stringdata0)) - return static_cast(this); - return QWidget::qt_metacast(_clname); -} - -int StarPilotListWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QWidget::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_StarPilotButtonControl_t { - QByteArrayData data[4]; - char stringdata0[41]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotButtonControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotButtonControl_t qt_meta_stringdata_StarPilotButtonControl = { - { -QT_MOC_LITERAL(0, 0, 22), // "StarPilotButtonControl" -QT_MOC_LITERAL(1, 23, 13), // "buttonClicked" -QT_MOC_LITERAL(2, 37, 0), // "" -QT_MOC_LITERAL(3, 38, 2) // "id" - - }, - "StarPilotButtonControl\0buttonClicked\0" - "\0id" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotButtonControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, 3, - - 0 // eod -}; - -void StarPilotButtonControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->buttonClicked((*reinterpret_cast< int(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotButtonControl::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotButtonControl::buttonClicked)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotButtonControl::staticMetaObject = { { - &ParamControl::staticMetaObject, - qt_meta_stringdata_StarPilotButtonControl.data, - qt_meta_data_StarPilotButtonControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotButtonControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotButtonControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotButtonControl.stringdata0)) - return static_cast(this); - return ParamControl::qt_metacast(_clname); -} - -int StarPilotButtonControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ParamControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotButtonControl::buttonClicked(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_StarPilotButtonsControl_t { - QByteArrayData data[5]; - char stringdata0[64]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotButtonsControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotButtonsControl_t qt_meta_stringdata_StarPilotButtonsControl = { - { -QT_MOC_LITERAL(0, 0, 23), // "StarPilotButtonsControl" -QT_MOC_LITERAL(1, 24, 13), // "buttonClicked" -QT_MOC_LITERAL(2, 38, 0), // "" -QT_MOC_LITERAL(3, 39, 2), // "id" -QT_MOC_LITERAL(4, 42, 21) // "disabledButtonClicked" - - }, - "StarPilotButtonsControl\0buttonClicked\0" - "\0id\0disabledButtonClicked" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotButtonsControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 2, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 2, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 24, 2, 0x06 /* Public */, - 4, 1, 27, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, 3, - QMetaType::Void, QMetaType::Int, 3, - - 0 // eod -}; - -void StarPilotButtonsControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->buttonClicked((*reinterpret_cast< int(*)>(_a[1]))); break; - case 1: _t->disabledButtonClicked((*reinterpret_cast< int(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotButtonsControl::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotButtonsControl::buttonClicked)) { - *result = 0; - return; - } - } - { - using _t = void (StarPilotButtonsControl::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotButtonsControl::disabledButtonClicked)) { - *result = 1; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotButtonsControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_StarPilotButtonsControl.data, - qt_meta_data_StarPilotButtonsControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotButtonsControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotButtonsControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotButtonsControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int StarPilotButtonsControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 2) - qt_static_metacall(this, _c, _id, _a); - _id -= 2; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 2) - *reinterpret_cast(_a[0]) = -1; - _id -= 2; - } - return _id; -} - -// SIGNAL 0 -void StarPilotButtonsControl::buttonClicked(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} - -// SIGNAL 1 -void StarPilotButtonsControl::disabledButtonClicked(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 1, _a); -} -struct qt_meta_stringdata_StarPilotButtonToggleControl_t { - QByteArrayData data[1]; - char stringdata0[29]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotButtonToggleControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotButtonToggleControl_t qt_meta_stringdata_StarPilotButtonToggleControl = { - { -QT_MOC_LITERAL(0, 0, 28) // "StarPilotButtonToggleControl" - - }, - "StarPilotButtonToggleControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotButtonToggleControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotButtonToggleControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotButtonToggleControl::staticMetaObject = { { - &StarPilotButtonControl::staticMetaObject, - qt_meta_stringdata_StarPilotButtonToggleControl.data, - qt_meta_data_StarPilotButtonToggleControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotButtonToggleControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotButtonToggleControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotButtonToggleControl.stringdata0)) - return static_cast(this); - return StarPilotButtonControl::qt_metacast(_clname); -} - -int StarPilotButtonToggleControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotButtonControl::qt_metacall(_c, _id, _a); - return _id; -} -struct qt_meta_stringdata_StarPilotManageControl_t { - QByteArrayData data[3]; - char stringdata0[44]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotManageControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotManageControl_t qt_meta_stringdata_StarPilotManageControl = { - { -QT_MOC_LITERAL(0, 0, 22), // "StarPilotManageControl" -QT_MOC_LITERAL(1, 23, 19), // "manageButtonClicked" -QT_MOC_LITERAL(2, 43, 0) // "" - - }, - "StarPilotManageControl\0manageButtonClicked\0" - "" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotManageControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, - - 0 // eod -}; - -void StarPilotManageControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->manageButtonClicked(); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotManageControl::*)(); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotManageControl::manageButtonClicked)) { - *result = 0; - return; - } - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotManageControl::staticMetaObject = { { - &ParamControl::staticMetaObject, - qt_meta_stringdata_StarPilotManageControl.data, - qt_meta_data_StarPilotManageControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotManageControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotManageControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotManageControl.stringdata0)) - return static_cast(this); - return ParamControl::qt_metacast(_clname); -} - -int StarPilotManageControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = ParamControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotManageControl::manageButtonClicked() -{ - QMetaObject::activate(this, &staticMetaObject, 0, nullptr); -} -struct qt_meta_stringdata_StarPilotParamValueControl_t { - QByteArrayData data[4]; - char stringdata0[47]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotParamValueControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotParamValueControl_t qt_meta_stringdata_StarPilotParamValueControl = { - { -QT_MOC_LITERAL(0, 0, 26), // "StarPilotParamValueControl" -QT_MOC_LITERAL(1, 27, 12), // "valueChanged" -QT_MOC_LITERAL(2, 40, 0), // "" -QT_MOC_LITERAL(3, 41, 5) // "value" - - }, - "StarPilotParamValueControl\0valueChanged\0" - "\0value" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotParamValueControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Float, 3, - - 0 // eod -}; - -void StarPilotParamValueControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->valueChanged((*reinterpret_cast< float(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotParamValueControl::*)(float ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotParamValueControl::valueChanged)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotParamValueControl::staticMetaObject = { { - &AbstractControl::staticMetaObject, - qt_meta_stringdata_StarPilotParamValueControl.data, - qt_meta_data_StarPilotParamValueControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotParamValueControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotParamValueControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotParamValueControl.stringdata0)) - return static_cast(this); - return AbstractControl::qt_metacast(_clname); -} - -int StarPilotParamValueControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = AbstractControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotParamValueControl::valueChanged(float _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_StarPilotParamValueButtonControl_t { - QByteArrayData data[4]; - char stringdata0[51]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotParamValueButtonControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotParamValueButtonControl_t qt_meta_stringdata_StarPilotParamValueButtonControl = { - { -QT_MOC_LITERAL(0, 0, 32), // "StarPilotParamValueButtonControl" -QT_MOC_LITERAL(1, 33, 13), // "buttonClicked" -QT_MOC_LITERAL(2, 47, 0), // "" -QT_MOC_LITERAL(3, 48, 2) // "id" - - }, - "StarPilotParamValueButtonControl\0" - "buttonClicked\0\0id" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotParamValueButtonControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 1, // signalCount - - // signals: name, argc, parameters, tag, flags - 1, 1, 19, 2, 0x06 /* Public */, - - // signals: parameters - QMetaType::Void, QMetaType::Int, 3, - - 0 // eod -}; - -void StarPilotParamValueButtonControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->buttonClicked((*reinterpret_cast< int(*)>(_a[1]))); break; - default: ; - } - } else if (_c == QMetaObject::IndexOfMethod) { - int *result = reinterpret_cast(_a[0]); - { - using _t = void (StarPilotParamValueButtonControl::*)(int ); - if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&StarPilotParamValueButtonControl::buttonClicked)) { - *result = 0; - return; - } - } - } -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotParamValueButtonControl::staticMetaObject = { { - &StarPilotParamValueControl::staticMetaObject, - qt_meta_stringdata_StarPilotParamValueButtonControl.data, - qt_meta_data_StarPilotParamValueButtonControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotParamValueButtonControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotParamValueButtonControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotParamValueButtonControl.stringdata0)) - return static_cast(this); - return StarPilotParamValueControl::qt_metacast(_clname); -} - -int StarPilotParamValueButtonControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = StarPilotParamValueControl::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} - -// SIGNAL 0 -void StarPilotParamValueButtonControl::buttonClicked(int _t1) -{ - void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; - QMetaObject::activate(this, &staticMetaObject, 0, _a); -} -struct qt_meta_stringdata_StarPilotDualParamValueControl_t { - QByteArrayData data[1]; - char stringdata0[31]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_StarPilotDualParamValueControl_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_StarPilotDualParamValueControl_t qt_meta_stringdata_StarPilotDualParamValueControl = { - { -QT_MOC_LITERAL(0, 0, 30) // "StarPilotDualParamValueControl" - - }, - "StarPilotDualParamValueControl" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_StarPilotDualParamValueControl[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 0, 0, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - 0 // eod -}; - -void StarPilotDualParamValueControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - Q_UNUSED(_o); - Q_UNUSED(_id); - Q_UNUSED(_c); - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject StarPilotDualParamValueControl::staticMetaObject = { { - &QFrame::staticMetaObject, - qt_meta_stringdata_StarPilotDualParamValueControl.data, - qt_meta_data_StarPilotDualParamValueControl, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *StarPilotDualParamValueControl::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *StarPilotDualParamValueControl::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_StarPilotDualParamValueControl.stringdata0)) - return static_cast(this); - return QFrame::qt_metacast(_clname); -} - -int StarPilotDualParamValueControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QFrame::qt_metacall(_c, _id, _a); - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/qt/widgets/navigation_functions.cc b/starpilot/ui/qt/widgets/navigation_functions.cc deleted file mode 100644 index e1744e81b..000000000 --- a/starpilot/ui/qt/widgets/navigation_functions.cc +++ /dev/null @@ -1,63 +0,0 @@ -#include "starpilot/ui/qt/widgets/navigation_functions.h" - -MapSelectionControl::MapSelectionControl(const QMap &map, bool isCountry) : selectionType(isCountry ? "nations" : "states") { - mapButtons = new QButtonGroup(this); - mapButtons->setExclusive(false); - - QGridLayout *mapLayout = new QGridLayout(this); - - QList keys = map.keys(); - for (int i = 0; i < keys.size(); ++i) { - QPushButton *button = new QPushButton(map[keys[i]], this); - button->setCheckable(true); - button->setProperty("mapKey", keys[i]); - button->setStyleSheet(buttonStyle); - - mapButtons->addButton(button, i); - - mapLayout->addWidget(button, i / 3, i % 3); - - QObject::connect(button, &QPushButton::toggled, this, &MapSelectionControl::updateSelectedMaps); - } - - loadSelectedMaps(); -} - -void MapSelectionControl::loadSelectedMaps() { - QString mapsSelected = QString::fromStdString(params.get("MapsSelected")); - QStringList mapList = mapsSelected.split(",", QString::SkipEmptyParts); - QString prefix = (selectionType == "nations") ? "nation." : "us_state."; - - QSet selectedMaps; - for (const QString &map : mapList) { - if (map.startsWith(prefix)) { - selectedMaps.insert(map.mid(prefix.length())); - } - } - - for (QAbstractButton *button : mapButtons->buttons()) { - button->setChecked(selectedMaps.contains(button->property("mapKey").toString())); - } -} - -void MapSelectionControl::updateSelectedMaps() { - QString mapsSelected = QString::fromStdString(params.get("MapsSelected")); - QStringList mapList = mapsSelected.split(",", QString::SkipEmptyParts); - QString prefix = (selectionType == "nations") ? "nation." : "us_state."; - - QStringList newMapList; - for (const QString &map : mapList) { - if (!map.startsWith(prefix)) { - newMapList.append(map); - } - } - - for (QAbstractButton *button : mapButtons->buttons()) { - if (button->isChecked()) { - newMapList.append(prefix + button->property("mapKey").toString()); - } - } - - newMapList.sort(); - params.putNonBlocking("MapsSelected", newMapList.join(",").toStdString()); -} diff --git a/starpilot/ui/qt/widgets/navigation_functions.h b/starpilot/ui/qt/widgets/navigation_functions.h deleted file mode 100644 index 8cfad8e2c..000000000 --- a/starpilot/ui/qt/widgets/navigation_functions.h +++ /dev/null @@ -1,214 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "starpilot/ui/qt/widgets/starpilot_controls.h" - -inline QMap midwestMap = { - {"IL", "Illinois"}, {"IN", "Indiana"}, {"IA", "Iowa"}, - {"KS", "Kansas"}, {"MI", "Michigan"}, {"MN", "Minnesota"}, - {"MO", "Missouri"}, {"NE", "Nebraska"}, {"ND", "North Dakota"}, - {"OH", "Ohio"}, {"SD", "South Dakota"}, {"WI", "Wisconsin"} -}; - -inline QMap northeastMap = { - {"CT", "Connecticut"}, {"ME", "Maine"}, {"MA", "Massachusetts"}, - {"NH", "New Hampshire"}, {"NJ", "New Jersey"}, {"NY", "New York"}, - {"PA", "Pennsylvania"}, {"RI", "Rhode Island"}, {"VT", "Vermont"} -}; - -inline QMap southMap = { - {"AL", "Alabama"}, {"AR", "Arkansas"}, {"DE", "Delaware"}, - {"DC", "District of Columbia"}, {"FL", "Florida"}, {"GA", "Georgia"}, - {"KY", "Kentucky"}, {"LA", "Louisiana"}, {"MD", "Maryland"}, - {"MS", "Mississippi"}, {"NC", "North Carolina"}, {"OK", "Oklahoma"}, - {"SC", "South Carolina"}, {"TN", "Tennessee"}, {"TX", "Texas"}, - {"VA", "Virginia"}, {"WV", "West Virginia"} -}; - -inline QMap westMap = { - {"AK", "Alaska"}, {"AZ", "Arizona"}, {"CA", "California"}, - {"CO", "Colorado"}, {"HI", "Hawaii"}, {"ID", "Idaho"}, - {"MT", "Montana"}, {"NV", "Nevada"}, {"NM", "New Mexico"}, - {"OR", "Oregon"}, {"UT", "Utah"}, {"WA", "Washington"}, - {"WY", "Wyoming"} -}; - -inline QMap territoriesMap = { - {"AS", "American Samoa"}, {"GU", "Guam"}, {"MP", "Northern Mariana Islands"}, - {"PR", "Puerto Rico"}, {"VI", "Virgin Islands"} -}; - -inline QMap africaMap = { - {"DZ", "Algeria"}, {"AO", "Angola"}, {"BJ", "Benin"}, - {"BW", "Botswana"}, {"BF", "Burkina Faso"}, {"BI", "Burundi"}, - {"CM", "Cameroon"}, {"CF", "Central African Republic"}, {"TD", "Chad"}, - {"KM", "Comoros"}, {"CG", "Congo (Brazzaville)"}, {"CD", "Congo (Kinshasa)"}, - {"DJ", "Djibouti"}, {"EG", "Egypt"}, {"GQ", "Equatorial Guinea"}, - {"ER", "Eritrea"}, {"ET", "Ethiopia"}, {"GA", "Gabon"}, - {"GM", "Gambia"}, {"GH", "Ghana"}, {"GN", "Guinea"}, - {"GW", "Guinea-Bissau"}, {"CI", "Ivory Coast"}, {"KE", "Kenya"}, - {"LS", "Lesotho"}, {"LR", "Liberia"}, {"LY", "Libya"}, - {"MG", "Madagascar"}, {"MW", "Malawi"}, {"ML", "Mali"}, - {"MR", "Mauritania"}, {"MA", "Morocco"}, {"MZ", "Mozambique"}, - {"NA", "Namibia"}, {"NE", "Niger"}, {"NG", "Nigeria"}, - {"RW", "Rwanda"}, {"SN", "Senegal"}, {"SL", "Sierra Leone"}, - {"SO", "Somalia"}, {"ZA", "South Africa"}, {"SS", "South Sudan"}, - {"SD", "Sudan"}, {"SZ", "Swaziland"}, {"TZ", "Tanzania"}, - {"TG", "Togo"}, {"TN", "Tunisia"}, {"UG", "Uganda"}, - {"ZM", "Zambia"}, {"ZW", "Zimbabwe"} -}; - -inline QMap antarcticaMap = { - {"AQ", "Antarctica"} -}; - -inline QMap asiaMap = { - {"AF", "Afghanistan"}, {"AM", "Armenia"}, {"AZ", "Azerbaijan"}, - {"BH", "Bahrain"}, {"BD", "Bangladesh"}, {"BT", "Bhutan"}, - {"BN", "Brunei"}, {"KH", "Cambodia"}, {"CN", "China"}, - {"CY", "Cyprus"}, {"TL", "East Timor"}, {"HK", "Hong Kong"}, - {"IN", "India"}, {"ID", "Indonesia"}, {"IR", "Iran"}, - {"IQ", "Iraq"}, {"IL", "Israel"}, {"JP", "Japan"}, - {"JO", "Jordan"}, {"KZ", "Kazakhstan"}, {"KW", "Kuwait"}, - {"KG", "Kyrgyzstan"}, {"LA", "Laos"}, {"LB", "Lebanon"}, - {"MY", "Malaysia"}, {"MV", "Maldives"}, {"MO", "Macao"}, - {"MN", "Mongolia"}, {"MM", "Myanmar"}, {"NP", "Nepal"}, - {"KP", "North Korea"}, {"OM", "Oman"}, {"PK", "Pakistan"}, - {"PS", "Palestine"}, {"PH", "Philippines"}, {"QA", "Qatar"}, - {"RU", "Russia"}, {"SA", "Saudi Arabia"}, {"SG", "Singapore"}, - {"KR", "South Korea"}, {"LK", "Sri Lanka"}, {"SY", "Syria"}, - {"TW", "Taiwan"}, {"TJ", "Tajikistan"}, {"TH", "Thailand"}, - {"TR", "Turkey"}, {"TM", "Turkmenistan"}, {"AE", "United Arab Emirates"}, - {"UZ", "Uzbekistan"}, {"VN", "Vietnam"}, {"YE", "Yemen"} -}; - -inline QMap europeMap = { - {"AL", "Albania"}, {"AT", "Austria"}, {"BY", "Belarus"}, - {"BE", "Belgium"}, {"BA", "Bosnia and Herzegovina"}, {"BG", "Bulgaria"}, - {"HR", "Croatia"}, {"CZ", "Czech Republic"}, {"DK", "Denmark"}, - {"EE", "Estonia"}, {"FI", "Finland"}, {"FR", "France"}, - {"GE", "Georgia"}, {"DE", "Germany"}, {"GR", "Greece"}, - {"HU", "Hungary"}, {"IS", "Iceland"}, {"IE", "Ireland"}, - {"IT", "Italy"}, {"KZ", "Kazakhstan"}, {"LV", "Latvia"}, - {"LT", "Lithuania"}, {"LU", "Luxembourg"}, {"MK", "Macedonia"}, - {"MD", "Moldova"}, {"ME", "Montenegro"}, {"NL", "Netherlands"}, - {"NO", "Norway"}, {"PL", "Poland"}, {"PT", "Portugal"}, - {"RO", "Romania"}, {"RS", "Serbia"}, {"SK", "Slovakia"}, - {"SI", "Slovenia"}, {"ES", "Spain"}, {"SE", "Sweden"}, - {"CH", "Switzerland"}, {"TR", "Turkey"}, {"UA", "Ukraine"}, - {"GB", "United Kingdom"} -}; - -inline QMap northAmericaMap = { - {"BS", "Bahamas"}, {"BZ", "Belize"}, {"CA", "Canada"}, - {"CR", "Costa Rica"}, {"CU", "Cuba"}, {"DO", "Dominican Republic"}, - {"SV", "El Salvador"}, {"GL", "Greenland"}, {"GD", "Grenada"}, - {"GT", "Guatemala"}, {"HT", "Haiti"}, {"HN", "Honduras"}, - {"JM", "Jamaica"}, {"MX", "Mexico"}, {"NI", "Nicaragua"}, - {"PA", "Panama"}, {"TT", "Trinidad and Tobago"}, {"US", "United States"} -}; - -inline QMap oceaniaMap = { - {"AU", "Australia"}, {"FJ", "Fiji"}, {"TF", "French Southern Territories"}, - {"NC", "New Caledonia"}, {"NZ", "New Zealand"}, {"PG", "Papua New Guinea"}, - {"SB", "Solomon Islands"}, {"VU", "Vanuatu"} -}; - -inline QMap southAmericaMap = { - {"AR", "Argentina"}, {"BO", "Bolivia"}, {"BR", "Brazil"}, - {"CL", "Chile"}, {"CO", "Colombia"}, {"EC", "Ecuador"}, - {"FK", "Falkland Islands"}, {"GY", "Guyana"}, {"PY", "Paraguay"}, - {"PE", "Peru"}, {"SR", "Suriname"}, {"UY", "Uruguay"}, - {"VE", "Venezuela"} -}; - -inline QString calculateDirectorySize(const QDir &directory) { - constexpr double MB = 1024.0 * 1024.0; - constexpr double GB = 1024.0 * MB; - - if (!directory.exists()) { - return QObject::tr("0 MB"); - } - - double totalSize = 0; - QDirIterator it(directory.absolutePath(), QDir::Files, QDirIterator::Subdirectories); - while (it.hasNext()) { - it.next(); - totalSize += it.fileInfo().size(); - } - - if (totalSize >= GB) { - return QString::number(totalSize / GB, 'f', 2) + QObject::tr(" GB"); - } - return QString::number(totalSize / MB, 'f', 2) + QObject::tr(" MB"); -} - -inline QString daySuffix(int day) { - if (day % 10 == 1 && day != 11) return "st"; - if (day % 10 == 2 && day != 12) return "nd"; - if (day % 10 == 3 && day != 13) return "rd"; - return "th"; -} - -inline QString formatCurrentDate() { - QDate currentDate = QDate::currentDate(); - return currentDate.toString("MMMM d'") + daySuffix(currentDate.day()) + QString(", %1").arg(currentDate.year()); -} - -inline QString formatElapsedTime(float elapsedMilliseconds) { - int totalSeconds = elapsedMilliseconds / 1000; - int hours = totalSeconds / 3600; - int minutes = (totalSeconds % 3600) / 60; - int seconds = totalSeconds % 60; - - QString formattedTime; - if (hours > 0) { - formattedTime += QString::number(hours) + (hours == 1 ? QObject::tr(" hour ") : QObject::tr(" hours ")); - } - if (minutes > 0) { - formattedTime += QString::number(minutes) + (minutes == 1 ? QObject::tr(" minute ") : QObject::tr(" minutes ")); - } - formattedTime += QString::number(seconds) + (seconds == 1 ? QObject::tr(" second") : QObject::tr(" seconds")); - - return formattedTime.trimmed(); -} - -inline QString formatETA(float elapsedTime, int downloadedFiles, int previousDownloadedFiles, int totalFiles, QDateTime &startTime) { - static QDateTime estimatedFinishTime; - - static float previousElapsedTime; - - if (downloadedFiles != previousDownloadedFiles) { - estimatedFinishTime = startTime.addMSecs((elapsedTime * totalFiles) / downloadedFiles); - } else { - estimatedFinishTime = estimatedFinishTime.addSecs((previousElapsedTime - elapsedTime) / 1000); - } - previousElapsedTime = elapsedTime; - - int remainingTime = QDateTime::currentDateTime().secsTo(estimatedFinishTime); - - QString estimatedFinishTimeStr = estimatedFinishTime.toString("h:mm AP"); - QString remainingTimeStr = formatElapsedTime(remainingTime * 1000); - - return QString("%1 (%2)").arg(remainingTimeStr).arg(estimatedFinishTimeStr); -} - -class MapSelectionControl : public QWidget { - Q_OBJECT - -public: - MapSelectionControl(const QMap &map, bool isCountry = false); - -private: - void loadSelectedMaps(); - void updateSelectedMaps(); - - Params params; - - QButtonGroup *mapButtons; - - QString selectionType; -}; diff --git a/starpilot/ui/qt/widgets/starpilot_controls.cc b/starpilot/ui/qt/widgets/starpilot_controls.cc deleted file mode 100644 index 01b340b72..000000000 --- a/starpilot/ui/qt/widgets/starpilot_controls.cc +++ /dev/null @@ -1,145 +0,0 @@ -#include "selfdrive/ui/ui.h" - -#include "starpilot/ui/starpilot_ui.h" - -bool StarPilotConfirmationDialog::toggleReboot(QWidget *parent) { - ConfirmationDialog d(tr("Reboot required to take effect."), tr("Reboot Now"), tr("Reboot Later"), false, parent); - return d.exec(); -} - -bool StarPilotConfirmationDialog::yesorno(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Yes"), tr("No"), false, parent); - return d.exec(); -} - -bool isFrogsGoMoo() { - static bool is_FrogsGoMoo = QFile::exists("/persist/frogsgomoo.py"); - return is_FrogsGoMoo; -} - -bool useKonikServer() { - static bool use_konik = QFile::exists("/cache/use_konik"); - return use_konik; -} - -void clearMovie(QSharedPointer &movie, QWidget *parent) { - if (!movie) { - return; - } - - QObject::disconnect(movie.data(), nullptr, parent, nullptr); - movie->stop(); - movie.reset(); -} - -void loadGif(const QString &gifPath, QSharedPointer &movie, const QSize &size, QWidget *parent) { - if (!parent || gifPath.isEmpty()) { - return; - } - - if (movie && movie->fileName() == gifPath && movie->state() == QMovie::Running) { - if (movie->scaledSize() != size) { - movie->setScaledSize(size); - } - return; - } - - if (!QFileInfo::exists(gifPath)) { - clearMovie(movie, parent); - return; - } - - clearMovie(movie, parent); - - movie = QSharedPointer::create(gifPath); - movie->setCacheMode(QMovie::CacheAll); - movie->setScaledSize(size); - - QPointer safeParent(parent); - QObject::connect(movie.data(), &QMovie::frameChanged, parent, [safeParent]() { - if (safeParent && safeParent->isVisible()) { - safeParent->update(); - } - }, Qt::UniqueConnection); - - movie->start(); -} - -static QString resolveImagePath(const QString &basePath, const QStringList &extensions) { - for (const QString &extension : extensions) { - const QString candidate = basePath + "." + extension; - if (QFileInfo::exists(candidate)) { - return candidate; - } - } - - return {}; -} - -void loadImage(const QString &basePath, QPixmap &pixmap, QSharedPointer &movie, const QSize &size, QWidget *parent) { - if (!parent || basePath.isEmpty()) { - return; - } - - static QHash pixmapCache; - const QString gifPath = resolveImagePath(basePath, {"gif"}); - if (!gifPath.isEmpty()) { - loadGif(gifPath, movie, size, parent); - if (!pixmap.isNull()) { - pixmap = QPixmap(); - } - return; - } - - clearMovie(movie, parent); - - const QString imagePath = resolveImagePath(basePath, {"png", "webp", "jpg", "jpeg"}); - if (imagePath.isEmpty()) { - if (!pixmap.isNull()) { - pixmap = QPixmap(); - parent->update(); - } - return; - } - - const QFileInfo imageInfo(imagePath); - const QString cacheKey = imagePath + QString("_%1x%2_%3").arg(size.width()).arg(size.height()).arg(imageInfo.lastModified().toMSecsSinceEpoch()); - - if (pixmapCache.contains(cacheKey)) { - QPixmap &cached = pixmapCache[cacheKey]; - if (pixmap.cacheKey() != cached.cacheKey()) { - pixmap = cached; - parent->update(); - } - return; - } - - QPixmap loadedPixmap(imagePath); - if (!loadedPixmap.isNull()) { - pixmap = loadedPixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); - pixmapCache.insert(cacheKey, pixmap); - } else { - pixmap = QPixmap(); - } - - parent->update(); -} - -void openDescriptions(bool forceOpenDescriptions, std::map toggles) { - if (forceOpenDescriptions) { - for (auto &[key, toggle] : toggles) { - if (key != "CESpeed" && key != "CCMSpeed") { - toggle->showDescription(); - } - } - } -} - -void updateStarPilotToggles() { - static Params params_memory{"", true}; - params_memory.putBool("StarPilotTogglesUpdated", true); -} - -QString cleanModelName(QString modelName) { - return modelName.remove("_default").remove("(Default)"); -} diff --git a/starpilot/ui/qt/widgets/starpilot_controls.h b/starpilot/ui/qt/widgets/starpilot_controls.h deleted file mode 100644 index ed6321afb..000000000 --- a/starpilot/ui/qt/widgets/starpilot_controls.h +++ /dev/null @@ -1,644 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" - -bool isFrogsGoMoo(); -bool useKonikServer(); - -void loadGif(const QString &gifPath, QSharedPointer &movie, const QSize &size, QWidget *parent); -void loadImage(const QString &basePath, QPixmap &pixmap, QSharedPointer &movie, const QSize &size, QWidget *parent); -void openDescriptions(bool forceOpenDescriptions, std::map toggles); -void updateStarPilotToggles(); - -QString cleanModelName(QString modelName); - -const QString buttonStyle = R"( - QPushButton { - padding: 0px 25px 0px 25px; - border-radius: 50px; - font-size: 35px; - font-weight: 500; - height: 100px; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:checked:enabled { - background-color: #33Ab4C; - } - QPushButton:disabled { - color: #33E4E4E4; - } -)"; - -class StarPilotConfirmationDialog : public ConfirmationDialog { - Q_OBJECT - -public: - explicit StarPilotConfirmationDialog(const QString &prompt_text, const QString &confirm_text, - const QString &cancel_text, const bool rich, QWidget *parent); - static bool toggleReboot(QWidget *parent); - static bool yesorno(const QString &prompt_text, QWidget *parent); -}; - -class StarPilotListWidget : public QWidget { - Q_OBJECT - public: - explicit StarPilotListWidget(QWidget *parent = 0) : QWidget(parent), outer_layout(this) { - outer_layout.setMargin(0); - outer_layout.setSpacing(0); - outer_layout.addLayout(&inner_layout); - inner_layout.setMargin(0); - inner_layout.setSpacing(25); // default spacing is 25 - outer_layout.addStretch(); - } - inline void addItem(QWidget *w, bool expanding = false) { - w->setSizePolicy(QSizePolicy::Preferred, expanding ? QSizePolicy::Expanding : QSizePolicy::Maximum); - inner_layout.addWidget(w); - } - inline void addItem(QLayout *layout) { inner_layout.addLayout(layout); } - inline void insertItem(int index, QWidget *w, bool expanding = false) { - w->setSizePolicy(QSizePolicy::Preferred, expanding ? QSizePolicy::Expanding : QSizePolicy::Fixed); - inner_layout.insertWidget(index, w); - } - inline void setSpacing(int spacing) { inner_layout.setSpacing(spacing); } - - void clear() { - while (QLayoutItem *child = inner_layout.takeAt(0)) { - if (child->widget()) { - child->widget()->deleteLater(); - } - delete child; - } - outer_layout.addStretch(); - } - -private: - void paintEvent(QPaintEvent *) override { - QPainter p(this); - p.setPen(Qt::gray); - for (int i = 0; i < inner_layout.count() - 1; ++i) { - QWidget *widget = inner_layout.itemAt(i)->widget(); - - QWidget *nextWidget = nullptr; - for (int j = i + 1; j < inner_layout.count(); ++j) { - nextWidget = inner_layout.itemAt(j)->widget(); - if (nextWidget != nullptr && nextWidget->isVisible()) { - break; - } - } - - if (widget == nullptr || (widget->isVisible() && nextWidget->isVisible())) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); - } - } - } - QVBoxLayout outer_layout; - QVBoxLayout inner_layout; -}; - -class StarPilotButtonControl : public ParamControl { - Q_OBJECT -public: - StarPilotButtonControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, bool checkable = false, - bool exclusive = false, int minimum_button_width = 225) : ParamControl(param, title, desc, icon) { - key = param.toStdString(); - - button_group = new QButtonGroup(this); - button_group->setExclusive(exclusive); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(checkable); - button->setStyleSheet(buttonStyle); - button->setMinimumWidth(minimum_button_width); - hlayout->addWidget(button); - button_group->addButton(button, i); - } - - hlayout->addWidget(&toggle); - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), [=](int id) { - emit buttonClicked(id); - }); - - QObject::connect(this, &ToggleControl::toggleFlipped, this, &StarPilotButtonControl::refresh); - - refresh(); - } - - virtual void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - } - - for (QAbstractButton *button : button_group->buttons()) { - button->setEnabled(state); - } - } - - void clearCheckedButtons() { - bool original_exclusive = button_group->exclusive(); - - button_group->setExclusive(false); - - for (QAbstractButton *button : button_group->buttons()) { - button->setChecked(false); - } - - button_group->setExclusive(original_exclusive); - } - - void setCheckedButton(int id) { - if (QAbstractButton *button = button_group->button(id)) { - button->setChecked(true); - } - } - - void setEnabledButton(int id, bool enable) { - if (QAbstractButton *button = button_group->button(id)) { - button->setEnabled(enable); - } - } - - void setVisibleButton(int id, bool visible) { - if (QAbstractButton *button = button_group->button(id)) { - button->setVisible(visible); - } - } - -signals: - void buttonClicked(int id); - -protected: - std::string key; - - Params params; - - QButtonGroup *button_group; -}; - -class StarPilotButtonsControl : public AbstractControl { - Q_OBJECT -public: - StarPilotButtonsControl(const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const bool &checkable = false, const bool &exclusive = true, - const int minimum_button_width = 225) : AbstractControl(title, desc, icon) { - button_group = new QButtonGroup(this); - button_group->setExclusive(exclusive); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->installEventFilter(this); - button->setCheckable(checkable); - button->setStyleSheet(buttonStyle); - button->setMinimumWidth(minimum_button_width); - hlayout->addWidget(button); - button_group->addButton(button, i); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), [=](int id) { - emit buttonClicked(id); - }); - } - - void clearCheckedButtons() { - bool original_exclusive = button_group->exclusive(); - - button_group->setExclusive(false); - - for (QAbstractButton *button : button_group->buttons()) { - button->setChecked(false); - } - - button_group->setExclusive(original_exclusive); - } - - void setCheckedButton(int id) { - if (QAbstractButton *button = button_group->button(id)) { - button->setChecked(true); - } - } - - void setEnabled(bool enable) { - for (QAbstractButton *button : button_group->buttons()) { - button->setEnabled(enable); - } - } - - void setEnabledButtons(int id, bool enable) { - if (QAbstractButton *button = button_group->button(id)) { - button->setEnabled(enable); - } - } - - void setText(int id, const QString &text) { - if (QAbstractButton *button = button_group->button(id)) { - button->setText(text); - } - } - - void setVisibleButton(int id, bool visible) { - if (QAbstractButton *button = button_group->button(id)) { - button->setVisible(visible); - } - } - -signals: - void buttonClicked(int id); - void disabledButtonClicked(int id); - -protected: - bool eventFilter(QObject *obj, QEvent *event) override { - if (event->type() == QEvent::MouseButtonPress) { - QPushButton *button = qobject_cast(obj); - if (button && !button->isEnabled()) { - emit disabledButtonClicked(button_group->id(button)); - } - } - return AbstractControl::eventFilter(obj, event); - } - -private: - QButtonGroup *button_group; -}; - -class StarPilotButtonToggleControl : public StarPilotButtonControl { - Q_OBJECT -public: - StarPilotButtonToggleControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_params, const std::vector &button_texts, - bool exclusive = false, int minimum_button_width = 225) - : StarPilotButtonControl(param, title, desc, icon, button_texts, true, exclusive, minimum_button_width), button_params(button_params) { - - for (int i = 0; i < button_texts.size(); i++) { - button_group->buttons()[i]->setChecked(params.getBool(button_params[i].toStdString())); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), [=](int id) { - params.putBool(button_params[id].toStdString(), button_group->button(id)->isChecked()); - emit buttonClicked(id); - }); - } - - void refresh() override { - StarPilotButtonControl::refresh(); - - for (int i = 0; i < button_group->buttons().size(); i++) { - QAbstractButton *button = button_group->button(i); - button->setChecked(params.getBool(button_params[i].toStdString())); - } - } - -private: - std::vector button_params; -}; - -class StarPilotManageControl : public ParamControl { - Q_OBJECT -public: - StarPilotManageControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon) : ParamControl(param, title, desc, icon) { - key = param.toStdString(); - - manageButton = new ButtonControl("", tr("MANAGE"), "", this); - - hlayout->insertWidget(hlayout->indexOf(&toggle) - 1, manageButton); - - QObject::connect(manageButton, &ButtonControl::clicked, this, &StarPilotManageControl::manageButtonClicked); - QObject::connect(this, &ToggleControl::toggleFlipped, this, &StarPilotManageControl::refresh); - } - - void refresh() { - manageButton->setEnabled(params.getBool(key)); - } - - void setManageVisibility(bool visible) { - manageButton->setVisible(visible); - } - - void showEvent(QShowEvent *event) override { - refresh(); - ParamControl::showEvent(event); - } - -signals: - void manageButtonClicked(); - -private: - std::string key; - - ButtonControl *manageButton; - - Params params; -}; - -class StarPilotParamValueControl : public AbstractControl { - Q_OBJECT -public: - StarPilotParamValueControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - float min_value, float max_value, const QString &label, const std::map &value_labels = {}, - float interval = 1.0f, bool fast_increase = false, int label_width = 350) - : AbstractControl(title, desc, icon), - fast_increase(fast_increase), interval(interval), label(label), min_value(min_value), max_value(max_value), value_labels(value_labels) { - factor = std::pow(10, std::ceil(-std::log10(interval))); - key = param.toStdString(); - key_type = params.getKeyType(key); - - setupButton(decrement_button, "-"); - setupButton(increment_button, "+"); - - value_label = new QLabel(this); - value_label->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - value_label->setFixedSize(QSize(label_width, 100)); - value_label->setStyleSheet("QLabel {color: #E0E879;}"); - - hlayout->addWidget(value_label); - hlayout->addWidget(&decrement_button); - hlayout->addWidget(&increment_button); - - QObject::connect(&decrement_button, &QPushButton::pressed, this, &StarPilotParamValueControl::decrementPressed); - QObject::connect(&increment_button, &QPushButton::pressed, this, &StarPilotParamValueControl::incrementPressed); - - last_action_timer.start(); - } - - void decrementPressed() { - if (display_warning && !warning_shown) { - showWarning(); - } - - if (last_action_timer.isValid() && last_action_timer.elapsed() > decrement_button.autoRepeatInterval() + 50) { - decrement_repeating = false; - } - - float delta = decrement_repeating && fast_increase ? interval * 5 : interval; - value = std::max(value - delta, min_value); - - updateValue(); - - if (std::lround(value / interval) % 5 == 0) { - decrement_repeating = true; - } - - last_action_timer.restart(); - } - - void hideEvent(QHideEvent *event) override { - AbstractControl::hideEvent(event); - - warning_shown = false; - - updateParam(); - } - - void incrementPressed() { - if (display_warning && !warning_shown) { - showWarning(); - } - - if (last_action_timer.isValid() && last_action_timer.elapsed() > increment_button.autoRepeatInterval() + 50) { - increment_repeating = false; - } - - float delta = increment_repeating && fast_increase ? interval * 5 : interval; - value = std::min(value + delta, max_value); - - updateValue(); - - if (std::lround(value / interval) % 5 == 0) { - increment_repeating = true; - } - - last_action_timer.restart(); - } - - void refresh() { - if (key_type == ParamKeyType::INT) { - value = std::clamp(std::round(params.getInt(key) * factor) / factor, min_value, max_value); - } else { - value = std::clamp(std::round(params.getFloat(key) * factor) / factor, min_value, max_value); - } - previous_value = value; - - updateDisplay(); - updateParam(); - } - - void setWarning(const QString &newWarning) { - display_warning = true; - - warning = newWarning; - } - - void setupButton(QPushButton &button, const QString &text) { - button.setAutoRepeat(true); - button.setAutoRepeatDelay(500); - button.setAutoRepeatInterval(150); - button.setFixedSize(150, 100); - button.setStyleSheet(buttonStyle); - if (text == "+" || text == "-") { - button.setStyleSheet(button.styleSheet() + " QPushButton { font-size: 50px; }"); - } - button.setText(text); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - - void showWarning() { - ConfirmationDialog::alert(warning, this); - - warning_shown = true; - } - - void updateControl(const float &newMinValue, const float &newMaxValue, const std::map &newValueLabels = {}) { - min_value = newMinValue; - max_value = newMaxValue; - - value_labels = newValueLabels; - - refresh(); - } - - void updateDisplay() { - QString displayText = QString::number(value) + label; - - for (const std::pair &entry : value_labels) { - if (std::lround(entry.first * factor) == std::lround(value * factor)) { - displayText = entry.second; - break; - } - } - - decrement_button.setEnabled(value > min_value); - increment_button.setEnabled(value < max_value); - - value_label->setText(displayText); - } - - void updateParam() { - if (value == previous_value) { - return; - } - - if (key_type == ParamKeyType::INT) { - params.putInt(key, value); - } else { - params.putFloat(key, value); - } - } - - void updateValue() { - value = std::round(value * factor) / factor; - - emit valueChanged(value); - - updateDisplay(); - } - -signals: - void valueChanged(float value); - -protected: - QLabel *value_label; - -private: - bool decrement_repeating; - bool display_warning; - bool fast_increase; - bool increment_repeating; - bool warning_shown; - - float interval; - float factor; - float max_value; - float min_value; - float previous_value; - float value; - - std::map value_labels; - - std::string key; - - ParamKeyType key_type; - - Params params; - - QElapsedTimer last_action_timer; - - QPushButton decrement_button; - QPushButton increment_button; - - QString label; - QString warning; -}; - -class StarPilotParamValueButtonControl : public StarPilotParamValueControl { - Q_OBJECT -public: - StarPilotParamValueButtonControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - float min_value, float max_value, const QString &label, const std::map &value_labels, - float interval, bool fast_increase, const std::vector &button_params, const std::vector &button_texts, - bool left_button = false, bool checkable = true, int minimum_button_width = 225) - : StarPilotParamValueControl(param, title, desc, icon, min_value, max_value, label, value_labels, interval, fast_increase, 200), - button_params(button_params), checkable(checkable) { - button_group = new QButtonGroup(this); - button_group->setExclusive(false); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(checkable); - button->setChecked(checkable && params.getBool(button_params[i].toStdString())); - button->setStyleSheet(buttonStyle); - button->setMinimumWidth(minimum_button_width); - if (left_button) { - hlayout->insertWidget(hlayout->indexOf(value_label) - 1, button); - } else { - hlayout->addWidget(button); - } - button_group->addButton(button, i); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), [=](int id) { - if (checkable) { - params.putBool(button_params[id].toStdString(), button_group->button(id)->isChecked()); - } - emit buttonClicked(id); - }); - } - - void refresh() { - if (checkable) { - for (int i = 0; i < button_group->buttons().size(); i++) { - QAbstractButton *button = button_group->button(i); - button->setChecked(params.getBool(button_params[i].toStdString())); - } - } - StarPilotParamValueControl::refresh(); - } - - void showEvent(QShowEvent *event) override { - refresh(); - StarPilotParamValueControl::showEvent(event); - } - -public: - void setEnabledButtons(int id, bool enable) { - if (QAbstractButton *button = button_group->button(id)) { - button->setEnabled(enable); - } - } - -signals: - void buttonClicked(int id); - -private: - bool checkable; - - std::vector button_params; - - Params params; - - QButtonGroup *button_group; -}; - -class StarPilotDualParamValueControl : public QFrame { - Q_OBJECT -public: - StarPilotDualParamValueControl(StarPilotParamValueControl *control1, StarPilotParamValueControl *control2, QWidget *parent = nullptr) : QFrame(parent), control1(control1), control2(control2) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->addWidget(control1); - hlayout->addWidget(control2); - } - - void updateControl(const float &newMinValue, const float &newMaxValue, const std::map &newValueLabels = {}) { - control1->updateControl(newMinValue, newMaxValue, newValueLabels); - control2->updateControl(newMinValue, newMaxValue, newValueLabels); - } - - void refresh() { - control1->refresh(); - control2->refresh(); - } - -private: - StarPilotParamValueControl *control1; - StarPilotParamValueControl *control2; -}; diff --git a/starpilot/ui/screenrecorder/blocking_queue.h b/starpilot/ui/screenrecorder/blocking_queue.h deleted file mode 100644 index a9cb23e83..000000000 --- a/starpilot/ui/screenrecorder/blocking_queue.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -template -class BlockingQueue { -public: - BlockingQueue(size_t capacity) : capacity(capacity) {} - - void push(T &&item) { - std::unique_lock lk(mutex); - not_full.wait(lk, [this]() { return content.size() < capacity; }); - content.push_back(std::move(item)); - not_empty.notify_one(); - } - - bool try_push(T &&item) { - std::unique_lock lk(mutex); - if (content.size() == capacity) return false; - content.push_back(std::move(item)); - not_empty.notify_one(); - return true; - } - - T pop() { - std::unique_lock lk(mutex); - not_empty.wait(lk, [this]() { return !content.empty(); }); - T item = std::move(content.front()); - content.pop_front(); - not_full.notify_one(); - return item; - } - - bool pop_wait_for(T &item, std::chrono::milliseconds duration) { - std::unique_lock lk(mutex); - if (!not_empty.wait_for(lk, duration, [this]() { return !content.empty(); })) { - return false; - } - item = std::move(content.front()); - content.pop_front(); - not_full.notify_one(); - return true; - } - - bool try_pop(T &item) { - std::unique_lock lk(mutex); - if (content.empty()) return false; - item = std::move(content.front()); - content.pop_front(); - not_full.notify_one(); - return true; - } - - void clear() { - std::unique_lock lk(mutex); - content.clear(); - not_full.notify_all(); - } - -private: - size_t capacity; - std::deque content; - std::mutex mutex; - std::condition_variable not_empty; - std::condition_variable not_full; -}; diff --git a/starpilot/ui/screenrecorder/moc_screenrecorder.cc b/starpilot/ui/screenrecorder/moc_screenrecorder.cc deleted file mode 100644 index bb5d2f5a6..000000000 --- a/starpilot/ui/screenrecorder/moc_screenrecorder.cc +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************** -** Meta object code from reading C++ file 'screenrecorder.h' -** -** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) -** -** WARNING! All changes made in this file will be lost! -*****************************************************************************/ - -#include "screenrecorder.h" -#include -#include -#if !defined(Q_MOC_OUTPUT_REVISION) -#error "The header file 'screenrecorder.h' doesn't include ." -#elif Q_MOC_OUTPUT_REVISION != 67 -#error "This file was generated using the moc from 5.12.8. It" -#error "cannot be used with the include files from this version of Qt." -#error "(The moc has changed too much.)" -#endif - -QT_BEGIN_MOC_NAMESPACE -QT_WARNING_PUSH -QT_WARNING_DISABLE_DEPRECATED -struct qt_meta_stringdata_ScreenRecorder_t { - QByteArrayData data[3]; - char stringdata0[32]; -}; -#define QT_MOC_LITERAL(idx, ofs, len) \ - Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ - qptrdiff(offsetof(qt_meta_stringdata_ScreenRecorder_t, stringdata0) + ofs \ - - idx * sizeof(QByteArrayData)) \ - ) -static const qt_meta_stringdata_ScreenRecorder_t qt_meta_stringdata_ScreenRecorder = { - { -QT_MOC_LITERAL(0, 0, 14), // "ScreenRecorder" -QT_MOC_LITERAL(1, 15, 15), // "toggleRecording" -QT_MOC_LITERAL(2, 31, 0) // "" - - }, - "ScreenRecorder\0toggleRecording\0" -}; -#undef QT_MOC_LITERAL - -static const uint qt_meta_data_ScreenRecorder[] = { - - // content: - 8, // revision - 0, // classname - 0, 0, // classinfo - 1, 14, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - 0, // flags - 0, // signalCount - - // slots: name, argc, parameters, tag, flags - 1, 0, 19, 2, 0x08 /* Private */, - - // slots: parameters - QMetaType::Void, - - 0 // eod -}; - -void ScreenRecorder::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) -{ - if (_c == QMetaObject::InvokeMetaMethod) { - auto *_t = static_cast(_o); - Q_UNUSED(_t) - switch (_id) { - case 0: _t->toggleRecording(); break; - default: ; - } - } - Q_UNUSED(_a); -} - -QT_INIT_METAOBJECT const QMetaObject ScreenRecorder::staticMetaObject = { { - &QPushButton::staticMetaObject, - qt_meta_stringdata_ScreenRecorder.data, - qt_meta_data_ScreenRecorder, - qt_static_metacall, - nullptr, - nullptr -} }; - - -const QMetaObject *ScreenRecorder::metaObject() const -{ - return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; -} - -void *ScreenRecorder::qt_metacast(const char *_clname) -{ - if (!_clname) return nullptr; - if (!strcmp(_clname, qt_meta_stringdata_ScreenRecorder.stringdata0)) - return static_cast(this); - return QPushButton::qt_metacast(_clname); -} - -int ScreenRecorder::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QPushButton::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - if (_id < 1) - qt_static_metacall(this, _c, _id, _a); - _id -= 1; - } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { - if (_id < 1) - *reinterpret_cast(_a[0]) = -1; - _id -= 1; - } - return _id; -} -QT_WARNING_POP -QT_END_MOC_NAMESPACE diff --git a/starpilot/ui/screenrecorder/omx_encoder.cc b/starpilot/ui/screenrecorder/omx_encoder.cc deleted file mode 100644 index b0222cc8b..000000000 --- a/starpilot/ui/screenrecorder/omx_encoder.cc +++ /dev/null @@ -1,432 +0,0 @@ -#include "starpilot/ui/screenrecorder/omx_encoder.h" - -#if defined(QCOM2) && !defined(__APPLE__) - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -extern "C" { -#include -} - -#include "libyuv.h" -#include "msm_media_info.h" - -#include "common/swaglog.h" -#include "common/util.h" - -#define OMX_CHECK(_expr) assert(OMX_ErrorNone == (_expr)) -#define PORT_INDEX_IN 0 -#define PORT_INDEX_OUT 1 - -using namespace libyuv; - -LIBYUV_API -int ABGRToNV12(const uint8_t* src_abgr, int src_stride_abgr, - uint8_t* dst_y, int dst_stride_y, - uint8_t* dst_uv, int dst_stride_uv, - int width, int height) { - int y; - int halfwidth = (width + 1) >> 1; - - void (*ABGRToUVRow)(const uint8_t* src_abgr0, int src_stride_abgr, - uint8_t* dst_u, uint8_t* dst_v, int width) = ABGRToUVRow_NEON; - void (*ABGRToYRow)(const uint8_t* src_abgr, uint8_t* dst_y, int width) = ABGRToYRow_NEON; - void (*MergeUVRow_)(const uint8_t* src_u, const uint8_t* src_v, - uint8_t* dst_uv, int width) = MergeUVRow_NEON; - - if (!src_abgr || !dst_y || !dst_uv || width <= 0 || height == 0) { - return -1; - } - - if (height < 0) { - height = -height; - src_abgr = src_abgr + (height - 1) * src_stride_abgr; - src_stride_abgr = -src_stride_abgr; - } - - align_buffer_64(row_u, ((halfwidth + 31) & ~31) * 2); - uint8_t* row_v = row_u + ((halfwidth + 31) & ~31); - - for (y = 0; y < height - 1; y += 2) { - ABGRToUVRow(src_abgr, src_stride_abgr, row_u, row_v, width); - MergeUVRow_(row_u, row_v, dst_uv, halfwidth); - ABGRToYRow(src_abgr, dst_y, width); - ABGRToYRow(src_abgr + src_stride_abgr, dst_y + dst_stride_y, width); - src_abgr += src_stride_abgr * 2; - dst_y += dst_stride_y * 2; - dst_uv += dst_stride_uv; - } - - if (height & 1) { - ABGRToUVRow(src_abgr, 0, row_u, row_v, width); - MergeUVRow_(row_u, row_v, dst_uv, halfwidth); - ABGRToYRow(src_abgr, dst_y, width); - } - - free_aligned_buffer_64(row_u); - return 0; -} - -void OmxEncoder::wait_for_state(OMX_STATETYPE state_) { - std::unique_lock lk(state_lock); - state_cv.wait(lk, [&]{ return state == state_; }); -} - -static OMX_CALLBACKTYPE omx_callbacks = { - .EventHandler = OmxEncoder::event_handler, - .EmptyBufferDone = OmxEncoder::empty_buffer_done, - .FillBufferDone = OmxEncoder::fill_buffer_done, -}; - -OMX_ERRORTYPE OmxEncoder::event_handler(OMX_HANDLETYPE component, OMX_PTR app_data, OMX_EVENTTYPE event, - OMX_U32 data1, OMX_U32 data2, OMX_PTR event_data) { - OmxEncoder *e = (OmxEncoder*)app_data; - if (event == OMX_EventCmdComplete) { - assert(data1 == OMX_CommandStateSet); - { - std::lock_guard lk(e->state_lock); - e->state = (OMX_STATETYPE)data2; - } - e->state_cv.notify_all(); - } else if (event == OMX_EventError) { - LOGE("OMX error 0x%08x", data1); - } - return OMX_ErrorNone; -} - -OMX_ERRORTYPE OmxEncoder::empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer) { - OmxEncoder *e = (OmxEncoder*)app_data; - e->free_in->push(std::move(buffer)); - return OMX_ErrorNone; -} - -OMX_ERRORTYPE OmxEncoder::fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer) { - OmxEncoder *e = (OmxEncoder*)app_data; - e->done_out->push(std::move(buffer)); - return OMX_ErrorNone; -} - -OmxEncoder::OmxEncoder(const char* path, int width, int height, int fps, int bitrate) - : path(path), width(width), height(height), fps(fps) { - - OMX_ERRORTYPE err = OMX_Init(); - if (err != OMX_ErrorNone) { - LOGE("OMX_Init failed: %x", err); - return; - } - - OMX_STRING component = (OMX_STRING)("OMX.qcom.video.encoder.avc"); - err = OMX_GetHandle(&handle, component, this, &omx_callbacks); - if (err != OMX_ErrorNone) { - LOGE("Error getting codec: %x", err); - OMX_Deinit(); - return; - } - - // Input Port Configuration - OMX_PARAM_PORTDEFINITIONTYPE in_port = {0}; - in_port.nSize = sizeof(in_port); - in_port.nPortIndex = (OMX_U32) PORT_INDEX_IN; - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - - in_port.format.video.nFrameWidth = width; - in_port.format.video.nFrameHeight = height; - in_port.format.video.nStride = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); - in_port.format.video.nSliceHeight = height; - in_port.nBufferSize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, width, height); - in_port.format.video.xFramerate = (fps * 65536); - in_port.format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; - in_port.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; - - OMX_CHECK(OMX_SetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - - in_buf_headers.resize(in_port.nBufferCountActual); - free_in = std::make_unique>(in_port.nBufferCountActual); - - // Output Port Configuration - OMX_PARAM_PORTDEFINITIONTYPE out_port = {0}; - out_port.nSize = sizeof(out_port); - out_port.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR)&out_port)); - - out_port.format.video.nFrameWidth = width; - out_port.format.video.nFrameHeight = height; - out_port.format.video.nBitrate = bitrate; - out_port.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC; - out_port.format.video.eColorFormat = OMX_COLOR_FormatUnused; - - OMX_CHECK(OMX_SetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR) &out_port)); - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamPortDefinition, (OMX_PTR) &out_port)); - - out_buf_headers.resize(out_port.nBufferCountActual); - done_out = std::make_unique>(out_port.nBufferCountActual); - - // Bitrate Control - OMX_VIDEO_PARAM_BITRATETYPE bitrate_type = {0}; - bitrate_type.nSize = sizeof(bitrate_type); - bitrate_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamVideoBitrate, (OMX_PTR) &bitrate_type)); - bitrate_type.eControlRate = OMX_Video_ControlRateVariable; - bitrate_type.nTargetBitrate = bitrate; - OMX_CHECK(OMX_SetParameter(handle, OMX_IndexParamVideoBitrate, (OMX_PTR) &bitrate_type)); - - // AVC Parameters - OMX_VIDEO_PARAM_AVCTYPE avc = {0}; - avc.nSize = sizeof(avc); - avc.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(handle, OMX_IndexParamVideoAvc, &avc)); - avc.nBFrames = 0; - avc.nPFrames = 15; - avc.eProfile = OMX_VIDEO_AVCProfileHigh; - avc.eLevel = OMX_VIDEO_AVCLevel31; - avc.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB; - avc.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable; - avc.nRefFrames = 1; - avc.bUseHadamard = OMX_TRUE; - avc.bEntropyCodingCABAC = OMX_TRUE; - avc.bWeightedPPrediction = OMX_TRUE; - avc.bconstIpred = OMX_TRUE; - OMX_CHECK(OMX_SetParameter(handle, OMX_IndexParamVideoAvc, &avc)); - - OMX_CHECK(OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateIdle, NULL)); - - for (OMX_BUFFERHEADERTYPE* &buf : in_buf_headers) { - OMX_CHECK(OMX_AllocateBuffer(handle, &buf, PORT_INDEX_IN, this, in_port.nBufferSize)); - } - for (OMX_BUFFERHEADERTYPE* &buf : out_buf_headers) { - OMX_CHECK(OMX_AllocateBuffer(handle, &buf, PORT_INDEX_OUT, this, out_port.nBufferSize)); - } - - wait_for_state(OMX_StateIdle); - OMX_CHECK(OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateExecuting, NULL)); - wait_for_state(OMX_StateExecuting); - - for (OMX_BUFFERHEADERTYPE* &buf : out_buf_headers) { - OMX_CHECK(OMX_FillThisBuffer(handle, buf)); - } - for (OMX_BUFFERHEADERTYPE* &buf : in_buf_headers) { - free_in->push(std::move(buf)); - } -} - -void OmxEncoder::handle_out_buf(OmxEncoder *encoder, OMX_BUFFERHEADERTYPE *out_buf) { - uint8_t *buf_data = out_buf->pBuffer + out_buf->nOffset; - - if (out_buf->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { - if (encoder->codec_config.size() < out_buf->nFilledLen) { - encoder->codec_config.resize(out_buf->nFilledLen); - } - memcpy(encoder->codec_config.data(), buf_data, out_buf->nFilledLen); -#ifdef QCOM2 - out_buf->nTimeStamp = 0; -#endif - } - - if (encoder->of) { - fwrite(buf_data, out_buf->nFilledLen, 1, encoder->of); - } - - if (!encoder->wrote_codec_config && !encoder->codec_config.empty()) { - encoder->out_stream->codecpar->extradata = (uint8_t*)av_mallocz(encoder->codec_config.size() + AV_INPUT_BUFFER_PADDING_SIZE); - encoder->out_stream->codecpar->extradata_size = encoder->codec_config.size(); - memcpy(encoder->out_stream->codecpar->extradata, encoder->codec_config.data(), encoder->codec_config.size()); - - int err = avformat_write_header(encoder->ofmt_ctx, NULL); - assert(err >= 0); - encoder->wrote_codec_config = true; - } - - if (out_buf->nTimeStamp > 0) { - AVRational in_timebase = {1, 1000000}; - AVPacket pkt; - av_init_packet(&pkt); - pkt.data = buf_data; - pkt.size = out_buf->nFilledLen; - - enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); - pkt.pts = pkt.dts = av_rescale_q_rnd(out_buf->nTimeStamp, in_timebase, encoder->out_stream->time_base, rnd); - pkt.duration = av_rescale_q(1, AVRational{1, encoder->fps}, encoder->out_stream->time_base); - - if (out_buf->nFlags & OMX_BUFFERFLAG_SYNCFRAME) { - pkt.flags |= AV_PKT_FLAG_KEY; - } - - if (av_write_frame(encoder->ofmt_ctx, &pkt) < 0) { - LOGW("ts encoder write issue"); - } - av_packet_unref(&pkt); - } - -#ifdef QCOM2 - if (out_buf->nFlags & OMX_BUFFERFLAG_EOS) { - out_buf->nTimeStamp = 0; - } -#endif - OMX_CHECK(OMX_FillThisBuffer(encoder->handle, out_buf)); -} - -int OmxEncoder::encode_frame_rgba(const uint8_t *ptr, int in_width, int in_height, uint64_t ts) { - if (!is_open) return -1; - - OMX_BUFFERHEADERTYPE* in_buf = nullptr; - if (!free_in->pop_wait_for(in_buf, std::chrono::milliseconds(50))) { - LOGW("OmxEncoder: dropped frame, input queue full"); - return -1; - } - - int ret = counter; - uint8_t *in_buf_ptr = in_buf->pBuffer; - - int in_y_stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); - int in_uv_stride = VENUS_UV_STRIDE(COLOR_FMT_NV12, width); - uint8_t *in_uv_ptr = in_buf_ptr + (in_y_stride * VENUS_Y_SCANLINES(COLOR_FMT_NV12, height)); - - int err = ABGRToNV12(ptr, width * 4, in_buf_ptr, in_y_stride, in_uv_ptr, in_uv_stride, width, height); - assert(err == 0); - - in_buf->nFilledLen = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, width, height); - in_buf->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; - in_buf->nOffset = 0; - in_buf->nTimeStamp = ts / 1000LL; - last_t = in_buf->nTimeStamp; - - OMX_CHECK(OMX_EmptyThisBuffer(handle, in_buf)); - - OMX_BUFFERHEADERTYPE *out_buf; - while (done_out->try_pop(out_buf)) { - handle_out_buf(this, out_buf); - } - - dirty = true; - counter++; - return ret; -} - -void OmxEncoder::encoder_open(const char* filename) { - if (!filename || strlen(filename) == 0) return; - - std::filesystem::path p(path); - std::error_code ec; - std::filesystem::create_directories(p, ec); - if (ec) { - LOGE("Failed to create directories: %s", ec.message().c_str()); - return; - } - - vid_path = (p / filename).string(); - - if (avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, vid_path.c_str()) < 0 || !ofmt_ctx) { - LOGE("Failed to allocate output context"); - return; - } - - out_stream = avformat_new_stream(ofmt_ctx, NULL); - if (!out_stream) { - avformat_free_context(ofmt_ctx); - ofmt_ctx = nullptr; - return; - } - - out_stream->time_base = AVRational{1, fps}; - out_stream->codecpar->codec_id = AV_CODEC_ID_H264; - out_stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; - out_stream->codecpar->width = width; - out_stream->codecpar->height = height; - - if (ofmt_ctx->oformat && ofmt_ctx->oformat->priv_class) { - av_opt_set(ofmt_ctx->priv_data, "movflags", "faststart", 0); - } - - if (avio_open(&ofmt_ctx->pb, vid_path.c_str(), AVIO_FLAG_WRITE) < 0) { - avformat_free_context(ofmt_ctx); - ofmt_ctx = nullptr; - LOGE("Failed to open output file"); - return; - } - - wrote_codec_config = false; - - lock_path = (p / (std::string(filename) + ".lock")).string(); - int lock_fd = HANDLE_EINTR(open(lock_path.c_str(), O_RDWR | O_CREAT, 0664)); - if (lock_fd >= 0) close(lock_fd); - - is_open = true; - counter = 0; -} - -void OmxEncoder::encoder_close() { - if (!is_open) return; - - if (dirty) { - OMX_BUFFERHEADERTYPE* in_buf = nullptr; - if(free_in->pop_wait_for(in_buf, std::chrono::milliseconds(100))) { - in_buf->nFilledLen = 0; - in_buf->nOffset = 0; - in_buf->nFlags = OMX_BUFFERFLAG_EOS; - in_buf->nTimeStamp = last_t + 1000000LL / fps; - OMX_CHECK(OMX_EmptyThisBuffer(handle, in_buf)); - - int retries = 0; - while (retries++ < 100) { - OMX_BUFFERHEADERTYPE *out_buf; - if(done_out->pop_wait_for(out_buf, std::chrono::milliseconds(10))) { - handle_out_buf(this, out_buf); - if (out_buf->nFlags & OMX_BUFFERFLAG_EOS) break; - } - } - } - dirty = false; - } - - if (out_stream) { - out_stream->nb_frames = counter; - out_stream->duration = av_rescale_q(counter, AVRational{1, fps}, out_stream->time_base); - } - - if (ofmt_ctx) { - av_write_trailer(ofmt_ctx); - avio_closep(&ofmt_ctx->pb); - avformat_free_context(ofmt_ctx); - ofmt_ctx = nullptr; - } - - if (!lock_path.empty()) { - unlink(lock_path.c_str()); - } - - is_open = false; -} - -OmxEncoder::~OmxEncoder() { - if (is_open) encoder_close(); - - if (!handle) return; - - OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateIdle, NULL); - wait_for_state(OMX_StateIdle); - OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateLoaded, NULL); - - for (auto buf : in_buf_headers) OMX_FreeBuffer(handle, PORT_INDEX_IN, buf); - for (auto buf : out_buf_headers) OMX_FreeBuffer(handle, PORT_INDEX_OUT, buf); - - wait_for_state(OMX_StateLoaded); - OMX_FreeHandle(handle); - OMX_Deinit(); -} - -#endif diff --git a/starpilot/ui/screenrecorder/omx_encoder.h b/starpilot/ui/screenrecorder/omx_encoder.h deleted file mode 100644 index 4068ec2a3..000000000 --- a/starpilot/ui/screenrecorder/omx_encoder.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once - -#include -#include -#include - -#if defined(__APPLE__) || !defined(QCOM2) -// Qualcomm OpenMAX is unavailable on macOS. Keep a no-op encoder so UI builds. -class OmxEncoder { -public: - OmxEncoder(const char* path, int width, int height, int fps, int bitrate) { (void)path; (void)width; (void)height; (void)fps; (void)bitrate; } - ~OmxEncoder() = default; - - int encode_frame_rgba(const uint8_t *ptr, int in_width, int in_height, uint64_t ts) { - (void)ptr; - (void)in_width; - (void)in_height; - (void)ts; - return -1; - } - void encoder_open(const char* filename) { (void)filename; is_open = false; } - void encoder_close() {} - - std::atomic is_open{false}; -}; -#else -#include -#include -#include -#include -#include -#include - -#include - -extern "C" { -#include -} - -#include "blocking_queue.h" - -class OmxEncoder { -public: - OmxEncoder(const char* path, int width, int height, int fps, int bitrate); - ~OmxEncoder(); - - int encode_frame_rgba(const uint8_t *ptr, int in_width, int in_height, uint64_t ts); - void encoder_open(const char* filename); - void encoder_close(); - - static OMX_ERRORTYPE event_handler(OMX_HANDLETYPE component, OMX_PTR app_data, OMX_EVENTTYPE event, - OMX_U32 data1, OMX_U32 data2, OMX_PTR event_data); - static OMX_ERRORTYPE empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer); - static OMX_ERRORTYPE fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer); - - std::atomic is_open{false}; - -private: - void wait_for_state(OMX_STATETYPE state); - static void handle_out_buf(OmxEncoder *e, OMX_BUFFERHEADERTYPE *out_buf); - - int width, height, fps; - std::string path; - std::string vid_path; - std::string lock_path; - - bool dirty = false; - int counter = 0; - - FILE *of = nullptr; - AVFormatContext *ofmt_ctx = nullptr; - AVStream *out_stream = nullptr; - - std::vector codec_config; - bool wrote_codec_config = false; - - std::mutex state_lock; - std::condition_variable state_cv; - OMX_STATETYPE state = OMX_StateLoaded; - OMX_HANDLETYPE handle = nullptr; - - std::vector in_buf_headers; - std::vector out_buf_headers; - - uint64_t last_t = 0; - - std::unique_ptr> free_in; - std::unique_ptr> done_out; -}; -#endif diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Audio.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Audio.h deleted file mode 100644 index 0d455766c..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Audio.h +++ /dev/null @@ -1,1312 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** @file OMX_Audio.h - OpenMax IL version 1.1.2 - * The structures needed by Audio components to exchange - * parameters and configuration data with the componenmilts. - */ - -#ifndef OMX_Audio_h -#define OMX_Audio_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/* Each OMX header must include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ - -#include - -/** @defgroup midi MIDI - * @ingroup audio - */ - -/** @defgroup effects Audio effects - * @ingroup audio - */ - -/** @defgroup audio OpenMAX IL Audio Domain - * Structures for OpenMAX IL Audio domain - * @{ - */ - -/** Enumeration used to define the possible audio codings. - * If "OMX_AUDIO_CodingUnused" is selected, the coding selection must - * be done in a vendor specific way. Since this is for an audio - * processing element this enum is relevant. However, for another - * type of component other enums would be in this area. - */ -typedef enum OMX_AUDIO_CODINGTYPE { - OMX_AUDIO_CodingUnused = 0, /**< Placeholder value when coding is N/A */ - OMX_AUDIO_CodingAutoDetect, /**< auto detection of audio format */ - OMX_AUDIO_CodingPCM, /**< Any variant of PCM coding */ - OMX_AUDIO_CodingADPCM, /**< Any variant of ADPCM encoded data */ - OMX_AUDIO_CodingAMR, /**< Any variant of AMR encoded data */ - OMX_AUDIO_CodingGSMFR, /**< Any variant of GSM fullrate (i.e. GSM610) */ - OMX_AUDIO_CodingGSMEFR, /**< Any variant of GSM Enhanced Fullrate encoded data*/ - OMX_AUDIO_CodingGSMHR, /**< Any variant of GSM Halfrate encoded data */ - OMX_AUDIO_CodingPDCFR, /**< Any variant of PDC Fullrate encoded data */ - OMX_AUDIO_CodingPDCEFR, /**< Any variant of PDC Enhanced Fullrate encoded data */ - OMX_AUDIO_CodingPDCHR, /**< Any variant of PDC Halfrate encoded data */ - OMX_AUDIO_CodingTDMAFR, /**< Any variant of TDMA Fullrate encoded data (TIA/EIA-136-420) */ - OMX_AUDIO_CodingTDMAEFR, /**< Any variant of TDMA Enhanced Fullrate encoded data (TIA/EIA-136-410) */ - OMX_AUDIO_CodingQCELP8, /**< Any variant of QCELP 8kbps encoded data */ - OMX_AUDIO_CodingQCELP13, /**< Any variant of QCELP 13kbps encoded data */ - OMX_AUDIO_CodingEVRC, /**< Any variant of EVRC encoded data */ - OMX_AUDIO_CodingSMV, /**< Any variant of SMV encoded data */ - OMX_AUDIO_CodingG711, /**< Any variant of G.711 encoded data */ - OMX_AUDIO_CodingG723, /**< Any variant of G.723 dot 1 encoded data */ - OMX_AUDIO_CodingG726, /**< Any variant of G.726 encoded data */ - OMX_AUDIO_CodingG729, /**< Any variant of G.729 encoded data */ - OMX_AUDIO_CodingAAC, /**< Any variant of AAC encoded data */ - OMX_AUDIO_CodingMP3, /**< Any variant of MP3 encoded data */ - OMX_AUDIO_CodingSBC, /**< Any variant of SBC encoded data */ - OMX_AUDIO_CodingVORBIS, /**< Any variant of VORBIS encoded data */ - OMX_AUDIO_CodingWMA, /**< Any variant of WMA encoded data */ - OMX_AUDIO_CodingRA, /**< Any variant of RA encoded data */ - OMX_AUDIO_CodingMIDI, /**< Any variant of MIDI encoded data */ - OMX_AUDIO_CodingAC3, /**< Any variant of AC3 encoded data */ - OMX_AUDIO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_CodingMax = 0x7FFFFFFF -} OMX_AUDIO_CODINGTYPE; - - -/** The PortDefinition structure is used to define all of the parameters - * necessary for the compliant component to setup an input or an output audio - * path. If additional information is needed to define the parameters of the - * port (such as frequency), additional structures must be sent such as the - * OMX_AUDIO_PARAM_PCMMODETYPE structure to supply the extra parameters for the port. - */ -typedef struct OMX_AUDIO_PORTDEFINITIONTYPE { - OMX_STRING cMIMEType; /**< MIME type of data for the port */ - OMX_NATIVE_DEVICETYPE pNativeRender; /** < platform specific reference - for an output device, - otherwise this field is 0 */ - OMX_BOOL bFlagErrorConcealment; /**< Turns on error concealment if it is - supported by the OMX component */ - OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this - port (e.g. PCM, AMR, MP3, etc) */ -} OMX_AUDIO_PORTDEFINITIONTYPE; - - -/** Port format parameter. This structure is used to enumerate - * the various data input/output format supported by the port. - */ -typedef struct OMX_AUDIO_PARAM_PORTFORMATTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Indicates which port to set */ - OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ - OMX_AUDIO_CODINGTYPE eEncoding; /**< Type of data expected for this port (e.g. PCM, AMR, MP3, etc) */ -} OMX_AUDIO_PARAM_PORTFORMATTYPE; - - -/** PCM mode type */ -typedef enum OMX_AUDIO_PCMMODETYPE { - OMX_AUDIO_PCMModeLinear = 0, /**< Linear PCM encoded data */ - OMX_AUDIO_PCMModeALaw, /**< A law PCM encoded data (G.711) */ - OMX_AUDIO_PCMModeMULaw, /**< Mu law PCM encoded data (G.711) */ - OMX_AUDIO_PCMModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_PCMModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_PCMModeMax = 0x7FFFFFFF -} OMX_AUDIO_PCMMODETYPE; - - -typedef enum OMX_AUDIO_CHANNELTYPE { - OMX_AUDIO_ChannelNone = 0x0, /**< Unused or empty */ - OMX_AUDIO_ChannelLF = 0x1, /**< Left front */ - OMX_AUDIO_ChannelRF = 0x2, /**< Right front */ - OMX_AUDIO_ChannelCF = 0x3, /**< Center front */ - OMX_AUDIO_ChannelLS = 0x4, /**< Left surround */ - OMX_AUDIO_ChannelRS = 0x5, /**< Right surround */ - OMX_AUDIO_ChannelLFE = 0x6, /**< Low frequency effects */ - OMX_AUDIO_ChannelCS = 0x7, /**< Back surround */ - OMX_AUDIO_ChannelLR = 0x8, /**< Left rear. */ - OMX_AUDIO_ChannelRR = 0x9, /**< Right rear. */ - OMX_AUDIO_ChannelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_ChannelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_ChannelMax = 0x7FFFFFFF -} OMX_AUDIO_CHANNELTYPE; - -#define OMX_AUDIO_MAXCHANNELS 16 /**< maximum number distinct audio channels that a buffer may contain */ -#define OMX_MIN_PCMPAYLOAD_MSEC 5 /**< Minimum audio buffer payload size for uncompressed (PCM) audio */ - -/** PCM format description */ -typedef struct OMX_AUDIO_PARAM_PCMMODETYPE { - OMX_U32 nSize; /**< Size of this structure, in Bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels (e.g. 2 for stereo) */ - OMX_NUMERICALDATATYPE eNumData; /**< indicates PCM data as signed or unsigned */ - OMX_ENDIANTYPE eEndian; /**< indicates PCM data as little or big endian */ - OMX_BOOL bInterleaved; /**< True for normal interleaved data; false for - non-interleaved data (e.g. block data) */ - OMX_U32 nBitPerSample; /**< Bit per sample */ - OMX_U32 nSamplingRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ - OMX_AUDIO_PCMMODETYPE ePCMMode; /**< PCM mode enumeration */ - OMX_AUDIO_CHANNELTYPE eChannelMapping[OMX_AUDIO_MAXCHANNELS]; /**< Slot i contains channel defined by eChannelMap[i] */ - -} OMX_AUDIO_PARAM_PCMMODETYPE; - - -/** Audio channel mode. This is used by both AAC and MP3, although the names are more appropriate - * for the MP3. For example, JointStereo for MP3 is CouplingChannels for AAC. - */ -typedef enum OMX_AUDIO_CHANNELMODETYPE { - OMX_AUDIO_ChannelModeStereo = 0, /**< 2 channels, the bitrate allocation between those - two channels changes accordingly to each channel information */ - OMX_AUDIO_ChannelModeJointStereo, /**< mode that takes advantage of what is common between - 2 channels for higher compression gain */ - OMX_AUDIO_ChannelModeDual, /**< 2 mono-channels, each channel is encoded with half - the bitrate of the overall bitrate */ - OMX_AUDIO_ChannelModeMono, /**< Mono channel mode */ - OMX_AUDIO_ChannelModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_ChannelModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_ChannelModeMax = 0x7FFFFFFF -} OMX_AUDIO_CHANNELMODETYPE; - - -typedef enum OMX_AUDIO_MP3STREAMFORMATTYPE { - OMX_AUDIO_MP3StreamFormatMP1Layer3 = 0, /**< MP3 Audio MPEG 1 Layer 3 Stream format */ - OMX_AUDIO_MP3StreamFormatMP2Layer3, /**< MP3 Audio MPEG 2 Layer 3 Stream format */ - OMX_AUDIO_MP3StreamFormatMP2_5Layer3, /**< MP3 Audio MPEG2.5 Layer 3 Stream format */ - OMX_AUDIO_MP3StreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_MP3StreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_MP3StreamFormatMax = 0x7FFFFFFF -} OMX_AUDIO_MP3STREAMFORMATTYPE; - -/** MP3 params */ -typedef struct OMX_AUDIO_PARAM_MP3TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable - rate or unknown bit rates */ - OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ - OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should - limit the audio signal. Use 0 to let encoder decide */ - OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ - OMX_AUDIO_MP3STREAMFORMATTYPE eFormat; /**< MP3 stream format */ -} OMX_AUDIO_PARAM_MP3TYPE; - - -typedef enum OMX_AUDIO_AACSTREAMFORMATTYPE { - OMX_AUDIO_AACStreamFormatMP2ADTS = 0, /**< AAC Audio Data Transport Stream 2 format */ - OMX_AUDIO_AACStreamFormatMP4ADTS, /**< AAC Audio Data Transport Stream 4 format */ - OMX_AUDIO_AACStreamFormatMP4LOAS, /**< AAC Low Overhead Audio Stream format */ - OMX_AUDIO_AACStreamFormatMP4LATM, /**< AAC Low overhead Audio Transport Multiplex */ - OMX_AUDIO_AACStreamFormatADIF, /**< AAC Audio Data Interchange Format */ - OMX_AUDIO_AACStreamFormatMP4FF, /**< AAC inside MPEG-4/ISO File Format */ - OMX_AUDIO_AACStreamFormatRAW, /**< AAC Raw Format */ - OMX_AUDIO_AACStreamFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_AACStreamFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_AACStreamFormatMax = 0x7FFFFFFF -} OMX_AUDIO_AACSTREAMFORMATTYPE; - - -/** AAC mode type. Note that the term profile is used with the MPEG-2 - * standard and the term object type and profile is used with MPEG-4 */ -typedef enum OMX_AUDIO_AACPROFILETYPE{ - OMX_AUDIO_AACObjectNull = 0, /**< Null, not used */ - OMX_AUDIO_AACObjectMain = 1, /**< AAC Main object */ - OMX_AUDIO_AACObjectLC, /**< AAC Low Complexity object (AAC profile) */ - OMX_AUDIO_AACObjectSSR, /**< AAC Scalable Sample Rate object */ - OMX_AUDIO_AACObjectLTP, /**< AAC Long Term Prediction object */ - OMX_AUDIO_AACObjectHE, /**< AAC High Efficiency (object type SBR, HE-AAC profile) */ - OMX_AUDIO_AACObjectScalable, /**< AAC Scalable object */ - OMX_AUDIO_AACObjectERLC = 17, /**< ER AAC Low Complexity object (Error Resilient AAC-LC) */ - OMX_AUDIO_AACObjectLD = 23, /**< AAC Low Delay object (Error Resilient) */ - OMX_AUDIO_AACObjectHE_PS = 29, /**< AAC High Efficiency with Parametric Stereo coding (HE-AAC v2, object type PS) */ - OMX_AUDIO_AACObjectKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_AACObjectVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_AACObjectMax = 0x7FFFFFFF -} OMX_AUDIO_AACPROFILETYPE; - - -/** AAC tool usage (for nAACtools in OMX_AUDIO_PARAM_AACPROFILETYPE). - * Required for encoder configuration and optional as decoder info output. - * For MP3, OMX_AUDIO_CHANNELMODETYPE is sufficient. */ -#define OMX_AUDIO_AACToolNone 0x00000000 /**< no AAC tools allowed (encoder config) or active (decoder info output) */ -#define OMX_AUDIO_AACToolMS 0x00000001 /**< MS: Mid/side joint coding tool allowed or active */ -#define OMX_AUDIO_AACToolIS 0x00000002 /**< IS: Intensity stereo tool allowed or active */ -#define OMX_AUDIO_AACToolTNS 0x00000004 /**< TNS: Temporal Noise Shaping tool allowed or active */ -#define OMX_AUDIO_AACToolPNS 0x00000008 /**< PNS: MPEG-4 Perceptual Noise substitution tool allowed or active */ -#define OMX_AUDIO_AACToolLTP 0x00000010 /**< LTP: MPEG-4 Long Term Prediction tool allowed or active */ -#define OMX_AUDIO_AACToolAll 0x7FFFFFFF /**< all AAC tools allowed or active (*/ - -/** MPEG-4 AAC error resilience (ER) tool usage (for nAACERtools in OMX_AUDIO_PARAM_AACPROFILETYPE). - * Required for ER encoder configuration and optional as decoder info output */ -#define OMX_AUDIO_AACERNone 0x00000000 /**< no AAC ER tools allowed/used */ -#define OMX_AUDIO_AACERVCB11 0x00000001 /**< VCB11: Virtual Code Books for AAC section data */ -#define OMX_AUDIO_AACERRVLC 0x00000002 /**< RVLC: Reversible Variable Length Coding */ -#define OMX_AUDIO_AACERHCR 0x00000004 /**< HCR: Huffman Codeword Reordering */ -#define OMX_AUDIO_AACERAll 0x7FFFFFFF /**< all AAC ER tools allowed/used */ - - -/** AAC params */ -typedef struct OMX_AUDIO_PARAM_AACPROFILETYPE { - OMX_U32 nSize; /**< Size of this structure, in Bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ - OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable - rate or unknown bit rates */ - OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should - limit the audio signal. Use 0 to let encoder decide */ - OMX_U32 nFrameLength; /**< Frame length (in audio samples per channel) of the codec. - Can be 1024 or 960 (AAC-LC), 2048 (HE-AAC), 480 or 512 (AAC-LD). - Use 0 to let encoder decide */ - OMX_U32 nAACtools; /**< AAC tool usage */ - OMX_U32 nAACERtools; /**< MPEG-4 AAC error resilience tool usage */ - OMX_AUDIO_AACPROFILETYPE eAACProfile; /**< AAC profile enumeration */ - OMX_AUDIO_AACSTREAMFORMATTYPE eAACStreamFormat; /**< AAC stream format enumeration */ - OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ -} OMX_AUDIO_PARAM_AACPROFILETYPE; - - -/** VORBIS params */ -typedef struct OMX_AUDIO_PARAM_VORBISTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nBitRate; /**< Bit rate of the encoded data data. Use 0 for variable - rate or unknown bit rates. Encoding is set to the - bitrate closest to specified value (in bps) */ - OMX_U32 nMinBitRate; /**< Sets minimum bitrate (in bps). */ - OMX_U32 nMaxBitRate; /**< Sets maximum bitrate (in bps). */ - - OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ - OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should - limit the audio signal. Use 0 to let encoder decide */ - OMX_S32 nQuality; /**< Sets encoding quality to n, between -1 (low) and 10 (high). - In the default mode of operation, teh quality level is 3. - Normal quality range is 0 - 10. */ - OMX_BOOL bManaged; /**< Set bitrate management mode. This turns off the - normal VBR encoding, but allows hard or soft bitrate - constraints to be enforced by the encoder. This mode can - be slower, and may also be lower quality. It is - primarily useful for streaming. */ - OMX_BOOL bDownmix; /**< Downmix input from stereo to mono (has no effect on - non-stereo streams). Useful for lower-bitrate encoding. */ -} OMX_AUDIO_PARAM_VORBISTYPE; - - -/** WMA Version */ -typedef enum OMX_AUDIO_WMAFORMATTYPE { - OMX_AUDIO_WMAFormatUnused = 0, /**< format unused or unknown */ - OMX_AUDIO_WMAFormat7, /**< Windows Media Audio format 7 */ - OMX_AUDIO_WMAFormat8, /**< Windows Media Audio format 8 */ - OMX_AUDIO_WMAFormat9, /**< Windows Media Audio format 9 */ - OMX_AUDIO_WMAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_WMAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_WMAFormatMax = 0x7FFFFFFF -} OMX_AUDIO_WMAFORMATTYPE; - - -/** WMA Profile */ -typedef enum OMX_AUDIO_WMAPROFILETYPE { - OMX_AUDIO_WMAProfileUnused = 0, /**< profile unused or unknown */ - OMX_AUDIO_WMAProfileL1, /**< Windows Media audio version 9 profile L1 */ - OMX_AUDIO_WMAProfileL2, /**< Windows Media audio version 9 profile L2 */ - OMX_AUDIO_WMAProfileL3, /**< Windows Media audio version 9 profile L3 */ - OMX_AUDIO_WMAProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_WMAProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_WMAProfileMax = 0x7FFFFFFF -} OMX_AUDIO_WMAPROFILETYPE; - - -/** WMA params */ -typedef struct OMX_AUDIO_PARAM_WMATYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U16 nChannels; /**< Number of channels */ - OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable - rate or unknown bit rates */ - OMX_AUDIO_WMAFORMATTYPE eFormat; /**< Version of WMA stream / data */ - OMX_AUDIO_WMAPROFILETYPE eProfile; /**< Profile of WMA stream / data */ - OMX_U32 nSamplingRate; /**< Sampling rate of the source data */ - OMX_U16 nBlockAlign; /**< is the block alignment, or block size, in bytes of the audio codec */ - OMX_U16 nEncodeOptions; /**< WMA Type-specific data */ - OMX_U32 nSuperBlockAlign; /**< WMA Type-specific data */ -} OMX_AUDIO_PARAM_WMATYPE; - -/** - * RealAudio format - */ -typedef enum OMX_AUDIO_RAFORMATTYPE { - OMX_AUDIO_RAFormatUnused = 0, /**< Format unused or unknown */ - OMX_AUDIO_RA8, /**< RealAudio 8 codec */ - OMX_AUDIO_RA9, /**< RealAudio 9 codec */ - OMX_AUDIO_RA10_AAC, /**< MPEG-4 AAC codec for bitrates of more than 128kbps */ - OMX_AUDIO_RA10_CODEC, /**< RealAudio codec for bitrates less than 128 kbps */ - OMX_AUDIO_RA10_LOSSLESS, /**< RealAudio Lossless */ - OMX_AUDIO_RA10_MULTICHANNEL, /**< RealAudio Multichannel */ - OMX_AUDIO_RA10_VOICE, /**< RealAudio Voice for bitrates below 15 kbps */ - OMX_AUDIO_RAFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_RAFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_RAFormatMax = 0x7FFFFFFF -} OMX_AUDIO_RAFORMATTYPE; - -/** RA (Real Audio) params */ -typedef struct OMX_AUDIO_PARAM_RATYPE { - OMX_U32 nSize; /**< Size of this structure, in Bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nSamplingRate; /**< is the sampling rate of the source data */ - OMX_U32 nBitsPerFrame; /**< is the value for bits per frame */ - OMX_U32 nSamplePerFrame; /**< is the value for samples per frame */ - OMX_U32 nCouplingQuantBits; /**< is the number of coupling quantization bits in the stream */ - OMX_U32 nCouplingStartRegion; /**< is the coupling start region in the stream */ - OMX_U32 nNumRegions; /**< is the number of regions value */ - OMX_AUDIO_RAFORMATTYPE eFormat; /**< is the RealAudio audio format */ -} OMX_AUDIO_PARAM_RATYPE; - - -/** SBC Allocation Method Type */ -typedef enum OMX_AUDIO_SBCALLOCMETHODTYPE { - OMX_AUDIO_SBCAllocMethodLoudness, /**< Loudness allocation method */ - OMX_AUDIO_SBCAllocMethodSNR, /**< SNR allocation method */ - OMX_AUDIO_SBCAllocMethodKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_SBCAllocMethodVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_SBCAllocMethodMax = 0x7FFFFFFF -} OMX_AUDIO_SBCALLOCMETHODTYPE; - - -/** SBC params */ -typedef struct OMX_AUDIO_PARAM_SBCTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable - rate or unknown bit rates */ - OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ - OMX_U32 nBlocks; /**< Number of blocks */ - OMX_U32 nSubbands; /**< Number of subbands */ - OMX_U32 nBitPool; /**< Bitpool value */ - OMX_BOOL bEnableBitrate; /**< Use bitrate value instead of bitpool */ - OMX_AUDIO_CHANNELMODETYPE eChannelMode; /**< Channel mode enumeration */ - OMX_AUDIO_SBCALLOCMETHODTYPE eSBCAllocType; /**< SBC Allocation method type */ -} OMX_AUDIO_PARAM_SBCTYPE; - - -/** ADPCM stream format parameters */ -typedef struct OMX_AUDIO_PARAM_ADPCMTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_U32 nBitsPerSample; /**< Number of bits in each sample */ - OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for - variable or unknown sampling rate. */ -} OMX_AUDIO_PARAM_ADPCMTYPE; - - -/** G723 rate */ -typedef enum OMX_AUDIO_G723RATE { - OMX_AUDIO_G723ModeUnused = 0, /**< AMRNB Mode unused / unknown */ - OMX_AUDIO_G723ModeLow, /**< 5300 bps */ - OMX_AUDIO_G723ModeHigh, /**< 6300 bps */ - OMX_AUDIO_G723ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_G723ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_G723ModeMax = 0x7FFFFFFF -} OMX_AUDIO_G723RATE; - - -/** G723 - Sample rate must be 8 KHz */ -typedef struct OMX_AUDIO_PARAM_G723TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_AUDIO_G723RATE eBitRate; /**< todo: Should this be moved to a config? */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ - OMX_BOOL bPostFilter; /**< Enable Post Filter */ -} OMX_AUDIO_PARAM_G723TYPE; - - -/** ITU G726 (ADPCM) rate */ -typedef enum OMX_AUDIO_G726MODE { - OMX_AUDIO_G726ModeUnused = 0, /**< G726 Mode unused / unknown */ - OMX_AUDIO_G726Mode16, /**< 16 kbps */ - OMX_AUDIO_G726Mode24, /**< 24 kbps */ - OMX_AUDIO_G726Mode32, /**< 32 kbps, most common rate, also G721 */ - OMX_AUDIO_G726Mode40, /**< 40 kbps */ - OMX_AUDIO_G726ModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_G726ModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_G726ModeMax = 0x7FFFFFFF -} OMX_AUDIO_G726MODE; - - -/** G.726 stream format parameters - must be at 8KHz */ -typedef struct OMX_AUDIO_PARAM_G726TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_AUDIO_G726MODE eG726Mode; -} OMX_AUDIO_PARAM_G726TYPE; - - -/** G729 coder type */ -typedef enum OMX_AUDIO_G729TYPE { - OMX_AUDIO_G729 = 0, /**< ITU G.729 encoded data */ - OMX_AUDIO_G729A, /**< ITU G.729 annex A encoded data */ - OMX_AUDIO_G729B, /**< ITU G.729 with annex B encoded data */ - OMX_AUDIO_G729AB, /**< ITU G.729 annexes A and B encoded data */ - OMX_AUDIO_G729KhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_G729VendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_G729Max = 0x7FFFFFFF -} OMX_AUDIO_G729TYPE; - - -/** G729 stream format parameters - fixed 6KHz sample rate */ -typedef struct OMX_AUDIO_PARAM_G729TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_AUDIO_G729TYPE eBitType; -} OMX_AUDIO_PARAM_G729TYPE; - - -/** AMR Frame format */ -typedef enum OMX_AUDIO_AMRFRAMEFORMATTYPE { - OMX_AUDIO_AMRFrameFormatConformance = 0, /**< Frame Format is AMR Conformance - (Standard) Format */ - OMX_AUDIO_AMRFrameFormatIF1, /**< Frame Format is AMR Interface - Format 1 */ - OMX_AUDIO_AMRFrameFormatIF2, /**< Frame Format is AMR Interface - Format 2*/ - OMX_AUDIO_AMRFrameFormatFSF, /**< Frame Format is AMR File Storage - Format */ - OMX_AUDIO_AMRFrameFormatRTPPayload, /**< Frame Format is AMR Real-Time - Transport Protocol Payload Format */ - OMX_AUDIO_AMRFrameFormatITU, /**< Frame Format is ITU Format (added at Motorola request) */ - OMX_AUDIO_AMRFrameFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_AMRFrameFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_AMRFrameFormatMax = 0x7FFFFFFF -} OMX_AUDIO_AMRFRAMEFORMATTYPE; - - -/** AMR band mode */ -typedef enum OMX_AUDIO_AMRBANDMODETYPE { - OMX_AUDIO_AMRBandModeUnused = 0, /**< AMRNB Mode unused / unknown */ - OMX_AUDIO_AMRBandModeNB0, /**< AMRNB Mode 0 = 4750 bps */ - OMX_AUDIO_AMRBandModeNB1, /**< AMRNB Mode 1 = 5150 bps */ - OMX_AUDIO_AMRBandModeNB2, /**< AMRNB Mode 2 = 5900 bps */ - OMX_AUDIO_AMRBandModeNB3, /**< AMRNB Mode 3 = 6700 bps */ - OMX_AUDIO_AMRBandModeNB4, /**< AMRNB Mode 4 = 7400 bps */ - OMX_AUDIO_AMRBandModeNB5, /**< AMRNB Mode 5 = 7950 bps */ - OMX_AUDIO_AMRBandModeNB6, /**< AMRNB Mode 6 = 10200 bps */ - OMX_AUDIO_AMRBandModeNB7, /**< AMRNB Mode 7 = 12200 bps */ - OMX_AUDIO_AMRBandModeWB0, /**< AMRWB Mode 0 = 6600 bps */ - OMX_AUDIO_AMRBandModeWB1, /**< AMRWB Mode 1 = 8850 bps */ - OMX_AUDIO_AMRBandModeWB2, /**< AMRWB Mode 2 = 12650 bps */ - OMX_AUDIO_AMRBandModeWB3, /**< AMRWB Mode 3 = 14250 bps */ - OMX_AUDIO_AMRBandModeWB4, /**< AMRWB Mode 4 = 15850 bps */ - OMX_AUDIO_AMRBandModeWB5, /**< AMRWB Mode 5 = 18250 bps */ - OMX_AUDIO_AMRBandModeWB6, /**< AMRWB Mode 6 = 19850 bps */ - OMX_AUDIO_AMRBandModeWB7, /**< AMRWB Mode 7 = 23050 bps */ - OMX_AUDIO_AMRBandModeWB8, /**< AMRWB Mode 8 = 23850 bps */ - OMX_AUDIO_AMRBandModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_AMRBandModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_AMRBandModeMax = 0x7FFFFFFF -} OMX_AUDIO_AMRBANDMODETYPE; - - -/** AMR Discontinuous Transmission mode */ -typedef enum OMX_AUDIO_AMRDTXMODETYPE { - OMX_AUDIO_AMRDTXModeOff = 0, /**< AMR Discontinuous Transmission Mode is disabled */ - OMX_AUDIO_AMRDTXModeOnVAD1, /**< AMR Discontinuous Transmission Mode using - Voice Activity Detector 1 (VAD1) is enabled */ - OMX_AUDIO_AMRDTXModeOnVAD2, /**< AMR Discontinuous Transmission Mode using - Voice Activity Detector 2 (VAD2) is enabled */ - OMX_AUDIO_AMRDTXModeOnAuto, /**< The codec will automatically select between - Off, VAD1 or VAD2 modes */ - - OMX_AUDIO_AMRDTXasEFR, /**< DTX as EFR instead of AMR standard (3GPP 26.101, frame type =8,9,10) */ - - OMX_AUDIO_AMRDTXModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_AMRDTXModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_AMRDTXModeMax = 0x7FFFFFFF -} OMX_AUDIO_AMRDTXMODETYPE; - - -/** AMR params */ -typedef struct OMX_AUDIO_PARAM_AMRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels */ - OMX_U32 nBitRate; /**< Bit rate read only field */ - OMX_AUDIO_AMRBANDMODETYPE eAMRBandMode; /**< AMR Band Mode enumeration */ - OMX_AUDIO_AMRDTXMODETYPE eAMRDTXMode; /**< AMR DTX Mode enumeration */ - OMX_AUDIO_AMRFRAMEFORMATTYPE eAMRFrameFormat; /**< AMR frame format enumeration */ -} OMX_AUDIO_PARAM_AMRTYPE; - - -/** GSM_FR (ETSI 06.10, 3GPP 46.010) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_GSMFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_GSMFRTYPE; - - -/** GSM-HR (ETSI 06.20, 3GPP 46.020) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_GSMHRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_GSMHRTYPE; - - -/** GSM-EFR (ETSI 06.60, 3GPP 46.060) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_GSMEFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_GSMEFRTYPE; - - -/** TDMA FR (TIA/EIA-136-420, VSELP 7.95kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_TDMAFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_TDMAFRTYPE; - - -/** TDMA EFR (TIA/EIA-136-410, ACELP 7.4kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_TDMAEFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_TDMAEFRTYPE; - - -/** PDC FR ( RCR-27, VSELP 6.7kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_PDCFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_PDCFRTYPE; - - -/** PDC EFR ( RCR-27, ACELP 6.7kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_PDCEFRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_PDCEFRTYPE; - -/** PDC HR ( RCR-27, PSI-CELP 3.45kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_PDCHRTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_BOOL bDTX; /**< Enable Discontinuous Transmisssion */ - OMX_BOOL bHiPassFilter; /**< Enable High Pass Filter */ -} OMX_AUDIO_PARAM_PDCHRTYPE; - - -/** CDMA Rate types */ -typedef enum OMX_AUDIO_CDMARATETYPE { - OMX_AUDIO_CDMARateBlank = 0, /**< CDMA encoded frame is blank */ - OMX_AUDIO_CDMARateFull, /**< CDMA encoded frame in full rate */ - OMX_AUDIO_CDMARateHalf, /**< CDMA encoded frame in half rate */ - OMX_AUDIO_CDMARateQuarter, /**< CDMA encoded frame in quarter rate */ - OMX_AUDIO_CDMARateEighth, /**< CDMA encoded frame in eighth rate (DTX)*/ - OMX_AUDIO_CDMARateErasure, /**< CDMA erasure frame */ - OMX_AUDIO_CDMARateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_CDMARateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_CDMARateMax = 0x7FFFFFFF -} OMX_AUDIO_CDMARATETYPE; - - -/** QCELP8 (TIA/EIA-96, up to 8kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_QCELP8TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_U32 nBitRate; /**< Bit rate of the input data. Use 0 for variable - rate or unknown bit rates */ - OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ - OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ - OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ -} OMX_AUDIO_PARAM_QCELP8TYPE; - - -/** QCELP13 ( CDMA, EIA/TIA-733, 13.3kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_QCELP13TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ - OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ - OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ -} OMX_AUDIO_PARAM_QCELP13TYPE; - - -/** EVRC ( CDMA, EIA/TIA-127, RCELP up to 8.55kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_EVRCTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_AUDIO_CDMARATETYPE eCDMARate; /**< actual Frame rate */ - OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ - OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 */ - OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 */ - OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter */ - OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ - OMX_BOOL bPostFilter; /**< Enable decoder's post Filter */ -} OMX_AUDIO_PARAM_EVRCTYPE; - - -/** SMV ( up to 8.55kbps coder) stream format parameters */ -typedef struct OMX_AUDIO_PARAM_SMVTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannels; /**< Number of channels in the data stream (not - necessarily the same as the number of channels - to be rendered. */ - OMX_AUDIO_CDMARATETYPE eCDMARate; /**< Frame rate */ - OMX_BOOL bRATE_REDUCon; /**< RATE_REDUCtion is requested for this frame */ - OMX_U32 nMinBitRate; /**< minmal rate for the encoder = 1,2,3,4, default = 1 ??*/ - OMX_U32 nMaxBitRate; /**< maximal rate for the encoder = 1,2,3,4, default = 4 ??*/ - OMX_BOOL bHiPassFilter; /**< Enable encoder's High Pass Filter ??*/ - OMX_BOOL bNoiseSuppressor; /**< Enable encoder's noise suppressor pre-processing */ - OMX_BOOL bPostFilter; /**< Enable decoder's post Filter ??*/ -} OMX_AUDIO_PARAM_SMVTYPE; - - -/** MIDI Format - * @ingroup midi - */ -typedef enum OMX_AUDIO_MIDIFORMATTYPE -{ - OMX_AUDIO_MIDIFormatUnknown = 0, /**< MIDI Format unknown or don't care */ - OMX_AUDIO_MIDIFormatSMF0, /**< Standard MIDI File Type 0 */ - OMX_AUDIO_MIDIFormatSMF1, /**< Standard MIDI File Type 1 */ - OMX_AUDIO_MIDIFormatSMF2, /**< Standard MIDI File Type 2 */ - OMX_AUDIO_MIDIFormatSPMIDI, /**< SP-MIDI */ - OMX_AUDIO_MIDIFormatXMF0, /**< eXtensible Music Format type 0 */ - OMX_AUDIO_MIDIFormatXMF1, /**< eXtensible Music Format type 1 */ - OMX_AUDIO_MIDIFormatMobileXMF, /**< Mobile XMF (eXtensible Music Format type 2) */ - OMX_AUDIO_MIDIFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_MIDIFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_MIDIFormatMax = 0x7FFFFFFF -} OMX_AUDIO_MIDIFORMATTYPE; - - -/** MIDI params - * @ingroup midi - */ -typedef struct OMX_AUDIO_PARAM_MIDITYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nFileSize; /**< size of the MIDI file in bytes, where the entire - MIDI file passed in, otherwise if 0x0, the MIDI data - is merged and streamed (instead of passed as an - entire MIDI file) */ - OMX_BU32 sMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic - voices. A value of zero indicates that the default - polyphony of the device is used */ - OMX_BOOL bLoadDefaultSound; /**< Whether to load default sound - bank at initialization */ - OMX_AUDIO_MIDIFORMATTYPE eMidiFormat; /**< Version of the MIDI file */ -} OMX_AUDIO_PARAM_MIDITYPE; - - -/** Type of the MIDI sound bank - * @ingroup midi - */ -typedef enum OMX_AUDIO_MIDISOUNDBANKTYPE { - OMX_AUDIO_MIDISoundBankUnused = 0, /**< unused/unknown soundbank type */ - OMX_AUDIO_MIDISoundBankDLS1, /**< DLS version 1 */ - OMX_AUDIO_MIDISoundBankDLS2, /**< DLS version 2 */ - OMX_AUDIO_MIDISoundBankMobileDLSBase, /**< Mobile DLS, using the base functionality */ - OMX_AUDIO_MIDISoundBankMobileDLSPlusOptions, /**< Mobile DLS, using the specification-defined optional feature set */ - OMX_AUDIO_MIDISoundBankKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_MIDISoundBankVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_MIDISoundBankMax = 0x7FFFFFFF -} OMX_AUDIO_MIDISOUNDBANKTYPE; - - -/** Bank Layout describes how bank MSB & LSB are used in the DLS instrument definitions sound bank - * @ingroup midi - */ -typedef enum OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE { - OMX_AUDIO_MIDISoundBankLayoutUnused = 0, /**< unused/unknown soundbank type */ - OMX_AUDIO_MIDISoundBankLayoutGM, /**< GS layout (based on bank MSB 0x00) */ - OMX_AUDIO_MIDISoundBankLayoutGM2, /**< General MIDI 2 layout (using MSB 0x78/0x79, LSB 0x00) */ - OMX_AUDIO_MIDISoundBankLayoutUser, /**< Does not conform to any bank numbering standards */ - OMX_AUDIO_MIDISoundBankLayoutKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_MIDISoundBankLayoutVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_MIDISoundBankLayoutMax = 0x7FFFFFFF -} OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE; - - -/** MIDI params to load/unload user soundbank - * @ingroup midi - */ -typedef struct OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nDLSIndex; /**< DLS file index to be loaded */ - OMX_U32 nDLSSize; /**< Size in bytes */ - OMX_PTR pDLSData; /**< Pointer to DLS file data */ - OMX_AUDIO_MIDISOUNDBANKTYPE eMidiSoundBank; /**< Midi sound bank type enumeration */ - OMX_AUDIO_MIDISOUNDBANKLAYOUTTYPE eMidiSoundBankLayout; /**< Midi sound bank layout enumeration */ -} OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE; - - -/** Structure for Live MIDI events and MIP messages. - * (MIP = Maximum Instantaneous Polyphony; part of the SP-MIDI standard.) - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port that this structure applies to */ - OMX_U32 nMidiEventSize; /**< Size of immediate MIDI events or MIP message in bytes */ - OMX_U8 nMidiEvents[1]; /**< MIDI event array to be rendered immediately, or an - array for the MIP message buffer, where the size is - indicated by nMidiEventSize */ -} OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE; - - -/** MIDI sound bank/ program pair in a given channel - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port that this structure applies to */ - OMX_U32 nChannel; /**< Valid channel values range from 1 to 16 */ - OMX_U16 nIDProgram; /**< Valid program ID range is 1 to 128 */ - OMX_U16 nIDSoundBank; /**< Sound bank ID */ - OMX_U32 nUserSoundBankIndex;/**< User soundbank index, easier to access soundbanks - by index if multiple banks are present */ -} OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE; - - -/** MIDI control - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDICONTROLTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BS32 sPitchTransposition; /**< Pitch transposition in semitones, stored as Q22.10 - format based on JAVA MMAPI (JSR-135) requirement */ - OMX_BU32 sPlayBackRate; /**< Relative playback rate, stored as Q14.17 fixed-point - number based on JSR-135 requirement */ - OMX_BU32 sTempo ; /**< Tempo in beats per minute (BPM), stored as Q22.10 - fixed-point number based on JSR-135 requirement */ - OMX_U32 nMaxPolyphony; /**< Specifies the maximum simultaneous polyphonic - voices. A value of zero indicates that the default - polyphony of the device is used */ - OMX_U32 nNumRepeat; /**< Number of times to repeat playback */ - OMX_U32 nStopTime; /**< Time in milliseconds to indicate when playback - will stop automatically. Set to zero if not used */ - OMX_U16 nChannelMuteMask; /**< 16 bit mask for channel mute status */ - OMX_U16 nChannelSoloMask; /**< 16 bit mask for channel solo status */ - OMX_U32 nTrack0031MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 0-31 */ - OMX_U32 nTrack3263MuteMask; /**< 32 bit mask for track mute status. Note: This is for tracks 32-63 */ - OMX_U32 nTrack0031SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 0-31 */ - OMX_U32 nTrack3263SoloMask; /**< 32 bit mask for track solo status. Note: This is for tracks 32-63 */ - -} OMX_AUDIO_CONFIG_MIDICONTROLTYPE; - - -/** MIDI Playback States - * @ingroup midi - */ -typedef enum OMX_AUDIO_MIDIPLAYBACKSTATETYPE { - OMX_AUDIO_MIDIPlayBackStateUnknown = 0, /**< Unknown state or state does not map to - other defined states */ - OMX_AUDIO_MIDIPlayBackStateClosedEngaged, /**< No MIDI resource is currently open. - The MIDI engine is currently processing - MIDI events. */ - OMX_AUDIO_MIDIPlayBackStateParsing, /**< A MIDI resource is open and is being - primed. The MIDI engine is currently - processing MIDI events. */ - OMX_AUDIO_MIDIPlayBackStateOpenEngaged, /**< A MIDI resource is open and primed but - not playing. The MIDI engine is currently - processing MIDI events. The transition to - this state is only possible from the - OMX_AUDIO_MIDIPlayBackStatePlaying state, - when the 'playback head' reaches the end - of media data or the playback stops due - to stop time set.*/ - OMX_AUDIO_MIDIPlayBackStatePlaying, /**< A MIDI resource is open and currently - playing. The MIDI engine is currently - processing MIDI events.*/ - OMX_AUDIO_MIDIPlayBackStatePlayingPartially, /**< Best-effort playback due to SP-MIDI/DLS - resource constraints */ - OMX_AUDIO_MIDIPlayBackStatePlayingSilently, /**< Due to system resource constraints and - SP-MIDI content constraints, there is - no audible MIDI content during playback - currently. The situation may change if - resources are freed later.*/ - OMX_AUDIO_MIDIPlayBackStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_MIDIPlayBackStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_MIDIPlayBackStateMax = 0x7FFFFFFF -} OMX_AUDIO_MIDIPLAYBACKSTATETYPE; - - -/** MIDI status - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDISTATUSTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U16 nNumTracks; /**< Number of MIDI tracks in the file, read only field. - NOTE: May not return a meaningful value until the entire - file is parsed and buffered. */ - OMX_U32 nDuration; /**< The length of the currently open MIDI resource - in milliseconds. NOTE: May not return a meaningful value - until the entire file is parsed and buffered. */ - OMX_U32 nPosition; /**< Current Position of the MIDI resource being played - in milliseconds */ - OMX_BOOL bVibra; /**< Does Vibra track exist? NOTE: May not return a meaningful - value until the entire file is parsed and buffered. */ - OMX_U32 nNumMetaEvents; /**< Total number of MIDI Meta Events in the currently - open MIDI resource. NOTE: May not return a meaningful value - until the entire file is parsed and buffered. */ - OMX_U32 nNumActiveVoices; /**< Number of active voices in the currently playing - MIDI resource. NOTE: May not return a meaningful value until - the entire file is parsed and buffered. */ - OMX_AUDIO_MIDIPLAYBACKSTATETYPE eMIDIPlayBackState; /**< MIDI playback state enumeration, read only field */ -} OMX_AUDIO_CONFIG_MIDISTATUSTYPE; - - -/** MIDI Meta Event structure one per Meta Event. - * MIDI Meta Events are like audio metadata, except that they are interspersed - * with the MIDI content throughout the file and are not localized in the header. - * As such, it is necessary to retrieve information about these Meta Events from - * the engine, as it encounters these Meta Events within the MIDI content. - * For example, SMF files can have up to 14 types of MIDI Meta Events (copyright, - * author, default tempo, etc.) scattered throughout the file. - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE{ - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nIndex; /**< Index of Meta Event */ - OMX_U8 nMetaEventType; /**< Meta Event Type, 7bits (i.e. 0 - 127) */ - OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ - OMX_U32 nTrack; /**< track number for the meta event */ - OMX_U32 nPosition; /**< Position of the meta-event in milliseconds */ -} OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE; - - -/** MIDI Meta Event Data structure - one per Meta Event. - * @ingroup midi - */ -typedef struct OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE{ - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nIndex; /**< Index of Meta Event */ - OMX_U32 nMetaEventSize; /**< size of the Meta Event in bytes */ - OMX_U8 nData[1]; /**< array of one or more bytes of meta data - as indicated by the nMetaEventSize field */ -} OMX_AUDIO_CONFIG__MIDIMETAEVENTDATATYPE; - - -/** Audio Volume adjustment for a port */ -typedef struct OMX_AUDIO_CONFIG_VOLUMETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port index indicating which port to - set. Select the input port to set - just that port's volume. Select the - output port to adjust the master - volume. */ - OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) - or logarithmic scale (mB) */ - OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR - Volume logarithmic setting for this port. The values - for volume are in mB (millibels = 1/100 dB) relative - to a gain of 1 (e.g. the output is the same as the - input level). Values are in mB from nMax - (maximum volume) to nMin mB (typically negative). - Since the volume is "voltage" - and not a "power", it takes a setting of - -600 mB to decrease the volume by 1/2. If - a component cannot accurately set the - volume to the requested value, it must - set the volume to the closest value BELOW - the requested value. When getting the - volume setting, the current actual volume - must be returned. */ -} OMX_AUDIO_CONFIG_VOLUMETYPE; - - -/** Audio Volume adjustment for a channel */ -typedef struct OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port index indicating which port to - set. Select the input port to set - just that port's volume. Select the - output port to adjust the master - volume. */ - OMX_U32 nChannel; /**< channel to select from 0 to N-1, - using OMX_ALL to apply volume settings - to all channels */ - OMX_BOOL bLinear; /**< Is the volume to be set in linear (0.100) or - logarithmic scale (mB) */ - OMX_BS32 sVolume; /**< Volume linear setting in the 0..100 range, OR - Volume logarithmic setting for this port. - The values for volume are in mB - (millibels = 1/100 dB) relative to a gain - of 1 (e.g. the output is the same as the - input level). Values are in mB from nMax - (maximum volume) to nMin mB (typically negative). - Since the volume is "voltage" - and not a "power", it takes a setting of - -600 mB to decrease the volume by 1/2. If - a component cannot accurately set the - volume to the requested value, it must - set the volume to the closest value BELOW - the requested value. When getting the - volume setting, the current actual volume - must be returned. */ - OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, - FALSE otherwise */ -} OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE; - - -/** Audio balance setting */ -typedef struct OMX_AUDIO_CONFIG_BALANCETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port index indicating which port to - set. Select the input port to set - just that port's balance. Select the - output port to adjust the master - balance. */ - OMX_S32 nBalance; /**< balance setting for this port - (-100 to 100, where -100 indicates - all left, and no right */ -} OMX_AUDIO_CONFIG_BALANCETYPE; - - -/** Audio Port mute */ -typedef struct OMX_AUDIO_CONFIG_MUTETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port index indicating which port to - set. Select the input port to set - just that port's mute. Select the - output port to adjust the master - mute. */ - OMX_BOOL bMute; /**< Mute setting for this port */ -} OMX_AUDIO_CONFIG_MUTETYPE; - - -/** Audio Channel mute */ -typedef struct OMX_AUDIO_CONFIG_CHANNELMUTETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nChannel; /**< channel to select from 0 to N-1, - using OMX_ALL to apply mute settings - to all channels */ - OMX_BOOL bMute; /**< Mute setting for this channel */ - OMX_BOOL bIsMIDI; /**< TRUE if nChannel refers to a MIDI channel, - FALSE otherwise */ -} OMX_AUDIO_CONFIG_CHANNELMUTETYPE; - - - -/** Enable / Disable for loudness control, which boosts bass and to a - * smaller extent high end frequencies to compensate for hearing - * ability at the extreme ends of the audio spectrum - */ -typedef struct OMX_AUDIO_CONFIG_LOUDNESSTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bLoudness; /**< Enable/disable for loudness */ -} OMX_AUDIO_CONFIG_LOUDNESSTYPE; - - -/** Enable / Disable for bass, which controls low frequencies - */ -typedef struct OMX_AUDIO_CONFIG_BASSTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for bass control */ - OMX_S32 nBass; /**< bass setting for the port, as a - continuous value from -100 to 100 - (0 means no change in bass level)*/ -} OMX_AUDIO_CONFIG_BASSTYPE; - - -/** Enable / Disable for treble, which controls high frequencies tones - */ -typedef struct OMX_AUDIO_CONFIG_TREBLETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for treble control */ - OMX_S32 nTreble; /**< treble setting for the port, as a - continuous value from -100 to 100 - (0 means no change in treble level) */ -} OMX_AUDIO_CONFIG_TREBLETYPE; - - -/** An equalizer is typically used for two reasons: to compensate for an - * sub-optimal frequency response of a system to make it sound more natural - * or to create intentionally some unnatural coloring to the sound to create - * an effect. - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_EQUALIZERTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for equalizer */ - OMX_BU32 sBandIndex; /**< Band number to be set. Upper Limit is - N-1, where N is the number of bands, lower limit is 0 */ - OMX_BU32 sCenterFreq; /**< Center frequecies in Hz. This is a - read only element and is used to determine - the lower, center and upper frequency of - this band. */ - OMX_BS32 sBandLevel; /**< band level in millibels */ -} OMX_AUDIO_CONFIG_EQUALIZERTYPE; - - -/** Stereo widening mode type - * @ingroup effects - */ -typedef enum OMX_AUDIO_STEREOWIDENINGTYPE { - OMX_AUDIO_StereoWideningHeadphones, /**< Stereo widening for loudspeakers */ - OMX_AUDIO_StereoWideningLoudspeakers, /**< Stereo widening for closely spaced loudspeakers */ - OMX_AUDIO_StereoWideningKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_StereoWideningVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_StereoWideningMax = 0x7FFFFFFF -} OMX_AUDIO_STEREOWIDENINGTYPE; - - -/** Control for stereo widening, which is a special 2-channel - * case of the audio virtualizer effect. For example, for 5.1-channel - * output, it translates to virtual surround sound. - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for stereo widening control */ - OMX_AUDIO_STEREOWIDENINGTYPE eWideningType; /**< Stereo widening algorithm type */ - OMX_U32 nStereoWidening; /**< stereo widening setting for the port, - as a continuous value from 0 to 100 */ -} OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE; - - -/** The chorus effect (or ``choralizer'') is any signal processor which makes - * one sound source (such as a voice) sound like many such sources singing - * (or playing) in unison. Since performance in unison is never exact, chorus - * effects simulate this by making independently modified copies of the input - * signal. Modifications may include (1) delay, (2) frequency shift, and - * (3) amplitude modulation. - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_CHORUSTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for chorus */ - OMX_BU32 sDelay; /**< average delay in milliseconds */ - OMX_BU32 sModulationRate; /**< rate of modulation in millihertz */ - OMX_U32 nModulationDepth; /**< depth of modulation as a percentage of - delay (i.e. 0 to 100) */ - OMX_BU32 nFeedback; /**< Feedback from chorus output to input in percentage */ -} OMX_AUDIO_CONFIG_CHORUSTYPE; - - -/** Reverberation is part of the reflected sound that follows the early - * reflections. In a typical room, this consists of a dense succession of - * echoes whose energy decays exponentially. The reverberation effect structure - * as defined here includes both (early) reflections as well as (late) reverberations. - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_REVERBERATIONTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bEnable; /**< Enable/disable for reverberation control */ - OMX_BS32 sRoomLevel; /**< Intensity level for the whole room effect - (i.e. both early reflections and late - reverberation) in millibels */ - OMX_BS32 sRoomHighFreqLevel; /**< Attenuation at high frequencies - relative to the intensity at low - frequencies in millibels */ - OMX_BS32 sReflectionsLevel; /**< Intensity level of early reflections - (relative to room value), in millibels */ - OMX_BU32 sReflectionsDelay; /**< Delay time of the first reflection relative - to the direct path, in milliseconds */ - OMX_BS32 sReverbLevel; /**< Intensity level of late reverberation - relative to room level, in millibels */ - OMX_BU32 sReverbDelay; /**< Time delay from the first early reflection - to the beginning of the late reverberation - section, in milliseconds */ - OMX_BU32 sDecayTime; /**< Late reverberation decay time at low - frequencies, in milliseconds */ - OMX_BU32 nDecayHighFreqRatio; /**< Ratio of high frequency decay time relative - to low frequency decay time in percent */ - OMX_U32 nDensity; /**< Modal density in the late reverberation decay, - in percent (i.e. 0 - 100) */ - OMX_U32 nDiffusion; /**< Echo density in the late reverberation decay, - in percent (i.e. 0 - 100) */ - OMX_BU32 sReferenceHighFreq; /**< Reference high frequency in Hertz. This is - the frequency used as the reference for all - the high-frequency settings above */ - -} OMX_AUDIO_CONFIG_REVERBERATIONTYPE; - - -/** Possible settings for the Echo Cancelation structure to use - * @ingroup effects - */ -typedef enum OMX_AUDIO_ECHOCANTYPE { - OMX_AUDIO_EchoCanOff = 0, /**< Echo Cancellation is disabled */ - OMX_AUDIO_EchoCanNormal, /**< Echo Cancellation normal operation - - echo from plastics and face */ - OMX_AUDIO_EchoCanHFree, /**< Echo Cancellation optimized for - Hands Free operation */ - OMX_AUDIO_EchoCanCarKit, /**< Echo Cancellation optimized for - Car Kit (longer echo) */ - OMX_AUDIO_EchoCanKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_AUDIO_EchoCanVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_AUDIO_EchoCanMax = 0x7FFFFFFF -} OMX_AUDIO_ECHOCANTYPE; - - -/** Enable / Disable for echo cancelation, which removes undesired echo's - * from the audio - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_AUDIO_ECHOCANTYPE eEchoCancelation; /**< Echo cancelation settings */ -} OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE; - - -/** Enable / Disable for noise reduction, which undesired noise from - * the audio - * @ingroup effects - */ -typedef struct OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BOOL bNoiseReduction; /**< Enable/disable for noise reduction */ -} OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE; - -/** @} */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ - diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Component.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Component.h deleted file mode 100644 index d5956405e..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Component.h +++ /dev/null @@ -1,579 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_Component.h - OpenMax IL version 1.1.2 - * The OMX_Component header file contains the definitions used to define - * the public interface of a component. This header file is intended to - * be used by both the application and the component. - */ - -#ifndef OMX_Component_h -#define OMX_Component_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - - -/* Each OMX header must include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ - -#include -#include -#include -#include - -/** @ingroup comp */ -typedef enum OMX_PORTDOMAINTYPE { - OMX_PortDomainAudio, - OMX_PortDomainVideo, - OMX_PortDomainImage, - OMX_PortDomainOther, - OMX_PortDomainKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_PortDomainVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_PortDomainMax = 0x7ffffff -} OMX_PORTDOMAINTYPE; - -/** @ingroup comp */ -typedef struct OMX_PARAM_PORTDEFINITIONTYPE { - OMX_U32 nSize; /**< Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port number the structure applies to */ - OMX_DIRTYPE eDir; /**< Direction (input or output) of this port */ - OMX_U32 nBufferCountActual; /**< The actual number of buffers allocated on this port */ - OMX_U32 nBufferCountMin; /**< The minimum number of buffers this port requires */ - OMX_U32 nBufferSize; /**< Size, in bytes, for buffers to be used for this channel */ - OMX_BOOL bEnabled; /**< Ports default to enabled and are enabled/disabled by - OMX_CommandPortEnable/OMX_CommandPortDisable. - When disabled a port is unpopulated. A disabled port - is not populated with buffers on a transition to IDLE. */ - OMX_BOOL bPopulated; /**< Port is populated with all of its buffers as indicated by - nBufferCountActual. A disabled port is always unpopulated. - An enabled port is populated on a transition to OMX_StateIdle - and unpopulated on a transition to loaded. */ - OMX_PORTDOMAINTYPE eDomain; /**< Domain of the port. Determines the contents of metadata below. */ - union { - OMX_AUDIO_PORTDEFINITIONTYPE audio; - OMX_VIDEO_PORTDEFINITIONTYPE video; - OMX_IMAGE_PORTDEFINITIONTYPE image; - OMX_OTHER_PORTDEFINITIONTYPE other; - } format; - OMX_BOOL bBuffersContiguous; - OMX_U32 nBufferAlignment; -} OMX_PARAM_PORTDEFINITIONTYPE; - -/** @ingroup comp */ -typedef struct OMX_PARAM_U32TYPE { - OMX_U32 nSize; /**< Size of this structure, in Bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_U32 nU32; /**< U32 value */ -} OMX_PARAM_U32TYPE; - -/** @ingroup rpm */ -typedef enum OMX_SUSPENSIONPOLICYTYPE { - OMX_SuspensionDisabled, /**< No suspension; v1.0 behavior */ - OMX_SuspensionEnabled, /**< Suspension allowed */ - OMX_SuspensionPolicyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_SuspensionPolicyStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_SuspensionPolicyMax = 0x7fffffff -} OMX_SUSPENSIONPOLICYTYPE; - -/** @ingroup rpm */ -typedef struct OMX_PARAM_SUSPENSIONPOLICYTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_SUSPENSIONPOLICYTYPE ePolicy; -} OMX_PARAM_SUSPENSIONPOLICYTYPE; - -/** @ingroup rpm */ -typedef enum OMX_SUSPENSIONTYPE { - OMX_NotSuspended, /**< component is not suspended */ - OMX_Suspended, /**< component is suspended */ - OMX_SuspensionKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_SuspensionVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_SuspendMax = 0x7FFFFFFF -} OMX_SUSPENSIONTYPE; - -/** @ingroup rpm */ -typedef struct OMX_PARAM_SUSPENSIONTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_SUSPENSIONTYPE eType; -} OMX_PARAM_SUSPENSIONTYPE ; - -typedef struct OMX_CONFIG_BOOLEANTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bEnabled; -} OMX_CONFIG_BOOLEANTYPE; - -/* Parameter specifying the content uri to use. */ -/** @ingroup cp */ -typedef struct OMX_PARAM_CONTENTURITYPE -{ - OMX_U32 nSize; /**< size of the structure in bytes, including - actual URI name */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U8 contentURI[1]; /**< The URI name */ -} OMX_PARAM_CONTENTURITYPE; - -/* Parameter specifying the pipe to use. */ -/** @ingroup cp */ -typedef struct OMX_PARAM_CONTENTPIPETYPE -{ - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_HANDLETYPE hPipe; /**< The pipe handle*/ -} OMX_PARAM_CONTENTPIPETYPE; - -/** @ingroup rpm */ -typedef struct OMX_RESOURCECONCEALMENTTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_BOOL bResourceConcealmentForbidden; /**< disallow the use of resource concealment - methods (like degrading algorithm quality to - lower resource consumption or functional bypass) - on a component as a resolution to resource conflicts. */ -} OMX_RESOURCECONCEALMENTTYPE; - - -/** @ingroup metadata */ -typedef enum OMX_METADATACHARSETTYPE { - OMX_MetadataCharsetUnknown = 0, - OMX_MetadataCharsetASCII, - OMX_MetadataCharsetBinary, - OMX_MetadataCharsetCodePage1252, - OMX_MetadataCharsetUTF8, - OMX_MetadataCharsetJavaConformantUTF8, - OMX_MetadataCharsetUTF7, - OMX_MetadataCharsetImapUTF7, - OMX_MetadataCharsetUTF16LE, - OMX_MetadataCharsetUTF16BE, - OMX_MetadataCharsetGB12345, - OMX_MetadataCharsetHZGB2312, - OMX_MetadataCharsetGB2312, - OMX_MetadataCharsetGB18030, - OMX_MetadataCharsetGBK, - OMX_MetadataCharsetBig5, - OMX_MetadataCharsetISO88591, - OMX_MetadataCharsetISO88592, - OMX_MetadataCharsetISO88593, - OMX_MetadataCharsetISO88594, - OMX_MetadataCharsetISO88595, - OMX_MetadataCharsetISO88596, - OMX_MetadataCharsetISO88597, - OMX_MetadataCharsetISO88598, - OMX_MetadataCharsetISO88599, - OMX_MetadataCharsetISO885910, - OMX_MetadataCharsetISO885913, - OMX_MetadataCharsetISO885914, - OMX_MetadataCharsetISO885915, - OMX_MetadataCharsetShiftJIS, - OMX_MetadataCharsetISO2022JP, - OMX_MetadataCharsetISO2022JP1, - OMX_MetadataCharsetISOEUCJP, - OMX_MetadataCharsetSMS7Bit, - OMX_MetadataCharsetKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_MetadataCharsetVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_MetadataCharsetTypeMax= 0x7FFFFFFF -} OMX_METADATACHARSETTYPE; - -/** @ingroup metadata */ -typedef enum OMX_METADATASCOPETYPE -{ - OMX_MetadataScopeAllLevels, - OMX_MetadataScopeTopLevel, - OMX_MetadataScopePortLevel, - OMX_MetadataScopeNodeLevel, - OMX_MetadataScopeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_MetadataScopeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_MetadataScopeTypeMax = 0x7fffffff -} OMX_METADATASCOPETYPE; - -/** @ingroup metadata */ -typedef enum OMX_METADATASEARCHMODETYPE -{ - OMX_MetadataSearchValueSizeByIndex, - OMX_MetadataSearchItemByIndex, - OMX_MetadataSearchNextItemByKey, - OMX_MetadataSearchKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_MetadataSearchVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_MetadataSearchTypeMax = 0x7fffffff -} OMX_METADATASEARCHMODETYPE; -/** @ingroup metadata */ -typedef struct OMX_CONFIG_METADATAITEMCOUNTTYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_METADATASCOPETYPE eScopeMode; - OMX_U32 nScopeSpecifier; - OMX_U32 nMetadataItemCount; -} OMX_CONFIG_METADATAITEMCOUNTTYPE; - -/** @ingroup metadata */ -typedef struct OMX_CONFIG_METADATAITEMTYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_METADATASCOPETYPE eScopeMode; - OMX_U32 nScopeSpecifier; - OMX_U32 nMetadataItemIndex; - OMX_METADATASEARCHMODETYPE eSearchMode; - OMX_METADATACHARSETTYPE eKeyCharset; - OMX_U8 nKeySizeUsed; - OMX_U8 nKey[128]; - OMX_METADATACHARSETTYPE eValueCharset; - OMX_STRING sLanguageCountry; - OMX_U32 nValueMaxSize; - OMX_U32 nValueSizeUsed; - OMX_U8 nValue[1]; -} OMX_CONFIG_METADATAITEMTYPE; - -/* @ingroup metadata */ -typedef struct OMX_CONFIG_CONTAINERNODECOUNTTYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bAllKeys; - OMX_U32 nParentNodeID; - OMX_U32 nNumNodes; -} OMX_CONFIG_CONTAINERNODECOUNTTYPE; - -/** @ingroup metadata */ -typedef struct OMX_CONFIG_CONTAINERNODEIDTYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bAllKeys; - OMX_U32 nParentNodeID; - OMX_U32 nNodeIndex; - OMX_U32 nNodeID; - OMX_STRING cNodeName; - OMX_BOOL bIsLeafType; -} OMX_CONFIG_CONTAINERNODEIDTYPE; - -/** @ingroup metadata */ -typedef struct OMX_PARAM_METADATAFILTERTYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bAllKeys; /* if true then this structure refers to all keys and - * the three key fields below are ignored */ - OMX_METADATACHARSETTYPE eKeyCharset; - OMX_U32 nKeySizeUsed; - OMX_U8 nKey [128]; - OMX_U32 nLanguageCountrySizeUsed; - OMX_U8 nLanguageCountry[128]; - OMX_BOOL bEnabled; /* if true then key is part of filter (e.g. - * retained for query later). If false then - * key is not part of filter */ -} OMX_PARAM_METADATAFILTERTYPE; - -/** The OMX_HANDLETYPE structure defines the component handle. The component - * handle is used to access all of the component's public methods and also - * contains pointers to the component's private data area. The component - * handle is initialized by the OMX core (with help from the component) - * during the process of loading the component. After the component is - * successfully loaded, the application can safely access any of the - * component's public functions (although some may return an error because - * the state is inappropriate for the access). - * - * @ingroup comp - */ -typedef struct OMX_COMPONENTTYPE -{ - /** The size of this structure, in bytes. It is the responsibility - of the allocator of this structure to fill in this value. Since - this structure is allocated by the GetHandle function, this - function will fill in this value. */ - OMX_U32 nSize; - - /** nVersion is the version of the OMX specification that the structure - is built against. It is the responsibility of the creator of this - structure to initialize this value and every user of this structure - should verify that it knows how to use the exact version of - this structure found herein. */ - OMX_VERSIONTYPE nVersion; - - /** pComponentPrivate is a pointer to the component private data area. - This member is allocated and initialized by the component when the - component is first loaded. The application should not access this - data area. */ - OMX_PTR pComponentPrivate; - - /** pApplicationPrivate is a pointer that is a parameter to the - OMX_GetHandle method, and contains an application private value - provided by the IL client. This application private data is - returned to the IL Client by OMX in all callbacks */ - OMX_PTR pApplicationPrivate; - - /** refer to OMX_GetComponentVersion in OMX_core.h or the OMX IL - specification for details on the GetComponentVersion method. - */ - OMX_ERRORTYPE (*GetComponentVersion)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_OUT OMX_STRING pComponentName, - OMX_OUT OMX_VERSIONTYPE* pComponentVersion, - OMX_OUT OMX_VERSIONTYPE* pSpecVersion, - OMX_OUT OMX_UUIDTYPE* pComponentUUID); - - /** refer to OMX_SendCommand in OMX_core.h or the OMX IL - specification for details on the SendCommand method. - */ - OMX_ERRORTYPE (*SendCommand)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_COMMANDTYPE Cmd, - OMX_IN OMX_U32 nParam1, - OMX_IN OMX_PTR pCmdData); - - /** refer to OMX_GetParameter in OMX_core.h or the OMX IL - specification for details on the GetParameter method. - */ - OMX_ERRORTYPE (*GetParameter)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_INDEXTYPE nParamIndex, - OMX_INOUT OMX_PTR pComponentParameterStructure); - - - /** refer to OMX_SetParameter in OMX_core.h or the OMX IL - specification for details on the SetParameter method. - */ - OMX_ERRORTYPE (*SetParameter)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_INDEXTYPE nIndex, - OMX_IN OMX_PTR pComponentParameterStructure); - - - /** refer to OMX_GetConfig in OMX_core.h or the OMX IL - specification for details on the GetConfig method. - */ - OMX_ERRORTYPE (*GetConfig)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_INDEXTYPE nIndex, - OMX_INOUT OMX_PTR pComponentConfigStructure); - - - /** refer to OMX_SetConfig in OMX_core.h or the OMX IL - specification for details on the SetConfig method. - */ - OMX_ERRORTYPE (*SetConfig)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_INDEXTYPE nIndex, - OMX_IN OMX_PTR pComponentConfigStructure); - - - /** refer to OMX_GetExtensionIndex in OMX_core.h or the OMX IL - specification for details on the GetExtensionIndex method. - */ - OMX_ERRORTYPE (*GetExtensionIndex)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_STRING cParameterName, - OMX_OUT OMX_INDEXTYPE* pIndexType); - - - /** refer to OMX_GetState in OMX_core.h or the OMX IL - specification for details on the GetState method. - */ - OMX_ERRORTYPE (*GetState)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_OUT OMX_STATETYPE* pState); - - - /** The ComponentTunnelRequest method will interact with another OMX - component to determine if tunneling is possible and to setup the - tunneling. The return codes for this method can be used to - determine if tunneling is not possible, or if tunneling is not - supported. - - Base profile components (i.e. non-interop) do not support this - method and should return OMX_ErrorNotImplemented - - The interop profile component MUST support tunneling to another - interop profile component with a compatible port parameters. - A component may also support proprietary communication. - - If proprietary communication is supported the negotiation of - proprietary communication is done outside of OMX in a vendor - specific way. It is only required that the proper result be - returned and the details of how the setup is done is left - to the component implementation. - - When this method is invoked when nPort in an output port, the - component will: - 1. Populate the pTunnelSetup structure with the output port's - requirements and constraints for the tunnel. - - When this method is invoked when nPort in an input port, the - component will: - 1. Query the necessary parameters from the output port to - determine if the ports are compatible for tunneling - 2. If the ports are compatible, the component should store - the tunnel step provided by the output port - 3. Determine which port (either input or output) is the buffer - supplier, and call OMX_SetParameter on the output port to - indicate this selection. - - The component will return from this call within 5 msec. - - @param [in] hComp - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle method. - @param [in] nPort - nPort is used to select the port on the component to be used - for tunneling. - @param [in] hTunneledComp - Handle of the component to tunnel with. This is the component - handle returned by the call to the OMX_GetHandle method. When - this parameter is 0x0 the component should setup the port for - communication with the application / IL Client. - @param [in] nPortOutput - nPortOutput is used indicate the port the component should - tunnel with. - @param [in] pTunnelSetup - Pointer to the tunnel setup structure. When nPort is an output port - the component should populate the fields of this structure. When - When nPort is an input port the component should review the setup - provided by the component with the output port. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup tun - */ - - OMX_ERRORTYPE (*ComponentTunnelRequest)( - OMX_IN OMX_HANDLETYPE hComp, - OMX_IN OMX_U32 nPort, - OMX_IN OMX_HANDLETYPE hTunneledComp, - OMX_IN OMX_U32 nTunneledPort, - OMX_INOUT OMX_TUNNELSETUPTYPE* pTunnelSetup); - - /** refer to OMX_UseBuffer in OMX_core.h or the OMX IL - specification for details on the UseBuffer method. - @ingroup buf - */ - OMX_ERRORTYPE (*UseBuffer)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, - OMX_IN OMX_U32 nPortIndex, - OMX_IN OMX_PTR pAppPrivate, - OMX_IN OMX_U32 nSizeBytes, - OMX_IN OMX_U8* pBuffer); - - /** refer to OMX_AllocateBuffer in OMX_core.h or the OMX IL - specification for details on the AllocateBuffer method. - @ingroup buf - */ - OMX_ERRORTYPE (*AllocateBuffer)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer, - OMX_IN OMX_U32 nPortIndex, - OMX_IN OMX_PTR pAppPrivate, - OMX_IN OMX_U32 nSizeBytes); - - /** refer to OMX_FreeBuffer in OMX_core.h or the OMX IL - specification for details on the FreeBuffer method. - @ingroup buf - */ - OMX_ERRORTYPE (*FreeBuffer)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_U32 nPortIndex, - OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); - - /** refer to OMX_EmptyThisBuffer in OMX_core.h or the OMX IL - specification for details on the EmptyThisBuffer method. - @ingroup buf - */ - OMX_ERRORTYPE (*EmptyThisBuffer)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); - - /** refer to OMX_FillThisBuffer in OMX_core.h or the OMX IL - specification for details on the FillThisBuffer method. - @ingroup buf - */ - OMX_ERRORTYPE (*FillThisBuffer)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); - - /** The SetCallbacks method is used by the core to specify the callback - structure from the application to the component. This is a blocking - call. The component will return from this call within 5 msec. - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the GetHandle function. - @param [in] pCallbacks - pointer to an OMX_CALLBACKTYPE structure used to provide the - callback information to the component - @param [in] pAppData - pointer to an application defined value. It is anticipated that - the application will pass a pointer to a data structure or a "this - pointer" in this area to allow the callback (in the application) - to determine the context of the call - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - */ - OMX_ERRORTYPE (*SetCallbacks)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_CALLBACKTYPE* pCallbacks, - OMX_IN OMX_PTR pAppData); - - /** ComponentDeInit method is used to deinitialize the component - providing a means to free any resources allocated at component - initialization. NOTE: After this call the component handle is - not valid for further use. - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the GetHandle function. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - */ - OMX_ERRORTYPE (*ComponentDeInit)( - OMX_IN OMX_HANDLETYPE hComponent); - - /** @ingroup buf */ - OMX_ERRORTYPE (*UseEGLImage)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr, - OMX_IN OMX_U32 nPortIndex, - OMX_IN OMX_PTR pAppPrivate, - OMX_IN void* eglImage); - - OMX_ERRORTYPE (*ComponentRoleEnum)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_OUT OMX_U8 *cRole, - OMX_IN OMX_U32 nIndex); - -} OMX_COMPONENTTYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_ContentPipe.h b/starpilot/ui/screenrecorder/openmax/include/OMX_ContentPipe.h deleted file mode 100644 index 5f6310c28..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_ContentPipe.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_ContentPipe.h - OpenMax IL version 1.1.2 - * The OMX_ContentPipe header file contains the definitions used to define - * the public interface for content piples. This header file is intended to - * be used by the component. - */ - -#ifndef OMX_CONTENTPIPE_H -#define OMX_CONTENTPIPE_H - -#ifndef KD_EACCES -/* OpenKODE error codes. CPResult values may be zero (indicating success - or one of the following values) */ -#define KD_EACCES (1) -#define KD_EADDRINUSE (2) -#define KD_EAGAIN (5) -#define KD_EBADF (7) -#define KD_EBUSY (8) -#define KD_ECONNREFUSED (9) -#define KD_ECONNRESET (10) -#define KD_EDEADLK (11) -#define KD_EDESTADDRREQ (12) -#define KD_ERANGE (35) -#define KD_EEXIST (13) -#define KD_EFBIG (14) -#define KD_EHOSTUNREACH (15) -#define KD_EINVAL (17) -#define KD_EIO (18) -#define KD_EISCONN (20) -#define KD_EISDIR (21) -#define KD_EMFILE (22) -#define KD_ENAMETOOLONG (23) -#define KD_ENOENT (24) -#define KD_ENOMEM (25) -#define KD_ENOSPC (26) -#define KD_ENOSYS (27) -#define KD_ENOTCONN (28) -#define KD_EPERM (33) -#define KD_ETIMEDOUT (36) -#define KD_EILSEQ (19) -#endif - -/** Map types from OMX standard types only here so interface is as generic as possible. */ -typedef OMX_U32 CPresult; -typedef char * CPstring; -typedef void * CPhandle; -typedef OMX_U32 CPuint; -typedef OMX_S32 CPint; -typedef char CPbyte; -typedef OMX_BOOL CPbool; - -/** enumeration of origin types used in the CP_PIPETYPE's Seek function - * @ingroup cp - */ -typedef enum CP_ORIGINTYPE { - CP_OriginBegin, - CP_OriginCur, - CP_OriginEnd, - CP_OriginKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - CP_OriginVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - CP_OriginMax = 0X7FFFFFFF -} CP_ORIGINTYPE; - -/** enumeration of contact access types used in the CP_PIPETYPE's Open function - * @ingroup cp - */ -typedef enum CP_ACCESSTYPE { - CP_AccessRead, - CP_AccessWrite, - CP_AccessReadWrite , - CP_AccessKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - CP_AccessVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - CP_AccessMax = 0X7FFFFFFF -} CP_ACCESSTYPE; - -/** enumeration of results returned by the CP_PIPETYPE's CheckAvailableBytes function - * @ingroup cp - */ -typedef enum CP_CHECKBYTESRESULTTYPE -{ - CP_CheckBytesOk, /**< There are at least the request number - of bytes available */ - CP_CheckBytesNotReady, /**< The pipe is still retrieving bytes - and presently lacks sufficient bytes. - Client will be called when they are - sufficient bytes are available. */ - CP_CheckBytesInsufficientBytes , /**< The pipe has retrieved all bytes - but those available are less than those - requested */ - CP_CheckBytesAtEndOfStream, /**< The pipe has reached the end of stream - and no more bytes are available. */ - CP_CheckBytesOutOfBuffers, /**< All read/write buffers are currently in use. */ - CP_CheckBytesKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - CP_CheckBytesVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - CP_CheckBytesMax = 0X7FFFFFFF -} CP_CHECKBYTESRESULTTYPE; - -/** enumeration of content pipe events sent to the client callback. - * @ingroup cp - */ -typedef enum CP_EVENTTYPE{ - CP_BytesAvailable, /** bytes requested in a CheckAvailableBytes call are now available*/ - CP_Overflow, /** enumeration of content pipe events sent to the client callback*/ - CP_PipeDisconnected , /** enumeration of content pipe events sent to the client callback*/ - CP_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - CP_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - CP_EventMax = 0X7FFFFFFF -} CP_EVENTTYPE; - -/** content pipe definition - * @ingroup cp - */ -typedef struct CP_PIPETYPE -{ - /** Open a content stream for reading or writing. */ - CPresult (*Open)( CPhandle* hContent, CPstring szURI, CP_ACCESSTYPE eAccess ); - - /** Close a content stream. */ - CPresult (*Close)( CPhandle hContent ); - - /** Create a content source and open it for writing. */ - CPresult (*Create)( CPhandle *hContent, CPstring szURI ); - - /** Check the that specified number of bytes are available for reading or writing (depending on access type).*/ - CPresult (*CheckAvailableBytes)( CPhandle hContent, CPuint nBytesRequested, CP_CHECKBYTESRESULTTYPE *eResult ); - - /** Seek to certain position in the content relative to the specified origin. */ - CPresult (*SetPosition)( CPhandle hContent, CPint nOffset, CP_ORIGINTYPE eOrigin); - - /** Retrieve the current position relative to the start of the content. */ - CPresult (*GetPosition)( CPhandle hContent, CPuint *pPosition); - - /** Retrieve data of the specified size from the content stream (advance content pointer by size of data). - Note: pipe client provides pointer. This function is appropriate for small high frequency reads. */ - CPresult (*Read)( CPhandle hContent, CPbyte *pData, CPuint nSize); - - /** Retrieve a buffer allocated by the pipe that contains the requested number of bytes. - Buffer contains the next block of bytes, as specified by nSize, of the content. nSize also - returns the size of the block actually read. Content pointer advances the by the returned size. - Note: pipe provides pointer. This function is appropriate for large reads. The client must call - ReleaseReadBuffer when done with buffer. - - In some cases the requested block may not reside in contiguous memory within the - pipe implementation. For instance if the pipe leverages a circular buffer then the requested - block may straddle the boundary of the circular buffer. By default a pipe implementation - performs a copy in this case to provide the block to the pipe client in one contiguous buffer. - If, however, the client sets bForbidCopy, then the pipe returns only those bytes preceding the memory - boundary. Here the client may retrieve the data in segments over successive calls. */ - CPresult (*ReadBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint *nSize, CPbool bForbidCopy); - - /** Release a buffer obtained by ReadBuffer back to the pipe. */ - CPresult (*ReleaseReadBuffer)(CPhandle hContent, CPbyte *pBuffer); - - /** Write data of the specified size to the content (advance content pointer by size of data). - Note: pipe client provides pointer. This function is appropriate for small high frequency writes. */ - CPresult (*Write)( CPhandle hContent, CPbyte *data, CPuint nSize); - - /** Retrieve a buffer allocated by the pipe used to write data to the content. - Client will fill buffer with output data. Note: pipe provides pointer. This function is appropriate - for large writes. The client must call WriteBuffer when done it has filled the buffer with data.*/ - CPresult (*GetWriteBuffer)( CPhandle hContent, CPbyte **ppBuffer, CPuint nSize); - - /** Deliver a buffer obtained via GetWriteBuffer to the pipe. Pipe will write the - the contents of the buffer to content and advance content pointer by the size of the buffer */ - CPresult (*WriteBuffer)( CPhandle hContent, CPbyte *pBuffer, CPuint nFilledSize); - - /** Register a per-handle client callback with the content pipe. */ - CPresult (*RegisterCallback)( CPhandle hContent, CPresult (*ClientCallback)(CP_EVENTTYPE eEvent, CPuint iParam)); - -} CP_PIPETYPE; - -#endif - diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Core.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Core.h deleted file mode 100644 index 52d211f0d..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Core.h +++ /dev/null @@ -1,1440 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_Core.h - OpenMax IL version 1.1.2 - * The OMX_Core header file contains the definitions used by both the - * application and the component to access common items. - */ - -#ifndef OMX_Core_h -#define OMX_Core_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/* Each OMX header shall include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ - -#include - - -/** The OMX_COMMANDTYPE enumeration is used to specify the action in the - * OMX_SendCommand macro. - * @ingroup core - */ -typedef enum OMX_COMMANDTYPE -{ - OMX_CommandStateSet, /**< Change the component state */ - OMX_CommandFlush, /**< Flush the data queue(s) of a component */ - OMX_CommandPortDisable, /**< Disable a port on a component. */ - OMX_CommandPortEnable, /**< Enable a port on a component. */ - OMX_CommandMarkBuffer, /**< Mark a component/buffer for observation */ - OMX_CommandKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_CommandVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_CommandMax = 0X7FFFFFFF -} OMX_COMMANDTYPE; - - - -/** The OMX_STATETYPE enumeration is used to indicate or change the component - * state. This enumeration reflects the current state of the component when - * used with the OMX_GetState macro or becomes the parameter in a state change - * command when used with the OMX_SendCommand macro. - * - * The component will be in the Loaded state after the component is initially - * loaded into memory. In the Loaded state, the component is not allowed to - * allocate or hold resources other than to build it's internal parameter - * and configuration tables. The application will send one or more - * SetParameters/GetParameters and SetConfig/GetConfig commands to the - * component and the component will record each of these parameter and - * configuration changes for use later. When the application sends the - * Idle command, the component will acquire the resources needed for the - * specified configuration and will transition to the idle state if the - * allocation is successful. If the component cannot successfully - * transition to the idle state for any reason, the state of the component - * shall be fully rolled back to the Loaded state (e.g. all allocated - * resources shall be released). When the component receives the command - * to go to the Executing state, it shall begin processing buffers by - * sending all input buffers it holds to the application. While - * the component is in the Idle state, the application may also send the - * Pause command. If the component receives the pause command while in the - * Idle state, the component shall send all input buffers it holds to the - * application, but shall not begin processing buffers. This will allow the - * application to prefill buffers. - * - * @ingroup comp - */ - -typedef enum OMX_STATETYPE -{ - OMX_StateInvalid, /**< component has detected that it's internal data - structures are corrupted to the point that - it cannot determine it's state properly */ - OMX_StateLoaded, /**< component has been loaded but has not completed - initialization. The OMX_SetParameter macro - and the OMX_GetParameter macro are the only - valid macros allowed to be sent to the - component in this state. */ - OMX_StateIdle, /**< component initialization has been completed - successfully and the component is ready to - to start. */ - OMX_StateExecuting, /**< component has accepted the start command and - is processing data (if data is available) */ - OMX_StatePause, /**< component has received pause command */ - OMX_StateWaitForResources, /**< component is waiting for resources, either after - preemption or before it gets the resources requested. - See specification for complete details. */ - OMX_StateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_StateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_StateMax = 0X7FFFFFFF -} OMX_STATETYPE; - -/** The OMX_ERRORTYPE enumeration defines the standard OMX Errors. These - * errors should cover most of the common failure cases. However, - * vendors are free to add additional error messages of their own as - * long as they follow these rules: - * 1. Vendor error messages shall be in the range of 0x90000000 to - * 0x9000FFFF. - * 2. Vendor error messages shall be defined in a header file provided - * with the component. No error messages are allowed that are - * not defined. - */ -typedef enum OMX_ERRORTYPE -{ - OMX_ErrorNone = 0, - - /** There were insufficient resources to perform the requested operation */ - OMX_ErrorInsufficientResources = (OMX_S32) 0x80001000, - - /** There was an error, but the cause of the error could not be determined */ - OMX_ErrorUndefined = (OMX_S32) 0x80001001, - - /** The component name string was not valid */ - OMX_ErrorInvalidComponentName = (OMX_S32) 0x80001002, - - /** No component with the specified name string was found */ - OMX_ErrorComponentNotFound = (OMX_S32) 0x80001003, - - /** The component specified did not have a "OMX_ComponentInit" or - "OMX_ComponentDeInit entry point */ - OMX_ErrorInvalidComponent = (OMX_S32) 0x80001004, - - /** One or more parameters were not valid */ - OMX_ErrorBadParameter = (OMX_S32) 0x80001005, - - /** The requested function is not implemented */ - OMX_ErrorNotImplemented = (OMX_S32) 0x80001006, - - /** The buffer was emptied before the next buffer was ready */ - OMX_ErrorUnderflow = (OMX_S32) 0x80001007, - - /** The buffer was not available when it was needed */ - OMX_ErrorOverflow = (OMX_S32) 0x80001008, - - /** The hardware failed to respond as expected */ - OMX_ErrorHardware = (OMX_S32) 0x80001009, - - /** The component is in the state OMX_StateInvalid */ - OMX_ErrorInvalidState = (OMX_S32) 0x8000100A, - - /** Stream is found to be corrupt */ - OMX_ErrorStreamCorrupt = (OMX_S32) 0x8000100B, - - /** Ports being connected are not compatible */ - OMX_ErrorPortsNotCompatible = (OMX_S32) 0x8000100C, - - /** Resources allocated to an idle component have been - lost resulting in the component returning to the loaded state */ - OMX_ErrorResourcesLost = (OMX_S32) 0x8000100D, - - /** No more indicies can be enumerated */ - OMX_ErrorNoMore = (OMX_S32) 0x8000100E, - - /** The component detected a version mismatch */ - OMX_ErrorVersionMismatch = (OMX_S32) 0x8000100F, - - /** The component is not ready to return data at this time */ - OMX_ErrorNotReady = (OMX_S32) 0x80001010, - - /** There was a timeout that occurred */ - OMX_ErrorTimeout = (OMX_S32) 0x80001011, - - /** This error occurs when trying to transition into the state you are already in */ - OMX_ErrorSameState = (OMX_S32) 0x80001012, - - /** Resources allocated to an executing or paused component have been - preempted, causing the component to return to the idle state */ - OMX_ErrorResourcesPreempted = (OMX_S32) 0x80001013, - - /** A non-supplier port sends this error to the IL client (via the EventHandler callback) - during the allocation of buffers (on a transition from the LOADED to the IDLE state or - on a port restart) when it deems that it has waited an unusually long time for the supplier - to send it an allocated buffer via a UseBuffer call. */ - OMX_ErrorPortUnresponsiveDuringAllocation = (OMX_S32) 0x80001014, - - /** A non-supplier port sends this error to the IL client (via the EventHandler callback) - during the deallocation of buffers (on a transition from the IDLE to LOADED state or - on a port stop) when it deems that it has waited an unusually long time for the supplier - to request the deallocation of a buffer header via a FreeBuffer call. */ - OMX_ErrorPortUnresponsiveDuringDeallocation = (OMX_S32) 0x80001015, - - /** A supplier port sends this error to the IL client (via the EventHandler callback) - during the stopping of a port (either on a transition from the IDLE to LOADED - state or a port stop) when it deems that it has waited an unusually long time for - the non-supplier to return a buffer via an EmptyThisBuffer or FillThisBuffer call. */ - OMX_ErrorPortUnresponsiveDuringStop = (OMX_S32) 0x80001016, - - /** Attempting a state transtion that is not allowed */ - OMX_ErrorIncorrectStateTransition = (OMX_S32) 0x80001017, - - /* Attempting a command that is not allowed during the present state. */ - OMX_ErrorIncorrectStateOperation = (OMX_S32) 0x80001018, - - /** The values encapsulated in the parameter or config structure are not supported. */ - OMX_ErrorUnsupportedSetting = (OMX_S32) 0x80001019, - - /** The parameter or config indicated by the given index is not supported. */ - OMX_ErrorUnsupportedIndex = (OMX_S32) 0x8000101A, - - /** The port index supplied is incorrect. */ - OMX_ErrorBadPortIndex = (OMX_S32) 0x8000101B, - - /** The port has lost one or more of its buffers and it thus unpopulated. */ - OMX_ErrorPortUnpopulated = (OMX_S32) 0x8000101C, - - /** Component suspended due to temporary loss of resources */ - OMX_ErrorComponentSuspended = (OMX_S32) 0x8000101D, - - /** Component suspended due to an inability to acquire dynamic resources */ - OMX_ErrorDynamicResourcesUnavailable = (OMX_S32) 0x8000101E, - - /** When the macroblock error reporting is enabled the component returns new error - for every frame that has errors */ - OMX_ErrorMbErrorsInFrame = (OMX_S32) 0x8000101F, - - /** A component reports this error when it cannot parse or determine the format of an input stream. */ - OMX_ErrorFormatNotDetected = (OMX_S32) 0x80001020, - - /** The content open operation failed. */ - OMX_ErrorContentPipeOpenFailed = (OMX_S32) 0x80001021, - - /** The content creation operation failed. */ - OMX_ErrorContentPipeCreationFailed = (OMX_S32) 0x80001022, - - /** Separate table information is being used */ - OMX_ErrorSeperateTablesUsed = (OMX_S32) 0x80001023, - - /** Tunneling is unsupported by the component*/ - OMX_ErrorTunnelingUnsupported = (OMX_S32) 0x80001024, - - OMX_ErrorKhronosExtensions = (OMX_S32)0x8F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_ErrorVendorStartUnused = (OMX_S32)0x90000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_ErrorMax = 0x7FFFFFFF -} OMX_ERRORTYPE; - -/** @ingroup core */ -typedef OMX_ERRORTYPE (* OMX_COMPONENTINITTYPE)(OMX_IN OMX_HANDLETYPE hComponent); - -/** @ingroup core */ -typedef struct OMX_COMPONENTREGISTERTYPE -{ - const char * pName; /* Component name, 128 byte limit (including '\0') applies */ - OMX_COMPONENTINITTYPE pInitialize; /* Component instance initialization function */ -} OMX_COMPONENTREGISTERTYPE; - -/** @ingroup core */ -extern OMX_COMPONENTREGISTERTYPE OMX_ComponentRegistered[]; - -/** @ingroup rpm */ -typedef struct OMX_PRIORITYMGMTTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nGroupPriority; /**< Priority of the component group */ - OMX_U32 nGroupID; /**< ID of the component group */ -} OMX_PRIORITYMGMTTYPE; - -/* Component name and Role names are limited to 128 characters including the terminating '\0'. */ -#define OMX_MAX_STRINGNAME_SIZE 128 - -/** @ingroup comp */ -typedef struct OMX_PARAM_COMPONENTROLETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U8 cRole[OMX_MAX_STRINGNAME_SIZE]; /**< name of standard component which defines component role */ -} OMX_PARAM_COMPONENTROLETYPE; - -/** End of Stream Buffer Flag: - * - * A component sets EOS when it has no more data to emit on a particular - * output port. Thus an output port shall set EOS on the last buffer it - * emits. A component's determination of when an output port should - * cease sending data is implemenation specific. - * @ingroup buf - */ - -#define OMX_BUFFERFLAG_EOS 0x00000001 - -/** Start Time Buffer Flag: - * - * The source of a stream (e.g. a demux component) sets the STARTTIME - * flag on the buffer that contains the starting timestamp for the - * stream. The starting timestamp corresponds to the first data that - * should be displayed at startup or after a seek. - * The first timestamp of the stream is not necessarily the start time. - * For instance, in the case of a seek to a particular video frame, - * the target frame may be an interframe. Thus the first buffer of - * the stream will be the intra-frame preceding the target frame and - * the starttime will occur with the target frame (with any other - * required frames required to reconstruct the target intervening). - * - * The STARTTIME flag is directly associated with the buffer's - * timestamp ' thus its association to buffer data and its - * propagation is identical to the timestamp's. - * - * When a Sync Component client receives a buffer with the - * STARTTIME flag it shall perform a SetConfig on its sync port - * using OMX_ConfigTimeClientStartTime and passing the buffer's - * timestamp. - * - * @ingroup buf - */ - -#define OMX_BUFFERFLAG_STARTTIME 0x00000002 - - - -/** Decode Only Buffer Flag: - * - * The source of a stream (e.g. a demux component) sets the DECODEONLY - * flag on any buffer that should shall be decoded but should not be - * displayed. This flag is used, for instance, when a source seeks to - * a target interframe that requires the decode of frames preceding the - * target to facilitate the target's reconstruction. In this case the - * source would emit the frames preceding the target downstream - * but mark them as decode only. - * - * The DECODEONLY is associated with buffer data and propagated in a - * manner identical to the buffer timestamp. - * - * A component that renders data should ignore all buffers with - * the DECODEONLY flag set. - * - * @ingroup buf - */ - -#define OMX_BUFFERFLAG_DECODEONLY 0x00000004 - - -/* Data Corrupt Flag: This flag is set when the IL client believes the data in the associated buffer is corrupt - * @ingroup buf - */ - -#define OMX_BUFFERFLAG_DATACORRUPT 0x00000008 - -/* End of Frame: The buffer contains exactly one end of frame and no data - * occurs after the end of frame. This flag is an optional hint. The absence - * of this flag does not imply the absence of an end of frame within the buffer. - * @ingroup buf -*/ -#define OMX_BUFFERFLAG_ENDOFFRAME 0x00000010 - -/* Sync Frame Flag: This flag is set when the buffer content contains a coded sync frame ' - * a frame that has no dependency on any other frame information - * @ingroup buf - */ -#define OMX_BUFFERFLAG_SYNCFRAME 0x00000020 - -/* Extra data present flag: there is extra data appended to the data stream - * residing in the buffer - * @ingroup buf - */ -#define OMX_BUFFERFLAG_EXTRADATA 0x00000040 - -/** Codec Config Buffer Flag: -* OMX_BUFFERFLAG_CODECCONFIG is an optional flag that is set by an -* output port when all bytes in the buffer form part or all of a set of -* codec specific configuration data. Examples include SPS/PPS nal units -* for OMX_VIDEO_CodingAVC or AudioSpecificConfig data for -* OMX_AUDIO_CodingAAC. Any component that for a given stream sets -* OMX_BUFFERFLAG_CODECCONFIG shall not mix codec configuration bytes -* with frame data in the same buffer, and shall send all buffers -* containing codec configuration bytes before any buffers containing -* frame data that those configurations bytes describe. -* If the stream format for a particular codec has a frame specific -* header at the start of each frame, for example OMX_AUDIO_CodingMP3 or -* OMX_AUDIO_CodingAAC in ADTS mode, then these shall be presented as -* normal without setting OMX_BUFFERFLAG_CODECCONFIG. - * @ingroup buf - */ -#define OMX_BUFFERFLAG_CODECCONFIG 0x00000080 - -/* -* OMX_BUFFERFLAG_READONLY: This flag is set when a component emitting the -* buffer on an output port or the IL client wishes to identify the buffer -* payload contents to be read-only. An IL client or an input port -* shall not alter the contents of the buffer. This flag shall only be -* cleared by the originator of the buffer when the buffer is returned. -* For tunneled ports, the usage of this flag shall be allowed only if the -* components negotiated a read-only tunnel -*/ -#define OMX_BUFFERFLAG_READONLY 0x00000200 - -/** @ingroup buf */ -typedef struct OMX_BUFFERHEADERTYPE -{ - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U8* pBuffer; /**< Pointer to actual block of memory - that is acting as the buffer */ - OMX_U32 nAllocLen; /**< size of the buffer allocated, in bytes */ - OMX_U32 nFilledLen; /**< number of bytes currently in the - buffer */ - OMX_U32 nOffset; /**< start offset of valid data in bytes from - the start of the buffer */ - OMX_PTR pAppPrivate; /**< pointer to any data the application - wants to associate with this buffer */ - OMX_PTR pPlatformPrivate; /**< pointer to any data the platform - wants to associate with this buffer */ - OMX_PTR pInputPortPrivate; /**< pointer to any data the input port - wants to associate with this buffer */ - OMX_PTR pOutputPortPrivate; /**< pointer to any data the output port - wants to associate with this buffer */ - OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will generate a - mark event upon processing this buffer. */ - OMX_PTR pMarkData; /**< Application specific data associated with - the mark sent on a mark event to disambiguate - this mark from others. */ - OMX_U32 nTickCount; /**< Optional entry that the component and - application can update with a tick count - when they access the component. This - value should be in microseconds. Since - this is a value relative to an arbitrary - starting point, this value cannot be used - to determine absolute time. This is an - optional entry and not all components - will update it.*/ - OMX_TICKS nTimeStamp; /**< Timestamp corresponding to the sample - starting at the first logical sample - boundary in the buffer. Timestamps of - successive samples within the buffer may - be inferred by adding the duration of the - of the preceding buffer to the timestamp - of the preceding buffer.*/ - OMX_U32 nFlags; /**< buffer specific flags */ - OMX_U32 nOutputPortIndex; /**< The index of the output port (if any) using - this buffer */ - OMX_U32 nInputPortIndex; /**< The index of the input port (if any) using - this buffer */ -} OMX_BUFFERHEADERTYPE; - -/** The OMX_EXTRADATATYPE enumeration is used to define the - * possible extra data payload types. - * NB: this enum is binary backwards compatible with the previous - * OMX_EXTRADATA_QUANT define. This should be replaced with - * OMX_ExtraDataQuantization. - */ -typedef enum OMX_EXTRADATATYPE -{ - OMX_ExtraDataNone = 0, /**< Indicates that no more extra data sections follow */ - OMX_ExtraDataQuantization, /**< The data payload contains quantization data */ - OMX_ExtraDataKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_ExtraDataVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_ExtraDataMax = 0x7FFFFFFF -} OMX_EXTRADATATYPE; - - -typedef struct OMX_OTHER_EXTRADATATYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_EXTRADATATYPE eType; /* Extra Data type */ - OMX_U32 nDataSize; /* Size of the supporting data to follow */ - OMX_U8 data[1]; /* Supporting data hint */ -} OMX_OTHER_EXTRADATATYPE; - -/** @ingroup comp */ -typedef struct OMX_PORT_PARAM_TYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPorts; /**< The number of ports for this component */ - OMX_U32 nStartPortNumber; /** first port number for this type of port */ -} OMX_PORT_PARAM_TYPE; - -/** @ingroup comp */ -typedef enum OMX_EVENTTYPE -{ - OMX_EventCmdComplete, /**< component has sucessfully completed a command */ - OMX_EventError, /**< component has detected an error condition */ - OMX_EventMark, /**< component has detected a buffer mark */ - OMX_EventPortSettingsChanged, /**< component is reported a port settings change */ - OMX_EventBufferFlag, /**< component has detected an EOS */ - OMX_EventResourcesAcquired, /**< component has been granted resources and is - automatically starting the state change from - OMX_StateWaitForResources to OMX_StateIdle. */ - OMX_EventComponentResumed, /**< Component resumed due to reacquisition of resources */ - OMX_EventDynamicResourcesAvailable, /**< Component has acquired previously unavailable dynamic resources */ - OMX_EventPortFormatDetected, /**< Component has detected a supported format. */ - OMX_EventKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_EventVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_EventMax = 0x7FFFFFFF -} OMX_EVENTTYPE; - -typedef struct OMX_CALLBACKTYPE -{ - /** The EventHandler method is used to notify the application when an - event of interest occurs. Events are defined in the OMX_EVENTTYPE - enumeration. Please see that enumeration for details of what will - be returned for each type of event. Callbacks should not return - an error to the component, so if an error occurs, the application - shall handle it internally. This is a blocking call. - - The application should return from this call within 5 msec to avoid - blocking the component for an excessively long period of time. - - @param hComponent - handle of the component to access. This is the component - handle returned by the call to the GetHandle function. - @param pAppData - pointer to an application defined value that was provided in the - pAppData parameter to the OMX_GetHandle method for the component. - This application defined value is provided so that the application - can have a component specific context when receiving the callback. - @param eEvent - Event that the component wants to notify the application about. - @param nData1 - nData will be the OMX_ERRORTYPE for an error event and will be - an OMX_COMMANDTYPE for a command complete event and OMX_INDEXTYPE for a OMX_PortSettingsChanged event. - @param nData2 - nData2 will hold further information related to the event. Can be OMX_STATETYPE for - a OMX_CommandStateSet command or port index for a OMX_PortSettingsChanged event. - Default value is 0 if not used. ) - @param pEventData - Pointer to additional event-specific data (see spec for meaning). - */ - - OMX_ERRORTYPE (*EventHandler)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_PTR pAppData, - OMX_IN OMX_EVENTTYPE eEvent, - OMX_IN OMX_U32 nData1, - OMX_IN OMX_U32 nData2, - OMX_IN OMX_PTR pEventData); - - /** The EmptyBufferDone method is used to return emptied buffers from an - input port back to the application for reuse. This is a blocking call - so the application should not attempt to refill the buffers during this - call, but should queue them and refill them in another thread. There - is no error return, so the application shall handle any errors generated - internally. - - The application should return from this call within 5 msec. - - @param hComponent - handle of the component to access. This is the component - handle returned by the call to the GetHandle function. - @param pAppData - pointer to an application defined value that was provided in the - pAppData parameter to the OMX_GetHandle method for the component. - This application defined value is provided so that the application - can have a component specific context when receiving the callback. - @param pBuffer - pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer - or AllocateBuffer indicating the buffer that was emptied. - @ingroup buf - */ - OMX_ERRORTYPE (*EmptyBufferDone)( - OMX_IN OMX_HANDLETYPE hComponent, - OMX_IN OMX_PTR pAppData, - OMX_IN OMX_BUFFERHEADERTYPE* pBuffer); - - /** The FillBufferDone method is used to return filled buffers from an - output port back to the application for emptying and then reuse. - This is a blocking call so the application should not attempt to - empty the buffers during this call, but should queue the buffers - and empty them in another thread. There is no error return, so - the application shall handle any errors generated internally. The - application shall also update the buffer header to indicate the - number of bytes placed into the buffer. - - The application should return from this call within 5 msec. - - @param hComponent - handle of the component to access. This is the component - handle returned by the call to the GetHandle function. - @param pAppData - pointer to an application defined value that was provided in the - pAppData parameter to the OMX_GetHandle method for the component. - This application defined value is provided so that the application - can have a component specific context when receiving the callback. - @param pBuffer - pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer - or AllocateBuffer indicating the buffer that was filled. - @ingroup buf - */ - OMX_ERRORTYPE (*FillBufferDone)( - OMX_OUT OMX_HANDLETYPE hComponent, - OMX_OUT OMX_PTR pAppData, - OMX_OUT OMX_BUFFERHEADERTYPE* pBuffer); - -} OMX_CALLBACKTYPE; - -/** The OMX_BUFFERSUPPLIERTYPE enumeration is used to dictate port supplier - preference when tunneling between two ports. - @ingroup tun buf -*/ -typedef enum OMX_BUFFERSUPPLIERTYPE -{ - OMX_BufferSupplyUnspecified = 0x0, /**< port supplying the buffers is unspecified, - or don't care */ - OMX_BufferSupplyInput, /**< input port supplies the buffers */ - OMX_BufferSupplyOutput, /**< output port supplies the buffers */ - OMX_BufferSupplyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_BufferSupplyVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_BufferSupplyMax = 0x7FFFFFFF -} OMX_BUFFERSUPPLIERTYPE; - - -/** buffer supplier parameter - * @ingroup tun - */ -typedef struct OMX_PARAM_BUFFERSUPPLIERTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_BUFFERSUPPLIERTYPE eBufferSupplier; /**< buffer supplier */ -} OMX_PARAM_BUFFERSUPPLIERTYPE; - - -/**< indicates that buffers received by an input port of a tunnel - may not modify the data in the buffers - @ingroup tun - */ -#define OMX_PORTTUNNELFLAG_READONLY 0x00000001 - - -/** The OMX_TUNNELSETUPTYPE structure is used to pass data from an output - port to an input port as part the two ComponentTunnelRequest calls - resulting from a OMX_SetupTunnel call from the IL Client. - @ingroup tun - */ -typedef struct OMX_TUNNELSETUPTYPE -{ - OMX_U32 nTunnelFlags; /**< bit flags for tunneling */ - OMX_BUFFERSUPPLIERTYPE eSupplier; /**< supplier preference */ -} OMX_TUNNELSETUPTYPE; - -/* OMX Component headers is included to enable the core to use - macros for functions into the component for OMX release 1.0. - Developers should not access any structures or data from within - the component header directly */ -/* TO BE REMOVED - #include */ - -/** GetComponentVersion will return information about the component. - This is a blocking call. This macro will go directly from the - application to the component (via a core macro). The - component will return from this call within 5 msec. - @param [in] hComponent - handle of component to execute the command - @param [out] pComponentName - pointer to an empty string of length 128 bytes. The component - will write its name into this string. The name will be - terminated by a single zero byte. The name of a component will - be 127 bytes or less to leave room for the trailing zero byte. - An example of a valid component name is "OMX.ABC.ChannelMixer\0". - @param [out] pComponentVersion - pointer to an OMX Version structure that the component will fill - in. The component will fill in a value that indicates the - component version. NOTE: the component version is NOT the same - as the OMX Specification version (found in all structures). The - component version is defined by the vendor of the component and - its value is entirely up to the component vendor. - @param [out] pSpecVersion - pointer to an OMX Version structure that the component will fill - in. The SpecVersion is the version of the specification that the - component was built against. Please note that this value may or - may not match the structure's version. For example, if the - component was built against the 2.0 specification, but the - application (which creates the structure is built against the - 1.0 specification the versions would be different. - @param [out] pComponentUUID - pointer to the UUID of the component which will be filled in by - the component. The UUID is a unique identifier that is set at - RUN time for the component and is unique to each instantion of - the component. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_GetComponentVersion( \ - hComponent, \ - pComponentName, \ - pComponentVersion, \ - pSpecVersion, \ - pComponentUUID) \ - ((OMX_COMPONENTTYPE*)hComponent)->GetComponentVersion( \ - hComponent, \ - pComponentName, \ - pComponentVersion, \ - pSpecVersion, \ - pComponentUUID) /* Macro End */ - - -/** Send a command to the component. This call is a non-blocking call. - The component should check the parameters and then queue the command - to the component thread to be executed. The component thread shall - send the EventHandler() callback at the conclusion of the command. - This macro will go directly from the application to the component (via - a core macro). The component will return from this call within 5 msec. - - When the command is "OMX_CommandStateSet" the component will queue a - state transition to the new state idenfied in nParam. - - When the command is "OMX_CommandFlush", to flush a port's buffer queues, - the command will force the component to return all buffers NOT CURRENTLY - BEING PROCESSED to the application, in the order in which the buffers - were received. - - When the command is "OMX_CommandPortDisable" or - "OMX_CommandPortEnable", the component's port (given by the value of - nParam) will be stopped or restarted. - - When the command "OMX_CommandMarkBuffer" is used to mark a buffer, the - pCmdData will point to a OMX_MARKTYPE structure containing the component - handle of the component to examine the buffer chain for the mark. nParam1 - contains the index of the port on which the buffer mark is applied. - - Specification text for more details. - - @param [in] hComponent - handle of component to execute the command - @param [in] Cmd - Command for the component to execute - @param [in] nParam - Parameter for the command to be executed. When Cmd has the value - OMX_CommandStateSet, value is a member of OMX_STATETYPE. When Cmd has - the value OMX_CommandFlush, value of nParam indicates which port(s) - to flush. -1 is used to flush all ports a single port index will - only flush that port. When Cmd has the value "OMX_CommandPortDisable" - or "OMX_CommandPortEnable", the component's port is given by - the value of nParam. When Cmd has the value "OMX_CommandMarkBuffer" - the components pot is given by the value of nParam. - @param [in] pCmdData - Parameter pointing to the OMX_MARKTYPE structure when Cmd has the value - "OMX_CommandMarkBuffer". - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_SendCommand( \ - hComponent, \ - Cmd, \ - nParam, \ - pCmdData) \ - ((OMX_COMPONENTTYPE*)hComponent)->SendCommand( \ - hComponent, \ - Cmd, \ - nParam, \ - pCmdData) /* Macro End */ - - -/** The OMX_GetParameter macro will get one of the current parameter - settings from the component. This macro cannot only be invoked when - the component is in the OMX_StateInvalid state. The nParamIndex - parameter is used to indicate which structure is being requested from - the component. The application shall allocate the correct structure - and shall fill in the structure size and version information before - invoking this macro. When the parameter applies to a port, the - caller shall fill in the appropriate nPortIndex value indicating the - port on which the parameter applies. If the component has not had - any settings changed, then the component should return a set of - valid DEFAULT parameters for the component. This is a blocking - call. - - The component should return from this call within 20 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] nParamIndex - Index of the structure to be filled. This value is from the - OMX_INDEXTYPE enumeration. - @param [in,out] pComponentParameterStructure - Pointer to application allocated structure to be filled by the - component. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_GetParameter( \ - hComponent, \ - nParamIndex, \ - pComponentParameterStructure) \ - ((OMX_COMPONENTTYPE*)hComponent)->GetParameter( \ - hComponent, \ - nParamIndex, \ - pComponentParameterStructure) /* Macro End */ - - -/** The OMX_SetParameter macro will send an initialization parameter - structure to a component. Each structure shall be sent one at a time, - in a separate invocation of the macro. This macro can only be - invoked when the component is in the OMX_StateLoaded state, or the - port is disabled (when the parameter applies to a port). The - nParamIndex parameter is used to indicate which structure is being - passed to the component. The application shall allocate the - correct structure and shall fill in the structure size and version - information (as well as the actual data) before invoking this macro. - The application is free to dispose of this structure after the call - as the component is required to copy any data it shall retain. This - is a blocking call. - - The component should return from this call within 20 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] nIndex - Index of the structure to be sent. This value is from the - OMX_INDEXTYPE enumeration. - @param [in] pComponentParameterStructure - pointer to application allocated structure to be used for - initialization by the component. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_SetParameter( \ - hComponent, \ - nParamIndex, \ - pComponentParameterStructure) \ - ((OMX_COMPONENTTYPE*)hComponent)->SetParameter( \ - hComponent, \ - nParamIndex, \ - pComponentParameterStructure) /* Macro End */ - - -/** The OMX_GetConfig macro will get one of the configuration structures - from a component. This macro can be invoked anytime after the - component has been loaded. The nParamIndex call parameter is used to - indicate which structure is being requested from the component. The - application shall allocate the correct structure and shall fill in the - structure size and version information before invoking this macro. - If the component has not had this configuration parameter sent before, - then the component should return a set of valid DEFAULT values for the - component. This is a blocking call. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] nIndex - Index of the structure to be filled. This value is from the - OMX_INDEXTYPE enumeration. - @param [in,out] pComponentConfigStructure - pointer to application allocated structure to be filled by the - component. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp -*/ -#define OMX_GetConfig( \ - hComponent, \ - nConfigIndex, \ - pComponentConfigStructure) \ - ((OMX_COMPONENTTYPE*)hComponent)->GetConfig( \ - hComponent, \ - nConfigIndex, \ - pComponentConfigStructure) /* Macro End */ - - -/** The OMX_SetConfig macro will send one of the configuration - structures to a component. Each structure shall be sent one at a time, - each in a separate invocation of the macro. This macro can be invoked - anytime after the component has been loaded. The application shall - allocate the correct structure and shall fill in the structure size - and version information (as well as the actual data) before invoking - this macro. The application is free to dispose of this structure after - the call as the component is required to copy any data it shall retain. - This is a blocking call. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] nConfigIndex - Index of the structure to be sent. This value is from the - OMX_INDEXTYPE enumeration above. - @param [in] pComponentConfigStructure - pointer to application allocated structure to be used for - initialization by the component. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_SetConfig( \ - hComponent, \ - nConfigIndex, \ - pComponentConfigStructure) \ - ((OMX_COMPONENTTYPE*)hComponent)->SetConfig( \ - hComponent, \ - nConfigIndex, \ - pComponentConfigStructure) /* Macro End */ - - -/** The OMX_GetExtensionIndex macro will invoke a component to translate - a vendor specific configuration or parameter string into an OMX - structure index. There is no requirement for the vendor to support - this command for the indexes already found in the OMX_INDEXTYPE - enumeration (this is done to save space in small components). The - component shall support all vendor supplied extension indexes not found - in the master OMX_INDEXTYPE enumeration. This is a blocking call. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the GetHandle function. - @param [in] cParameterName - OMX_STRING that shall be less than 128 characters long including - the trailing null byte. This is the string that will get - translated by the component into a configuration index. - @param [out] pIndexType - a pointer to a OMX_INDEXTYPE to receive the index value. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_GetExtensionIndex( \ - hComponent, \ - cParameterName, \ - pIndexType) \ - ((OMX_COMPONENTTYPE*)hComponent)->GetExtensionIndex( \ - hComponent, \ - cParameterName, \ - pIndexType) /* Macro End */ - - -/** The OMX_GetState macro will invoke the component to get the current - state of the component and place the state value into the location - pointed to by pState. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [out] pState - pointer to the location to receive the state. The value returned - is one of the OMX_STATETYPE members - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp - */ -#define OMX_GetState( \ - hComponent, \ - pState) \ - ((OMX_COMPONENTTYPE*)hComponent)->GetState( \ - hComponent, \ - pState) /* Macro End */ - - -/** The OMX_UseBuffer macro will request that the component use - a buffer (and allocate its own buffer header) already allocated - by another component, or by the IL Client. This is a blocking - call. - - The component should return from this call within 20 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [out] ppBuffer - pointer to an OMX_BUFFERHEADERTYPE structure used to receive the - pointer to the buffer header - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ - -#define OMX_UseBuffer( \ - hComponent, \ - ppBufferHdr, \ - nPortIndex, \ - pAppPrivate, \ - nSizeBytes, \ - pBuffer) \ - ((OMX_COMPONENTTYPE*)hComponent)->UseBuffer( \ - hComponent, \ - ppBufferHdr, \ - nPortIndex, \ - pAppPrivate, \ - nSizeBytes, \ - pBuffer) - - -/** The OMX_AllocateBuffer macro will request that the component allocate - a new buffer and buffer header. The component will allocate the - buffer and the buffer header and return a pointer to the buffer - header. This is a blocking call. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [out] ppBuffer - pointer to an OMX_BUFFERHEADERTYPE structure used to receive - the pointer to the buffer header - @param [in] nPortIndex - nPortIndex is used to select the port on the component the buffer will - be used with. The port can be found by using the nPortIndex - value as an index into the Port Definition array of the component. - @param [in] pAppPrivate - pAppPrivate is used to initialize the pAppPrivate member of the - buffer header structure. - @param [in] nSizeBytes - size of the buffer to allocate. Used when bAllocateNew is true. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ -#define OMX_AllocateBuffer( \ - hComponent, \ - ppBuffer, \ - nPortIndex, \ - pAppPrivate, \ - nSizeBytes) \ - ((OMX_COMPONENTTYPE*)hComponent)->AllocateBuffer( \ - hComponent, \ - ppBuffer, \ - nPortIndex, \ - pAppPrivate, \ - nSizeBytes) /* Macro End */ - - -/** The OMX_FreeBuffer macro will release a buffer header from the component - which was allocated using either OMX_AllocateBuffer or OMX_UseBuffer. If - the component allocated the buffer (see the OMX_UseBuffer macro) then - the component shall free the buffer and buffer header. This is a - blocking call. - - The component should return from this call within 20 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] nPortIndex - nPortIndex is used to select the port on the component the buffer will - be used with. - @param [in] pBuffer - pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer - or AllocateBuffer. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ -#define OMX_FreeBuffer( \ - hComponent, \ - nPortIndex, \ - pBuffer) \ - ((OMX_COMPONENTTYPE*)hComponent)->FreeBuffer( \ - hComponent, \ - nPortIndex, \ - pBuffer) /* Macro End */ - - -/** The OMX_EmptyThisBuffer macro will send a buffer full of data to an - input port of a component. The buffer will be emptied by the component - and returned to the application via the EmptyBufferDone call back. - This is a non-blocking call in that the component will record the buffer - and return immediately and then empty the buffer, later, at the proper - time. As expected, this macro may be invoked only while the component - is in the OMX_StateExecuting. If nPortIndex does not specify an input - port, the component shall return an error. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] pBuffer - pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer - or AllocateBuffer. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ -#define OMX_EmptyThisBuffer( \ - hComponent, \ - pBuffer) \ - ((OMX_COMPONENTTYPE*)hComponent)->EmptyThisBuffer( \ - hComponent, \ - pBuffer) /* Macro End */ - - -/** The OMX_FillThisBuffer macro will send an empty buffer to an - output port of a component. The buffer will be filled by the component - and returned to the application via the FillBufferDone call back. - This is a non-blocking call in that the component will record the buffer - and return immediately and then fill the buffer, later, at the proper - time. As expected, this macro may be invoked only while the component - is in the OMX_ExecutingState. If nPortIndex does not specify an output - port, the component shall return an error. - - The component should return from this call within 5 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [in] pBuffer - pointer to an OMX_BUFFERHEADERTYPE structure allocated with UseBuffer - or AllocateBuffer. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ -#define OMX_FillThisBuffer( \ - hComponent, \ - pBuffer) \ - ((OMX_COMPONENTTYPE*)hComponent)->FillThisBuffer( \ - hComponent, \ - pBuffer) /* Macro End */ - - - -/** The OMX_UseEGLImage macro will request that the component use - a EGLImage provided by EGL (and allocate its own buffer header) - This is a blocking call. - - The component should return from this call within 20 msec. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the OMX_GetHandle function. - @param [out] ppBuffer - pointer to an OMX_BUFFERHEADERTYPE structure used to receive the - pointer to the buffer header. Note that the memory location used - for this buffer is NOT visible to the IL Client. - @param [in] nPortIndex - nPortIndex is used to select the port on the component the buffer will - be used with. The port can be found by using the nPortIndex - value as an index into the Port Definition array of the component. - @param [in] pAppPrivate - pAppPrivate is used to initialize the pAppPrivate member of the - buffer header structure. - @param [in] eglImage - eglImage contains the handle of the EGLImage to use as a buffer on the - specified port. The component is expected to validate properties of - the EGLImage against the configuration of the port to ensure the component - can use the EGLImage as a buffer. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup comp buf - */ -#define OMX_UseEGLImage( \ - hComponent, \ - ppBufferHdr, \ - nPortIndex, \ - pAppPrivate, \ - eglImage) \ - ((OMX_COMPONENTTYPE*)hComponent)->UseEGLImage( \ - hComponent, \ - ppBufferHdr, \ - nPortIndex, \ - pAppPrivate, \ - eglImage) - -/** The OMX_Init method is used to initialize the OMX core. It shall be the - first call made into OMX and it should only be executed one time without - an interviening OMX_Deinit call. - - The core should return from this call within 20 msec. - - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Init(void); - - -/** The OMX_Deinit method is used to deinitialize the OMX core. It shall be - the last call made into OMX. In the event that the core determines that - thare are components loaded when this call is made, the core may return - with an error rather than try to unload the components. - - The core should return from this call within 20 msec. - - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Deinit(void); - - -/** The OMX_ComponentNameEnum method will enumerate through all the names of - recognised valid components in the system. This function is provided - as a means to detect all the components in the system run-time. There is - no strict ordering to the enumeration order of component names, although - each name will only be enumerated once. If the OMX core supports run-time - installation of new components, it is only requried to detect newly - installed components when the first call to enumerate component names - is made (i.e. when nIndex is 0x0). - - The core should return from this call in 20 msec. - - @param [out] cComponentName - pointer to a null terminated string with the component name. The - names of the components are strings less than 127 bytes in length - plus the trailing null for a maximum size of 128 bytes. An example - of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are - assigned by the vendor, but shall start with "OMX." and then have - the Vendor designation next. - @param [in] nNameLength - number of characters in the cComponentName string. With all - component name strings restricted to less than 128 characters - (including the trailing null) it is recomended that the caller - provide a input string for the cComponentName of 128 characters. - @param [in] nIndex - number containing the enumeration index for the component. - Multiple calls to OMX_ComponentNameEnum with increasing values - of nIndex will enumerate through the component names in the - system until OMX_ErrorNoMore is returned. The value of nIndex - is 0 to (N-1), where N is the number of valid installed components - in the system. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. When the value of nIndex exceeds the number of - components in the system minus 1, OMX_ErrorNoMore will be - returned. Otherwise the appropriate OMX error will be returned. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_ComponentNameEnum( - OMX_OUT OMX_STRING cComponentName, - OMX_IN OMX_U32 nNameLength, - OMX_IN OMX_U32 nIndex); - - -/** The OMX_GetHandle method will locate the component specified by the - component name given, load that component into memory and then invoke - the component's methods to create an instance of the component. - - The core should return from this call within 20 msec. - - @param [out] pHandle - pointer to an OMX_HANDLETYPE pointer to be filled in by this method. - @param [in] cComponentName - pointer to a null terminated string with the component name. The - names of the components are strings less than 127 bytes in length - plus the trailing null for a maximum size of 128 bytes. An example - of a valid component name is "OMX.TI.AUDIO.DSP.MIXER\0". Names are - assigned by the vendor, but shall start with "OMX." and then have - the Vendor designation next. - @param [in] pAppData - pointer to an application defined value that will be returned - during callbacks so that the application can identify the source - of the callback. - @param [in] pCallBacks - pointer to a OMX_CALLBACKTYPE structure that will be passed to the - component to initialize it with. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_GetHandle( - OMX_OUT OMX_HANDLETYPE* pHandle, - OMX_IN OMX_STRING cComponentName, - OMX_IN OMX_PTR pAppData, - OMX_IN OMX_CALLBACKTYPE* pCallBacks); - - -/** The OMX_FreeHandle method will free a handle allocated by the OMX_GetHandle - method. If the component reference count goes to zero, the component will - be unloaded from memory. - - The core should return from this call within 20 msec when the component is - in the OMX_StateLoaded state. - - @param [in] hComponent - Handle of the component to be accessed. This is the component - handle returned by the call to the GetHandle function. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_FreeHandle( - OMX_IN OMX_HANDLETYPE hComponent); - - - -/** The OMX_SetupTunnel method will handle the necessary calls to the components - to setup the specified tunnel the two components. NOTE: This is - an actual method (not a #define macro). This method will make calls into - the component ComponentTunnelRequest method to do the actual tunnel - connection. - - The ComponentTunnelRequest method on both components will be called. - This method shall not be called unless the component is in the - OMX_StateLoaded state except when the ports used for the tunnel are - disabled. In this case, the component may be in the OMX_StateExecuting, - OMX_StatePause, or OMX_StateIdle states. - - The core should return from this call within 20 msec. - - @param [in] hOutput - Handle of the component to be accessed. Also this is the handle - of the component whose port, specified in the nPortOutput parameter - will be used the source for the tunnel. This is the component handle - returned by the call to the OMX_GetHandle function. There is a - requirement that hOutput be the source for the data when - tunelling (i.e. nPortOutput is an output port). If 0x0, the component - specified in hInput will have it's port specified in nPortInput - setup for communication with the application / IL client. - @param [in] nPortOutput - nPortOutput is used to select the source port on component to be - used in the tunnel. - @param [in] hInput - This is the component to setup the tunnel with. This is the handle - of the component whose port, specified in the nPortInput parameter - will be used the destination for the tunnel. This is the component handle - returned by the call to the OMX_GetHandle function. There is a - requirement that hInput be the destination for the data when - tunelling (i.e. nPortInut is an input port). If 0x0, the component - specified in hOutput will have it's port specified in nPortPOutput - setup for communication with the application / IL client. - @param [in] nPortInput - nPortInput is used to select the destination port on component to be - used in the tunnel. - @return OMX_ERRORTYPE - If the command successfully executes, the return code will be - OMX_ErrorNone. Otherwise the appropriate OMX error will be returned. - When OMX_ErrorNotImplemented is returned, one or both components is - a non-interop component and does not support tunneling. - - On failure, the ports of both components are setup for communication - with the application / IL Client. - @ingroup core tun - */ -OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_SetupTunnel( - OMX_IN OMX_HANDLETYPE hOutput, - OMX_IN OMX_U32 nPortOutput, - OMX_IN OMX_HANDLETYPE hInput, - OMX_IN OMX_U32 nPortInput); - -/** @ingroup cp */ -OMX_API OMX_ERRORTYPE OMX_GetContentPipe( - OMX_OUT OMX_HANDLETYPE *hPipe, - OMX_IN OMX_STRING szURI); - -/** The OMX_GetComponentsOfRole method will return the number of components that support the given - role and (if the compNames field is non-NULL) the names of those components. The call will fail if - an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the - client should: - * first call this function with the compNames field NULL to determine the number of component names - * second call this function with the compNames field pointing to an array of names allocated - according to the number returned by the first call. - - The core should return from this call within 5 msec. - - @param [in] role - This is generic standard component name consisting only of component class - name and the type within that class (e.g. 'audio_decoder.aac'). - @param [inout] pNumComps - This is used both as input and output. - - If compNames is NULL, the input is ignored and the output specifies how many components support - the given role. - - If compNames is not NULL, on input it bounds the size of the input structure and - on output, it specifies the number of components string names listed within the compNames parameter. - @param [inout] compNames - If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings which accepts - a list of the names of all physical components that implement the specified standard component name. - Each name is NULL terminated. numComps indicates the number of names. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_GetComponentsOfRole ( - OMX_IN OMX_STRING role, - OMX_INOUT OMX_U32 *pNumComps, - OMX_INOUT OMX_U8 **compNames); - -/** The OMX_GetRolesOfComponent method will return the number of roles supported by the given - component and (if the roles field is non-NULL) the names of those roles. The call will fail if - an insufficiently sized array of names is supplied. To ensure the array is sufficiently sized the - client should: - * first call this function with the roles field NULL to determine the number of role names - * second call this function with the roles field pointing to an array of names allocated - according to the number returned by the first call. - - The core should return from this call within 5 msec. - - @param [in] compName - This is the name of the component being queried about. - @param [inout] pNumRoles - This is used both as input and output. - - If roles is NULL, the input is ignored and the output specifies how many roles the component supports. - - If compNames is not NULL, on input it bounds the size of the input structure and - on output, it specifies the number of roles string names listed within the roles parameter. - @param [out] roles - If NULL this field is ignored. If non-NULL this points to an array of 128-byte strings - which accepts a list of the names of all standard components roles implemented on the - specified component name. numComps indicates the number of names. - @ingroup core - */ -OMX_API OMX_ERRORTYPE OMX_GetRolesOfComponent ( - OMX_IN OMX_STRING compName, - OMX_INOUT OMX_U32 *pNumRoles, - OMX_OUT OMX_U8 **roles); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ - diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_CoreExt.h b/starpilot/ui/screenrecorder/openmax/include/OMX_CoreExt.h deleted file mode 100644 index 3ec14b05f..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_CoreExt.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2009 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_CoreExt.h - OpenMax IL version 1.1.2 - * The OMX_CoreExt header file contains extensions to the definitions used - * by both the application and the component to access common items. - */ - -#ifndef OMX_CoreExt_h -#define OMX_CoreExt_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Each OMX header shall include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ -#include - - -/** Event type extensions. */ -typedef enum OMX_EVENTEXTTYPE -{ - OMX_EventIndexSettingChanged = OMX_EventKhronosExtensions, /**< component signals the IL client of a change - in a param, config, or extension */ - OMX_EventExtMax = 0x7FFFFFFF -} OMX_EVENTEXTTYPE; - - -/** Enable or disable a callback event. */ -typedef struct OMX_CONFIG_CALLBACKREQUESTTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_INDEXTYPE nIndex; /**< the index the callback is requested for */ - OMX_BOOL bEnable; /**< enable (OMX_TRUE) or disable (OMX_FALSE) the callback */ -} OMX_CONFIG_CALLBACKREQUESTTYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* OMX_CoreExt_h */ -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_IVCommon.h b/starpilot/ui/screenrecorder/openmax/include/OMX_IVCommon.h deleted file mode 100644 index ec717565a..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_IVCommon.h +++ /dev/null @@ -1,933 +0,0 @@ -/** - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** - * @file OMX_IVCommon.h - OpenMax IL version 1.1.2 - * The structures needed by Video and Image components to exchange - * parameters and configuration data with the components. - */ -#ifndef OMX_IVCommon_h -#define OMX_IVCommon_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** - * Each OMX header must include all required header files to allow the header - * to compile without errors. The includes below are required for this header - * file to compile successfully - */ - -#include - -/** @defgroup iv OpenMAX IL Imaging and Video Domain - * Common structures for OpenMAX IL Imaging and Video domains - * @{ - */ - - -/** - * Enumeration defining possible uncompressed image/video formats. - * - * ENUMS: - * Unused : Placeholder value when format is N/A - * Monochrome : black and white - * 8bitRGB332 : Red 7:5, Green 4:2, Blue 1:0 - * 12bitRGB444 : Red 11:8, Green 7:4, Blue 3:0 - * 16bitARGB4444 : Alpha 15:12, Red 11:8, Green 7:4, Blue 3:0 - * 16bitARGB1555 : Alpha 15, Red 14:10, Green 9:5, Blue 4:0 - * 16bitRGB565 : Red 15:11, Green 10:5, Blue 4:0 - * 16bitBGR565 : Blue 15:11, Green 10:5, Red 4:0 - * 18bitRGB666 : Red 17:12, Green 11:6, Blue 5:0 - * 18bitARGB1665 : Alpha 17, Red 16:11, Green 10:5, Blue 4:0 - * 19bitARGB1666 : Alpha 18, Red 17:12, Green 11:6, Blue 5:0 - * 24bitRGB888 : Red 24:16, Green 15:8, Blue 7:0 - * 24bitBGR888 : Blue 24:16, Green 15:8, Red 7:0 - * 24bitARGB1887 : Alpha 23, Red 22:15, Green 14:7, Blue 6:0 - * 25bitARGB1888 : Alpha 24, Red 23:16, Green 15:8, Blue 7:0 - * 32bitBGRA8888 : Blue 31:24, Green 23:16, Red 15:8, Alpha 7:0 - * 32bitARGB8888 : Alpha 31:24, Red 23:16, Green 15:8, Blue 7:0 - * YUV411Planar : U,Y are subsampled by a factor of 4 horizontally - * YUV411PackedPlanar : packed per payload in planar slices - * YUV420Planar : Three arrays Y,U,V. - * YUV420PackedPlanar : packed per payload in planar slices - * YUV420SemiPlanar : Two arrays, one is all Y, the other is U and V - * YUV422Planar : Three arrays Y,U,V. - * YUV422PackedPlanar : packed per payload in planar slices - * YUV422SemiPlanar : Two arrays, one is all Y, the other is U and V - * YCbYCr : Organized as 16bit YUYV (i.e. YCbYCr) - * YCrYCb : Organized as 16bit YVYU (i.e. YCrYCb) - * CbYCrY : Organized as 16bit UYVY (i.e. CbYCrY) - * CrYCbY : Organized as 16bit VYUY (i.e. CrYCbY) - * YUV444Interleaved : Each pixel contains equal parts YUV - * RawBayer8bit : SMIA camera output format - * RawBayer10bit : SMIA camera output format - * RawBayer8bitcompressed : SMIA camera output format - */ -typedef enum OMX_COLOR_FORMATTYPE { - OMX_COLOR_FormatUnused, - OMX_COLOR_FormatMonochrome, - OMX_COLOR_Format8bitRGB332, - OMX_COLOR_Format12bitRGB444, - OMX_COLOR_Format16bitARGB4444, - OMX_COLOR_Format16bitARGB1555, - OMX_COLOR_Format16bitRGB565, - OMX_COLOR_Format16bitBGR565, - OMX_COLOR_Format18bitRGB666, - OMX_COLOR_Format18bitARGB1665, - OMX_COLOR_Format19bitARGB1666, - OMX_COLOR_Format24bitRGB888, - OMX_COLOR_Format24bitBGR888, - OMX_COLOR_Format24bitARGB1887, - OMX_COLOR_Format25bitARGB1888, - OMX_COLOR_Format32bitBGRA8888, - OMX_COLOR_Format32bitARGB8888, - OMX_COLOR_FormatYUV411Planar, - OMX_COLOR_FormatYUV411PackedPlanar, - OMX_COLOR_FormatYUV420Planar, - OMX_COLOR_FormatYUV420PackedPlanar, - OMX_COLOR_FormatYUV420SemiPlanar, - OMX_COLOR_FormatYUV422Planar, - OMX_COLOR_FormatYUV422PackedPlanar, - OMX_COLOR_FormatYUV422SemiPlanar, - OMX_COLOR_FormatYCbYCr, - OMX_COLOR_FormatYCrYCb, - OMX_COLOR_FormatCbYCrY, - OMX_COLOR_FormatCrYCbY, - OMX_COLOR_FormatYUV444Interleaved, - OMX_COLOR_FormatRawBayer8bit, - OMX_COLOR_FormatRawBayer10bit, - OMX_COLOR_FormatRawBayer8bitcompressed, - OMX_COLOR_FormatL2, - OMX_COLOR_FormatL4, - OMX_COLOR_FormatL8, - OMX_COLOR_FormatL16, - OMX_COLOR_FormatL24, - OMX_COLOR_FormatL32, - OMX_COLOR_FormatYUV420PackedSemiPlanar, - OMX_COLOR_FormatYUV422PackedSemiPlanar, - OMX_COLOR_Format18BitBGR666, - OMX_COLOR_Format24BitARGB6666, - OMX_COLOR_Format24BitABGR6666, - OMX_COLOR_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_COLOR_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - /** - -/** @defgroup imaging OpenMAX IL Imaging Domain - * @ingroup iv - * Structures for OpenMAX IL Imaging domain - * @{ - */ - -/** - * Enumeration used to define the possible image compression coding. - */ -typedef enum OMX_IMAGE_CODINGTYPE { - OMX_IMAGE_CodingUnused, /**< Value when format is N/A */ - OMX_IMAGE_CodingAutoDetect, /**< Auto detection of image format */ - OMX_IMAGE_CodingJPEG, /**< JPEG/JFIF image format */ - OMX_IMAGE_CodingJPEG2K, /**< JPEG 2000 image format */ - OMX_IMAGE_CodingEXIF, /**< EXIF image format */ - OMX_IMAGE_CodingTIFF, /**< TIFF image format */ - OMX_IMAGE_CodingGIF, /**< Graphics image format */ - OMX_IMAGE_CodingPNG, /**< PNG image format */ - OMX_IMAGE_CodingLZW, /**< LZW image format */ - OMX_IMAGE_CodingBMP, /**< Windows Bitmap format */ - OMX_IMAGE_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_IMAGE_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_IMAGE_CodingMax = 0x7FFFFFFF -} OMX_IMAGE_CODINGTYPE; - - -/** - * Data structure used to define an image path. The number of image paths - * for input and output will vary by type of the image component. - * - * Input (aka Source) : Zero Inputs, one Output, - * Splitter : One Input, 2 or more Outputs, - * Processing Element : One Input, one output, - * Mixer : 2 or more inputs, one output, - * Output (aka Sink) : One Input, zero outputs. - * - * The PortDefinition structure is used to define all of the parameters - * necessary for the compliant component to setup an input or an output - * image path. If additional vendor specific data is required, it should - * be transmitted to the component using the CustomCommand function. - * Compliant components will prepopulate this structure with optimal - * values during the OMX_GetParameter() command. - * - * STRUCT MEMBERS: - * cMIMEType : MIME type of data for the port - * pNativeRender : Platform specific reference for a display if a - * sync, otherwise this field is 0 - * nFrameWidth : Width of frame to be used on port if - * uncompressed format is used. Use 0 for - * unknown, don't care or variable - * nFrameHeight : Height of frame to be used on port if - * uncompressed format is used. Use 0 for - * unknown, don't care or variable - * nStride : Number of bytes per span of an image (i.e. - * indicates the number of bytes to get from - * span N to span N+1, where negative stride - * indicates the image is bottom up - * nSliceHeight : Height used when encoding in slices - * bFlagErrorConcealment : Turns on error concealment if it is supported by - * the OMX component - * eCompressionFormat : Compression format used in this instance of - * the component. When OMX_IMAGE_CodingUnused is - * specified, eColorFormat is valid - * eColorFormat : Decompressed format used by this component - * pNativeWindow : Platform specific reference for a window object if a - * display sink , otherwise this field is 0x0. - */ -typedef struct OMX_IMAGE_PORTDEFINITIONTYPE { - OMX_STRING cMIMEType; - OMX_NATIVE_DEVICETYPE pNativeRender; - OMX_U32 nFrameWidth; - OMX_U32 nFrameHeight; - OMX_S32 nStride; - OMX_U32 nSliceHeight; - OMX_BOOL bFlagErrorConcealment; - OMX_IMAGE_CODINGTYPE eCompressionFormat; - OMX_COLOR_FORMATTYPE eColorFormat; - OMX_NATIVE_WINDOWTYPE pNativeWindow; -} OMX_IMAGE_PORTDEFINITIONTYPE; - - -/** - * Port format parameter. This structure is used to enumerate the various - * data input/output format supported by the port. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Indicates which port to set - * nIndex : Indicates the enumeration index for the format from - * 0x0 to N-1 - * eCompressionFormat : Compression format used in this instance of the - * component. When OMX_IMAGE_CodingUnused is specified, - * eColorFormat is valid - * eColorFormat : Decompressed format used by this component - */ -typedef struct OMX_IMAGE_PARAM_PORTFORMATTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nIndex; - OMX_IMAGE_CODINGTYPE eCompressionFormat; - OMX_COLOR_FORMATTYPE eColorFormat; -} OMX_IMAGE_PARAM_PORTFORMATTYPE; - - -/** - * Flash control type - * - * ENUMS - * Torch : Flash forced constantly on - */ -typedef enum OMX_IMAGE_FLASHCONTROLTYPE { - OMX_IMAGE_FlashControlOn = 0, - OMX_IMAGE_FlashControlOff, - OMX_IMAGE_FlashControlAuto, - OMX_IMAGE_FlashControlRedEyeReduction, - OMX_IMAGE_FlashControlFillin, - OMX_IMAGE_FlashControlTorch, - OMX_IMAGE_FlashControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_IMAGE_FlashControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_IMAGE_FlashControlMax = 0x7FFFFFFF -} OMX_IMAGE_FLASHCONTROLTYPE; - - -/** - * Flash control configuration - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFlashControl : Flash control type - */ -typedef struct OMX_IMAGE_PARAM_FLASHCONTROLTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_IMAGE_FLASHCONTROLTYPE eFlashControl; -} OMX_IMAGE_PARAM_FLASHCONTROLTYPE; - - -/** - * Focus control type - */ -typedef enum OMX_IMAGE_FOCUSCONTROLTYPE { - OMX_IMAGE_FocusControlOn = 0, - OMX_IMAGE_FocusControlOff, - OMX_IMAGE_FocusControlAuto, - OMX_IMAGE_FocusControlAutoLock, - OMX_IMAGE_FocusControlKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_IMAGE_FocusControlVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_IMAGE_FocusControlMax = 0x7FFFFFFF -} OMX_IMAGE_FOCUSCONTROLTYPE; - - -/** - * Focus control configuration - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFocusControl : Focus control - * nFocusSteps : Focus can take on values from 0 mm to infinity. - * Interest is only in number of steps over this range. - * nFocusStepIndex : Current focus step index - */ -typedef struct OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_IMAGE_FOCUSCONTROLTYPE eFocusControl; - OMX_U32 nFocusSteps; - OMX_U32 nFocusStepIndex; -} OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE; - - -/** - * Q Factor for JPEG compression, which controls the tradeoff between image - * quality and size. Q Factor provides a more simple means of controlling - * JPEG compression quality, without directly programming Quantization - * tables for chroma and luma - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nQFactor : JPEG Q factor value in the range of 1-100. A factor of 1 - * produces the smallest, worst quality images, and a factor - * of 100 produces the largest, best quality images. A - * typical default is 75 for small good quality images - */ -typedef struct OMX_IMAGE_PARAM_QFACTORTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nQFactor; -} OMX_IMAGE_PARAM_QFACTORTYPE; - -/** - * Quantization table type - */ - -typedef enum OMX_IMAGE_QUANTIZATIONTABLETYPE { - OMX_IMAGE_QuantizationTableLuma = 0, - OMX_IMAGE_QuantizationTableChroma, - OMX_IMAGE_QuantizationTableChromaCb, - OMX_IMAGE_QuantizationTableChromaCr, - OMX_IMAGE_QuantizationTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_IMAGE_QuantizationTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_IMAGE_QuantizationTableMax = 0x7FFFFFFF -} OMX_IMAGE_QUANTIZATIONTABLETYPE; - -/** - * JPEG quantization tables are used to determine DCT compression for - * YUV data, as an alternative to specifying Q factor, providing exact - * control of compression - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eQuantizationTable : Quantization table type - * nQuantizationMatrix[64] : JPEG quantization table of coefficients stored - * in increasing columns then by rows of data (i.e. - * row 1, ... row 8). Quantization values are in - * the range 0-255 and stored in linear order - * (i.e. the component will zig-zag the - * quantization table data if required internally) - */ -typedef struct OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_IMAGE_QUANTIZATIONTABLETYPE eQuantizationTable; - OMX_U8 nQuantizationMatrix[64]; -} OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE; - - -/** - * Huffman table type, the same Huffman table is applied for chroma and - * luma component - */ -typedef enum OMX_IMAGE_HUFFMANTABLETYPE { - OMX_IMAGE_HuffmanTableAC = 0, - OMX_IMAGE_HuffmanTableDC, - OMX_IMAGE_HuffmanTableACLuma, - OMX_IMAGE_HuffmanTableACChroma, - OMX_IMAGE_HuffmanTableDCLuma, - OMX_IMAGE_HuffmanTableDCChroma, - OMX_IMAGE_HuffmanTableKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_IMAGE_HuffmanTableVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_IMAGE_HuffmanTableMax = 0x7FFFFFFF -} OMX_IMAGE_HUFFMANTABLETYPE; - -/** - * JPEG Huffman table - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eHuffmanTable : Huffman table type - * nNumberOfHuffmanCodeOfLength[16] : 0-16, number of Huffman codes of each - * possible length - * nHuffmanTable[256] : 0-255, the size used for AC and DC - * HuffmanTable are 16 and 162 - */ -typedef struct OMX_IMAGE_PARAM_HUFFMANTTABLETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_IMAGE_HUFFMANTABLETYPE eHuffmanTable; - OMX_U8 nNumberOfHuffmanCodeOfLength[16]; - OMX_U8 nHuffmanTable[256]; -}OMX_IMAGE_PARAM_HUFFMANTTABLETYPE; - -/** @} */ -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Index.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Index.h deleted file mode 100644 index a1f17487d..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Index.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** @file OMX_Index.h - OpenMax IL version 1.1.2 - * The OMX_Index header file contains the definitions for both applications - * and components . - */ - - -#ifndef OMX_Index_h -#define OMX_Index_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/* Each OMX header must include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ -#include - - -/** The OMX_INDEXTYPE enumeration is used to select a structure when either - * getting or setting parameters and/or configuration data. Each entry in - * this enumeration maps to an OMX specified structure. When the - * OMX_GetParameter, OMX_SetParameter, OMX_GetConfig or OMX_SetConfig methods - * are used, the second parameter will always be an entry from this enumeration - * and the third entry will be the structure shown in the comments for the entry. - * For example, if the application is initializing a cropping function, the - * OMX_SetConfig command would have OMX_IndexConfigCommonInputCrop as the second parameter - * and would send a pointer to an initialized OMX_RECTTYPE structure as the - * third parameter. - * - * The enumeration entries named with the OMX_Config prefix are sent using - * the OMX_SetConfig command and the enumeration entries named with the - * OMX_PARAM_ prefix are sent using the OMX_SetParameter command. - */ -typedef enum OMX_INDEXTYPE { - - OMX_IndexComponentStartUnused = 0x01000000, - OMX_IndexParamPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ - OMX_IndexParamAudioInit, /**< reference: OMX_PORT_PARAM_TYPE */ - OMX_IndexParamImageInit, /**< reference: OMX_PORT_PARAM_TYPE */ - OMX_IndexParamVideoInit, /**< reference: OMX_PORT_PARAM_TYPE */ - OMX_IndexParamOtherInit, /**< reference: OMX_PORT_PARAM_TYPE */ - OMX_IndexParamNumAvailableStreams, /**< reference: OMX_PARAM_U32TYPE */ - OMX_IndexParamActiveStream, /**< reference: OMX_PARAM_U32TYPE */ - OMX_IndexParamSuspensionPolicy, /**< reference: OMX_PARAM_SUSPENSIONPOLICYTYPE */ - OMX_IndexParamComponentSuspended, /**< reference: OMX_PARAM_SUSPENSIONTYPE */ - OMX_IndexConfigCapturing, /**< reference: OMX_CONFIG_BOOLEANTYPE */ - OMX_IndexConfigCaptureMode, /**< reference: OMX_CONFIG_CAPTUREMODETYPE */ - OMX_IndexAutoPauseAfterCapture, /**< reference: OMX_CONFIG_BOOLEANTYPE */ - OMX_IndexParamContentURI, /**< reference: OMX_PARAM_CONTENTURITYPE */ - OMX_IndexParamCustomContentPipe, /**< reference: OMX_PARAM_CONTENTPIPETYPE */ - OMX_IndexParamDisableResourceConcealment, /**< reference: OMX_RESOURCECONCEALMENTTYPE */ - OMX_IndexConfigMetadataItemCount, /**< reference: OMX_CONFIG_METADATAITEMCOUNTTYPE */ - OMX_IndexConfigContainerNodeCount, /**< reference: OMX_CONFIG_CONTAINERNODECOUNTTYPE */ - OMX_IndexConfigMetadataItem, /**< reference: OMX_CONFIG_METADATAITEMTYPE */ - OMX_IndexConfigCounterNodeID, /**< reference: OMX_CONFIG_CONTAINERNODEIDTYPE */ - OMX_IndexParamMetadataFilterType, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ - OMX_IndexParamMetadataKeyFilter, /**< reference: OMX_PARAM_METADATAFILTERTYPE */ - OMX_IndexConfigPriorityMgmt, /**< reference: OMX_PRIORITYMGMTTYPE */ - OMX_IndexParamStandardComponentRole, /**< reference: OMX_PARAM_COMPONENTROLETYPE */ - - OMX_IndexPortStartUnused = 0x02000000, - OMX_IndexParamPortDefinition, /**< reference: OMX_PARAM_PORTDEFINITIONTYPE */ - OMX_IndexParamCompBufferSupplier, /**< reference: OMX_PARAM_BUFFERSUPPLIERTYPE */ - OMX_IndexReservedStartUnused = 0x03000000, - - /* Audio parameters and configurations */ - OMX_IndexAudioStartUnused = 0x04000000, - OMX_IndexParamAudioPortFormat, /**< reference: OMX_AUDIO_PARAM_PORTFORMATTYPE */ - OMX_IndexParamAudioPcm, /**< reference: OMX_AUDIO_PARAM_PCMMODETYPE */ - OMX_IndexParamAudioAac, /**< reference: OMX_AUDIO_PARAM_AACPROFILETYPE */ - OMX_IndexParamAudioRa, /**< reference: OMX_AUDIO_PARAM_RATYPE */ - OMX_IndexParamAudioMp3, /**< reference: OMX_AUDIO_PARAM_MP3TYPE */ - OMX_IndexParamAudioAdpcm, /**< reference: OMX_AUDIO_PARAM_ADPCMTYPE */ - OMX_IndexParamAudioG723, /**< reference: OMX_AUDIO_PARAM_G723TYPE */ - OMX_IndexParamAudioG729, /**< reference: OMX_AUDIO_PARAM_G729TYPE */ - OMX_IndexParamAudioAmr, /**< reference: OMX_AUDIO_PARAM_AMRTYPE */ - OMX_IndexParamAudioWma, /**< reference: OMX_AUDIO_PARAM_WMATYPE */ - OMX_IndexParamAudioSbc, /**< reference: OMX_AUDIO_PARAM_SBCTYPE */ - OMX_IndexParamAudioMidi, /**< reference: OMX_AUDIO_PARAM_MIDITYPE */ - OMX_IndexParamAudioGsm_FR, /**< reference: OMX_AUDIO_PARAM_GSMFRTYPE */ - OMX_IndexParamAudioMidiLoadUserSound, /**< reference: OMX_AUDIO_PARAM_MIDILOADUSERSOUNDTYPE */ - OMX_IndexParamAudioG726, /**< reference: OMX_AUDIO_PARAM_G726TYPE */ - OMX_IndexParamAudioGsm_EFR, /**< reference: OMX_AUDIO_PARAM_GSMEFRTYPE */ - OMX_IndexParamAudioGsm_HR, /**< reference: OMX_AUDIO_PARAM_GSMHRTYPE */ - OMX_IndexParamAudioPdc_FR, /**< reference: OMX_AUDIO_PARAM_PDCFRTYPE */ - OMX_IndexParamAudioPdc_EFR, /**< reference: OMX_AUDIO_PARAM_PDCEFRTYPE */ - OMX_IndexParamAudioPdc_HR, /**< reference: OMX_AUDIO_PARAM_PDCHRTYPE */ - OMX_IndexParamAudioTdma_FR, /**< reference: OMX_AUDIO_PARAM_TDMAFRTYPE */ - OMX_IndexParamAudioTdma_EFR, /**< reference: OMX_AUDIO_PARAM_TDMAEFRTYPE */ - OMX_IndexParamAudioQcelp8, /**< reference: OMX_AUDIO_PARAM_QCELP8TYPE */ - OMX_IndexParamAudioQcelp13, /**< reference: OMX_AUDIO_PARAM_QCELP13TYPE */ - OMX_IndexParamAudioEvrc, /**< reference: OMX_AUDIO_PARAM_EVRCTYPE */ - OMX_IndexParamAudioSmv, /**< reference: OMX_AUDIO_PARAM_SMVTYPE */ - OMX_IndexParamAudioVorbis, /**< reference: OMX_AUDIO_PARAM_VORBISTYPE */ - - OMX_IndexConfigAudioMidiImmediateEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIIMMEDIATEEVENTTYPE */ - OMX_IndexConfigAudioMidiControl, /**< reference: OMX_AUDIO_CONFIG_MIDICONTROLTYPE */ - OMX_IndexConfigAudioMidiSoundBankProgram, /**< reference: OMX_AUDIO_CONFIG_MIDISOUNDBANKPROGRAMTYPE */ - OMX_IndexConfigAudioMidiStatus, /**< reference: OMX_AUDIO_CONFIG_MIDISTATUSTYPE */ - OMX_IndexConfigAudioMidiMetaEvent, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTTYPE */ - OMX_IndexConfigAudioMidiMetaEventData, /**< reference: OMX_AUDIO_CONFIG_MIDIMETAEVENTDATATYPE */ - OMX_IndexConfigAudioVolume, /**< reference: OMX_AUDIO_CONFIG_VOLUMETYPE */ - OMX_IndexConfigAudioBalance, /**< reference: OMX_AUDIO_CONFIG_BALANCETYPE */ - OMX_IndexConfigAudioChannelMute, /**< reference: OMX_AUDIO_CONFIG_CHANNELMUTETYPE */ - OMX_IndexConfigAudioMute, /**< reference: OMX_AUDIO_CONFIG_MUTETYPE */ - OMX_IndexConfigAudioLoudness, /**< reference: OMX_AUDIO_CONFIG_LOUDNESSTYPE */ - OMX_IndexConfigAudioEchoCancelation, /**< reference: OMX_AUDIO_CONFIG_ECHOCANCELATIONTYPE */ - OMX_IndexConfigAudioNoiseReduction, /**< reference: OMX_AUDIO_CONFIG_NOISEREDUCTIONTYPE */ - OMX_IndexConfigAudioBass, /**< reference: OMX_AUDIO_CONFIG_BASSTYPE */ - OMX_IndexConfigAudioTreble, /**< reference: OMX_AUDIO_CONFIG_TREBLETYPE */ - OMX_IndexConfigAudioStereoWidening, /**< reference: OMX_AUDIO_CONFIG_STEREOWIDENINGTYPE */ - OMX_IndexConfigAudioChorus, /**< reference: OMX_AUDIO_CONFIG_CHORUSTYPE */ - OMX_IndexConfigAudioEqualizer, /**< reference: OMX_AUDIO_CONFIG_EQUALIZERTYPE */ - OMX_IndexConfigAudioReverberation, /**< reference: OMX_AUDIO_CONFIG_REVERBERATIONTYPE */ - OMX_IndexConfigAudioChannelVolume, /**< reference: OMX_AUDIO_CONFIG_CHANNELVOLUMETYPE */ - - /* Image specific parameters and configurations */ - OMX_IndexImageStartUnused = 0x05000000, - OMX_IndexParamImagePortFormat, /**< reference: OMX_IMAGE_PARAM_PORTFORMATTYPE */ - OMX_IndexParamFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ - OMX_IndexConfigFocusControl, /**< reference: OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE */ - OMX_IndexParamQFactor, /**< reference: OMX_IMAGE_PARAM_QFACTORTYPE */ - OMX_IndexParamQuantizationTable, /**< reference: OMX_IMAGE_PARAM_QUANTIZATIONTABLETYPE */ - OMX_IndexParamHuffmanTable, /**< reference: OMX_IMAGE_PARAM_HUFFMANTTABLETYPE */ - OMX_IndexConfigFlashControl, /**< reference: OMX_IMAGE_PARAM_FLASHCONTROLTYPE */ - - /* Video specific parameters and configurations */ - OMX_IndexVideoStartUnused = 0x06000000, - OMX_IndexParamVideoPortFormat, /**< reference: OMX_VIDEO_PARAM_PORTFORMATTYPE */ - OMX_IndexParamVideoQuantization, /**< reference: OMX_VIDEO_PARAM_QUANTIZATIONTYPE */ - OMX_IndexParamVideoFastUpdate, /**< reference: OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE */ - OMX_IndexParamVideoBitrate, /**< reference: OMX_VIDEO_PARAM_BITRATETYPE */ - OMX_IndexParamVideoMotionVector, /**< reference: OMX_VIDEO_PARAM_MOTIONVECTORTYPE */ - OMX_IndexParamVideoIntraRefresh, /**< reference: OMX_VIDEO_PARAM_INTRAREFRESHTYPE */ - OMX_IndexParamVideoErrorCorrection, /**< reference: OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE */ - OMX_IndexParamVideoVBSMC, /**< reference: OMX_VIDEO_PARAM_VBSMCTYPE */ - OMX_IndexParamVideoMpeg2, /**< reference: OMX_VIDEO_PARAM_MPEG2TYPE */ - OMX_IndexParamVideoMpeg4, /**< reference: OMX_VIDEO_PARAM_MPEG4TYPE */ - OMX_IndexParamVideoWmv, /**< reference: OMX_VIDEO_PARAM_WMVTYPE */ - OMX_IndexParamVideoRv, /**< reference: OMX_VIDEO_PARAM_RVTYPE */ - OMX_IndexParamVideoAvc, /**< reference: OMX_VIDEO_PARAM_AVCTYPE */ - OMX_IndexParamVideoH263, /**< reference: OMX_VIDEO_PARAM_H263TYPE */ - OMX_IndexParamVideoProfileLevelQuerySupported, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ - OMX_IndexParamVideoProfileLevelCurrent, /**< reference: OMX_VIDEO_PARAM_PROFILELEVELTYPE */ - OMX_IndexConfigVideoBitrate, /**< reference: OMX_VIDEO_CONFIG_BITRATETYPE */ - OMX_IndexConfigVideoFramerate, /**< reference: OMX_CONFIG_FRAMERATETYPE */ - OMX_IndexConfigVideoIntraVOPRefresh, /**< reference: OMX_CONFIG_INTRAREFRESHVOPTYPE */ - OMX_IndexConfigVideoIntraMBRefresh, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ - OMX_IndexConfigVideoMBErrorReporting, /**< reference: OMX_CONFIG_MBERRORREPORTINGTYPE */ - OMX_IndexParamVideoMacroblocksPerFrame, /**< reference: OMX_PARAM_MACROBLOCKSTYPE */ - OMX_IndexConfigVideoMacroBlockErrorMap, /**< reference: OMX_CONFIG_MACROBLOCKERRORMAPTYPE */ - OMX_IndexParamVideoSliceFMO, /**< reference: OMX_VIDEO_PARAM_AVCSLICEFMO */ - OMX_IndexConfigVideoAVCIntraPeriod, /**< reference: OMX_VIDEO_CONFIG_AVCINTRAPERIOD */ - OMX_IndexConfigVideoNalSize, /**< reference: OMX_VIDEO_CONFIG_NALSIZE */ - OMX_IndexConfigCommonDeinterlace, /**< reference: OMX_VIDEO_CONFIG_DEINTERLACE */ - - /* Image & Video common Configurations */ - OMX_IndexCommonStartUnused = 0x07000000, - OMX_IndexParamCommonDeblocking, /**< reference: OMX_PARAM_DEBLOCKINGTYPE */ - OMX_IndexParamCommonSensorMode, /**< reference: OMX_PARAM_SENSORMODETYPE */ - OMX_IndexParamCommonInterleave, /**< reference: OMX_PARAM_INTERLEAVETYPE */ - OMX_IndexConfigCommonColorFormatConversion, /**< reference: OMX_CONFIG_COLORCONVERSIONTYPE */ - OMX_IndexConfigCommonScale, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ - OMX_IndexConfigCommonImageFilter, /**< reference: OMX_CONFIG_IMAGEFILTERTYPE */ - OMX_IndexConfigCommonColorEnhancement, /**< reference: OMX_CONFIG_COLORENHANCEMENTTYPE */ - OMX_IndexConfigCommonColorKey, /**< reference: OMX_CONFIG_COLORKEYTYPE */ - OMX_IndexConfigCommonColorBlend, /**< reference: OMX_CONFIG_COLORBLENDTYPE */ - OMX_IndexConfigCommonFrameStabilisation,/**< reference: OMX_CONFIG_FRAMESTABTYPE */ - OMX_IndexConfigCommonRotate, /**< reference: OMX_CONFIG_ROTATIONTYPE */ - OMX_IndexConfigCommonMirror, /**< reference: OMX_CONFIG_MIRRORTYPE */ - OMX_IndexConfigCommonOutputPosition, /**< reference: OMX_CONFIG_POINTTYPE */ - OMX_IndexConfigCommonInputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ - OMX_IndexConfigCommonOutputCrop, /**< reference: OMX_CONFIG_RECTTYPE */ - OMX_IndexConfigCommonDigitalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE */ - OMX_IndexConfigCommonOpticalZoom, /**< reference: OMX_CONFIG_SCALEFACTORTYPE*/ - OMX_IndexConfigCommonWhiteBalance, /**< reference: OMX_CONFIG_WHITEBALCONTROLTYPE */ - OMX_IndexConfigCommonExposure, /**< reference: OMX_CONFIG_EXPOSURECONTROLTYPE */ - OMX_IndexConfigCommonContrast, /**< reference: OMX_CONFIG_CONTRASTTYPE */ - OMX_IndexConfigCommonBrightness, /**< reference: OMX_CONFIG_BRIGHTNESSTYPE */ - OMX_IndexConfigCommonBacklight, /**< reference: OMX_CONFIG_BACKLIGHTTYPE */ - OMX_IndexConfigCommonGamma, /**< reference: OMX_CONFIG_GAMMATYPE */ - OMX_IndexConfigCommonSaturation, /**< reference: OMX_CONFIG_SATURATIONTYPE */ - OMX_IndexConfigCommonLightness, /**< reference: OMX_CONFIG_LIGHTNESSTYPE */ - OMX_IndexConfigCommonExclusionRect, /**< reference: OMX_CONFIG_RECTTYPE */ - OMX_IndexConfigCommonDithering, /**< reference: OMX_CONFIG_DITHERTYPE */ - OMX_IndexConfigCommonPlaneBlend, /**< reference: OMX_CONFIG_PLANEBLENDTYPE */ - OMX_IndexConfigCommonExposureValue, /**< reference: OMX_CONFIG_EXPOSUREVALUETYPE */ - OMX_IndexConfigCommonOutputSize, /**< reference: OMX_FRAMESIZETYPE */ - OMX_IndexParamCommonExtraQuantData, /**< reference: OMX_OTHER_EXTRADATATYPE */ - OMX_IndexConfigCommonFocusRegion, /**< reference: OMX_CONFIG_FOCUSREGIONTYPE */ - OMX_IndexConfigCommonFocusStatus, /**< reference: OMX_PARAM_FOCUSSTATUSTYPE */ - OMX_IndexConfigCommonTransitionEffect, /**< reference: OMX_CONFIG_TRANSITIONEFFECTTYPE */ - - /* Reserved Configuration range */ - OMX_IndexOtherStartUnused = 0x08000000, - OMX_IndexParamOtherPortFormat, /**< reference: OMX_OTHER_PARAM_PORTFORMATTYPE */ - OMX_IndexConfigOtherPower, /**< reference: OMX_OTHER_CONFIG_POWERTYPE */ - OMX_IndexConfigOtherStats, /**< reference: OMX_OTHER_CONFIG_STATSTYPE */ - - - /* Reserved Time range */ - OMX_IndexTimeStartUnused = 0x09000000, - OMX_IndexConfigTimeScale, /**< reference: OMX_TIME_CONFIG_SCALETYPE */ - OMX_IndexConfigTimeClockState, /**< reference: OMX_TIME_CONFIG_CLOCKSTATETYPE */ - OMX_IndexConfigTimeActiveRefClock, /**< reference: OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE */ - OMX_IndexConfigTimeCurrentMediaTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ - OMX_IndexConfigTimeCurrentWallTime, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (read only) */ - OMX_IndexConfigTimeCurrentAudioReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ - OMX_IndexConfigTimeCurrentVideoReference, /**< reference: OMX_TIME_CONFIG_TIMESTAMPTYPE (write only) */ - OMX_IndexConfigTimeMediaTimeRequest, /**< reference: OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE (write only) */ - OMX_IndexConfigTimeClientStartTime, /** - - -/** Khronos standard extension indices. - -This enum lists the current Khronos extension indices to OpenMAX IL. -*/ -typedef enum OMX_INDEXEXTTYPE { - - /* Component parameters and configurations */ - OMX_IndexExtComponentStartUnused = OMX_IndexKhronosExtensions + 0x00100000, - OMX_IndexConfigCallbackRequest, /**< reference: OMX_CONFIG_CALLBACKREQUESTTYPE */ - OMX_IndexConfigCommitMode, /**< reference: OMX_CONFIG_COMMITMODETYPE */ - OMX_IndexConfigCommit, /**< reference: OMX_CONFIG_COMMITTYPE */ - - /* Port parameters and configurations */ - OMX_IndexExtPortStartUnused = OMX_IndexKhronosExtensions + 0x00200000, - - /* Audio parameters and configurations */ - OMX_IndexExtAudioStartUnused = OMX_IndexKhronosExtensions + 0x00400000, - - /* Image parameters and configurations */ - OMX_IndexExtImageStartUnused = OMX_IndexKhronosExtensions + 0x00500000, - - /* Video parameters and configurations */ - OMX_IndexExtVideoStartUnused = OMX_IndexKhronosExtensions + 0x00600000, - OMX_IndexParamNalStreamFormatSupported, /**< reference: OMX_NALSTREAMFORMATTYPE */ - OMX_IndexParamNalStreamFormat, /**< reference: OMX_NALSTREAMFORMATTYPE */ - OMX_IndexParamNalStreamFormatSelect, /**< reference: OMX_NALSTREAMFORMATTYPE */ - OMX_IndexParamVideoVp8, /**< reference: OMX_VIDEO_PARAM_VP8TYPE */ - OMX_IndexConfigVideoVp8ReferenceFrame, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMETYPE */ - OMX_IndexConfigVideoVp8ReferenceFrameType, /**< reference: OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE */ - OMX_IndexParamVideoReserved, /**< Reserved for future index */ - OMX_IndexParamVideoHevc, /**< reference: OMX_VIDEO_PARAM_HEVCTYPE */ - - /* Image & Video common configurations */ - OMX_IndexExtCommonStartUnused = OMX_IndexKhronosExtensions + 0x00700000, - - /* Other configurations */ - OMX_IndexExtOtherStartUnused = OMX_IndexKhronosExtensions + 0x00800000, - OMX_IndexConfigAutoFramerateConversion, /**< reference: OMX_CONFIG_BOOLEANTYPE */ - OMX_IndexConfigPriority, /**< reference: OMX_PARAM_U32TYPE */ - OMX_IndexConfigOperatingRate, /**< reference: OMX_PARAM_U32TYPE in Q16 format for video and in Hz for audio */ - - /* Time configurations */ - OMX_IndexExtTimeStartUnused = OMX_IndexKhronosExtensions + 0x00900000, - - OMX_IndexExtMax = 0x7FFFFFFF -} OMX_INDEXEXTTYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* OMX_IndexExt_h */ -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Other.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Other.h deleted file mode 100644 index caf7f3844..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Other.h +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** @file OMX_Other.h - OpenMax IL version 1.1.2 - * The structures needed by Other components to exchange - * parameters and configuration data with the components. - */ - -#ifndef OMX_Other_h -#define OMX_Other_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/* Each OMX header must include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ - -#include - - -/** - * Enumeration of possible data types which match to multiple domains or no - * domain at all. For types which are vendor specific, a value above - * OMX_OTHER_VENDORTSTART should be used. - */ -typedef enum OMX_OTHER_FORMATTYPE { - OMX_OTHER_FormatTime = 0, /**< Transmission of various timestamps, elapsed time, - time deltas, etc */ - OMX_OTHER_FormatPower, /**< Perhaps used for enabling/disabling power - management, setting clocks? */ - OMX_OTHER_FormatStats, /**< Could be things such as frame rate, frames - dropped, etc */ - OMX_OTHER_FormatBinary, /**< Arbitrary binary data */ - OMX_OTHER_FormatVendorReserved = 1000, /**< Starting value for vendor specific - formats */ - - OMX_OTHER_FormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_OTHER_FormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_OTHER_FormatMax = 0x7FFFFFFF -} OMX_OTHER_FORMATTYPE; - -/** - * Enumeration of seek modes. - */ -typedef enum OMX_TIME_SEEKMODETYPE { - OMX_TIME_SeekModeFast = 0, /**< Prefer seeking to an approximation - * of the requested seek position over - * the actual seek position if it - * results in a faster seek. */ - OMX_TIME_SeekModeAccurate, /**< Prefer seeking to the actual seek - * position over an approximation - * of the requested seek position even - * if it results in a slower seek. */ - OMX_TIME_SeekModeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_TIME_SeekModeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_TIME_SeekModeMax = 0x7FFFFFFF -} OMX_TIME_SEEKMODETYPE; - -/* Structure representing the seekmode of the component */ -typedef struct OMX_TIME_CONFIG_SEEKMODETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_TIME_SEEKMODETYPE eType; /**< The seek mode */ -} OMX_TIME_CONFIG_SEEKMODETYPE; - -/** Structure representing a time stamp used with the following configs - * on the Clock Component (CC): - * - * OMX_IndexConfigTimeCurrentWallTime: query of the CCs current wall - * time - * OMX_IndexConfigTimeCurrentMediaTime: query of the CCs current media - * time - * OMX_IndexConfigTimeCurrentAudioReference and - * OMX_IndexConfigTimeCurrentVideoReference: audio/video reference - * clock sending SC its reference time - * OMX_IndexConfigTimeClientStartTime: a Clock Component client sends - * this structure to the Clock Component via a SetConfig on its - * client port when it receives a buffer with - * OMX_BUFFERFLAG_STARTTIME set. It must use the timestamp - * specified by that buffer for nStartTimestamp. - * - * Its also used with the following config on components in general: - * - * OMX_IndexConfigTimePosition: IL client querying component position - * (GetConfig) or commanding a component to seek to the given location - * (SetConfig) - */ -typedef struct OMX_TIME_CONFIG_TIMESTAMPTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version - * information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_TICKS nTimestamp; /**< timestamp .*/ -} OMX_TIME_CONFIG_TIMESTAMPTYPE; - -/** Enumeration of possible reference clocks to the media time. */ -typedef enum OMX_TIME_UPDATETYPE { - OMX_TIME_UpdateRequestFulfillment, /**< Update is the fulfillment of a media time request. */ - OMX_TIME_UpdateScaleChanged, /**< Update was generated because the scale chagned. */ - OMX_TIME_UpdateClockStateChanged, /**< Update was generated because the clock state changed. */ - OMX_TIME_UpdateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_TIME_UpdateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_TIME_UpdateMax = 0x7FFFFFFF -} OMX_TIME_UPDATETYPE; - -/** Enumeration of possible reference clocks to the media time. */ -typedef enum OMX_TIME_REFCLOCKTYPE { - OMX_TIME_RefClockNone, /**< Use no references. */ - OMX_TIME_RefClockAudio, /**< Use references sent through OMX_IndexConfigTimeCurrentAudioReference */ - OMX_TIME_RefClockVideo, /**< Use references sent through OMX_IndexConfigTimeCurrentVideoReference */ - OMX_TIME_RefClockKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_TIME_RefClockVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_TIME_RefClockMax = 0x7FFFFFFF -} OMX_TIME_REFCLOCKTYPE; - -/** Enumeration of clock states. */ -typedef enum OMX_TIME_CLOCKSTATE { - OMX_TIME_ClockStateRunning, /**< Clock running. */ - OMX_TIME_ClockStateWaitingForStartTime, /**< Clock waiting until the - * prescribed clients emit their - * start time. */ - OMX_TIME_ClockStateStopped, /**< Clock stopped. */ - OMX_TIME_ClockStateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_TIME_ClockStateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_TIME_ClockStateMax = 0x7FFFFFFF -} OMX_TIME_CLOCKSTATE; - -/** Structure representing a media time request to the clock component. - * - * A client component sends this structure to the Clock Component via a SetConfig - * on its client port to specify a media timestamp the Clock Component - * should emit. The Clock Component should fulfill the request by sending a - * OMX_TIME_MEDIATIMETYPE when its media clock matches the requested - * timestamp. - * - * The client may require a media time request be fulfilled slightly - * earlier than the media time specified. In this case the client specifies - * an offset which is equal to the difference between wall time corresponding - * to the requested media time and the wall time when it will be - * fulfilled. - * - * A client component may uses these requests and the OMX_TIME_MEDIATIMETYPE to - * time events according to timestamps. If a client must perform an operation O at - * a time T (e.g. deliver a video frame at its corresponding timestamp), it makes a - * media time request at T (perhaps specifying an offset to ensure the request fulfillment - * is a little early). When the clock component passes the resulting OMX_TIME_MEDIATIMETYPE - * structure back to the client component, the client may perform operation O (perhaps having - * to wait a slight amount more time itself as specified by the return values). - */ - -typedef struct OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< port that this structure applies to */ - OMX_PTR pClientPrivate; /**< Client private data to disabiguate this media time - * from others (e.g. the number of the frame to deliver). - * Duplicated in the media time structure that fulfills - * this request. A value of zero is reserved for time scale - * updates. */ - OMX_TICKS nMediaTimestamp; /**< Media timestamp requested.*/ - OMX_TICKS nOffset; /**< Amount of wall clock time by which this - * request should be fulfilled early */ -} OMX_TIME_CONFIG_MEDIATIMEREQUESTTYPE; - -/**< Structure sent from the clock component client either when fulfilling - * a media time request or when the time scale has changed. - * - * In the former case the Clock Component fills this structure and times its emission - * to a client component (via the client port) according to the corresponding media - * time request sent by the client. The Clock Component should time the emission to occur - * when the requested timestamp matches the Clock Component's media time but also the - * prescribed offset early. - * - * Upon scale changes the clock component clears the nClientPrivate data, sends the current - * media time and sets the nScale to the new scale via the client port. It emits a - * OMX_TIME_MEDIATIMETYPE to all clients independent of any requests. This allows clients to - * alter processing to accomodate scaling. For instance a video component might skip inter-frames - * in the case of extreme fastforward. Likewise an audio component might add or remove samples - * from an audio frame to scale audio data. - * - * It is expected that some clock components may not be able to fulfill requests - * at exactly the prescribed time. This is acceptable so long as the request is - * fulfilled at least as early as described and not later. This structure provides - * fields the client may use to wait for the remaining time. - * - * The client may use either the nOffset or nWallTimeAtMedia fields to determine the - * wall time until the nMediaTimestamp actually occurs. In the latter case the - * client can get a more accurate value for offset by getting the current wall - * from the cloc component and subtracting it from nWallTimeAtMedia. - */ - -typedef struct OMX_TIME_MEDIATIMETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nClientPrivate; /**< Client private data to disabiguate this media time - * from others. Copied from the media time request. - * A value of zero is reserved for time scale updates. */ - OMX_TIME_UPDATETYPE eUpdateType; /**< Reason for the update */ - OMX_TICKS nMediaTimestamp; /**< Media time requested. If no media time was - * requested then this is the current media time. */ - OMX_TICKS nOffset; /**< Amount of wall clock time by which this - * request was actually fulfilled early */ - - OMX_TICKS nWallTimeAtMediaTime; /**< Wall time corresponding to nMediaTimeStamp. - * A client may compare this value to current - * media time obtained from the Clock Component to determine - * the wall time until the media timestamp is really - * current. */ - OMX_S32 xScale; /**< Current media time scale in Q16 format. */ - OMX_TIME_CLOCKSTATE eState; /* Seeking Change. Added 7/12.*/ - /**< State of the media time. */ -} OMX_TIME_MEDIATIMETYPE; - -/** Structure representing the current media time scale factor. Applicable only to clock - * component, other components see scale changes via OMX_TIME_MEDIATIMETYPE buffers sent via - * the clock component client ports. Upon recieving this config the clock component changes - * the rate by which the media time increases or decreases effectively implementing trick modes. - */ -typedef struct OMX_TIME_CONFIG_SCALETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_S32 xScale; /**< This is a value in Q16 format which is used for - * scaling the media time */ -} OMX_TIME_CONFIG_SCALETYPE; - -/** Bits used to identify a clock port. Used in OMX_TIME_CONFIG_CLOCKSTATETYPEs nWaitMask field */ -#define OMX_CLOCKPORT0 0x00000001 -#define OMX_CLOCKPORT1 0x00000002 -#define OMX_CLOCKPORT2 0x00000004 -#define OMX_CLOCKPORT3 0x00000008 -#define OMX_CLOCKPORT4 0x00000010 -#define OMX_CLOCKPORT5 0x00000020 -#define OMX_CLOCKPORT6 0x00000040 -#define OMX_CLOCKPORT7 0x00000080 - -/** Structure representing the current mode of the media clock. - * IL Client uses this config to change or query the mode of the - * media clock of the clock component. Applicable only to clock - * component. - * - * On a SetConfig if eState is OMX_TIME_ClockStateRunning media time - * starts immediately at the prescribed start time. If - * OMX_TIME_ClockStateWaitingForStartTime the Clock Component ignores - * the given nStartTime and waits for all clients specified in the - * nWaitMask to send starttimes (via - * OMX_IndexConfigTimeClientStartTime). The Clock Component then starts - * the media clock using the earliest start time supplied. */ -typedef struct OMX_TIME_CONFIG_CLOCKSTATETYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version - * information */ - OMX_TIME_CLOCKSTATE eState; /**< State of the media time. */ - OMX_TICKS nStartTime; /**< Start time of the media time. */ - OMX_TICKS nOffset; /**< Time to offset the media time by - * (e.g. preroll). Media time will be - * reported to be nOffset ticks earlier. - */ - OMX_U32 nWaitMask; /**< Mask of OMX_CLOCKPORT values. */ -} OMX_TIME_CONFIG_CLOCKSTATETYPE; - -/** Structure representing the reference clock currently being used to - * compute media time. IL client uses this config to change or query the - * clock component's active reference clock */ -typedef struct OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_TIME_REFCLOCKTYPE eClock; /**< Reference clock used to compute media time */ -} OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE; - -/** Descriptor for setting specifics of power type. - * Note: this structure is listed for backwards compatibility. */ -typedef struct OMX_OTHER_CONFIG_POWERTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_BOOL bEnablePM; /**< Flag to enable Power Management */ -} OMX_OTHER_CONFIG_POWERTYPE; - - -/** Descriptor for setting specifics of stats type. - * Note: this structure is listed for backwards compatibility. */ -typedef struct OMX_OTHER_CONFIG_STATSTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - /* what goes here */ -} OMX_OTHER_CONFIG_STATSTYPE; - - -/** - * The PortDefinition structure is used to define all of the parameters - * necessary for the compliant component to setup an input or an output other - * path. - */ -typedef struct OMX_OTHER_PORTDEFINITIONTYPE { - OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ -} OMX_OTHER_PORTDEFINITIONTYPE; - -/** Port format parameter. This structure is used to enumerate - * the various data input/output format supported by the port. - */ -typedef struct OMX_OTHER_PARAM_PORTFORMATTYPE { - OMX_U32 nSize; /**< size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Indicates which port to set */ - OMX_U32 nIndex; /**< Indicates the enumeration index for the format from 0x0 to N-1 */ - OMX_OTHER_FORMATTYPE eFormat; /**< Type of data expected for this channel */ -} OMX_OTHER_PARAM_PORTFORMATTYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_QCOMExtns.h b/starpilot/ui/screenrecorder/openmax/include/OMX_QCOMExtns.h deleted file mode 100644 index 20917932b..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_QCOMExtns.h +++ /dev/null @@ -1,1888 +0,0 @@ -/*-------------------------------------------------------------------------- -Copyright (c) 2009-2015, The Linux Foundation. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of The Linux Foundation nor - the names of its contributors may be used to endorse or promote - products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ -#ifndef __OMX_QCOM_EXTENSIONS_H__ -#define __OMX_QCOM_EXTENSIONS_H__ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/*============================================================================ -*//** @file OMX_QCOMExtns.h - This header contains constants and type definitions that specify the - extensions added to the OpenMAX Vendor specific APIs. - -*//*========================================================================*/ - - -/////////////////////////////////////////////////////////////////////////////// -// Include Files -/////////////////////////////////////////////////////////////////////////////// -#include "OMX_Core.h" -#include "OMX_Video.h" - -#define OMX_VIDEO_MAX_HP_LAYERS 6 -/** - * This extension is used to register mapping of a virtual - * address to a physical address. This extension is a parameter - * which can be set using the OMX_SetParameter macro. The data - * pointer corresponding to this extension is - * OMX_QCOM_MemMapEntry. This parameter is a 'write only' - * parameter (Current value cannot be queried using - * OMX_GetParameter macro). - */ -#define OMX_QCOM_EXTN_REGISTER_MMAP "OMX.QCOM.index.param.register_mmap" - -/** - * This structure describes the data pointer corresponding to - * the OMX_QCOM_MMAP_REGISTER_EXTN extension. This parameter - * must be set only 'after' populating a port with a buffer - * using OMX_UseBuffer, wherein the data pointer of the buffer - * corresponds to the virtual address as specified in this - * structure. - */ -struct OMX_QCOM_PARAM_MEMMAPENTRYTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /**< OMX specification version information */ - OMX_U32 nPortIndex; /**< Port number the structure applies to */ - - /** - * The virtual address of memory block - */ - OMX_U64 nVirtualAddress; - - /** - * The physical address corresponding to the virtual address. The physical - * address is contiguous for the entire valid range of the virtual - * address. - */ - OMX_U64 nPhysicalAddress; -}; - -#define QOMX_VIDEO_IntraRefreshRandom (OMX_VIDEO_IntraRefreshVendorStartUnused + 0) - -/* This error event is used for H.264 long-term reference (LTR) encoding. - * When IL client specifies an LTR frame with its identifier via - * OMX_QCOM_INDEX_CONFIG_VIDEO_LTRUSE to the encoder, if the specified - * LTR frame can not be located by the encoder in its LTR list, the encoder - * issues this error event to IL client to notify the failure of LTRUse config. - */ -#define QOMX_ErrorLTRUseFailed (OMX_ErrorVendorStartUnused + 1) - -#define QOMX_VIDEO_BUFFERFLAG_BFRAME 0x00100000 - -#define QOMX_VIDEO_BUFFERFLAG_EOSEQ 0x00200000 - -#define QOMX_VIDEO_BUFFERFLAG_MBAFF 0x00400000 - -#define QOMX_VIDEO_BUFFERFLAG_CANCEL 0x00800000 - -#define OMX_QCOM_PORTDEFN_EXTN "OMX.QCOM.index.param.portdefn" -/* Allowed APIs on the above Index: OMX_GetParameter() and OMX_SetParameter() */ - -typedef enum OMX_QCOMMemoryRegion -{ - OMX_QCOM_MemRegionInvalid, - OMX_QCOM_MemRegionEBI1, - OMX_QCOM_MemRegionSMI, - OMX_QCOM_MemRegionMax = 0X7FFFFFFF -} OMX_QCOMMemoryRegion; - -typedef enum OMX_QCOMCacheAttr -{ - OMX_QCOM_CacheAttrNone, - OMX_QCOM_CacheAttrWriteBack, - OMX_QCOM_CacheAttrWriteThrough, - OMX_QCOM_CacheAttrMAX = 0X7FFFFFFF -} OMX_QCOMCacheAttr; - -typedef struct OMX_QCOMRectangle -{ - OMX_S32 x; - OMX_S32 y; - OMX_S32 dx; - OMX_S32 dy; -} OMX_QCOMRectangle; - -/** OMX_QCOMFramePackingFormat - * Input or output buffer format - */ -typedef enum OMX_QCOMFramePackingFormat -{ - /* 0 - unspecified - */ - OMX_QCOM_FramePacking_Unspecified, - - /* 1 - Partial frames may be present OMX IL 1.1.1 Figure 2-10: - * Case 1??Each Buffer Filled In Whole or In Part - */ - OMX_QCOM_FramePacking_Arbitrary, - - /* 2 - Multiple complete frames per buffer (integer number) - * OMX IL 1.1.1 Figure 2-11: Case 2Each Buffer Filled with - * Only Complete Frames of Data - */ - OMX_QCOM_FramePacking_CompleteFrames, - - /* 3 - Only one complete frame per buffer, no partial frame - * OMX IL 1.1.1 Figure 2-12: Case 3Each Buffer Filled with - * Only One Frame of Compressed Data. Usually at least one - * complete unit of data will be delivered in a buffer for - * uncompressed data formats. - */ - OMX_QCOM_FramePacking_OnlyOneCompleteFrame, - - /* 4 - Only one complete subframe per buffer, no partial subframe - * Example: In H264, one complete NAL per buffer, where one frame - * can contatin multiple NAL - */ - OMX_QCOM_FramePacking_OnlyOneCompleteSubFrame, - - OMX_QCOM_FramePacking_MAX = 0X7FFFFFFF -} OMX_QCOMFramePackingFormat; - -typedef struct OMX_QCOM_PARAM_PORTDEFINITIONTYPE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - - /** Platform specific memory region EBI1, SMI, etc.,*/ - OMX_QCOMMemoryRegion nMemRegion; - - OMX_QCOMCacheAttr nCacheAttr; /** Cache attributes */ - - /** Input or output buffer format */ - OMX_U32 nFramePackingFormat; - -} OMX_QCOM_PARAM_PORTDEFINITIONTYPE; - -typedef struct OMX_QCOM_VIDEO_PARAM_QPRANGETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 minQP; - OMX_U32 maxQP; -} OMX_QCOM_VIDEO_PARAM_QPRANGETYPE; - -#define OMX_QCOM_PLATFORMPVT_EXTN "OMX.QCOM.index.param.platformprivate" -/** Allowed APIs on the above Index: OMX_SetParameter() */ - -typedef enum OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE -{ - /** Enum for PMEM information */ - OMX_QCOM_PLATFORM_PRIVATE_PMEM = 0x1 -} OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE; - -/** IL client will set the following structure. A failure - * code will be returned if component does not support the - * value provided for 'type'. - */ -struct OMX_QCOM_PLATFORMPRIVATE_EXTN -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX spec version information */ - OMX_U32 nPortIndex; /** Port number on which usebuffer extn is applied */ - - /** Type of extensions should match an entry from - OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE - */ - OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE type; -}; - -typedef struct OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO -{ - /** pmem file descriptor */ - unsigned long pmem_fd; - /** Offset from pmem device base address */ - OMX_U32 offset; - OMX_U32 size; - OMX_U32 mapped_size; - OMX_PTR buffer; -}OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO; - -typedef struct OMX_QCOM_PLATFORM_PRIVATE_ENTRY -{ - /** Entry type */ - OMX_QCOM_PLATFORM_PRIVATE_ENTRY_TYPE type; - - /** Pointer to platform specific entry */ - OMX_PTR entry; -}OMX_QCOM_PLATFORM_PRIVATE_ENTRY; - -typedef struct OMX_QCOM_PLATFORM_PRIVATE_LIST -{ - /** Number of entries */ - OMX_U32 nEntries; - - /** Pointer to array of platform specific entries * - * Contiguous block of OMX_QCOM_PLATFORM_PRIVATE_ENTRY element - */ - OMX_QCOM_PLATFORM_PRIVATE_ENTRY* entryList; -}OMX_QCOM_PLATFORM_PRIVATE_LIST; - -#define OMX_QCOM_FRAME_PACKING_FORMAT "OMX.QCOM.index.param.framepackfmt" -/* Allowed API call: OMX_GetParameter() */ -/* IL client can use this index to rerieve the list of frame formats * - * supported by the component */ - -typedef struct OMX_QCOM_FRAME_PACKINGFORMAT_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nIndex; - OMX_QCOMFramePackingFormat eframePackingFormat; -} OMX_QCOM_FRAME_PACKINGFORMAT_TYPE; - - -/** - * Following is the enum for color formats supported on Qualcomm - * MSMs YVU420SemiPlanar color format is not defined in OpenMAX - * 1.1.1 and prior versions of OpenMAX specification. - */ - -enum OMX_QCOM_COLOR_FORMATTYPE -{ - -/** YVU420SemiPlanar: YVU planar format, organized with a first - * plane containing Y pixels, and a second plane containing - * interleaved V and U pixels. V and U pixels are sub-sampled - * by a factor of two both horizontally and vertically. - */ - QOMX_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00, - QOMX_COLOR_FormatYVU420PackedSemiPlanar32m4ka, - QOMX_COLOR_FormatYUV420PackedSemiPlanar16m2ka, - QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka, - QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m, - QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView, - QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mCompressed, - QOMX_COLOR_Format32bitRGBA8888, - QOMX_COLOR_Format32bitRGBA8888Compressed, - QOMX_COLOR_FormatAndroidOpaque = (OMX_COLOR_FORMATTYPE) OMX_COLOR_FormatVendorStartUnused + 0x789, -}; - -enum OMX_QCOM_VIDEO_CODINGTYPE -{ -/** Codecs support by qualcomm which are not listed in OMX 1.1.x - * spec - * */ - OMX_QCOM_VIDEO_CodingVC1 = 0x7FA30C00 , - OMX_QCOM_VIDEO_CodingWMV9 = 0x7FA30C01, - QOMX_VIDEO_CodingDivx = 0x7FA30C02, /**< Value when coding is Divx */ - QOMX_VIDEO_CodingSpark = 0x7FA30C03, /**< Value when coding is Sorenson Spark */ - QOMX_VIDEO_CodingVp = 0x7FA30C04, - QOMX_VIDEO_CodingVp8 = OMX_VIDEO_CodingVP8, /**< keeping old enum for backwards compatibility*/ - QOMX_VIDEO_CodingHevc = OMX_VIDEO_CodingHEVC, /**< keeping old enum for backwards compatibility*/ - QOMX_VIDEO_CodingMVC = 0x7FA30C07, - QOMX_VIDEO_CodingVp9 = OMX_VIDEO_CodingVP9, /**< keeping old enum for backwards compatibility*/ -}; - -enum OMX_QCOM_EXTN_INDEXTYPE -{ - /** Qcom proprietary extension index list */ - - /* "OMX.QCOM.index.param.register_mmap" */ - OMX_QcomIndexRegmmap = 0x7F000000, - - /* "OMX.QCOM.index.param.platformprivate" */ - OMX_QcomIndexPlatformPvt = 0x7F000001, - - /* "OMX.QCOM.index.param.portdefn" */ - OMX_QcomIndexPortDefn = 0x7F000002, - - /* "OMX.QCOM.index.param.framepackingformat" */ - OMX_QcomIndexPortFramePackFmt = 0x7F000003, - - /*"OMX.QCOM.index.param.Interlaced */ - OMX_QcomIndexParamInterlaced = 0x7F000004, - - /*"OMX.QCOM.index.config.interlaceformat */ - OMX_QcomIndexConfigInterlaced = 0x7F000005, - - /*"OMX.QCOM.index.param.syntaxhdr" */ - QOMX_IndexParamVideoSyntaxHdr = 0x7F000006, - - /*"OMX.QCOM.index.config.intraperiod" */ - QOMX_IndexConfigVideoIntraperiod = 0x7F000007, - - /*"OMX.QCOM.index.config.randomIntrarefresh" */ - QOMX_IndexConfigVideoIntraRefresh = 0x7F000008, - - /*"OMX.QCOM.index.config.video.TemporalSpatialTradeOff" */ - QOMX_IndexConfigVideoTemporalSpatialTradeOff = 0x7F000009, - - /*"OMX.QCOM.index.param.video.EncoderMode" */ - QOMX_IndexParamVideoEncoderMode = 0x7F00000A, - - /*"OMX.QCOM.index.param.Divxtype */ - OMX_QcomIndexParamVideoDivx = 0x7F00000B, - - /*"OMX.QCOM.index.param.Sparktype */ - OMX_QcomIndexParamVideoSpark = 0x7F00000C, - - /*"OMX.QCOM.index.param.Vptype */ - OMX_QcomIndexParamVideoVp = 0x7F00000D, - - OMX_QcomIndexQueryNumberOfVideoDecInstance = 0x7F00000E, - - OMX_QcomIndexParamVideoSyncFrameDecodingMode = 0x7F00000F, - - OMX_QcomIndexParamVideoDecoderPictureOrder = 0x7F000010, - - /* "OMX.QCOM.index.config.video.FramePackingInfo" */ - OMX_QcomIndexConfigVideoFramePackingArrangement = 0x7F000011, - - OMX_QcomIndexParamConcealMBMapExtraData = 0x7F000012, - - OMX_QcomIndexParamFrameInfoExtraData = 0x7F000013, - - OMX_QcomIndexParamInterlaceExtraData = 0x7F000014, - - OMX_QcomIndexParamH264TimeInfo = 0x7F000015, - - OMX_QcomIndexParamIndexExtraDataType = 0x7F000016, - - OMX_GoogleAndroidIndexEnableAndroidNativeBuffers = 0x7F000017, - - OMX_GoogleAndroidIndexUseAndroidNativeBuffer = 0x7F000018, - - OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage = 0x7F000019, - - /*"OMX.QCOM.index.config.video.QPRange" */ - OMX_QcomIndexConfigVideoQPRange = 0x7F00001A, - - /*"OMX.QCOM.index.param.EnableTimeStampReoder"*/ - OMX_QcomIndexParamEnableTimeStampReorder = 0x7F00001B, - - /*"OMX.google.android.index.storeMetaDataInBuffers"*/ - OMX_QcomIndexParamVideoMetaBufferMode = 0x7F00001C, - - /*"OMX.google.android.index.useAndroidNativeBuffer2"*/ - OMX_GoogleAndroidIndexUseAndroidNativeBuffer2 = 0x7F00001D, - - /*"OMX.QCOM.index.param.VideoMaxAllowedBitrateCheck"*/ - OMX_QcomIndexParamVideoMaxAllowedBitrateCheck = 0x7F00001E, - - OMX_QcomIndexEnableSliceDeliveryMode = 0x7F00001F, - - /* "OMX.QCOM.index.param.video.ExtnUserExtraData" */ - OMX_QcomIndexEnableExtnUserData = 0x7F000020, - - /*"OMX.QCOM.index.param.video.EnableSmoothStreaming"*/ - OMX_QcomIndexParamEnableSmoothStreaming = 0x7F000021, - - /*"OMX.QCOM.index.param.video.QPRange" */ - OMX_QcomIndexParamVideoQPRange = 0x7F000022, - - OMX_QcomIndexEnableH263PlusPType = 0x7F000023, - - /*"OMX.QCOM.index.param.video.LTRCountRangeSupported"*/ - QOMX_IndexParamVideoLTRCountRangeSupported = 0x7F000024, - - /*"OMX.QCOM.index.param.video.LTRMode"*/ - QOMX_IndexParamVideoLTRMode = 0x7F000025, - - /*"OMX.QCOM.index.param.video.LTRCount"*/ - QOMX_IndexParamVideoLTRCount = 0x7F000026, - - /*"OMX.QCOM.index.config.video.LTRPeriod"*/ - QOMX_IndexConfigVideoLTRPeriod = 0x7F000027, - - /*"OMX.QCOM.index.config.video.LTRUse"*/ - QOMX_IndexConfigVideoLTRUse = 0x7F000028, - - /*"OMX.QCOM.index.config.video.LTRMark"*/ - QOMX_IndexConfigVideoLTRMark = 0x7F000029, - - /* OMX.google.android.index.prependSPSPPSToIDRFrames */ - OMX_QcomIndexParamSequenceHeaderWithIDR = 0x7F00002A, - - OMX_QcomIndexParamH264AUDelimiter = 0x7F00002B, - - OMX_QcomIndexParamVideoDownScalar = 0x7F00002C, - - /* "OMX.QCOM.index.param.video.FramePackingExtradata" */ - OMX_QcomIndexParamVideoFramePackingExtradata = 0x7F00002D, - - /* "OMX.QCOM.index.config.activeregiondetection" */ - OMX_QcomIndexConfigActiveRegionDetection = 0x7F00002E, - - /* "OMX.QCOM.index.config.activeregiondetectionstatus" */ - OMX_QcomIndexConfigActiveRegionDetectionStatus = 0x7F00002F, - - /* "OMX.QCOM.index.config.scalingmode" */ - OMX_QcomIndexConfigScalingMode = 0x7F000030, - - /* "OMX.QCOM.index.config.noisereduction" */ - OMX_QcomIndexConfigNoiseReduction = 0x7F000031, - - /* "OMX.QCOM.index.config.imageenhancement" */ - OMX_QcomIndexConfigImageEnhancement = 0x7F000032, - - /* google smooth-streaming support */ - OMX_QcomIndexParamVideoAdaptivePlaybackMode = 0x7F000033, - - /* H.264 MVC codec index */ - QOMX_IndexParamVideoMvc = 0x7F000034, - - /* "OMX.QCOM.index.param.video.QPExtradata" */ - OMX_QcomIndexParamVideoQPExtraData = 0x7F000035, - - /* "OMX.QCOM.index.param.video.InputBitsInfoExtradata" */ - OMX_QcomIndexParamVideoInputBitsInfoExtraData = 0x7F000036, - - /* VP8 Hierarchical P support */ - OMX_QcomIndexHierarchicalStructure = 0x7F000037, - - OMX_QcomIndexParamPerfLevel = 0x7F000038, - - OMX_QcomIndexParamH264VUITimingInfo = 0x7F000039, - - OMX_QcomIndexParamPeakBitrate = 0x7F00003A, - - /* Enable InitialQP index */ - QOMX_IndexParamVideoInitialQp = 0x7F00003B, - - OMX_QcomIndexParamSetMVSearchrange = 0x7F00003C, - - OMX_QcomIndexConfigPerfLevel = 0x7F00003D, - - /*"OMX.QCOM.index.param.video.LTRCount"*/ - OMX_QcomIndexParamVideoLTRCount = QOMX_IndexParamVideoLTRCount, - - /*"OMX.QCOM.index.config.video.LTRUse"*/ - OMX_QcomIndexConfigVideoLTRUse = QOMX_IndexConfigVideoLTRUse, - - /*"OMX.QCOM.index.config.video.LTRMark"*/ - OMX_QcomIndexConfigVideoLTRMark = QOMX_IndexConfigVideoLTRMark, - - /*"OMX.QCOM.index.param.video.CustomBufferSize"*/ - OMX_QcomIndexParamVideoCustomBufferSize = 0x7F00003E, - - /* Max Hierarchical P layers */ - OMX_QcomIndexMaxHierarchicallayers = 0x7F000041, - - /* Set Encoder Performance Index */ - OMX_QcomIndexConfigVideoVencPerfMode = 0x7F000042, - - /* Set Hybrid Hier-p layers */ - OMX_QcomIndexParamVideoHybridHierpMode = 0x7F000043, - - OMX_QcomIndexFlexibleYUVDescription = 0x7F000044, - - /* Vpp Hqv Control Type */ - OMX_QcomIndexParamVppHqvControl = 0x7F000045, - - /* Enable VPP */ - OMX_QcomIndexParamEnableVpp = 0x7F000046, - - /* MBI statistics mode */ - OMX_QcomIndexParamMBIStatisticsMode = 0x7F000047, - - /* Set PictureTypeDecode */ - OMX_QcomIndexConfigPictureTypeDecode = 0x7F000048, - - OMX_QcomIndexConfigH264EntropyCodingCabac = 0x7F000049, - - /* "OMX.QCOM.index.param.video.InputBatch" */ - OMX_QcomIndexParamBatchSize = 0x7F00004A, - - OMX_QcomIndexConfigNumHierPLayers = 0x7F00004B, - - OMX_QcomIndexConfigRectType = 0x7F00004C, - - OMX_QcomIndexConfigBaseLayerId = 0x7F00004E, - - OMX_QcomIndexParamDriverVersion = 0x7F00004F, - - OMX_QcomIndexConfigQp = 0x7F000050, - - OMX_QcomIndexParamVencAspectRatio = 0x7F000051, - - OMX_QTIIndexParamVQZipSEIExtraData = 0x7F000052, - - /* Enable VQZIP SEI NAL type */ - OMX_QTIIndexParamVQZIPSEIType = 0x7F000053, - - OMX_QTIIndexParamPassInputBufferFd = 0x7F000054, - - /* Set Prefer-adaptive playback*/ - /* "OMX.QTI.index.param.video.PreferAdaptivePlayback" */ - OMX_QTIIndexParamVideoPreferAdaptivePlayback = 0x7F000055, - - /* Set time params */ - OMX_QTIIndexConfigSetTimeData = 0x7F000056, - /* Force Compressed format for DPB when resolution <=1080p - * and OPB is cpu_access */ - /* OMX.QTI.index.param.video.ForceCompressedForDPB */ - OMX_QTIIndexParamForceCompressedForDPB = 0x7F000057, - - /* Enable ROI info */ - OMX_QTIIndexParamVideoEnableRoiInfo = 0x7F000058, - - /* Configure ROI info */ - OMX_QTIIndexConfigVideoRoiInfo = 0x7F000059, - - /* Set Low Latency Mode */ - OMX_QTIIndexParamLowLatencyMode = 0x7F00005A, - - /* Force OPB to UnCompressed mode */ - OMX_QTIIndexParamForceUnCompressedForOPB = 0x7F00005B, - -}; - -/** -* This is custom extension to configure Low Latency Mode. -* -* STRUCT MEMBERS -* -* nSize : Size of Structure in bytes -* nVersion : OpenMAX IL specification version information -* bLowLatencyMode : Enable/Disable Low Latency mode -*/ - -typedef struct QOMX_EXTNINDEX_VIDEO_VENC_LOW_LATENCY_MODE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bLowLatencyMode; -} QOMX_EXTNINDEX_VIDEO_VENC_LOW_LATENCY_MODE; - -/** -* This is custom extension to configure Encoder Aspect Ratio. -* -* STRUCT MEMBERS -* -* nSize : Size of Structure in bytes -* nVersion : OpenMAX IL specification version information -* nSARWidth : Horizontal aspect size -* nSARHeight : Vertical aspect size -*/ - -typedef struct QOMX_EXTNINDEX_VIDEO_VENC_SAR -{ - OMX_U32 nSize; - OMX_U32 nVersion; - OMX_U32 nSARWidth; - OMX_U32 nSARHeight; -} QOMX_EXTNINDEX_VIDEO_VENC_SAR; - -/** -* This is custom extension to configure Hier-p layers. -* This mode configures Hier-p layers dynamically. -* -* STRUCT MEMBERS -* -* nSize : Size of Structure in bytes -* nVersion : OpenMAX IL specification version information -* nNumHierLayers: Set the number of Hier-p layers for the session -* - This should be less than the MAX Hier-P -* layers set for the session. -*/ - -typedef struct QOMX_EXTNINDEX_VIDEO_HIER_P_LAYERS { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nNumHierLayers; -} QOMX_EXTNINDEX_VIDEO_HIER_P_LAYERS; - - -/** -* This is custom extension to configure Hybrid Hier-p settings. -* This mode is different from enabling Hier-p mode. This -* property enables Hier-p encoding with LTR referencing in each -* sub-GOP. -* -* STRUCT MEMBERS -* -* nSize : Size of Structure in bytes -* nVersion : OpenMAX IL specification version information -* nKeyFrameInterval : Indicates the I frame interval -* nHpLayers : Set the number of Hier-p layers for the session -* - This should be <= 6. (1 Base layer + -* 5 Enhancement layers) -* nTemporalLayerBitrateRatio[OMX_VIDEO_MAX_HP_LAYERS] : Bitrate to -* be set for each enhancement layer -* nMinQuantizer : minimum session QP -* nMaxQuantizer : Maximun session QP -*/ - -typedef struct QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nKeyFrameInterval; - OMX_U32 nTemporalLayerBitrateRatio[OMX_VIDEO_MAX_HP_LAYERS]; - OMX_U32 nMinQuantizer; - OMX_U32 nMaxQuantizer; - OMX_U32 nHpLayers; -} QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE; - -/** - * Encoder Performance Mode. This structure is used to set - * performance mode or power save mode when encoding. The search - * range is modified to save power or improve quality. - * - * STRUCT MEMBERS: - * OMX_U32 nPerfMode : Performance mode: - * 1: MAX_QUALITY - * 2: POWER_SAVE - */ - -typedef struct QOMX_EXTNINDEX_VIDEO_PERFMODE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPerfMode; -} QOMX_EXTNINDEX_VIDEO_PERFMODE; - -/** - * Initial QP parameter. This structure is used to enable - * vendor specific extension to let client enable setting - * initial QP values to I P B Frames - * - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * OMX_U32 nQpI : First Iframe QP - * OMX_U32 nQpP : First Pframe QP - * OMX_U32 nQpB : First Bframe QP - * OMX_U32 bEnableInitQp : Bit field indicating which frame type(s) shall - * use the specified initial QP. - * Bit 0: Enable initial QP for I/IDR - * and use value specified in nInitQpI - * Bit 1: Enable initial QP for P - * and use value specified in nInitQpP - * Bit 2: Enable initial QP for B - * and use value specified in nInitQpB - */ - -typedef struct QOMX_EXTNINDEX_VIDEO_INITIALQP { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nQpI; - OMX_U32 nQpP; - OMX_U32 nQpB; - OMX_U32 bEnableInitQp; -} QOMX_EXTNINDEX_VIDEO_INITIALQP; - -/** - * Extension index parameter. This structure is used to enable - * vendor specific extension on input/output port and - * to pass the required flags and data, if any. - * The format of flags and data being passed is known to - * the client and component apriori. - * - * STRUCT MEMBERS: - * nSize : Size of Structure plus pData size - * nVersion : OMX specification version information - * nPortIndex : Indicates which port to set - * bEnable : Extension index enable (1) or disable (0) - * nFlags : Extension index flags, if any - * nDataSize : Size of the extension index data to follow - * pData : Extension index data, if present. - */ -typedef struct QOMX_EXTNINDEX_PARAMTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; - OMX_U32 nFlags; - OMX_U32 nDataSize; - OMX_PTR pData; -} QOMX_EXTNINDEX_PARAMTYPE; - -/** - * Range index parameter. This structure is used to enable - * vendor specific extension on input/output port and - * to pass the required minimum and maximum values - * - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * nMin : Minimum value - * nMax : Maximum value - * nSteSize : Step size - */ -typedef struct QOMX_EXTNINDEX_RANGETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_S32 nMin; - OMX_S32 nMax; - OMX_S32 nStepSize; -} QOMX_EXTNINDEX_RANGETYPE; - -/** - * Specifies LTR mode types. - */ -typedef enum QOMX_VIDEO_LTRMODETYPE -{ - QOMX_VIDEO_LTRMode_Disable = 0x0, /**< LTR encoding is disabled */ - QOMX_VIDEO_LTRMode_Manual = 0x1, /**< In this mode, IL client configures - ** the encoder the LTR count and manually - ** controls the marking and use of LTR - ** frames during video encoding. - */ - QOMX_VIDEO_LTRMode_Auto = 0x2, /**< In this mode, IL client configures - ** the encoder the LTR count and LTR - ** period. The encoder marks LTR frames - ** automatically based on the LTR period - ** during video encoding. IL client controls - ** the use of LTR frames. - */ - QOMX_VIDEO_LTRMode_MAX = 0x7FFFFFFF /** Maximum LTR Mode type */ -} QOMX_VIDEO_LTRMODETYPE; - -/** - * LTR mode index parameter. This structure is used - * to enable vendor specific extension on output port - * to pass the LTR mode information. - * - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * eLTRMode : Specifies the LTR mode used in encoder - */ -typedef struct QOMX_VIDEO_PARAM_LTRMODE_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_LTRMODETYPE eLTRMode; -} QOMX_VIDEO_PARAM_LTRMODE_TYPE; - -/** - * LTR count index parameter. This structure is used - * to enable vendor specific extension on output port - * to pass the LTR count information. - * - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * nCount : Specifies the number of LTR frames stored in the - * encoder component - */ -typedef struct QOMX_VIDEO_PARAM_LTRCOUNT_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nCount; -} QOMX_VIDEO_PARAM_LTRCOUNT_TYPE; - - -/** - * This should be used with OMX_QcomIndexParamVideoLTRCount extension. - */ -typedef QOMX_VIDEO_PARAM_LTRCOUNT_TYPE OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE; - -/** - * LTR period index parameter. This structure is used - * to enable vendor specific extension on output port - * to pass the LTR period information. - * - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * nFrames : Specifies the number of frames between two consecutive - * LTR frames. - */ -typedef struct QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nFrames; -} QOMX_VIDEO_CONFIG_LTRPERIOD_TYPE; - -/** - * Marks the next encoded frame as an LTR frame. - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * nID : Specifies the identifier of the LTR frame to be marked - * as reference frame for encoding subsequent frames. - */ -typedef struct QOMX_VIDEO_CONFIG_LTRMARK_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nID; -} QOMX_VIDEO_CONFIG_LTRMARK_TYPE; - -/** - * This should be used with OMX_QcomIndexConfigVideoLTRMark extension. - */ -typedef QOMX_VIDEO_CONFIG_LTRMARK_TYPE OMX_QCOM_VIDEO_CONFIG_LTRMARK_TYPE; - -/** - * Specifies an LTR frame to encode subsequent frames. - * STRUCT MEMBERS: - * nSize : Size of Structure in bytes - * nVersion : OpenMAX IL specification version information - * nPortIndex : Index of the port to which this structure applies - * nID : Specifies the identifier of the LTR frame to be used - as reference frame for encoding subsequent frames. - * nFrames : Specifies the number of subsequent frames to be - encoded using the LTR frame with its identifier - nID as reference frame. Short-term reference frames - will be used thereafter. The value of 0xFFFFFFFF - indicates that all subsequent frames will be - encodedusing this LTR frame as reference frame. - */ -typedef struct QOMX_VIDEO_CONFIG_LTRUSE_TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nID; - OMX_U32 nFrames; -} QOMX_VIDEO_CONFIG_LTRUSE_TYPE; - -/** - * This should be used with OMX_QcomIndexConfigVideoLTRUse extension. - */ -typedef QOMX_VIDEO_CONFIG_LTRUSE_TYPE OMX_QCOM_VIDEO_CONFIG_LTRUSE_TYPE; - -/** - * Enumeration used to define the video encoder modes - * - * ENUMS: - * EncoderModeDefault : Default video recording mode. - * All encoder settings made through - * OMX_SetParameter/OMX_SetConfig are applied. No - * parameter is overridden. - * EncoderModeMMS : Video recording mode for MMS (Multimedia Messaging - * Service). This mode is similar to EncoderModeDefault - * except that here the Rate control mode is overridden - * internally and set as a variant of variable bitrate with - * variable frame rate. After this mode is set if the IL - * client tries to set OMX_VIDEO_CONTROLRATETYPE via - * OMX_IndexParamVideoBitrate that would be rejected. For - * this, client should set mode back to EncoderModeDefault - * first and then change OMX_VIDEO_CONTROLRATETYPE. - */ -typedef enum QOMX_VIDEO_ENCODERMODETYPE -{ - QOMX_VIDEO_EncoderModeDefault = 0x00, - QOMX_VIDEO_EncoderModeMMS = 0x01, - QOMX_VIDEO_EncoderModeMax = 0x7FFFFFFF -} QOMX_VIDEO_ENCODERMODETYPE; - -/** - * This structure is used to set the video encoder mode. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version info - * nPortIndex : Port that this structure applies to - * nMode : defines the video encoder mode - */ -typedef struct QOMX_VIDEO_PARAM_ENCODERMODETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_ENCODERMODETYPE nMode; -} QOMX_VIDEO_PARAM_ENCODERMODETYPE; - -/** - * This structure describes the parameters corresponding to the - * QOMX_VIDEO_SYNTAXHDRTYPE extension. This parameter can be queried - * during the loaded state. - */ - -typedef struct QOMX_VIDEO_SYNTAXHDRTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nBytes; /** The number of bytes filled in to the buffer */ - OMX_U8 data[1]; /** Buffer to store the header information */ -} QOMX_VIDEO_SYNTAXHDRTYPE; - -/** - * This structure describes the parameters corresponding to the - * QOMX_VIDEO_TEMPORALSPATIALTYPE extension. This parameter can be set - * dynamically during any state except the state invalid. This is primarily - * used for setting MaxQP from the application. This is set on the out port. - */ - -typedef struct QOMX_VIDEO_TEMPORALSPATIALTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nTSFactor; /** Temoral spatial tradeoff factor value in 0-100 */ -} QOMX_VIDEO_TEMPORALSPATIALTYPE; - -/** - * This structure describes the parameters corresponding to the - * OMX_QCOM_VIDEO_CONFIG_INTRAPERIODTYPE extension. This parameter can be set - * dynamically during any state except the state invalid. This is set on the out port. - */ - -typedef struct QOMX_VIDEO_INTRAPERIODTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nIDRPeriod; /** This specifies coding a frame as IDR after every nPFrames - of intra frames. If this parameter is set to 0, only the - first frame of the encode session is an IDR frame. This - field is ignored for non-AVC codecs and is used only for - codecs that support IDR Period */ - OMX_U32 nPFrames; /** The number of "P" frames between two "I" frames */ - OMX_U32 nBFrames; /** The number of "B" frames between two "I" frames */ -} QOMX_VIDEO_INTRAPERIODTYPE; - -/** - * This structure describes the parameters corresponding to the - * OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE extension. This parameter can be set - * dynamically during any state except the state invalid. This is used for the buffer negotiation - * with other clients. This is set on the out port. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nBufferOccupancy; /** The number of bytes to be set for the buffer occupancy */ -} OMX_QCOM_VIDEO_CONFIG_ULBUFFEROCCUPANCYTYPE; - -/** - * This structure describes the parameters corresponding to the - * OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE extension. This parameter can be set - * dynamically during any state except the state invalid. This is primarily used for the dynamic/random - * intrarefresh. This is set on the out port. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nRirMBs; /** The number of MBs to be set for intrarefresh */ -} OMX_QCOM_VIDEO_CONFIG_RANDOMINTRAREFRESHTYPE; - - -/** - * This structure describes the parameters corresponding to the - * OMX_QCOM_VIDEO_CONFIG_QPRANGE extension. This parameter can be set - * dynamically during any state except the state invalid. This is primarily - * used for the min/max QP to be set from the application. This - * is set on the out port. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_QPRANGE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nMinQP; /** The number for minimum quantization parameter */ - OMX_U32 nMaxQP; /** The number for maximum quantization parameter */ -} OMX_QCOM_VIDEO_CONFIG_QPRANGE; - -/** - * This structure describes the parameters for the - * OMX_QcomIndexParamH264AUDelimiter extension. It enables/disables - * the AU delimiters in the H264 stream, which is used by WFD. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_H264_AUD -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_BOOL bEnable; /** Enable/disable the setting */ -} OMX_QCOM_VIDEO_CONFIG_H264_AUD; - -typedef enum QOMX_VIDEO_PERF_LEVEL -{ - OMX_QCOM_PerfLevelNominal, - OMX_QCOM_PerfLevelTurbo -} QOMX_VIDEO_PERF_LEVEL; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexParamPerfLevel extension. It will set - * the performance mode specified as QOMX_VIDEO_PERF_LEVEL. - */ -typedef struct OMX_QCOM_VIDEO_PARAM_PERF_LEVEL { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - QOMX_VIDEO_PERF_LEVEL ePerfLevel; /** Performance level */ -} OMX_QCOM_VIDEO_PARAM_PERF_LEVEL; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexConfigPerfLevel extension. It will set - * the performance mode specified as QOMX_VIDEO_PERF_LEVEL. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - QOMX_VIDEO_PERF_LEVEL ePerfLevel; /** Performance level */ -} OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL; - -typedef enum QOMX_VIDEO_PICTURE_TYPE_DECODE -{ - OMX_QCOM_PictypeDecode_IPB, - OMX_QCOM_PictypeDecode_I -} QOMX_VIDEO_PICTURE_TYPE_DECODE; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexConfigPictureTypeDecode extension. It - * will set the picture type decode specified by eDecodeType. - */ -typedef struct OMX_QCOM_VIDEO_CONFIG_PICTURE_TYPE_DECODE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - QOMX_VIDEO_PICTURE_TYPE_DECODE eDecodeType; /** Decode type */ -} OMX_QCOM_VIDEO_CONFIG_PICTURE_TYPE_DECODE; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexParamH264VUITimingInfo extension. It - * will enable/disable the VUI timing info. - */ -typedef struct OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_BOOL bEnable; /** Enable/disable the setting */ -} OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexParamVQZIPSEIType extension. It - * will enable/disable the VQZIP SEI info. - */ -typedef struct OMX_QTI_VIDEO_PARAM_VQZIP_SEI_TYPE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_BOOL bEnable; /** Enable/disable the setting */ -} OMX_QTI_VIDEO_PARAM_VQZIP_SEI_TYPE; - -/** - * This structure describes the parameters corresponding - * to OMX_QcomIndexParamPeakBitrate extension. It will - * set the peak bitrate specified by nPeakBitrate. - */ -typedef struct OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_U32 nPeakBitrate; /** Peak bitrate value */ -} OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE; - -/** - * This structure describes the parameters corresponding - * to OMX_QTIIndexParamForceCompressedForDPB extension. Enabling - * this extension will force the split mode DPB(compressed)/OPB(Linear) - * for all resolutions.On some chipsets preferred mode would be combined - * Linear for both DPB/OPB to save memory. For example on 8996 preferred mode - * would be combined linear for resolutions <= 1080p . - * Enabling this might save power but with the cost - * of increased memory i.e almost double the number on output YUV buffers. - */ -typedef struct OMX_QTI_VIDEO_PARAM_FORCE_COMPRESSED_FOR_DPB_TYPE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_BOOL bEnable; /** Enable/disable the setting */ -} OMX_QTI_VIDEO_PARAM_FORCE_COMPRESSED_FOR_DPB_TYPE; - -/** - * This structure describes the parameters corresponding - * to OMX_QTIIndexParamForceUnCompressedForOPB extension. Enabling this - * extension will force the OPB to be linear for the current video session. - * If this property is not set, then the OPB will be set to linear or compressed - * based on resolution selected and/or if cpu access is requested on the - * OPB buffer. - */ -typedef struct OMX_QTI_VIDEO_PARAM_FORCE_UNCOMPRESSED_FOR_OPB_TYPE { - OMX_U32 nSize; /** Sizeo f the structure in bytes */ - OMX_VERSIONTYPE nVersion; /** OMX specification version information */ - OMX_BOOL bEnable; /** Enable/disable the setting */ -} OMX_QTI_VIDEO_PARAM_FORCE_UNCOMPRESSED_FOR_OPB_TYPE; - -typedef struct OMX_VENDOR_EXTRADATATYPE { - OMX_U32 nPortIndex; - OMX_U32 nDataSize; - OMX_U8 *pData; // cdata (codec_data/extradata) -} OMX_VENDOR_EXTRADATATYPE; - -/** - * This structure describes the parameters corresponding to the - * OMX_VENDOR_VIDEOFRAMERATE extension. This parameter can be set - * dynamically during any state except the state invalid. This is - * used for frame rate to be set from the application. This - * is set on the in port. - */ -typedef struct OMX_VENDOR_VIDEOFRAMERATE { - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_U32 nFps; /** Frame rate value */ - OMX_BOOL bEnabled; /** Flag to enable or disable client's frame rate value */ -} OMX_VENDOR_VIDEOFRAMERATE; - -typedef enum OMX_INDEXVENDORTYPE { - OMX_IndexVendorFileReadInputFilename = 0xFF000001, - OMX_IndexVendorParser3gpInputFilename = 0xFF000002, - OMX_IndexVendorVideoExtraData = 0xFF000003, - OMX_IndexVendorAudioExtraData = 0xFF000004, - OMX_IndexVendorVideoFrameRate = 0xFF000005, -} OMX_INDEXVENDORTYPE; - -typedef enum OMX_QCOM_VC1RESOLUTIONTYPE -{ - OMX_QCOM_VC1_PICTURE_RES_1x1, - OMX_QCOM_VC1_PICTURE_RES_2x1, - OMX_QCOM_VC1_PICTURE_RES_1x2, - OMX_QCOM_VC1_PICTURE_RES_2x2 -} OMX_QCOM_VC1RESOLUTIONTYPE; - -typedef enum OMX_QCOM_INTERLACETYPE -{ - OMX_QCOM_InterlaceFrameProgressive, - OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst, - OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst, - OMX_QCOM_InterlaceFrameTopFieldFirst, - OMX_QCOM_InterlaceFrameBottomFieldFirst, - OMX_QCOM_InterlaceFieldTop, - OMX_QCOM_InterlaceFieldBottom -}OMX_QCOM_INTERLACETYPE; - -typedef struct OMX_QCOM_PARAM_VIDEO_INTERLACETYPE -{ - OMX_U32 nSize; /** Size of the structure in bytes */ - OMX_VERSIONTYPE nVersion;/** OMX specification version information */ - OMX_U32 nPortIndex; /** Portindex which is extended by this structure */ - OMX_BOOL bInterlace; /** Interlace content **/ -}OMX_QCOM_PARAM_VIDEO_INTERLACETYPE; - -typedef struct OMX_QCOM_CONFIG_INTERLACETYPE -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nIndex; - OMX_QCOM_INTERLACETYPE eInterlaceType; -}OMX_QCOM_CONFIG_INTERLACETYPE; - -#define MAX_PAN_SCAN_WINDOWS 4 - -typedef struct OMX_QCOM_PANSCAN -{ - OMX_U32 numWindows; - OMX_QCOMRectangle window[MAX_PAN_SCAN_WINDOWS]; -} OMX_QCOM_PANSCAN; - -typedef struct OMX_QCOM_ASPECT_RATIO -{ - OMX_U32 aspectRatioX; - OMX_U32 aspectRatioY; -} OMX_QCOM_ASPECT_RATIO; - -typedef struct OMX_QCOM_DISPLAY_ASPECT_RATIO -{ - OMX_U32 displayVerticalSize; - OMX_U32 displayHorizontalSize; -} OMX_QCOM_DISPLAY_ASPECT_RATIO; - -typedef struct OMX_QCOM_FRAME_PACK_ARRANGEMENT -{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 id; - OMX_U32 cancel_flag; - OMX_U32 type; - OMX_U32 quincunx_sampling_flag; - OMX_U32 content_interpretation_type; - OMX_U32 spatial_flipping_flag; - OMX_U32 frame0_flipped_flag; - OMX_U32 field_views_flag; - OMX_U32 current_frame_is_frame0_flag; - OMX_U32 frame0_self_contained_flag; - OMX_U32 frame1_self_contained_flag; - OMX_U32 frame0_grid_position_x; - OMX_U32 frame0_grid_position_y; - OMX_U32 frame1_grid_position_x; - OMX_U32 frame1_grid_position_y; - OMX_U32 reserved_byte; - OMX_U32 repetition_period; - OMX_U32 extension_flag; -} OMX_QCOM_FRAME_PACK_ARRANGEMENT; - -typedef struct OMX_QCOM_EXTRADATA_QP -{ - OMX_U32 nQP; -} OMX_QCOM_EXTRADATA_QP; - -typedef struct OMX_QCOM_EXTRADATA_BITS_INFO -{ - OMX_U32 header_bits; - OMX_U32 frame_bits; -} OMX_QCOM_EXTRADATA_BITS_INFO; - -typedef struct OMX_QCOM_EXTRADATA_USERDATA { - OMX_U32 type; - OMX_U32 data[1]; -} OMX_QCOM_EXTRADATA_USERDATA; - -typedef struct OMX_QCOM_EXTRADATA_FRAMEINFO -{ - // common frame meta data. interlace related info removed - OMX_VIDEO_PICTURETYPE ePicType; - OMX_QCOM_INTERLACETYPE interlaceType; - OMX_QCOM_PANSCAN panScan; - OMX_QCOM_ASPECT_RATIO aspectRatio; - OMX_QCOM_DISPLAY_ASPECT_RATIO displayAspectRatio; - OMX_U32 nConcealedMacroblocks; - OMX_U32 nFrameRate; - OMX_TICKS nTimeStamp; -} OMX_QCOM_EXTRADATA_FRAMEINFO; - -typedef struct OMX_QCOM_EXTRADATA_FRAMEDIMENSION -{ - /** Frame Dimensions added to each YUV buffer */ - OMX_U32 nDecWidth; /** Width rounded to multiple of 16 */ - OMX_U32 nDecHeight; /** Height rounded to multiple of 16 */ - OMX_U32 nActualWidth; /** Actual Frame Width */ - OMX_U32 nActualHeight; /** Actual Frame Height */ - -} OMX_QCOM_EXTRADATA_FRAMEDIMENSION; - -typedef struct OMX_QCOM_H264EXTRADATA -{ - OMX_U64 seiTimeStamp; -} OMX_QCOM_H264EXTRADATA; - -typedef struct OMX_QCOM_VC1EXTRADATA -{ - OMX_U32 nVC1RangeY; - OMX_U32 nVC1RangeUV; - OMX_QCOM_VC1RESOLUTIONTYPE eVC1PicResolution; -} OMX_QCOM_VC1EXTRADATA; - -typedef union OMX_QCOM_EXTRADATA_CODEC_DATA -{ - OMX_QCOM_H264EXTRADATA h264ExtraData; - OMX_QCOM_VC1EXTRADATA vc1ExtraData; -} OMX_QCOM_EXTRADATA_CODEC_DATA; - -typedef struct OMX_QCOM_EXTRADATA_MBINFO -{ - OMX_U32 nFormat; - OMX_U32 nDataSize; - OMX_U8 data[0]; -} OMX_QCOM_EXTRADATA_MBINFO; - -typedef struct OMX_QCOM_EXTRADATA_VQZIPSEI { - OMX_U32 nSize; - OMX_U8 data[0]; -} OMX_QCOM_EXTRADATA_VQZIPSEI; - -typedef struct OMX_QTI_VIDEO_PARAM_ENABLE_ROIINFO { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnableRoiInfo; -} OMX_QTI_VIDEO_PARAM_ENABLE_ROIINFO; - -typedef struct OMX_QTI_VIDEO_CONFIG_ROIINFO { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_S32 nUpperQpOffset; - OMX_S32 nLowerQpOffset; - OMX_BOOL bUseRoiInfo; - OMX_S32 nRoiMBInfoSize; - OMX_PTR pRoiMBInfo; -} OMX_QTI_VIDEO_CONFIG_ROIINFO; - -typedef enum OMX_QCOM_EXTRADATATYPE -{ - OMX_ExtraDataFrameInfo = 0x7F000001, - OMX_ExtraDataH264 = 0x7F000002, - OMX_ExtraDataVC1 = 0x7F000003, - OMX_ExtraDataFrameDimension = 0x7F000004, - OMX_ExtraDataVideoEncoderSliceInfo = 0x7F000005, - OMX_ExtraDataConcealMB = 0x7F000006, - OMX_ExtraDataInterlaceFormat = 0x7F000007, - OMX_ExtraDataPortDef = 0x7F000008, - OMX_ExtraDataMP2ExtnData = 0x7F000009, - OMX_ExtraDataMP2UserData = 0x7F00000a, - OMX_ExtraDataVideoLTRInfo = 0x7F00000b, - OMX_ExtraDataFramePackingArrangement = 0x7F00000c, - OMX_ExtraDataQP = 0x7F00000d, - OMX_ExtraDataInputBitsInfo = 0x7F00000e, - OMX_ExtraDataVideoEncoderMBInfo = 0x7F00000f, - OMX_ExtraDataVQZipSEI = 0x7F000010, -} OMX_QCOM_EXTRADATATYPE; - -typedef struct OMX_STREAMINTERLACEFORMATTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bInterlaceFormat; - OMX_U32 nInterlaceFormats; -} OMX_STREAMINTERLACEFORMAT; - -typedef enum OMX_INTERLACETYPE -{ - OMX_InterlaceFrameProgressive, - OMX_InterlaceInterleaveFrameTopFieldFirst, - OMX_InterlaceInterleaveFrameBottomFieldFirst, - OMX_InterlaceFrameTopFieldFirst, - OMX_InterlaceFrameBottomFieldFirst -} OMX_INTERLACES; - - -#define OMX_EXTRADATA_HEADER_SIZE 20 - -/** - * AVC profile types, each profile indicates support for various - * performance bounds and different annexes. - */ -typedef enum QOMX_VIDEO_AVCPROFILETYPE { - QOMX_VIDEO_AVCProfileBaseline = OMX_VIDEO_AVCProfileBaseline, - QOMX_VIDEO_AVCProfileMain = OMX_VIDEO_AVCProfileMain, - QOMX_VIDEO_AVCProfileExtended = OMX_VIDEO_AVCProfileExtended, - QOMX_VIDEO_AVCProfileHigh = OMX_VIDEO_AVCProfileHigh, - QOMX_VIDEO_AVCProfileHigh10 = OMX_VIDEO_AVCProfileHigh10, - QOMX_VIDEO_AVCProfileHigh422 = OMX_VIDEO_AVCProfileHigh422, - QOMX_VIDEO_AVCProfileHigh444 = OMX_VIDEO_AVCProfileHigh444, - /* QCom specific profile indexes */ - QOMX_VIDEO_AVCProfileConstrained = OMX_VIDEO_AVCProfileVendorStartUnused, - QOMX_VIDEO_AVCProfileConstrainedBaseline, - QOMX_VIDEO_AVCProfileConstrainedHigh, -} QOMX_VIDEO_AVCPROFILETYPE; - - -/** - * H.264 MVC Profiles - */ -typedef enum QOMX_VIDEO_MVCPROFILETYPE { - QOMX_VIDEO_MVCProfileStereoHigh = 0x1, - QOMX_VIDEO_MVCProfileMultiViewHigh = 0x2, - QOMX_VIDEO_MVCProfileKhronosExtensions = 0x6F000000, - QOMX_VIDEO_MVCProfileVendorStartUnused = 0x7F000000, - QOMX_VIDEO_MVCProfileMax = 0x7FFFFFFF -} QOMX_VIDEO_MVCPROFILETYPE; - -/** - * H.264 MVC Levels - */ -typedef enum QOMX_VIDEO_MVCLEVELTYPE { - QOMX_VIDEO_MVCLevel1 = 0x01, /**< Level 1 */ - QOMX_VIDEO_MVCLevel1b = 0x02, /**< Level 1b */ - QOMX_VIDEO_MVCLevel11 = 0x04, /**< Level 1.1 */ - QOMX_VIDEO_MVCLevel12 = 0x08, /**< Level 1.2 */ - QOMX_VIDEO_MVCLevel13 = 0x10, /**< Level 1.3 */ - QOMX_VIDEO_MVCLevel2 = 0x20, /**< Level 2 */ - QOMX_VIDEO_MVCLevel21 = 0x40, /**< Level 2.1 */ - QOMX_VIDEO_MVCLevel22 = 0x80, /**< Level 2.2 */ - QOMX_VIDEO_MVCLevel3 = 0x100, /**< Level 3 */ - QOMX_VIDEO_MVCLevel31 = 0x200, /**< Level 3.1 */ - QOMX_VIDEO_MVCLevel32 = 0x400, /**< Level 3.2 */ - QOMX_VIDEO_MVCLevel4 = 0x800, /**< Level 4 */ - QOMX_VIDEO_MVCLevel41 = 0x1000, /**< Level 4.1 */ - QOMX_VIDEO_MVCLevel42 = 0x2000, /**< Level 4.2 */ - QOMX_VIDEO_MVCLevel5 = 0x4000, /**< Level 5 */ - QOMX_VIDEO_MVCLevel51 = 0x8000, /**< Level 5.1 */ - QOMX_VIDEO_MVCLevelKhronosExtensions = 0x6F000000, - QOMX_VIDEO_MVCLevelVendorStartUnused = 0x7F000000, - QOMX_VIDEO_MVCLevelMax = 0x7FFFFFFF -} QOMX_VIDEO_MVCLEVELTYPE; - -/** - * DivX Versions - */ -typedef enum QOMX_VIDEO_DIVXFORMATTYPE { - QOMX_VIDEO_DIVXFormatUnused = 0x01, /**< Format unused or unknown */ - QOMX_VIDEO_DIVXFormat311 = 0x02, /**< DivX 3.11 */ - QOMX_VIDEO_DIVXFormat4 = 0x04, /**< DivX 4 */ - QOMX_VIDEO_DIVXFormat5 = 0x08, /**< DivX 5 */ - QOMX_VIDEO_DIVXFormat6 = 0x10, /**< DivX 6 */ - QOMX_VIDEO_DIVXFormatKhronosExtensions = 0x6F000000, - QOMX_VIDEO_DIVXFormatVendorStartUnused = 0x7F000000, - QOMX_VIDEO_DIVXFormatMax = 0x7FFFFFFF -} QOMX_VIDEO_DIVXFORMATTYPE; - -/** - * DivX profile types, each profile indicates support for - * various performance bounds. - */ -typedef enum QOMX_VIDEO_DIVXPROFILETYPE { - QOMX_VIDEO_DivXProfileqMobile = 0x01, /**< qMobile Profile */ - QOMX_VIDEO_DivXProfileMobile = 0x02, /**< Mobile Profile */ - QOMX_VIDEO_DivXProfileMT = 0x04, /**< Mobile Theatre Profile */ - QOMX_VIDEO_DivXProfileHT = 0x08, /**< Home Theatre Profile */ - QOMX_VIDEO_DivXProfileHD = 0x10, /**< High Definition Profile */ - QOMX_VIDEO_DIVXProfileKhronosExtensions = 0x6F000000, - QOMX_VIDEO_DIVXProfileVendorStartUnused = 0x7F000000, - QOMX_VIDEO_DIVXProfileMax = 0x7FFFFFFF -} QOMX_VIDEO_DIVXPROFILETYPE; - -/** - * DivX Video Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFormat : Version of DivX stream / data - * eProfile : Profile of DivX stream / data - */ -typedef struct QOMX_VIDEO_PARAM_DIVXTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_DIVXFORMATTYPE eFormat; - QOMX_VIDEO_DIVXPROFILETYPE eProfile; -} QOMX_VIDEO_PARAM_DIVXTYPE; - - - -/** - * VP Versions - */ -typedef enum QOMX_VIDEO_VPFORMATTYPE { - QOMX_VIDEO_VPFormatUnused = 0x01, /**< Format unused or unknown */ - QOMX_VIDEO_VPFormat6 = 0x02, /**< VP6 Video Format */ - QOMX_VIDEO_VPFormat7 = 0x04, /**< VP7 Video Format */ - QOMX_VIDEO_VPFormat8 = 0x08, /**< VP8 Video Format */ - QOMX_VIDEO_VPFormat9 = 0x10, /**< VP9 Video Format */ - QOMX_VIDEO_VPFormatKhronosExtensions = 0x6F000000, - QOMX_VIDEO_VPFormatVendorStartUnused = 0x7F000000, - QOMX_VIDEO_VPFormatMax = 0x7FFFFFFF -} QOMX_VIDEO_VPFORMATTYPE; - -/** - * VP profile types, each profile indicates support for various - * encoding tools. - */ -typedef enum QOMX_VIDEO_VPPROFILETYPE { - QOMX_VIDEO_VPProfileSimple = 0x01, /**< Simple Profile, applies to VP6 only */ - QOMX_VIDEO_VPProfileAdvanced = 0x02, /**< Advanced Profile, applies to VP6 only */ - QOMX_VIDEO_VPProfileVersion0 = 0x04, /**< Version 0, applies to VP7 and VP8 */ - QOMX_VIDEO_VPProfileVersion1 = 0x08, /**< Version 1, applies to VP7 and VP8 */ - QOMX_VIDEO_VPProfileVersion2 = 0x10, /**< Version 2, applies to VP8 only */ - QOMX_VIDEO_VPProfileVersion3 = 0x20, /**< Version 3, applies to VP8 only */ - QOMX_VIDEO_VPProfileKhronosExtensions = 0x6F000000, - QOMX_VIDEO_VPProfileVendorStartUnused = 0x7F000000, - QOMX_VIDEO_VPProfileMax = 0x7FFFFFFF -} QOMX_VIDEO_VPPROFILETYPE; - -/** - * VP Video Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFormat : Format of VP stream / data - * eProfile : Profile or Version of VP stream / data - */ -typedef struct QOMX_VIDEO_PARAM_VPTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_VPFORMATTYPE eFormat; - QOMX_VIDEO_VPPROFILETYPE eProfile; -} QOMX_VIDEO_PARAM_VPTYPE; - -/** - * Spark Versions - */ -typedef enum QOMX_VIDEO_SPARKFORMATTYPE { - QOMX_VIDEO_SparkFormatUnused = 0x01, /**< Format unused or unknown */ - QOMX_VIDEO_SparkFormat0 = 0x02, /**< Video Format Version 0 */ - QOMX_VIDEO_SparkFormat1 = 0x04, /**< Video Format Version 1 */ - QOMX_VIDEO_SparkFormatKhronosExtensions = 0x6F000000, - QOMX_VIDEO_SparkFormatVendorStartUnused = 0x7F000000, - QOMX_VIDEO_SparkFormatMax = 0x7FFFFFFF -} QOMX_VIDEO_SPARKFORMATTYPE; - -/** - * Spark Video Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFormat : Version of Spark stream / data - */ -typedef struct QOMX_VIDEO_PARAM_SPARKTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_SPARKFORMATTYPE eFormat; -} QOMX_VIDEO_PARAM_SPARKTYPE; - - -typedef struct QOMX_VIDEO_QUERY_DECODER_INSTANCES { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nNumOfInstances; -} QOMX_VIDEO_QUERY_DECODER_INSTANCES; - -typedef struct QOMX_ENABLETYPE { - OMX_BOOL bEnable; -} QOMX_ENABLETYPE; - -typedef enum QOMX_VIDEO_EVENTS { - OMX_EventIndexsettingChanged = OMX_EventVendorStartUnused -} QOMX_VIDEO_EVENTS; - -typedef enum QOMX_VIDEO_PICTURE_ORDER { - QOMX_VIDEO_DISPLAY_ORDER = 0x1, - QOMX_VIDEO_DECODE_ORDER = 0x2 -} QOMX_VIDEO_PICTURE_ORDER; - -typedef struct QOMX_VIDEO_DECODER_PICTURE_ORDER { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - QOMX_VIDEO_PICTURE_ORDER eOutputPictureOrder; -} QOMX_VIDEO_DECODER_PICTURE_ORDER; - -typedef struct QOMX_INDEXEXTRADATATYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnabled; - OMX_INDEXTYPE nIndex; -} QOMX_INDEXEXTRADATATYPE; - -typedef struct QOMX_INDEXTIMESTAMPREORDER { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; -} QOMX_INDEXTIMESTAMPREORDER; - -typedef struct QOMX_INDEXDOWNSCALAR { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; -} QOMX_INDEXDOWNSCALAR; - -typedef struct QOMX_VIDEO_CUSTOM_BUFFERSIZE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nBufferSize; -} QOMX_VIDEO_CUSTOM_BUFFERSIZE; - -#define OMX_QCOM_INDEX_PARAM_VIDEO_SYNCFRAMEDECODINGMODE "OMX.QCOM.index.param.video.SyncFrameDecodingMode" -#define OMX_QCOM_INDEX_PARAM_INDEXEXTRADATA "OMX.QCOM.index.param.IndexExtraData" -#define OMX_QCOM_INDEX_PARAM_VIDEO_SLICEDELIVERYMODE "OMX.QCOM.index.param.SliceDeliveryMode" -#define OMX_QCOM_INDEX_PARAM_VIDEO_FRAMEPACKING_EXTRADATA "OMX.QCOM.index.param.video.FramePackingExtradata" -#define OMX_QCOM_INDEX_PARAM_VIDEO_QP_EXTRADATA "OMX.QCOM.index.param.video.QPExtradata" -#define OMX_QCOM_INDEX_PARAM_VIDEO_INPUTBITSINFO_EXTRADATA "OMX.QCOM.index.param.video.InputBitsInfoExtradata" -#define OMX_QCOM_INDEX_PARAM_VIDEO_EXTNUSER_EXTRADATA "OMX.QCOM.index.param.video.ExtnUserExtraData" -#define OMX_QCOM_INDEX_CONFIG_VIDEO_FRAMEPACKING_INFO "OMX.QCOM.index.config.video.FramePackingInfo" -#define OMX_QCOM_INDEX_PARAM_VIDEO_MPEG2SEQDISP_EXTRADATA "OMX.QCOM.index.param.video.Mpeg2SeqDispExtraData" - -#define OMX_QCOM_INDEX_PARAM_VIDEO_HIERSTRUCTURE "OMX.QCOM.index.param.video.HierStructure" -#define OMX_QCOM_INDEX_PARAM_VIDEO_LTRCOUNT "OMX.QCOM.index.param.video.LTRCount" -#define OMX_QCOM_INDEX_PARAM_VIDEO_LTRPERIOD "OMX.QCOM.index.param.video.LTRPeriod" -#define OMX_QCOM_INDEX_CONFIG_VIDEO_LTRUSE "OMX.QCOM.index.config.video.LTRUse" -#define OMX_QCOM_INDEX_CONFIG_VIDEO_LTRMARK "OMX.QCOM.index.config.video.LTRMark" -#define OMX_QCOM_INDEX_CONFIG_VIDEO_HIER_P_LAYERS "OMX.QCOM.index.config.video.hierplayers" -#define OMX_QCOM_INDEX_CONFIG_RECTANGLE_TYPE "OMX.QCOM.index.config.video.rectangle" -#define OMX_QCOM_INDEX_PARAM_VIDEO_BASE_LAYER_ID "OMX.QCOM.index.param.video.baselayerid" -#define OMX_QCOM_INDEX_CONFIG_VIDEO_QP "OMX.QCOM.index.config.video.qp" -#define OMX_QCOM_INDEX_PARAM_VIDEO_SAR "OMX.QCOM.index.param.video.sar" -#define OMX_QTI_INDEX_PARAM_VIDEO_LOW_LATENCY "OMX.QTI.index.param.video.LowLatency" - -#define OMX_QCOM_INDEX_PARAM_VIDEO_PASSINPUTBUFFERFD "OMX.QCOM.index.param.video.PassInputBufferFd" -#define OMX_QTI_INDEX_PARAM_VIDEO_PREFER_ADAPTIVE_PLAYBACK "OMX.QTI.index.param.video.PreferAdaptivePlayback" -#define OMX_QTI_INDEX_CONFIG_VIDEO_SETTIMEDATA "OMX.QTI.index.config.video.settimedata" -#define OMX_QTI_INDEX_PARAM_VIDEO_FORCE_COMPRESSED_FOR_DPB "OMX.QTI.index.param.video.ForceCompressedForDPB" -#define OMX_QTI_INDEX_PARAM_VIDEO_ENABLE_ROIINFO "OMX.QTI.index.param.enableRoiInfo" -#define OMX_QTI_INDEX_CONFIG_VIDEO_ROIINFO "OMX.QTI.index.config.RoiInfo" - -typedef enum { - QOMX_VIDEO_FRAME_PACKING_CHECKERBOARD = 0, - QOMX_VIDEO_FRAME_PACKING_COLUMN_INTERLEAVE = 1, - QOMX_VIDEO_FRAME_PACKING_ROW_INTERLEAVE = 2, - QOMX_VIDEO_FRAME_PACKING_SIDE_BY_SIDE = 3, - QOMX_VIDEO_FRAME_PACKING_TOP_BOTTOM = 4, - QOMX_VIDEO_FRAME_PACKING_TEMPORAL = 5, -} QOMX_VIDEO_FRAME_PACKING_ARRANGEMENT; - -typedef enum { - QOMX_VIDEO_CONTENT_UNSPECIFIED = 0, - QOMX_VIDEO_CONTENT_LR_VIEW = 1, - QOMX_VIDEO_CONTENT_RL_VIEW = 2, -} QOMX_VIDEO_CONTENT_INTERPRETATION; - -/** - * Specifies the extended picture types. These values should be - * OR'd along with the types defined in OMX_VIDEO_PICTURETYPE to - * signal all pictures types which are allowed. - * - * ENUMS: - * H.264 Specific Picture Types: IDR - */ -typedef enum QOMX_VIDEO_PICTURETYPE { - QOMX_VIDEO_PictureTypeIDR = OMX_VIDEO_PictureTypeVendorStartUnused + 0x1000 -} QOMX_VIDEO_PICTURETYPE; - -#define OMX_QCOM_INDEX_CONFIG_ACTIVE_REGION_DETECTION "OMX.QCOM.index.config.activeregiondetection" -#define OMX_QCOM_INDEX_CONFIG_ACTIVE_REGION_DETECTION_STATUS "OMX.QCOM.index.config.activeregiondetectionstatus" -#define OMX_QCOM_INDEX_CONFIG_SCALING_MODE "OMX.QCOM.index.config.scalingmode" -#define OMX_QCOM_INDEX_CONFIG_NOISEREDUCTION "OMX.QCOM.index.config.noisereduction" -#define OMX_QCOM_INDEX_CONFIG_IMAGEENHANCEMENT "OMX.QCOM.index.config.imageenhancement" -#define OMX_QCOM_INDEX_PARAM_HELDBUFFERCOUNT "OMX.QCOM.index.param.HeldBufferCount" /**< reference: QOMX_HELDBUFFERCOUNTTYPE */ - - -typedef struct QOMX_RECTTYPE { - OMX_S32 nLeft; - OMX_S32 nTop; - OMX_U32 nWidth; - OMX_U32 nHeight; -} QOMX_RECTTYPE; - -typedef struct QOMX_ACTIVEREGIONDETECTIONTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; - QOMX_RECTTYPE sROI; - OMX_U32 nNumExclusionRegions; - QOMX_RECTTYPE sExclusionRegions[1]; -} QOMX_ACTIVEREGIONDETECTIONTYPE; - -typedef struct QOMX_ACTIVEREGIONDETECTION_STATUSTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bDetected; - QOMX_RECTTYPE sDetectedRegion; -} QOMX_ACTIVEREGIONDETECTION_STATUSTYPE; - -typedef enum QOMX_SCALE_MODETYPE { - QOMX_SCALE_MODE_Normal, - QOMX_SCALE_MODE_Anamorphic, - QOMX_SCALE_MODE_Max = 0x7FFFFFFF -} QOMX_SCALE_MODETYPE; - -typedef struct QOMX_SCALINGMODETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - QOMX_SCALE_MODETYPE eScaleMode; -} QOMX_SCALINGMODETYPE; - -typedef struct QOMX_NOISEREDUCTIONTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; - OMX_BOOL bAutoMode; - OMX_S32 nNoiseReduction; -} QOMX_NOISEREDUCTIONTYPE; - -typedef struct QOMX_IMAGEENHANCEMENTTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnable; - OMX_BOOL bAutoMode; - OMX_S32 nImageEnhancement; -} QOMX_IMAGEENHANCEMENTTYPE; - -/* - * these are part of OMX1.2 but JB MR2 branch doesn't have them defined - * OMX_IndexParamInterlaceFormat - * OMX_INTERLACEFORMATTYPE - */ -#ifndef OMX_IndexParamInterlaceFormat -#define OMX_IndexParamInterlaceFormat (0x7FF00000) -typedef struct OMX_INTERLACEFORMATTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nFormat; - OMX_TICKS nTimeStamp; -} OMX_INTERLACEFORMATTYPE; -#endif - -/** - * This structure is used to indicate the maximum number of buffers - * that a port will hold during data flow. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version info - * nPortIndex : Port that this structure applies to - * nHeldBufferCount : Read-only, maximum number of buffers that will be held - */ -typedef struct QOMX_HELDBUFFERCOUNTTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nHeldBufferCount; -} QOMX_HELDBUFFERCOUNTTYPE; - -typedef enum QOMX_VIDEO_HIERARCHICALCODINGTYPE { - QOMX_HIERARCHICALCODING_P = 0x01, - QOMX_HIERARCHICALCODING_B = 0x02, -} QOMX_VIDEO_HIERARCHICALCODINGTYPE; - -typedef struct QOMX_VIDEO_HIERARCHICALLAYERS { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nNumLayers; - QOMX_VIDEO_HIERARCHICALCODINGTYPE eHierarchicalCodingType; -} QOMX_VIDEO_HIERARCHICALLAYERS; - -typedef struct QOMX_VIDEO_H264ENTROPYCODINGTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_BOOL bCabac; - OMX_U32 nCabacInitIdc; -} QOMX_VIDEO_H264ENTROPYCODINGTYPE; - - -/* VIDEO POSTPROCESSING CTRLS AND ENUMS */ -#define QOMX_VPP_HQV_CUSTOMPAYLOAD_SZ 256 -#define VPP_HQV_CONTROL_GLOBAL_START (VPP_HQV_CONTROL_CUST + 1) - -typedef enum QOMX_VPP_HQV_MODE { - VPP_HQV_MODE_OFF, - VPP_HQV_MODE_AUTO, - VPP_HQV_MODE_MANUAL, - VPP_HQV_MODE_MAX -} QOMX_VPP_HQV_MODE; - -typedef enum QOMX_VPP_HQVCONTROLTYPE { - VPP_HQV_CONTROL_CADE = 0x1, - VPP_HQV_CONTROL_CNR = 0x04, - VPP_HQV_CONTROL_AIE = 0x05, - VPP_HQV_CONTROL_FRC = 0x06, - VPP_HQV_CONTROL_CUST = 0x07, - VPP_HQV_CONTROL_GLOBAL_DEMO = VPP_HQV_CONTROL_GLOBAL_START, - VPP_HQV_CONTROL_MAX, -} QOMX_VPP_HQVCONTROLTYPE; - -typedef enum QOMX_VPP_HQV_HUE_MODE { - VPP_HQV_HUE_MODE_OFF, - VPP_HQV_HUE_MODE_ON, - VPP_HQV_HUE_MODE_MAX, -} QOMX_VPP_HQV_HUE_MODE; - -typedef enum QOMX_VPP_HQV_FRC_MODE { - VPP_HQV_FRC_MODE_OFF, - VPP_HQV_FRC_MODE_LOW, - VPP_HQV_FRC_MODE_MED, - VPP_HQV_FRC_MODE_HIGH, - VPP_HQV_FRC_MODE_MAX, -} QOMX_VPP_HQV_FRC_MODE; - - -typedef struct QOMX_VPP_HQVCTRL_CADE { - QOMX_VPP_HQV_MODE mode; - OMX_U32 level; - OMX_S32 contrast; - OMX_S32 saturation; -} QOMX_VPP_HQVCTRL_CADE; - -typedef struct QOMX_VPP_HQVCTRL_CNR { - QOMX_VPP_HQV_MODE mode; - OMX_U32 level; -} QOMX_VPP_HQVCTRL_CNR; - -typedef struct QOMX_VPP_HQVCTRL_AIE { - QOMX_VPP_HQV_MODE mode; - QOMX_VPP_HQV_HUE_MODE hue_mode; - OMX_U32 cade_level; - OMX_U32 ltm_level; -} QOMX_VPP_HQVCTRL_AIE; - -typedef struct QOMX_VPP_HQVCTRL_CUSTOM { - OMX_U32 id; - OMX_U32 len; - OMX_U8 data[QOMX_VPP_HQV_CUSTOMPAYLOAD_SZ]; -} QOMX_VPP_HQVCTRL_CUSTOM; - -typedef struct QOMX_VPP_HQVCTRL_GLOBAL_DEMO { - OMX_U32 process_percent; -} QOMX_VPP_HQVCTRL_GLOBAL_DEMO; - -typedef struct QOMX_VPP_HQVCTRL_FRC { - QOMX_VPP_HQV_FRC_MODE mode; -} QOMX_VPP_HQVCTRL_FRC; - -typedef struct QOMX_VPP_HQVCONTROL { - QOMX_VPP_HQV_MODE mode; - QOMX_VPP_HQVCONTROLTYPE ctrl_type; - union { - QOMX_VPP_HQVCTRL_CADE cade; - QOMX_VPP_HQVCTRL_CNR cnr; - QOMX_VPP_HQVCTRL_AIE aie; - QOMX_VPP_HQVCTRL_CUSTOM custom; - QOMX_VPP_HQVCTRL_GLOBAL_DEMO global_demo; - QOMX_VPP_HQVCTRL_FRC frc; - }; -} QOMX_VPP_HQVCONTROL; - -/* STRUCTURE TO TURN VPP ON */ -typedef struct QOMX_VPP_ENABLE { - OMX_BOOL enable_vpp; -} QOMX_VPP_ENABLE; - -typedef enum OMX_QOMX_VIDEO_MBISTATISTICSTYPE { - QOMX_MBI_STATISTICS_MODE_DEFAULT = 0, - QOMX_MBI_STATISTICS_MODE_1 = 0x01, - QOMX_MBI_STATISTICS_MODE_2 = 0x02, -} OMX_QOMX_VIDEO_MBISTATISTICSTYPE; - -typedef struct OMX_QOMX_VIDEO_MBI_STATISTICS { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_QOMX_VIDEO_MBISTATISTICSTYPE eMBIStatisticsType; -} OMX_QOMX_VIDEO_MBI_STATISTICS; - -typedef struct QOMX_VIDEO_BATCHSIZETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nBatchSize; -} QOMX_VIDEO_BATCHSIZETYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __OMX_QCOM_EXTENSIONS_H__ */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Skype_VideoExtensions.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Skype_VideoExtensions.h deleted file mode 100644 index 5cc832930..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Skype_VideoExtensions.h +++ /dev/null @@ -1,155 +0,0 @@ -/*@@@+++@@@@****************************************************************** - - Microsoft Skype Engineering - Copyright (C) 2014 Microsoft Corporation. - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - -*@@@---@@@@******************************************************************/ - - -#ifndef __OMX_SKYPE_VIDEOEXTENSIONS_H__ -#define __OMX_SKYPE_VIDEOEXTENSIONS_H__ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -#pragma pack(push, 1) - - -typedef enum OMX_SKYPE_VIDEO_SliceControlMode -{ - OMX_SKYPE_VIDEO_SliceControlModeNone = 0, - OMX_SKYPE_VIDEO_SliceControlModeMB = 1, - OMX_SKYPE_VIDEO_SliceControlModeByte = 2, - OMX_SKYPE_VIDEO_SliceControlModMBRow = 3, -} OMX_SKYPE_VIDEO_SliceControlMode; - - -typedef enum OMX_SKYPE_VIDEO_HierarType -{ - OMX_SKYPE_VIDEO_HierarType_P = 0x01, - OMX_SKYPE_VIDEO_HierarType_B = 0x02, -} OMX_SKYPE_VIDEO_HIERAR_HierarType; - -typedef enum OMX_VIDEO_EXTENSION_AVCPROFILETYPE -{ - OMX_VIDEO_EXT_AVCProfileConstrainedBaseline = 0x01, - OMX_VIDEO_EXT_AVCProfileConstrainedHigh = 0x02, -} OMX_VIDEO_EXTENSION_AVCPROFILETYPE; - -typedef struct OMX_SKYPE_VIDEO_ENCODERPARAMS { - OMX_BOOL bLowLatency; - OMX_BOOL bUseExtendedProfile; - OMX_BOOL bSequenceHeaderWithIDR; - OMX_VIDEO_EXTENSION_AVCPROFILETYPE eProfile; - OMX_U32 nLTRFrames; - OMX_SKYPE_VIDEO_HierarType eHierarType; - OMX_U32 nMaxTemporalLayerCount; - OMX_SKYPE_VIDEO_SliceControlMode eSliceControlMode; - OMX_U32 nSarIndex; - OMX_U32 nSarWidth; - OMX_U32 nSarHeight; -} OMX_SKYPE_VIDEO_ENCODERPARAMS; - -typedef struct OMX_SKYPE_VIDEO_PARAM_ENCODERSETTING { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_SKYPE_VIDEO_ENCODERPARAMS stEncParam; -} OMX_SKYPE_VIDEO_PARAM_ENCODESETTING; - -typedef struct OMX_SKYPE_VIDEO_ENCODERCAP { - OMX_BOOL bLowLatency; - OMX_U32 nMaxFrameWidth; - OMX_U32 nMaxFrameHeight; - OMX_U32 nMaxInstances; - OMX_U32 nMaxTemporaLayerCount; - OMX_U32 nMaxRefFrames; - OMX_U32 nMaxLTRFrames; - OMX_VIDEO_AVCLEVELTYPE nMaxLevel; - OMX_U32 nSliceControlModesBM; - OMX_U32 nMaxMacroblockProcessingRate; - OMX_U32 xMinScaleFactor; -} OMX_SKYPE_VIDEO_ENCODERCAP; - -typedef struct OMX_SKYPE_VIDEO_PARAM_ENCODERCAP { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_SKYPE_VIDEO_ENCODERCAP stEncCap; -} OMX_SKYPE_VIDEO_PARAM_ENCODERCAP; - -typedef struct OMX_SKYPE_VIDEO_DECODERCAP { - OMX_BOOL bLowLatency; - OMX_U32 nMaxFrameWidth; - OMX_U32 nMaxFrameHeight; - OMX_U32 nMaxInstances; - OMX_VIDEO_AVCLEVELTYPE nMaxLevel; - OMX_U32 nMaxMacroblockProcessingRate; -} OMX_SKYPE_VIDEO_DECODERCAP; - -typedef struct OMX_SKYPE_VIDEO_PARAM_DECODERCAP { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_SKYPE_VIDEO_DECODERCAP stDecoderCap; -} OMX_SKYPE_VIDEO_PARAM_DECODERCAP; - -typedef struct OMX_SKYPE_VIDEO_CONFIG_QP { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nQP; -} OMX_SKYPE_VIDEO_CONFIG_QP; - -typedef struct OMX_SKYPE_VIDEO_CONFIG_BASELAYERPID{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nPID; -} OMX_SKYPE_VIDEO_CONFIG_BASELAYERPID; - -typedef struct OMX_SKYPE_VIDEO_PARAM_DRIVERVER { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U64 nDriverVersion; -} OMX_SKYPE_VIDEO_PARAM_DRIVERVER; - -typedef enum OMX_SKYPE_VIDEO_DownScaleFactor -{ - OMX_SKYPE_VIDEO_DownScaleFactor_1_1 = 0, - OMX_SKYPE_VIDEO_DownScaleFactor_Equal_AR = 1, - OMX_SKYPE_VIDEO_DownScaleFactor_Any = 2, -} OMX_SKYPE_VIDEO_DownScaleFactor; - -#pragma pack(pop) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Types.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Types.h deleted file mode 100644 index 3b9fab4fc..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Types.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_Types.h - OpenMax IL version 1.1.2 - * The OMX_Types header file contains the primitive type definitions used by - * the core, the application and the component. This file may need to be - * modified to be used on systems that do not have "char" set to 8 bits, - * "short" set to 16 bits and "long" set to 32 bits. - */ - -#ifndef OMX_Types_h -#define OMX_Types_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** The OMX_API and OMX_APIENTRY are platform specific definitions used - * to declare OMX function prototypes. They are modified to meet the - * requirements for a particular platform */ -#ifdef __SYMBIAN32__ -# ifdef __OMX_EXPORTS -# define OMX_API __declspec(dllexport) -# else -# ifdef _WIN32 -# define OMX_API __declspec(dllexport) -# else -# define OMX_API __declspec(dllimport) -# endif -# endif -#else -# ifdef _WIN32 -# ifdef __OMX_EXPORTS -# define OMX_API __declspec(dllexport) -# else -# define OMX_API __declspec(dllimport) -# endif -# else -# ifdef __OMX_EXPORTS -# define OMX_API -# else -# define OMX_API extern -# endif -# endif -#endif - -#ifndef OMX_APIENTRY -#define OMX_APIENTRY -#endif - -/** OMX_IN is used to identify inputs to an OMX function. This designation - will also be used in the case of a pointer that points to a parameter - that is used as an output. */ -#ifndef OMX_IN -#define OMX_IN -#endif - -/** OMX_OUT is used to identify outputs from an OMX function. This - designation will also be used in the case of a pointer that points - to a parameter that is used as an input. */ -#ifndef OMX_OUT -#define OMX_OUT -#endif - - -/** OMX_INOUT is used to identify parameters that may be either inputs or - outputs from an OMX function at the same time. This designation will - also be used in the case of a pointer that points to a parameter that - is used both as an input and an output. */ -#ifndef OMX_INOUT -#define OMX_INOUT -#endif - -/** OMX_ALL is used to as a wildcard to select all entities of the same type - * when specifying the index, or referring to a object by an index. (i.e. - * use OMX_ALL to indicate all N channels). When used as a port index - * for a config or parameter this OMX_ALL denotes that the config or - * parameter applies to the entire component not just one port. */ -#define OMX_ALL 0xFFFFFFFF - -/** In the following we define groups that help building doxygen documentation */ - -/** @defgroup core OpenMAX IL core - * Functions and structure related to the OMX IL core - */ - - /** @defgroup comp OpenMAX IL component - * Functions and structure related to the OMX IL component - */ - -/** @defgroup rpm Resource and Policy Management - * Structures for resource and policy management of components - */ - -/** @defgroup buf Buffer Management - * Buffer handling functions and structures - */ - -/** @defgroup tun Tunneling - * @ingroup core comp - * Structures and functions to manage tunnels among component ports - */ - -/** @defgroup cp Content Pipes - * @ingroup core - */ - - /** @defgroup metadata Metadata handling - * - */ - -/** OMX_U8 is an 8 bit unsigned quantity that is byte aligned */ -typedef unsigned char OMX_U8; - -/** OMX_S8 is an 8 bit signed quantity that is byte aligned */ -typedef signed char OMX_S8; - -/** OMX_U16 is a 16 bit unsigned quantity that is 16 bit word aligned */ -typedef unsigned short OMX_U16; - -/** OMX_S16 is a 16 bit signed quantity that is 16 bit word aligned */ -typedef signed short OMX_S16; - -/** OMX_U32 is a 32 bit unsigned quantity that is 32 bit word aligned */ -typedef unsigned int OMX_U32; - -/** OMX_S32 is a 32 bit signed quantity that is 32 bit word aligned */ -typedef signed int OMX_S32; - - -/* Users with compilers that cannot accept the "long long" designation should - define the OMX_SKIP64BIT macro. It should be noted that this may cause - some components to fail to compile if the component was written to require - 64 bit integral types. However, these components would NOT compile anyway - since the compiler does not support the way the component was written. -*/ -#ifndef OMX_SKIP64BIT -#ifdef __SYMBIAN32__ -/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ -typedef unsigned long long OMX_U64; - -/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ -typedef signed long long OMX_S64; - -#elif defined(WIN32) - -/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ -typedef unsigned __int64 OMX_U64; - -/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ -typedef signed __int64 OMX_S64; - -#else /* WIN32 */ - -/** OMX_U64 is a 64 bit unsigned quantity that is 64 bit word aligned */ -typedef unsigned long long OMX_U64; - -/** OMX_S64 is a 64 bit signed quantity that is 64 bit word aligned */ -typedef signed long long OMX_S64; - -#endif /* WIN32 */ -#endif - - -/** The OMX_BOOL type is intended to be used to represent a true or a false - value when passing parameters to and from the OMX core and components. The - OMX_BOOL is a 32 bit quantity and is aligned on a 32 bit word boundary. - */ -typedef enum OMX_BOOL { - OMX_FALSE = 0, - OMX_TRUE = !OMX_FALSE, - OMX_BOOL_MAX = 0x7FFFFFFF -} OMX_BOOL; - -#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS - -typedef OMX_U32 OMX_PTR; -typedef OMX_PTR OMX_STRING; -typedef OMX_PTR OMX_BYTE; - -#else - -/** The OMX_PTR type is intended to be used to pass pointers between the OMX - applications and the OMX Core and components. This is a 32 bit pointer and - is aligned on a 32 bit boundary. - */ -typedef void* OMX_PTR; - -/** The OMX_STRING type is intended to be used to pass "C" type strings between - the application and the core and component. The OMX_STRING type is a 32 - bit pointer to a zero terminated string. The pointer is word aligned and - the string is byte aligned. - */ -typedef char* OMX_STRING; - -/** The OMX_BYTE type is intended to be used to pass arrays of bytes such as - buffers between the application and the component and core. The OMX_BYTE - type is a 32 bit pointer to a zero terminated string. The pointer is word - aligned and the string is byte aligned. - */ -typedef unsigned char* OMX_BYTE; - -/** OMX_UUIDTYPE is a very long unique identifier to uniquely identify - at runtime. This identifier should be generated by a component in a way - that guarantees that every instance of the identifier running on the system - is unique. */ - - -#endif - -typedef unsigned char OMX_UUIDTYPE[128]; - -/** The OMX_DIRTYPE enumeration is used to indicate if a port is an input or - an output port. This enumeration is common across all component types. - */ -typedef enum OMX_DIRTYPE -{ - OMX_DirInput, /**< Port is an input port */ - OMX_DirOutput, /**< Port is an output port */ - OMX_DirMax = 0x7FFFFFFF -} OMX_DIRTYPE; - -/** The OMX_ENDIANTYPE enumeration is used to indicate the bit ordering - for numerical data (i.e. big endian, or little endian). - */ -typedef enum OMX_ENDIANTYPE -{ - OMX_EndianBig, /**< big endian */ - OMX_EndianLittle, /**< little endian */ - OMX_EndianMax = 0x7FFFFFFF -} OMX_ENDIANTYPE; - - -/** The OMX_NUMERICALDATATYPE enumeration is used to indicate if data - is signed or unsigned - */ -typedef enum OMX_NUMERICALDATATYPE -{ - OMX_NumericalDataSigned, /**< signed data */ - OMX_NumericalDataUnsigned, /**< unsigned data */ - OMX_NumercialDataMax = 0x7FFFFFFF -} OMX_NUMERICALDATATYPE; - - -/** Unsigned bounded value type */ -typedef struct OMX_BU32 { - OMX_U32 nValue; /**< actual value */ - OMX_U32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ - OMX_U32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ -} OMX_BU32; - - -/** Signed bounded value type */ -typedef struct OMX_BS32 { - OMX_S32 nValue; /**< actual value */ - OMX_S32 nMin; /**< minimum for value (i.e. nValue >= nMin) */ - OMX_S32 nMax; /**< maximum for value (i.e. nValue <= nMax) */ -} OMX_BS32; - - -/** Structure representing some time or duration in microseconds. This structure - * must be interpreted as a signed 64 bit value. The quantity is signed to accommodate - * negative deltas and preroll scenarios. The quantity is represented in microseconds - * to accomodate high resolution timestamps (e.g. DVD presentation timestamps based - * on a 90kHz clock) and to allow more accurate and synchronized delivery (e.g. - * individual audio samples delivered at 192 kHz). The quantity is 64 bit to - * accommodate a large dynamic range (signed 32 bit values would allow only for plus - * or minus 35 minutes). - * - * Implementations with limited precision may convert the signed 64 bit value to - * a signed 32 bit value internally but risk loss of precision. - */ -#ifndef OMX_SKIP64BIT -typedef OMX_S64 OMX_TICKS; -#else -typedef struct OMX_TICKS -{ - OMX_U32 nLowPart; /** low bits of the signed 64 bit tick value */ - OMX_U32 nHighPart; /** high bits of the signed 64 bit tick value */ -} OMX_TICKS; -#endif -#define OMX_TICKS_PER_SECOND 1000000 - -/** Define the public interface for the OMX Handle. The core will not use - this value internally, but the application should only use this value. - */ -typedef void* OMX_HANDLETYPE; - -typedef struct OMX_MARKTYPE -{ - OMX_HANDLETYPE hMarkTargetComponent; /**< The component that will - generate a mark event upon - processing the mark. */ - OMX_PTR pMarkData; /**< Application specific data associated with - the mark sent on a mark event to disambiguate - this mark from others. */ -} OMX_MARKTYPE; - - -/** OMX_NATIVE_DEVICETYPE is used to map a OMX video port to the - * platform & operating specific object used to reference the display - * or can be used by a audio port for native audio rendering */ -typedef void* OMX_NATIVE_DEVICETYPE; - -/** OMX_NATIVE_WINDOWTYPE is used to map a OMX video port to the - * platform & operating specific object used to reference the window */ -typedef void* OMX_NATIVE_WINDOWTYPE; - -/** The OMX_VERSIONTYPE union is used to specify the version for - a structure or component. For a component, the version is entirely - specified by the component vendor. Components doing the same function - from different vendors may or may not have the same version. For - structures, the version shall be set by the entity that allocates the - structure. For structures specified in the OMX 1.1 specification, the - value of the version shall be set to 1.1.0.0 in all cases. Access to the - OMX_VERSIONTYPE can be by a single 32 bit access (e.g. by nVersion) or - by accessing one of the structure elements to, for example, check only - the Major revision. - */ -typedef union OMX_VERSIONTYPE -{ - struct - { - OMX_U8 nVersionMajor; /**< Major version accessor element */ - OMX_U8 nVersionMinor; /**< Minor version accessor element */ - OMX_U8 nRevision; /**< Revision version accessor element */ - OMX_U8 nStep; /**< Step version accessor element */ - } s; - OMX_U32 nVersion; /**< 32 bit value to make accessing the - version easily done in a single word - size copy/compare operation */ -} OMX_VERSIONTYPE; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_Video.h b/starpilot/ui/screenrecorder/openmax/include/OMX_Video.h deleted file mode 100644 index 64dbe87b4..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_Video.h +++ /dev/null @@ -1,1082 +0,0 @@ -/** - * Copyright (c) 2008 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** - * @file OMX_Video.h - OpenMax IL version 1.1.2 - * The structures is needed by Video components to exchange parameters - * and configuration data with OMX components. - */ -#ifndef OMX_Video_h -#define OMX_Video_h - -/** @defgroup video OpenMAX IL Video Domain - * @ingroup iv - * Structures for OpenMAX IL Video domain - * @{ - */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/** - * Each OMX header must include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ - -#include - - -/** - * Enumeration used to define the possible video compression codings. - * NOTE: This essentially refers to file extensions. If the coding is - * being used to specify the ENCODE type, then additional work - * must be done to configure the exact flavor of the compression - * to be used. For decode cases where the user application can - * not differentiate between MPEG-4 and H.264 bit streams, it is - * up to the codec to handle this. - */ -typedef enum OMX_VIDEO_CODINGTYPE { - OMX_VIDEO_CodingUnused, /**< Value when coding is N/A */ - OMX_VIDEO_CodingAutoDetect, /**< Autodetection of coding type */ - OMX_VIDEO_CodingMPEG2, /**< AKA: H.262 */ - OMX_VIDEO_CodingH263, /**< H.263 */ - OMX_VIDEO_CodingMPEG4, /**< MPEG-4 */ - OMX_VIDEO_CodingWMV, /**< all versions of Windows Media Video */ - OMX_VIDEO_CodingRV, /**< all versions of Real Video */ - OMX_VIDEO_CodingAVC, /**< H.264/AVC */ - OMX_VIDEO_CodingMJPEG, /**< Motion JPEG */ - OMX_VIDEO_CodingVP8, /**< Google VP8, formerly known as On2 VP8 */ - OMX_VIDEO_CodingVP9, /**< Google VP9 */ - OMX_VIDEO_CodingHEVC, /**< HEVC */ - OMX_VIDEO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_CodingMax = 0x7FFFFFFF -} OMX_VIDEO_CODINGTYPE; - - -/** - * Data structure used to define a video path. The number of Video paths for - * input and output will vary by type of the Video component. - * - * Input (aka Source) : zero Inputs, one Output, - * Splitter : one Input, 2 or more Outputs, - * Processing Element : one Input, one output, - * Mixer : 2 or more inputs, one output, - * Output (aka Sink) : one Input, zero outputs. - * - * The PortDefinition structure is used to define all of the parameters - * necessary for the compliant component to setup an input or an output video - * path. If additional vendor specific data is required, it should be - * transmitted to the component using the CustomCommand function. Compliant - * components will prepopulate this structure with optimal values during the - * GetDefaultInitParams command. - * - * STRUCT MEMBERS: - * cMIMEType : MIME type of data for the port - * pNativeRender : Platform specific reference for a display if a - * sync, otherwise this field is 0 - * nFrameWidth : Width of frame to be used on channel if - * uncompressed format is used. Use 0 for unknown, - * don't care or variable - * nFrameHeight : Height of frame to be used on channel if - * uncompressed format is used. Use 0 for unknown, - * don't care or variable - * nStride : Number of bytes per span of an image - * (i.e. indicates the number of bytes to get - * from span N to span N+1, where negative stride - * indicates the image is bottom up - * nSliceHeight : Height used when encoding in slices - * nBitrate : Bit rate of frame to be used on channel if - * compressed format is used. Use 0 for unknown, - * don't care or variable - * xFramerate : Frame rate to be used on channel if uncompressed - * format is used. Use 0 for unknown, don't care or - * variable. Units are Q16 frames per second. - * bFlagErrorConcealment : Turns on error concealment if it is supported by - * the OMX component - * eCompressionFormat : Compression format used in this instance of the - * component. When OMX_VIDEO_CodingUnused is - * specified, eColorFormat is used - * eColorFormat : Decompressed format used by this component - * pNativeWindow : Platform specific reference for a window object if a - * display sink , otherwise this field is 0x0. - */ -typedef struct OMX_VIDEO_PORTDEFINITIONTYPE { - OMX_STRING cMIMEType; - OMX_NATIVE_DEVICETYPE pNativeRender; - OMX_U32 nFrameWidth; - OMX_U32 nFrameHeight; - OMX_S32 nStride; - OMX_U32 nSliceHeight; - OMX_U32 nBitrate; - OMX_U32 xFramerate; - OMX_BOOL bFlagErrorConcealment; - OMX_VIDEO_CODINGTYPE eCompressionFormat; - OMX_COLOR_FORMATTYPE eColorFormat; - OMX_NATIVE_WINDOWTYPE pNativeWindow; -} OMX_VIDEO_PORTDEFINITIONTYPE; - -/** - * Port format parameter. This structure is used to enumerate the various - * data input/output format supported by the port. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Indicates which port to set - * nIndex : Indicates the enumeration index for the format from - * 0x0 to N-1 - * eCompressionFormat : Compression format used in this instance of the - * component. When OMX_VIDEO_CodingUnused is specified, - * eColorFormat is used - * eColorFormat : Decompressed format used by this component - * xFrameRate : Indicates the video frame rate in Q16 format - */ -typedef struct OMX_VIDEO_PARAM_PORTFORMATTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nIndex; - OMX_VIDEO_CODINGTYPE eCompressionFormat; - OMX_COLOR_FORMATTYPE eColorFormat; - OMX_U32 xFramerate; -} OMX_VIDEO_PARAM_PORTFORMATTYPE; - - -/** - * This is a structure for configuring video compression quantization - * parameter values. Codecs may support different QP values for different - * frame types. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version info - * nPortIndex : Port that this structure applies to - * nQpI : QP value to use for index frames - * nQpP : QP value to use for P frames - * nQpB : QP values to use for bidirectional frames - */ -typedef struct OMX_VIDEO_PARAM_QUANTIZATIONTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nQpI; - OMX_U32 nQpP; - OMX_U32 nQpB; -} OMX_VIDEO_PARAM_QUANTIZATIONTYPE; - - -/** - * Structure for configuration of video fast update parameters. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version info - * nPortIndex : Port that this structure applies to - * bEnableVFU : Enable/Disable video fast update - * nFirstGOB : Specifies the number of the first macroblock row - * nFirstMB : specifies the first MB relative to the specified first GOB - * nNumMBs : Specifies the number of MBs to be refreshed from nFirstGOB - * and nFirstMB - */ -typedef struct OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnableVFU; - OMX_U32 nFirstGOB; - OMX_U32 nFirstMB; - OMX_U32 nNumMBs; -} OMX_VIDEO_PARAM_VIDEOFASTUPDATETYPE; - - -/** - * Enumeration of possible bitrate control types - */ -typedef enum OMX_VIDEO_CONTROLRATETYPE { - OMX_Video_ControlRateDisable, - OMX_Video_ControlRateVariable, - OMX_Video_ControlRateConstant, - OMX_Video_ControlRateVariableSkipFrames, - OMX_Video_ControlRateConstantSkipFrames, - OMX_Video_ControlRateKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_Video_ControlRateVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_Video_ControlRateMax = 0x7FFFFFFF -} OMX_VIDEO_CONTROLRATETYPE; - - -/** - * Structure for configuring bitrate mode of a codec. - * - * STRUCT MEMBERS: - * nSize : Size of the struct in bytes - * nVersion : OMX spec version info - * nPortIndex : Port that this struct applies to - * eControlRate : Control rate type enum - * nTargetBitrate : Target bitrate to encode with - */ -typedef struct OMX_VIDEO_PARAM_BITRATETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_CONTROLRATETYPE eControlRate; - OMX_U32 nTargetBitrate; -} OMX_VIDEO_PARAM_BITRATETYPE; - - -/** - * Enumeration of possible motion vector (MV) types - */ -typedef enum OMX_VIDEO_MOTIONVECTORTYPE { - OMX_Video_MotionVectorPixel, - OMX_Video_MotionVectorHalfPel, - OMX_Video_MotionVectorQuarterPel, - OMX_Video_MotionVectorEighthPel, - OMX_Video_MotionVectorKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_Video_MotionVectorVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_Video_MotionVectorMax = 0x7FFFFFFF -} OMX_VIDEO_MOTIONVECTORTYPE; - - -/** - * Structure for configuring the number of motion vectors used as well - * as their accuracy. - * - * STRUCT MEMBERS: - * nSize : Size of the struct in bytes - * nVersion : OMX spec version info - * nPortIndex : port that this structure applies to - * eAccuracy : Enumerated MV accuracy - * bUnrestrictedMVs : Allow unrestricted MVs - * bFourMV : Allow use of 4 MVs - * sXSearchRange : Search range in horizontal direction for MVs - * sYSearchRange : Search range in vertical direction for MVs - */ -typedef struct OMX_VIDEO_PARAM_MOTIONVECTORTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_MOTIONVECTORTYPE eAccuracy; - OMX_BOOL bUnrestrictedMVs; - OMX_BOOL bFourMV; - OMX_S32 sXSearchRange; - OMX_S32 sYSearchRange; -} OMX_VIDEO_PARAM_MOTIONVECTORTYPE; - - -/** - * Enumeration of possible methods to use for Intra Refresh - */ -typedef enum OMX_VIDEO_INTRAREFRESHTYPE { - OMX_VIDEO_IntraRefreshCyclic, - OMX_VIDEO_IntraRefreshAdaptive, - OMX_VIDEO_IntraRefreshBoth, - OMX_VIDEO_IntraRefreshKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_IntraRefreshVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_IntraRefreshRandom, - OMX_VIDEO_IntraRefreshMax = 0x7FFFFFFF -} OMX_VIDEO_INTRAREFRESHTYPE; - - -/** - * Structure for configuring intra refresh mode - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eRefreshMode : Cyclic, Adaptive, or Both - * nAirMBs : Number of intra macroblocks to refresh in a frame when - * AIR is enabled - * nAirRef : Number of times a motion marked macroblock has to be - * intra coded - * nCirMBs : Number of consecutive macroblocks to be coded as "intra" - * when CIR is enabled - */ -typedef struct OMX_VIDEO_PARAM_INTRAREFRESHTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_INTRAREFRESHTYPE eRefreshMode; - OMX_U32 nAirMBs; - OMX_U32 nAirRef; - OMX_U32 nCirMBs; -} OMX_VIDEO_PARAM_INTRAREFRESHTYPE; - - -/** - * Structure for enabling various error correction methods for video - * compression. - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * bEnableHEC : Enable/disable header extension codes (HEC) - * bEnableResync : Enable/disable resynchronization markers - * nResynchMarkerSpacing : Resynch markers interval (in bits) to be - * applied in the stream - * bEnableDataPartitioning : Enable/disable data partitioning - * bEnableRVLC : Enable/disable reversible variable length - * coding - */ -typedef struct OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnableHEC; - OMX_BOOL bEnableResync; - OMX_U32 nResynchMarkerSpacing; - OMX_BOOL bEnableDataPartitioning; - OMX_BOOL bEnableRVLC; -} OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE; - - -/** - * Configuration of variable block-size motion compensation (VBSMC) - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * b16x16 : Enable inter block search 16x16 - * b16x8 : Enable inter block search 16x8 - * b8x16 : Enable inter block search 8x16 - * b8x8 : Enable inter block search 8x8 - * b8x4 : Enable inter block search 8x4 - * b4x8 : Enable inter block search 4x8 - * b4x4 : Enable inter block search 4x4 - */ -typedef struct OMX_VIDEO_PARAM_VBSMCTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL b16x16; - OMX_BOOL b16x8; - OMX_BOOL b8x16; - OMX_BOOL b8x8; - OMX_BOOL b8x4; - OMX_BOOL b4x8; - OMX_BOOL b4x4; -} OMX_VIDEO_PARAM_VBSMCTYPE; - - -/** - * H.263 profile types, each profile indicates support for various - * performance bounds and different annexes. - * - * ENUMS: - * Baseline : Baseline Profile: H.263 (V1), no optional modes - * H320 Coding : H.320 Coding Efficiency Backward Compatibility - * Profile: H.263+ (V2), includes annexes I, J, L.4 - * and T - * BackwardCompatible : Backward Compatibility Profile: H.263 (V1), - * includes annex F - * ISWV2 : Interactive Streaming Wireless Profile: H.263+ - * (V2), includes annexes I, J, K and T - * ISWV3 : Interactive Streaming Wireless Profile: H.263++ - * (V3), includes profile 3 and annexes V and W.6.3.8 - * HighCompression : Conversational High Compression Profile: H.263++ - * (V3), includes profiles 1 & 2 and annexes D and U - * Internet : Conversational Internet Profile: H.263++ (V3), - * includes profile 5 and annex K - * Interlace : Conversational Interlace Profile: H.263++ (V3), - * includes profile 5 and annex W.6.3.11 - * HighLatency : High Latency Profile: H.263++ (V3), includes - * profile 6 and annexes O.1 and P.5 - */ -typedef enum OMX_VIDEO_H263PROFILETYPE { - OMX_VIDEO_H263ProfileBaseline = 0x01, - OMX_VIDEO_H263ProfileH320Coding = 0x02, - OMX_VIDEO_H263ProfileBackwardCompatible = 0x04, - OMX_VIDEO_H263ProfileISWV2 = 0x08, - OMX_VIDEO_H263ProfileISWV3 = 0x10, - OMX_VIDEO_H263ProfileHighCompression = 0x20, - OMX_VIDEO_H263ProfileInternet = 0x40, - OMX_VIDEO_H263ProfileInterlace = 0x80, - OMX_VIDEO_H263ProfileHighLatency = 0x100, - OMX_VIDEO_H263ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_H263ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_H263ProfileMax = 0x7FFFFFFF -} OMX_VIDEO_H263PROFILETYPE; - - -/** - * H.263 level types, each level indicates support for various frame sizes, - * bit rates, decoder frame rates. - */ -typedef enum OMX_VIDEO_H263LEVELTYPE { - OMX_VIDEO_H263Level10 = 0x01, - OMX_VIDEO_H263Level20 = 0x02, - OMX_VIDEO_H263Level30 = 0x04, - OMX_VIDEO_H263Level40 = 0x08, - OMX_VIDEO_H263Level45 = 0x10, - OMX_VIDEO_H263Level50 = 0x20, - OMX_VIDEO_H263Level60 = 0x40, - OMX_VIDEO_H263Level70 = 0x80, - OMX_VIDEO_H263LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_H263LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_H263LevelMax = 0x7FFFFFFF -} OMX_VIDEO_H263LEVELTYPE; - - -/** - * Specifies the picture type. These values should be OR'd to signal all - * pictures types which are allowed. - * - * ENUMS: - * Generic Picture Types: I, P and B - * H.263 Specific Picture Types: SI and SP - * H.264 Specific Picture Types: EI and EP - * MPEG-4 Specific Picture Types: S - */ -typedef enum OMX_VIDEO_PICTURETYPE { - OMX_VIDEO_PictureTypeI = 0x01, - OMX_VIDEO_PictureTypeP = 0x02, - OMX_VIDEO_PictureTypeB = 0x04, - OMX_VIDEO_PictureTypeSI = 0x08, - OMX_VIDEO_PictureTypeSP = 0x10, - OMX_VIDEO_PictureTypeEI = 0x11, - OMX_VIDEO_PictureTypeEP = 0x12, - OMX_VIDEO_PictureTypeS = 0x14, - OMX_VIDEO_PictureTypeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_PictureTypeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_PictureTypeMax = 0x7FFFFFFF -} OMX_VIDEO_PICTURETYPE; - - -/** - * H.263 Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nPFrames : Number of P frames between each I frame - * nBFrames : Number of B frames between each I frame - * eProfile : H.263 profile(s) to use - * eLevel : H.263 level(s) to use - * bPLUSPTYPEAllowed : Indicating that it is allowed to use PLUSPTYPE - * (specified in the 1998 version of H.263) to - * indicate custom picture sizes or clock - * frequencies - * nAllowedPictureTypes : Specifies the picture types allowed in the - * bitstream - * bForceRoundingTypeToZero : value of the RTYPE bit (bit 6 of MPPTYPE) is - * not constrained. It is recommended to change - * the value of the RTYPE bit for each reference - * picture in error-free communication - * nPictureHeaderRepetition : Specifies the frequency of picture header - * repetition - * nGOBHeaderInterval : Specifies the interval of non-empty GOB - * headers in units of GOBs - */ -typedef struct OMX_VIDEO_PARAM_H263TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nPFrames; - OMX_U32 nBFrames; - OMX_VIDEO_H263PROFILETYPE eProfile; - OMX_VIDEO_H263LEVELTYPE eLevel; - OMX_BOOL bPLUSPTYPEAllowed; - OMX_U32 nAllowedPictureTypes; - OMX_BOOL bForceRoundingTypeToZero; - OMX_U32 nPictureHeaderRepetition; - OMX_U32 nGOBHeaderInterval; -} OMX_VIDEO_PARAM_H263TYPE; - - -/** - * MPEG-2 profile types, each profile indicates support for various - * performance bounds and different annexes. - */ -typedef enum OMX_VIDEO_MPEG2PROFILETYPE { - OMX_VIDEO_MPEG2ProfileSimple = 0, /**< Simple Profile */ - OMX_VIDEO_MPEG2ProfileMain, /**< Main Profile */ - OMX_VIDEO_MPEG2Profile422, /**< 4:2:2 Profile */ - OMX_VIDEO_MPEG2ProfileSNR, /**< SNR Profile */ - OMX_VIDEO_MPEG2ProfileSpatial, /**< Spatial Profile */ - OMX_VIDEO_MPEG2ProfileHigh, /**< High Profile */ - OMX_VIDEO_MPEG2ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_MPEG2ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_MPEG2ProfileMax = 0x7FFFFFFF -} OMX_VIDEO_MPEG2PROFILETYPE; - - -/** - * MPEG-2 level types, each level indicates support for various frame - * sizes, bit rates, decoder frame rates. No need - */ -typedef enum OMX_VIDEO_MPEG2LEVELTYPE { - OMX_VIDEO_MPEG2LevelLL = 0, /**< Low Level */ - OMX_VIDEO_MPEG2LevelML, /**< Main Level */ - OMX_VIDEO_MPEG2LevelH14, /**< High 1440 */ - OMX_VIDEO_MPEG2LevelHL, /**< High Level */ - OMX_VIDEO_MPEG2LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_MPEG2LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_MPEG2LevelMax = 0x7FFFFFFF -} OMX_VIDEO_MPEG2LEVELTYPE; - - -/** - * MPEG-2 params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nPFrames : Number of P frames between each I frame - * nBFrames : Number of B frames between each I frame - * eProfile : MPEG-2 profile(s) to use - * eLevel : MPEG-2 levels(s) to use - */ -typedef struct OMX_VIDEO_PARAM_MPEG2TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nPFrames; - OMX_U32 nBFrames; - OMX_VIDEO_MPEG2PROFILETYPE eProfile; - OMX_VIDEO_MPEG2LEVELTYPE eLevel; -} OMX_VIDEO_PARAM_MPEG2TYPE; - - -/** - * MPEG-4 profile types, each profile indicates support for various - * performance bounds and different annexes. - * - * ENUMS: - * - Simple Profile, Levels 1-3 - * - Simple Scalable Profile, Levels 1-2 - * - Core Profile, Levels 1-2 - * - Main Profile, Levels 2-4 - * - N-bit Profile, Level 2 - * - Scalable Texture Profile, Level 1 - * - Simple Face Animation Profile, Levels 1-2 - * - Simple Face and Body Animation (FBA) Profile, Levels 1-2 - * - Basic Animated Texture Profile, Levels 1-2 - * - Hybrid Profile, Levels 1-2 - * - Advanced Real Time Simple Profiles, Levels 1-4 - * - Core Scalable Profile, Levels 1-3 - * - Advanced Coding Efficiency Profile, Levels 1-4 - * - Advanced Core Profile, Levels 1-2 - * - Advanced Scalable Texture, Levels 2-3 - */ -typedef enum OMX_VIDEO_MPEG4PROFILETYPE { - OMX_VIDEO_MPEG4ProfileSimple = 0x01, - OMX_VIDEO_MPEG4ProfileSimpleScalable = 0x02, - OMX_VIDEO_MPEG4ProfileCore = 0x04, - OMX_VIDEO_MPEG4ProfileMain = 0x08, - OMX_VIDEO_MPEG4ProfileNbit = 0x10, - OMX_VIDEO_MPEG4ProfileScalableTexture = 0x20, - OMX_VIDEO_MPEG4ProfileSimpleFace = 0x40, - OMX_VIDEO_MPEG4ProfileSimpleFBA = 0x80, - OMX_VIDEO_MPEG4ProfileBasicAnimated = 0x100, - OMX_VIDEO_MPEG4ProfileHybrid = 0x200, - OMX_VIDEO_MPEG4ProfileAdvancedRealTime = 0x400, - OMX_VIDEO_MPEG4ProfileCoreScalable = 0x800, - OMX_VIDEO_MPEG4ProfileAdvancedCoding = 0x1000, - OMX_VIDEO_MPEG4ProfileAdvancedCore = 0x2000, - OMX_VIDEO_MPEG4ProfileAdvancedScalable = 0x4000, - OMX_VIDEO_MPEG4ProfileAdvancedSimple = 0x8000, - OMX_VIDEO_MPEG4ProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_MPEG4ProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_MPEG4ProfileMax = 0x7FFFFFFF -} OMX_VIDEO_MPEG4PROFILETYPE; - - -/** - * MPEG-4 level types, each level indicates support for various frame - * sizes, bit rates, decoder frame rates. No need - */ -typedef enum OMX_VIDEO_MPEG4LEVELTYPE { - OMX_VIDEO_MPEG4Level0 = 0x01, /**< Level 0 */ - OMX_VIDEO_MPEG4Level0b = 0x02, /**< Level 0b */ - OMX_VIDEO_MPEG4Level1 = 0x04, /**< Level 1 */ - OMX_VIDEO_MPEG4Level2 = 0x08, /**< Level 2 */ - OMX_VIDEO_MPEG4Level3 = 0x10, /**< Level 3 */ - OMX_VIDEO_MPEG4Level4 = 0x20, /**< Level 4 */ - OMX_VIDEO_MPEG4Level4a = 0x40, /**< Level 4a */ - OMX_VIDEO_MPEG4Level5 = 0x80, /**< Level 5 */ - OMX_VIDEO_MPEG4LevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_MPEG4LevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_MPEG4LevelMax = 0x7FFFFFFF -} OMX_VIDEO_MPEG4LEVELTYPE; - - -/** - * MPEG-4 configuration. This structure handles configuration options - * which are specific to MPEG4 algorithms - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nSliceHeaderSpacing : Number of macroblocks between slice header (H263+ - * Annex K). Put zero if not used - * bSVH : Enable Short Video Header mode - * bGov : Flag to enable GOV - * nPFrames : Number of P frames between each I frame (also called - * GOV period) - * nBFrames : Number of B frames between each I frame - * nIDCVLCThreshold : Value of intra DC VLC threshold - * bACPred : Flag to use ac prediction - * nMaxPacketSize : Maximum size of packet in bytes. - * nTimeIncRes : Used to pass VOP time increment resolution for MPEG4. - * Interpreted as described in MPEG4 standard. - * eProfile : MPEG-4 profile(s) to use. - * eLevel : MPEG-4 level(s) to use. - * nAllowedPictureTypes : Specifies the picture types allowed in the bitstream - * nHeaderExtension : Specifies the number of consecutive video packet - * headers within a VOP - * bReversibleVLC : Specifies whether reversible variable length coding - * is in use - */ -typedef struct OMX_VIDEO_PARAM_MPEG4TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nSliceHeaderSpacing; - OMX_BOOL bSVH; - OMX_BOOL bGov; - OMX_U32 nPFrames; - OMX_U32 nBFrames; - OMX_U32 nIDCVLCThreshold; - OMX_BOOL bACPred; - OMX_U32 nMaxPacketSize; - OMX_U32 nTimeIncRes; - OMX_VIDEO_MPEG4PROFILETYPE eProfile; - OMX_VIDEO_MPEG4LEVELTYPE eLevel; - OMX_U32 nAllowedPictureTypes; - OMX_U32 nHeaderExtension; - OMX_BOOL bReversibleVLC; -} OMX_VIDEO_PARAM_MPEG4TYPE; - - -/** - * WMV Versions - */ -typedef enum OMX_VIDEO_WMVFORMATTYPE { - OMX_VIDEO_WMVFormatUnused = 0x01, /**< Format unused or unknown */ - OMX_VIDEO_WMVFormat7 = 0x02, /**< Windows Media Video format 7 */ - OMX_VIDEO_WMVFormat8 = 0x04, /**< Windows Media Video format 8 */ - OMX_VIDEO_WMVFormat9 = 0x08, /**< Windows Media Video format 9 */ - OMX_VIDEO_WMFFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_WMFFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_WMVFormatMax = 0x7FFFFFFF -} OMX_VIDEO_WMVFORMATTYPE; - - -/** - * WMV Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFormat : Version of WMV stream / data - */ -typedef struct OMX_VIDEO_PARAM_WMVTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_WMVFORMATTYPE eFormat; -} OMX_VIDEO_PARAM_WMVTYPE; - - -/** - * Real Video Version - */ -typedef enum OMX_VIDEO_RVFORMATTYPE { - OMX_VIDEO_RVFormatUnused = 0, /**< Format unused or unknown */ - OMX_VIDEO_RVFormat8, /**< Real Video format 8 */ - OMX_VIDEO_RVFormat9, /**< Real Video format 9 */ - OMX_VIDEO_RVFormatG2, /**< Real Video Format G2 */ - OMX_VIDEO_RVFormatKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_RVFormatVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_RVFormatMax = 0x7FFFFFFF -} OMX_VIDEO_RVFORMATTYPE; - - -/** - * Real Video Params - * - * STUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * eFormat : Version of RV stream / data - * nBitsPerPixel : Bits per pixel coded in the frame - * nPaddedWidth : Padded width in pixel of a video frame - * nPaddedHeight : Padded Height in pixels of a video frame - * nFrameRate : Rate of video in frames per second - * nBitstreamFlags : Flags which internal information about the bitstream - * nBitstreamVersion : Bitstream version - * nMaxEncodeFrameSize: Max encoded frame size - * bEnablePostFilter : Turn on/off post filter - * bEnableTemporalInterpolation : Turn on/off temporal interpolation - * bEnableLatencyMode : When enabled, the decoder does not display a decoded - * frame until it has detected that no enhancement layer - * frames or dependent B frames will be coming. This - * detection usually occurs when a subsequent non-B - * frame is encountered - */ -typedef struct OMX_VIDEO_PARAM_RVTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_RVFORMATTYPE eFormat; - OMX_U16 nBitsPerPixel; - OMX_U16 nPaddedWidth; - OMX_U16 nPaddedHeight; - OMX_U32 nFrameRate; - OMX_U32 nBitstreamFlags; - OMX_U32 nBitstreamVersion; - OMX_U32 nMaxEncodeFrameSize; - OMX_BOOL bEnablePostFilter; - OMX_BOOL bEnableTemporalInterpolation; - OMX_BOOL bEnableLatencyMode; -} OMX_VIDEO_PARAM_RVTYPE; - - -/** - * AVC profile types, each profile indicates support for various - * performance bounds and different annexes. - */ -typedef enum OMX_VIDEO_AVCPROFILETYPE { - OMX_VIDEO_AVCProfileBaseline = 0x01, /**< Baseline profile */ - OMX_VIDEO_AVCProfileMain = 0x02, /**< Main profile */ - OMX_VIDEO_AVCProfileExtended = 0x04, /**< Extended profile */ - OMX_VIDEO_AVCProfileHigh = 0x08, /**< High profile */ - OMX_VIDEO_AVCProfileHigh10 = 0x10, /**< High 10 profile */ - OMX_VIDEO_AVCProfileHigh422 = 0x20, /**< High 4:2:2 profile */ - OMX_VIDEO_AVCProfileHigh444 = 0x40, /**< High 4:4:4 profile */ - OMX_VIDEO_AVCProfileKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_AVCProfileVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_AVCProfileMax = 0x7FFFFFFF -} OMX_VIDEO_AVCPROFILETYPE; - - -/** - * AVC level types, each level indicates support for various frame sizes, - * bit rates, decoder frame rates. No need - */ -typedef enum OMX_VIDEO_AVCLEVELTYPE { - OMX_VIDEO_AVCLevel1 = 0x01, /**< Level 1 */ - OMX_VIDEO_AVCLevel1b = 0x02, /**< Level 1b */ - OMX_VIDEO_AVCLevel11 = 0x04, /**< Level 1.1 */ - OMX_VIDEO_AVCLevel12 = 0x08, /**< Level 1.2 */ - OMX_VIDEO_AVCLevel13 = 0x10, /**< Level 1.3 */ - OMX_VIDEO_AVCLevel2 = 0x20, /**< Level 2 */ - OMX_VIDEO_AVCLevel21 = 0x40, /**< Level 2.1 */ - OMX_VIDEO_AVCLevel22 = 0x80, /**< Level 2.2 */ - OMX_VIDEO_AVCLevel3 = 0x100, /**< Level 3 */ - OMX_VIDEO_AVCLevel31 = 0x200, /**< Level 3.1 */ - OMX_VIDEO_AVCLevel32 = 0x400, /**< Level 3.2 */ - OMX_VIDEO_AVCLevel4 = 0x800, /**< Level 4 */ - OMX_VIDEO_AVCLevel41 = 0x1000, /**< Level 4.1 */ - OMX_VIDEO_AVCLevel42 = 0x2000, /**< Level 4.2 */ - OMX_VIDEO_AVCLevel5 = 0x4000, /**< Level 5 */ - OMX_VIDEO_AVCLevel51 = 0x8000, /**< Level 5.1 */ - OMX_VIDEO_AVCLevel52 = 0x10000, /**< Level 5.2 */ - OMX_VIDEO_AVCLevelKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_AVCLevelVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_AVCLevelMax = 0x7FFFFFFF -} OMX_VIDEO_AVCLEVELTYPE; - - -/** - * AVC loop filter modes - * - * OMX_VIDEO_AVCLoopFilterEnable : Enable - * OMX_VIDEO_AVCLoopFilterDisable : Disable - * OMX_VIDEO_AVCLoopFilterDisableSliceBoundary : Disabled on slice boundaries - */ -typedef enum OMX_VIDEO_AVCLOOPFILTERTYPE { - OMX_VIDEO_AVCLoopFilterEnable = 0, - OMX_VIDEO_AVCLoopFilterDisable, - OMX_VIDEO_AVCLoopFilterDisableSliceBoundary, - OMX_VIDEO_AVCLoopFilterKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_AVCLoopFilterVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_AVCLoopFilterMax = 0x7FFFFFFF -} OMX_VIDEO_AVCLOOPFILTERTYPE; - - -/** - * AVC params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nSliceHeaderSpacing : Number of macroblocks between slice header, put - * zero if not used - * nPFrames : Number of P frames between each I frame - * nBFrames : Number of B frames between each I frame - * bUseHadamard : Enable/disable Hadamard transform - * nRefFrames : Max number of reference frames to use for inter - * motion search (1-16) - * nRefIdxTrailing : Pic param set ref frame index (index into ref - * frame buffer of trailing frames list), B frame - * support - * nRefIdxForward : Pic param set ref frame index (index into ref - * frame buffer of forward frames list), B frame - * support - * bEnableUEP : Enable/disable unequal error protection. This - * is only valid of data partitioning is enabled. - * bEnableFMO : Enable/disable flexible macroblock ordering - * bEnableASO : Enable/disable arbitrary slice ordering - * bEnableRS : Enable/disable sending of redundant slices - * eProfile : AVC profile(s) to use - * eLevel : AVC level(s) to use - * nAllowedPictureTypes : Specifies the picture types allowed in the - * bitstream - * bFrameMBsOnly : specifies that every coded picture of the - * coded video sequence is a coded frame - * containing only frame macroblocks - * bMBAFF : Enable/disable switching between frame and - * field macroblocks within a picture - * bEntropyCodingCABAC : Entropy decoding method to be applied for the - * syntax elements for which two descriptors appear - * in the syntax tables - * bWeightedPPrediction : Enable/disable weighted prediction shall not - * be applied to P and SP slices - * nWeightedBipredicitonMode : Default weighted prediction is applied to B - * slices - * bconstIpred : Enable/disable intra prediction - * bDirect8x8Inference : Specifies the method used in the derivation - * process for luma motion vectors for B_Skip, - * B_Direct_16x16 and B_Direct_8x8 as specified - * in subclause 8.4.1.2 of the AVC spec - * bDirectSpatialTemporal : Flag indicating spatial or temporal direct - * mode used in B slice coding (related to - * bDirect8x8Inference) . Spatial direct mode is - * more common and should be the default. - * nCabacInitIdx : Index used to init CABAC contexts - * eLoopFilterMode : Enable/disable loop filter - */ -typedef struct OMX_VIDEO_PARAM_AVCTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nSliceHeaderSpacing; - OMX_U32 nPFrames; - OMX_U32 nBFrames; - OMX_BOOL bUseHadamard; - OMX_U32 nRefFrames; - OMX_U32 nRefIdx10ActiveMinus1; - OMX_U32 nRefIdx11ActiveMinus1; - OMX_BOOL bEnableUEP; - OMX_BOOL bEnableFMO; - OMX_BOOL bEnableASO; - OMX_BOOL bEnableRS; - OMX_VIDEO_AVCPROFILETYPE eProfile; - OMX_VIDEO_AVCLEVELTYPE eLevel; - OMX_U32 nAllowedPictureTypes; - OMX_BOOL bFrameMBsOnly; - OMX_BOOL bMBAFF; - OMX_BOOL bEntropyCodingCABAC; - OMX_BOOL bWeightedPPrediction; - OMX_U32 nWeightedBipredicitonMode; - OMX_BOOL bconstIpred ; - OMX_BOOL bDirect8x8Inference; - OMX_BOOL bDirectSpatialTemporal; - OMX_U32 nCabacInitIdc; - OMX_VIDEO_AVCLOOPFILTERTYPE eLoopFilterMode; -} OMX_VIDEO_PARAM_AVCTYPE; - -typedef struct OMX_VIDEO_PARAM_PROFILELEVELTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 eProfile; /**< type is OMX_VIDEO_AVCPROFILETYPE, OMX_VIDEO_H263PROFILETYPE, - or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ - OMX_U32 eLevel; /**< type is OMX_VIDEO_AVCLEVELTYPE, OMX_VIDEO_H263LEVELTYPE, - or OMX_VIDEO_MPEG4PROFILETYPE depending on context */ - OMX_U32 nProfileIndex; /**< Used to query for individual profile support information, - This parameter is valid only for - OMX_IndexParamVideoProfileLevelQuerySupported index, - For all other indices this parameter is to be ignored. */ -} OMX_VIDEO_PARAM_PROFILELEVELTYPE; - -/** - * Structure for dynamically configuring bitrate mode of a codec. - * - * STRUCT MEMBERS: - * nSize : Size of the struct in bytes - * nVersion : OMX spec version info - * nPortIndex : Port that this struct applies to - * nEncodeBitrate : Target average bitrate to be generated in bps - */ -typedef struct OMX_VIDEO_CONFIG_BITRATETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nEncodeBitrate; -} OMX_VIDEO_CONFIG_BITRATETYPE; - -/** - * Defines Encoder Frame Rate setting - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * xEncodeFramerate : Encoding framerate represented in Q16 format - */ -typedef struct OMX_CONFIG_FRAMERATETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 xEncodeFramerate; /* Q16 format */ -} OMX_CONFIG_FRAMERATETYPE; - -typedef struct OMX_CONFIG_INTRAREFRESHVOPTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL IntraRefreshVOP; -} OMX_CONFIG_INTRAREFRESHVOPTYPE; - -typedef struct OMX_CONFIG_MACROBLOCKERRORMAPTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nErrMapSize; /* Size of the Error Map in bytes */ - OMX_U8 ErrMap[1]; /* Error map hint */ -} OMX_CONFIG_MACROBLOCKERRORMAPTYPE; - -typedef struct OMX_CONFIG_MBERRORREPORTINGTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bEnabled; -} OMX_CONFIG_MBERRORREPORTINGTYPE; - -typedef struct OMX_PARAM_MACROBLOCKSTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nMacroblocks; -} OMX_PARAM_MACROBLOCKSTYPE; - -/** - * AVC Slice Mode modes - * - * OMX_VIDEO_SLICEMODE_AVCDefault : Normal frame encoding, one slice per frame - * OMX_VIDEO_SLICEMODE_AVCMBSlice : NAL mode, number of MBs per frame - * OMX_VIDEO_SLICEMODE_AVCByteSlice : NAL mode, number of bytes per frame - */ -typedef enum OMX_VIDEO_AVCSLICEMODETYPE { - OMX_VIDEO_SLICEMODE_AVCDefault = 0, - OMX_VIDEO_SLICEMODE_AVCMBSlice, - OMX_VIDEO_SLICEMODE_AVCByteSlice, - OMX_VIDEO_SLICEMODE_AVCKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ - OMX_VIDEO_SLICEMODE_AVCVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */ - OMX_VIDEO_SLICEMODE_AVCLevelMax = 0x7FFFFFFF -} OMX_VIDEO_AVCSLICEMODETYPE; - -/** - * AVC FMO Slice Mode Params - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nNumSliceGroups : Specifies the number of slice groups - * nSliceGroupMapType : Specifies the type of slice groups - * eSliceMode : Specifies the type of slice - */ -typedef struct OMX_VIDEO_PARAM_AVCSLICEFMO { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U8 nNumSliceGroups; - OMX_U8 nSliceGroupMapType; - OMX_VIDEO_AVCSLICEMODETYPE eSliceMode; -} OMX_VIDEO_PARAM_AVCSLICEFMO; - -/** - * AVC IDR Period Configs - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nIDRPeriod : Specifies periodicity of IDR frames - * nPFrames : Specifies internal of coding Intra frames - */ -typedef struct OMX_VIDEO_CONFIG_AVCINTRAPERIOD { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nIDRPeriod; - OMX_U32 nPFrames; -} OMX_VIDEO_CONFIG_AVCINTRAPERIOD; - -/** - * AVC NAL Size Configs - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nNaluBytes : Specifies the NAL unit size - */ -typedef struct OMX_VIDEO_CONFIG_NALSIZE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nNaluBytes; -} OMX_VIDEO_CONFIG_NALSIZE; - - -/** - * Deinterlace Config - * - * STRUCT MEMBERS: - * nSize : Size of the structure in bytes - * nVersion : OMX specification version information - * nPortIndex : Port that this structure applies to - * nEnable : Specifies to enable deinterlace - */ -typedef struct OMX_VIDEO_CONFIG_DEINTERLACE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_U32 nEnable; -} OMX_VIDEO_CONFIG_DEINTERLACE; - -/** @} */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -/* File EOF */ - diff --git a/starpilot/ui/screenrecorder/openmax/include/OMX_VideoExt.h b/starpilot/ui/screenrecorder/openmax/include/OMX_VideoExt.h deleted file mode 100644 index 5bf6fd487..000000000 --- a/starpilot/ui/screenrecorder/openmax/include/OMX_VideoExt.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2010 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject - * to the following conditions: - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** OMX_VideoExt.h - OpenMax IL version 1.1.2 - * The OMX_VideoExt header file contains extensions to the - * definitions used by both the application and the component to - * access video items. - */ - -#ifndef OMX_VideoExt_h -#define OMX_VideoExt_h - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Each OMX header shall include all required header files to allow the - * header to compile without errors. The includes below are required - * for this header file to compile successfully - */ -#include - -/** NALU Formats */ -typedef enum OMX_NALUFORMATSTYPE { - OMX_NaluFormatStartCodes = 1, - OMX_NaluFormatOneNaluPerBuffer = 2, - OMX_NaluFormatOneByteInterleaveLength = 4, - OMX_NaluFormatTwoByteInterleaveLength = 8, - OMX_NaluFormatFourByteInterleaveLength = 16, - OMX_NaluFormatCodingMax = 0x7FFFFFFF -} OMX_NALUFORMATSTYPE; - -/** NAL Stream Format */ -typedef struct OMX_NALSTREAMFORMATTYPE{ - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_NALUFORMATSTYPE eNaluFormat; -} OMX_NALSTREAMFORMATTYPE; - -/** VP8 profiles */ -typedef enum OMX_VIDEO_VP8PROFILETYPE { - OMX_VIDEO_VP8ProfileMain = 0x01, - OMX_VIDEO_VP8ProfileUnknown = 0x6EFFFFFF, - OMX_VIDEO_VP8ProfileMax = 0x7FFFFFFF -} OMX_VIDEO_VP8PROFILETYPE; - -/** VP8 levels */ -typedef enum OMX_VIDEO_VP8LEVELTYPE { - OMX_VIDEO_VP8Level_Version0 = 0x01, - OMX_VIDEO_VP8Level_Version1 = 0x02, - OMX_VIDEO_VP8Level_Version2 = 0x04, - OMX_VIDEO_VP8Level_Version3 = 0x08, - OMX_VIDEO_VP8LevelUnknown = 0x6EFFFFFF, - OMX_VIDEO_VP8LevelMax = 0x7FFFFFFF -} OMX_VIDEO_VP8LEVELTYPE; - -/** VP8 Param */ -typedef struct OMX_VIDEO_PARAM_VP8TYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_VP8PROFILETYPE eProfile; - OMX_VIDEO_VP8LEVELTYPE eLevel; - OMX_U32 nDCTPartitions; - OMX_BOOL bErrorResilientMode; -} OMX_VIDEO_PARAM_VP8TYPE; - -/** Structure for configuring VP8 reference frames */ -typedef struct OMX_VIDEO_VP8REFERENCEFRAMETYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bPreviousFrameRefresh; - OMX_BOOL bGoldenFrameRefresh; - OMX_BOOL bAlternateFrameRefresh; - OMX_BOOL bUsePreviousFrame; - OMX_BOOL bUseGoldenFrame; - OMX_BOOL bUseAlternateFrame; -} OMX_VIDEO_VP8REFERENCEFRAMETYPE; - -/** Structure for querying VP8 reference frame type */ -typedef struct OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_BOOL bIsIntraFrame; - OMX_BOOL bIsGoldenOrAlternateFrame; -} OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE; - -/** HEVC Profiles */ -typedef enum OMX_VIDEO_HEVCPROFILETYPE { - OMX_VIDEO_HEVCProfileMain = 0x01, - OMX_VIDEO_HEVCProfileMain10 = 0x02, - OMX_VIDEO_HEVCProfileUnknown = 0x6EFFFFFF, - OMX_VIDEO_HEVCProfileMax = 0x7FFFFFFF -} OMX_VIDEO_HEVCPROFILETYPE; - -/** HEVC levels */ -typedef enum OMX_VIDEO_HEVCLEVELTYPE { - OMX_VIDEO_HEVCLevel_Version0 = 0x0, - OMX_VIDEO_HEVCMainTierLevel1 = 0x1, - OMX_VIDEO_HEVCHighTierLevel1 = 0x2, - OMX_VIDEO_HEVCMainTierLevel2 = 0x4, - OMX_VIDEO_HEVCHighTierLevel2 = 0x8, - OMX_VIDEO_HEVCMainTierLevel21 = 0x10, - OMX_VIDEO_HEVCHighTierLevel21 = 0x20, - OMX_VIDEO_HEVCMainTierLevel3 = 0x40, - OMX_VIDEO_HEVCHighTierLevel3 = 0x80, - OMX_VIDEO_HEVCMainTierLevel31 = 0x100, - OMX_VIDEO_HEVCHighTierLevel31 = 0x200, - OMX_VIDEO_HEVCMainTierLevel4 = 0x400, - OMX_VIDEO_HEVCHighTierLevel4 = 0x800, - OMX_VIDEO_HEVCMainTierLevel41 = 0x1000, - OMX_VIDEO_HEVCHighTierLevel41 = 0x2000, - OMX_VIDEO_HEVCMainTierLevel5 = 0x4000, - OMX_VIDEO_HEVCHighTierLevel5 = 0x8000, - OMX_VIDEO_HEVCMainTierLevel51 = 0x10000, - OMX_VIDEO_HEVCHighTierLevel51 = 0x20000, - OMX_VIDEO_HEVCMainTierLevel52 = 0x40000, - OMX_VIDEO_HEVCHighTierLevel52 = 0x80000, - OMX_VIDEO_HEVCMainTierLevel6 = 0x100000, - OMX_VIDEO_HEVCHighTierLevel6 = 0x200000, - OMX_VIDEO_HEVCMainTierLevel61 = 0x400000, - OMX_VIDEO_HEVCHighTierLevel61 = 0x800000, - OMX_VIDEO_HEVCMainTierLevel62 = 0x1000000, - OMX_VIDEO_HEVCLevelUnknown = 0x6EFFFFFF, - OMX_VIDEO_HEVCLevelMax = 0x7FFFFFFF -} OMX_VIDEO_HEVCLEVELTYPE; - -/** HEVC Param */ -typedef struct OMX_VIDEO_PARAM_HEVCTYPE { - OMX_U32 nSize; - OMX_VERSIONTYPE nVersion; - OMX_U32 nPortIndex; - OMX_VIDEO_HEVCPROFILETYPE eProfile; - OMX_VIDEO_HEVCLEVELTYPE eLevel; -} OMX_VIDEO_PARAM_HEVCTYPE; - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* OMX_VideoExt_h */ -/* File EOF */ diff --git a/starpilot/ui/screenrecorder/screenrecorder.cc b/starpilot/ui/screenrecorder/screenrecorder.cc deleted file mode 100644 index 5a47698c9..000000000 --- a/starpilot/ui/screenrecorder/screenrecorder.cc +++ /dev/null @@ -1,151 +0,0 @@ -#include "libyuv.h" - -#include "selfdrive/ui/qt/util.h" - -#include "starpilot/ui/screenrecorder/screenrecorder.h" - -constexpr int BITRATE = 8 * 1024 * 1024; -constexpr int MAX_DURATION = 1000 * 60 * 5; -constexpr int SCREEN_WIDTH = 2160; -constexpr int SCREEN_HEIGHT = 1080; - -const QDir RECORDINGS_FOLDER("/data/media/screen_recordings"); - -ScreenRecorder::ScreenRecorder(QWidget *parent) : QPushButton(parent) { - setFixedSize(btn_size, btn_size); - - rootWidget = topWidget(this); - - QObject::connect(this, &QPushButton::clicked, this, &ScreenRecorder::toggleRecording); - QObject::connect(uiState(), &UIState::offroadTransition, this, &ScreenRecorder::stopRecording); - QObject::connect(uiState(), &UIState::uiUpdate, this, &ScreenRecorder::updateState); -} - -void ScreenRecorder::updateState() { - if (!recording) { - return; - } - - if (QDateTime::currentMSecsSinceEpoch() - startedTime > MAX_DURATION) { - stopRecording(); - startRecording(); - return; - } - - if (captureBuffer.size() != QSize(SCREEN_WIDTH, SCREEN_HEIGHT)) { - captureBuffer = QImage(SCREEN_WIDTH, SCREEN_HEIGHT, QImage::Format_RGBA8888); - } - - QPainter p(&captureBuffer); - rootWidget->render(&p); - p.end(); - - imageQueue.push(QImage(captureBuffer)); -} - -void ScreenRecorder::toggleRecording() { - recording ? stopRecording() : startRecording(); -} - -void ScreenRecorder::startRecording() { - encoder = std::make_unique( - RECORDINGS_FOLDER.path().toStdString().c_str(), - SCREEN_WIDTH, - SCREEN_HEIGHT, - UI_FREQ, - BITRATE - ); - encoder->encoder_open((QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss").toStdString() + ".mp4").c_str()); - - if (!encoder->is_open) { - encoder.reset(); - return; - } - - recording = true; - - startedTime = QDateTime::currentMSecsSinceEpoch(); - - imageQueue.clear(); - - encodingThread = std::thread(&ScreenRecorder::encodeImage, this); - - update(); -} - -void ScreenRecorder::stopRecording() { - if (!recording) { - return; - } - - recording = false; - - if (encodingThread.joinable()) { - encodingThread.join(); - } - - if (encoder) { - encoder->encoder_close(); - encoder.reset(); - } - - update(); -} - -void ScreenRecorder::encodeImage() { - while (recording) { - QImage image; - if (imageQueue.pop_wait_for(image, std::chrono::milliseconds(1000))) { - uint64_t currentTimestamp = nanos_since_boot(); - - if (image.format() != QImage::Format_RGBA8888) { - image = image.convertToFormat(QImage::Format_RGBA8888); - } - - const uint8_t *bits = image.constBits(); - if (bits) { - encoder->encode_frame_rgba(bits, SCREEN_WIDTH, SCREEN_HEIGHT, currentTimestamp); - } - } - } -} - -void ScreenRecorder::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); - - if (recording) { - qint64 elapsed = QDateTime::currentMSecsSinceEpoch() - startedTime; - - qreal phase = (elapsed % 2000) / 2000.0 * 2 * M_PI; - qreal alphaFactor = 0.5 + 0.5 * sin(phase); - - QColor glowColor = redColor(); - glowColor.setAlphaF(0.3 + 0.7 * alphaFactor); - - int glowWidth = 8 + static_cast(2 * alphaFactor); - - p.setBrush(blackColor(166)); - p.setFont(InterFont(25, QFont::Bold)); - p.setPen(QPen(glowColor, glowWidth)); - } else { - p.setBrush(blackColor(166)); - p.setFont(InterFont(25, QFont::DemiBold)); - p.setPen(QPen(redColor(), 8)); - } - - int centeringOffset = 10; - - QRect buttonRect(centeringOffset, btn_size / 3, btn_size - centeringOffset * 2, btn_size / 3); - p.drawRoundedRect(buttonRect, 24, 24); - - QRect textRect = buttonRect.adjusted(centeringOffset, 0, -centeringOffset, 0); - p.setPen(QPen(whiteColor(), 6)); - p.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, recording ? tr("RECORDING") : tr("RECORD")); - - if (!recording) { - p.setBrush(redColor(166)); - p.setPen(Qt::NoPen); - p.drawEllipse(QPoint(buttonRect.right() - btn_size / 10 - centeringOffset, buttonRect.center().y()), btn_size / 10, btn_size / 10); - } -} diff --git a/starpilot/ui/screenrecorder/screenrecorder.h b/starpilot/ui/screenrecorder/screenrecorder.h deleted file mode 100644 index f7b49351b..000000000 --- a/starpilot/ui/screenrecorder/screenrecorder.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include "omx_encoder.h" -#include "blocking_queue.h" - -#include "selfdrive/ui/qt/onroad/buttons.h" - -class ScreenRecorder : public QPushButton { - Q_OBJECT - -public: - explicit ScreenRecorder(QWidget *parent = nullptr); - - void startRecording(); - void stopRecording(); - -protected: - void paintEvent(QPaintEvent *event) override; - -private slots: - void toggleRecording(); - -private: - void encodeImage(); - void updateState(); - - bool recording; - - qint64 startedTime; - - std::thread encodingThread; - - std::unique_ptr encoder; - - BlockingQueue imageQueue{UI_FREQ}; - - QColor blackColor(int alpha = 255) { return QColor(0, 0, 0, alpha); } - QColor redColor(int alpha = 255) { return QColor(201, 34, 49, alpha); } - QColor whiteColor(int alpha = 255) { return QColor(255, 255, 255, alpha); } - - QImage captureBuffer; - - QWidget *rootWidget; -}; diff --git a/starpilot/ui/starpilot_ui.cc b/starpilot/ui/starpilot_ui.cc deleted file mode 100644 index 643c8ed0c..000000000 --- a/starpilot/ui/starpilot_ui.cc +++ /dev/null @@ -1,124 +0,0 @@ -#include "starpilot/ui/starpilot_ui.h" - -#include -#include - -#include -#include - -#include "system/hardware/hw.h" - -static void update_state(StarPilotUIState *fs) { - StarPilotUIScene &starpilot_scene = fs->starpilot_scene; - - SubMaster &fpsm = *(fs->sm); - fpsm.update(0); - - const char *desktop_fake_wifi_env = std::getenv("SP_ALLOW_DESKTOP_FAKE_WIFI"); - const bool desktop_force_online = Hardware::PC() && desktop_fake_wifi_env != nullptr && std::string(desktop_fake_wifi_env) != "0"; - if (desktop_force_online) { - starpilot_scene.online = true; - } - - if (fpsm.updated("deviceState")) { - const cereal::DeviceState::Reader &deviceState = fpsm["deviceState"].getDeviceState(); - if (!desktop_force_online) { - starpilot_scene.online = deviceState.getNetworkType() != cereal::DeviceState::NetworkType::NONE; - } - } - starpilot_scene.switchback_mode_enabled = fs->params_memory.getBool("SwitchbackModeEnabled"); - - if (fpsm.updated("starpilotCarState")) { - const cereal::StarPilotCarState::Reader &starpilotCarState = fpsm["starpilotCarState"].getStarpilotCarState(); - starpilot_scene.always_on_lateral_active = !starpilot_scene.enabled && starpilotCarState.getAlwaysOnLateralEnabled(); - starpilot_scene.traffic_mode_enabled = starpilotCarState.getTrafficModeEnabled(); - } - if (fpsm.updated("starpilotPlan")) { - const cereal::StarPilotPlan::Reader &starpilotPlan = fpsm["starpilotPlan"].getStarpilotPlan(); - if (starpilotPlan.getThemeUpdated()) { - emit fs->themeUpdated(); - } - capnp::Text::Reader toggles = starpilotPlan.getStarpilotToggles(); - QByteArray current_toggles(toggles.cStr(), toggles.size()); - // starpilot_process only broadcasts the full toggles JSON periodically and - // sends an empty string on every other frame. Skip the empty broadcasts so - // we don't parse "" (QJsonParseError "illegal value") every frame. - if (!current_toggles.trimmed().isEmpty()) { - static QByteArray previous_toggles; - if (previous_toggles != current_toggles) { - QJsonParseError parse_error; - QJsonDocument toggles_doc = QJsonDocument::fromJson(current_toggles, &parse_error); - if (parse_error.error == QJsonParseError::NoError && toggles_doc.isObject()) { - QJsonObject updated_toggles = starpilot_scene.starpilot_toggles; - const QJsonObject parsed_toggles = toggles_doc.object(); - for (auto it = parsed_toggles.begin(); it != parsed_toggles.end(); ++it) { - updated_toggles.insert(it.key(), it.value()); - } - starpilot_scene.starpilot_toggles = updated_toggles; - } else { - qWarning() << "Ignoring invalid StarPilot toggles JSON:" << parse_error.errorString(); - } - previous_toggles = current_toggles; - } - } - } - - // Keep force drive-state toggles authoritative from params so UI state - // switches immediately even if starpilotPlan is delayed. - starpilot_scene.starpilot_toggles["force_offroad"] = fs->params.getBool("ForceOffroad"); - starpilot_scene.starpilot_toggles["force_onroad"] = fs->params.getBool("ForceOnroad"); - - if (fpsm.updated("selfdriveState")) { - const cereal::SelfdriveState::Reader &selfdriveState = fpsm["selfdriveState"].getSelfdriveState(); - starpilot_scene.enabled = selfdriveState.getEnabled(); - } -} - -StarPilotUIState::StarPilotUIState(QObject *parent) : QObject(parent) { - sm = std::make_unique>({ - "carControl", "deviceState", "starpilotCarState", "starpilotDeviceState", - "starpilotPlan", "starpilotRadarState", "starpilotSelfdriveState", "liveDelay", - "liveParameters", "liveTorqueParameters", "liveTracks", "mapdExtendedOut", "mapdOut", "selfdriveState" - }); - - // Provide sane local defaults until starpilotPlan publishes real toggles. - starpilot_scene.starpilot_toggles = { - {"debug_mode", false}, - {"driver_camera_in_reverse", false}, - {"force_offroad", false}, - {"force_onroad", false}, - {"screen_brightness", 101}, - {"screen_brightness_onroad", 101}, - {"screen_timeout", 30}, - {"screen_timeout_onroad", 10}, - {"sidebar_color1", "#FFFFFFFF"}, - {"sidebar_color2", "#FFFFFFFF"}, - {"sidebar_color3", "#FFFFFFFF"}, - {"simple_mode", false}, - {"standby_mode", false}, - {"tethering_config", 0}, - }; - - wifi = new WifiManager(this); - - if (params.getInt("TetheringEnabled") == 1) { - wifi->setTetheringEnabled(true); - } -} - -StarPilotUIState *starpilotUIState() { - static StarPilotUIState starpilot_ui_state; - return &starpilot_ui_state; -} - -void StarPilotUIState::update() { - update_state(this); - - if (starpilot_scene.enabled && starpilot_scene.starpilot_toggles.value("conditional_chill_mode").toBool() && - !starpilot_scene.starpilot_toggles.value("conditional_experimental_mode").toBool()) { - starpilot_scene.conditional_status = params_memory.getInt("CCStatus"); - } else { - starpilot_scene.conditional_status = starpilot_scene.enabled ? params_memory.getInt("CEStatus") : 0; - } - starpilot_scene.driver_camera_timer = starpilot_scene.reverse && starpilot_scene.starpilot_toggles.value("driver_camera_in_reverse").toBool() ? starpilot_scene.driver_camera_timer + 1 : 0; -} diff --git a/starpilot/ui/starpilot_ui.h b/starpilot/ui/starpilot_ui.h deleted file mode 100644 index e31626055..000000000 --- a/starpilot/ui/starpilot_ui.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include "cereal/messaging/messaging.h" -#include "selfdrive/ui/qt/network/wifi_manager.h" - -#include "starpilot/ui/qt/widgets/starpilot_controls.h" - -struct StarPilotUIScene { - bool always_on_lateral_active; - bool downloading_update; - bool enabled; - bool starpilot_panel_active; - bool online; - bool parked; - bool reverse; - bool sidebars_open; - bool standstill; - bool switchback_mode_enabled; - bool traffic_mode_enabled; - bool wake_up_screen; - - int conditional_status; - int driver_camera_timer; - int started_timer; - - QJsonObject starpilot_toggles; -}; - -class StarPilotUIState : public QObject { - Q_OBJECT - -public: - explicit StarPilotUIState(QObject *parent = nullptr); - - void update(); - - std::unique_ptr sm; - - StarPilotUIScene starpilot_scene; - - Params params; - Params params_memory{"", true}; - - WifiManager *wifi; - -signals: - void themeUpdated(); -}; - -StarPilotUIState *starpilotUIState(); diff --git a/system/manager/launch_param_migrations.py b/system/manager/launch_param_migrations.py index 888cb2384..5504a4d8f 100644 --- a/system/manager/launch_param_migrations.py +++ b/system/manager/launch_param_migrations.py @@ -10,7 +10,7 @@ LONG_PITCH_KEY = "LongPitch" LANE_CHANGE_SMOOTHING_KEY = "LaneChangeSmoothing" STEER_KP_KEY = "SteerKP" STEER_KP_STOCK_KEY = "SteerKPStock" -USE_OLD_UI_KEY = "UseOldUI" +LEGACY_UI_SELECTION_KEYS = ("UseOldUI", "TryRaylibUI") VISION_SPEED_LIMIT_DETECTION_KEY = "VisionSpeedLimitDetection" DEVELOPER_METRIC_DISPLAY_KEYS = ( "FPSCounter", @@ -25,12 +25,12 @@ CAMERA_VIEW_KEY = "CameraView" DEFAULT_STEER_KP = 0.6 LEGACY_STEER_KP = 0.7 -QT_STEER_KP_PLACEHOLDER = 1.0 +LEGACY_STEER_KP_STOCK_PLACEHOLDER = 1.0 LAUNCH_PARAM_MIGRATION_MARKER = ".starpilot_launch_param_migrations_v2" BRANCH_DEFAULTS_MIGRATION_MARKER = ".starpilot_branch_defaults_migrations_v1" ACCELERATION_PROFILE_MIGRATION_MARKER = ".starpilot_acceleration_profile_default_v1" -USE_OLD_UI_MIGRATION_MARKER = ".starpilot_use_old_ui_migration_v2" +LEGACY_UI_SELECTION_MIGRATION_MARKER = ".starpilot_remove_legacy_ui_selection_v1" LATERAL_METHOD_REBRAND_MIGRATION_MARKER = ".starpilot_lateral_method_rebrand_v1" VISION_SPEED_LIMIT_DETECTION_MIGRATION_MARKER = ".starpilot_vision_speed_limit_detection_v1" DEVELOPER_METRIC_DISPLAY_MIGRATION_MARKER = ".starpilot_developer_metric_display_off_v1" @@ -113,8 +113,8 @@ def _acceleration_profile_marker_path(params: ParamsLike) -> Path: return _marker_dir_path(params) / ACCELERATION_PROFILE_MIGRATION_MARKER -def _use_old_ui_marker_path(params: ParamsLike) -> Path: - return _marker_dir_path(params) / USE_OLD_UI_MIGRATION_MARKER +def _legacy_ui_selection_marker_path(params: ParamsLike) -> Path: + return _marker_dir_path(params) / LEGACY_UI_SELECTION_MIGRATION_MARKER def _lateral_method_rebrand_marker_path(params: ParamsLike) -> Path: @@ -184,7 +184,7 @@ def _apply_legacy_launch_param_migrations(params: ParamsLike, marker: Path) -> N steer_kp_stock = params.get_float(STEER_KP_STOCK_KEY) if (_approx_equal(steer_kp_stock, 0.0) or _approx_equal(steer_kp_stock, LEGACY_STEER_KP) or - _approx_equal(steer_kp_stock, QT_STEER_KP_PLACEHOLDER)): + _approx_equal(steer_kp_stock, LEGACY_STEER_KP_STOCK_PLACEHOLDER)): params.put_float(STEER_KP_STOCK_KEY, DEFAULT_STEER_KP) # Initialize UsePrebuilt to True if never explicitly set, so the UI default @@ -225,13 +225,14 @@ def _apply_acceleration_profile_default_migration(params: ParamsLike, marker: Pa marker.touch() -def _apply_use_old_ui_migration(params: ParamsLike, marker: Path) -> None: +def _remove_legacy_ui_selection(params: ParamsLike, marker: Path) -> None: if marker.exists(): return marker.parent.mkdir(parents=True, exist_ok=True) - params.put_bool(USE_OLD_UI_KEY, False) + for key in LEGACY_UI_SELECTION_KEYS: + Path(params.get_param_path(key)).unlink(missing_ok=True) marker.touch() @@ -333,7 +334,7 @@ def _apply_camera_view_default_migration(params: ParamsLike, marker: Path) -> No def apply_launch_param_migrations(params: ParamsLike, marker_path: Path | None = None, branch_defaults_marker_path: Path | None = None, acceleration_profile_marker_path: Path | None = None, - use_old_ui_marker_path: Path | None = None, + legacy_ui_selection_marker_path: Path | None = None, lateral_method_rebrand_marker_path: Path | None = None, vision_speed_limit_detection_marker_path: Path | None = None, developer_metric_display_marker_path: Path | None = None, @@ -348,7 +349,9 @@ def apply_launch_param_migrations(params: ParamsLike, marker_path: Path | None = _apply_acceleration_profile_default_migration( params, acceleration_profile_marker_path or _acceleration_profile_marker_path(params) ) - _apply_use_old_ui_migration(params, use_old_ui_marker_path or _use_old_ui_marker_path(params)) + _remove_legacy_ui_selection( + params, legacy_ui_selection_marker_path or _legacy_ui_selection_marker_path(params) + ) _apply_lateral_method_rebrand_migration( params, lateral_method_rebrand_marker_path or _lateral_method_rebrand_marker_path(params) ) diff --git a/system/manager/process_config.py b/system/manager/process_config.py index 115fe9277..6d55e9f2f 100644 --- a/system/manager/process_config.py +++ b/system/manager/process_config.py @@ -105,83 +105,14 @@ def run_v_asm(started: bool, params: Params, CP: car.CarParams, starpilot_toggle return started and getattr(starpilot_toggles, "v_asm_enabled", False) -class BigDeviceUIProcess: - name = "ui" - enabled = True - sigkill = False - daemon = False - - def __init__(self, should_run, watchdog_max_dt=None): - self.should_run_fn = should_run - self.watchdog_max_dt = watchdog_max_dt - self._started = False - self._params = None - self._active_process = None - self._qt_process = NativeProcess("ui", "selfdrive/ui", ["./ui"], should_run, watchdog_max_dt=watchdog_max_dt) - self._raylib_process = NativeProcess( - "ui", - ".", - ["/usr/bin/env", "BIG=1", sys.executable, "-m", "openpilot.selfdrive.ui.ui"], - should_run, - watchdog_max_dt=watchdog_max_dt, - ) - - @property - def proc(self): - return self._active_process.proc if self._active_process is not None else None - - @property - def shutting_down(self): - return self._active_process.shutting_down if self._active_process is not None else False - - def prepare(self) -> None: - self._qt_process.prepare() - - def should_run(self, started: bool, params: Params, CP: car.CarParams, starpilot_toggles: SimpleNamespace) -> bool: - self._started = started - self._params = params - return self.should_run_fn(started, params, CP, starpilot_toggles) - - def _desired_process(self): - return self._qt_process if self._params is not None and self._params.get_bool("UseOldUI") else self._raylib_process - - def start(self) -> None: - desired_process = self._desired_process() - - # Never swap UI implementations mid-drive. Direct param writes while onroad - # take effect the next time the device is offroad. - if self._started and self._active_process is not None and self._active_process is not desired_process: - desired_process = self._active_process - - if self._active_process is not None and self._active_process is not desired_process: - self._active_process.stop() - - for process in (self._qt_process, self._raylib_process): - if process is not desired_process and process.proc is not None: - process.stop() - - self._active_process = desired_process - self._active_process.start() - - def stop(self, retry: bool = True, block: bool = True, sig=None): - ret = None - for process in (self._qt_process, self._raylib_process): - process_ret = process.stop(retry=retry, block=block, sig=sig) - if process is self._active_process: - ret = process_ret - return ret - - def restart(self) -> None: - self.stop() - self.start() - - def check_watchdog(self, started: bool) -> None: - if self._active_process is not None: - self._active_process.check_watchdog(started) - - def get_process_state_msg(self): - process = self._active_process or self._qt_process - return process.get_process_state_msg() +def big_device_ui_process() -> NativeProcess: + return NativeProcess( + "ui", + ".", + ["/usr/bin/env", "BIG=1", sys.executable, "-m", "openpilot.selfdrive.ui.ui"], + always_run, + watchdog_max_dt=UI_WATCHDOG_MAX_DT, + ) procs = [ @@ -247,9 +178,8 @@ procs += [ device_type = HARDWARE.get_device_type() if device_type in ("tici", "tizi"): - procs.append(BigDeviceUIProcess(always_run, watchdog_max_dt=UI_WATCHDOG_MAX_DT)) + procs.append(big_device_ui_process()) else: - # C4 (mici) already runs the Python raylib UI path; UseOldUI must not affect it. procs.append(PythonProcess("ui", "selfdrive.ui.ui", always_run, watchdog_max_dt=UI_WATCHDOG_MAX_DT)) procs += [ diff --git a/system/manager/test/test_launch_param_migrations.py b/system/manager/test/test_launch_param_migrations.py index f2579565f..45205715e 100644 --- a/system/manager/test/test_launch_param_migrations.py +++ b/system/manager/test/test_launch_param_migrations.py @@ -16,7 +16,7 @@ from openpilot.system.manager.launch_param_migrations import ( MARKER_DIRNAME, STANDARD_ACCELERATION_PROFILE, SPEED_LIMIT_VISIBILITY_MIGRATION_MARKER, - USE_OLD_UI_MIGRATION_MARKER, + LEGACY_UI_SELECTION_MIGRATION_MARKER, VISION_SPEED_LIMIT_DETECTION_MIGRATION_MARKER, apply_launch_param_migrations, ) @@ -297,33 +297,28 @@ def test_apply_launch_param_migrations_preserves_custom_acceleration_profile_wit assert params.get_int("AccelerationProfile") == 1 -def test_apply_launch_param_migrations_defaults_old_ui_off_from_try_raylib_enabled(tmp_path): - params = FileBackedFakeParams(tmp_path / "params") - params.put_bool("TryRaylibUI", True) - - apply_launch_param_migrations(params) - - assert not params.get_bool("UseOldUI") - assert marker_path(tmp_path, USE_OLD_UI_MIGRATION_MARKER).is_file() - - -def test_apply_launch_param_migrations_defaults_old_ui_off_from_try_raylib_disabled(tmp_path): +def test_apply_launch_param_migrations_removes_legacy_ui_selection(tmp_path): params = FileBackedFakeParams(tmp_path / "params") + params.put_bool("UseOldUI", True) params.put_bool("TryRaylibUI", False) apply_launch_param_migrations(params) - assert not params.get_bool("UseOldUI") - assert marker_path(tmp_path, USE_OLD_UI_MIGRATION_MARKER).is_file() + assert not Path(params.get_param_path("UseOldUI")).exists() + assert not Path(params.get_param_path("TryRaylibUI")).exists() + assert marker_path(tmp_path, LEGACY_UI_SELECTION_MIGRATION_MARKER).is_file() -def test_apply_launch_param_migrations_resets_existing_use_old_ui(tmp_path): +def test_apply_launch_param_migrations_removes_legacy_ui_selection_once(tmp_path): params = FileBackedFakeParams(tmp_path / "params") - params.put_bool("UseOldUI", True) + marker = marker_path(tmp_path, LEGACY_UI_SELECTION_MIGRATION_MARKER) + apply_launch_param_migrations(params) + params.put_bool("UseOldUI", True) + marker.touch() apply_launch_param_migrations(params) - assert not params.get_bool("UseOldUI") + assert Path(params.get_param_path("UseOldUI")).exists() def test_apply_launch_param_migrations_preserves_active_lateral_method_trial(tmp_path): diff --git a/system/manager/test/test_manager.py b/system/manager/test/test_manager.py index 14f491ed0..2ad3eded5 100644 --- a/system/manager/test/test_manager.py +++ b/system/manager/test/test_manager.py @@ -4,13 +4,12 @@ import signal import time from pathlib import Path import json -from types import SimpleNamespace from cereal import car from openpilot.common.params import Params import openpilot.system.manager.manager as manager from openpilot.system.manager.process import ensure_running -from openpilot.system.manager.process_config import BigDeviceUIProcess, managed_processes, procs +from openpilot.system.manager.process_config import big_device_ui_process, managed_processes, procs from openpilot.system.hardware import HARDWARE os.environ['FAKEUPLOAD'] = "1" @@ -206,40 +205,6 @@ def test_offroad_cleanup_does_not_remove_destination_replaced_after_snapshot(tmp assert "NavDestination" not in params.removed -class FakeManagedProcess: - def __init__(self): - self.proc = None - self.shutting_down = False - self.starts = 0 - self.stops = 0 - - def prepare(self): - pass - - def start(self): - if self.proc is not None: - return - - self.starts += 1 - self.shutting_down = False - self.proc = SimpleNamespace(exitcode=None, pid=self.starts, is_alive=lambda: True) - - def stop(self, retry=True, block=True, sig=None): - if self.proc is None: - return None - - self.stops += 1 - self.shutting_down = False - self.proc = None - return 0 - - def check_watchdog(self, started): - pass - - def get_process_state_msg(self): - return SimpleNamespace(name="ui") - - def test_reboot_guard_only_defers_automatic_requests(): assert manager.should_defer_reboot("DoReboot", started=True, ignition=False) assert manager.should_defer_reboot("DoReboot", started=False, ignition=True) @@ -247,6 +212,14 @@ def test_reboot_guard_only_defers_automatic_requests(): assert not manager.should_defer_reboot("DoUserReboot", started=True, ignition=True) +def test_big_device_ui_process_always_launches_c3_ui(): + ui_process = big_device_ui_process() + + assert ui_process.cwd == "." + assert ui_process.cmdline[0:2] == ["/usr/bin/env", "BIG=1"] + assert ui_process.cmdline[-2:] == ["-m", "openpilot.selfdrive.ui.ui"] + + class TestManager: @pytest.fixture(autouse=True) def isolate_boot_backup(self, monkeypatch): @@ -276,34 +249,6 @@ class TestManager: assert names.index("the_galaxy") < ui_idx assert names.index("galaxy") < ui_idx - def test_big_device_ui_process_swaps_offroad_only(self, tmp_path): - ui_process = BigDeviceUIProcess(lambda *args: True) - qt_process = FakeManagedProcess() - raylib_process = FakeManagedProcess() - ui_process._qt_process = qt_process - ui_process._raylib_process = raylib_process - - params = FileBackedFakeParams(tmp_path / "params", {"UseOldUI": False}) - - assert ui_process.should_run(False, params, car.CarParams.new_message(), SimpleNamespace()) - ui_process.start() - assert ui_process.proc is raylib_process.proc - assert qt_process.starts == 0 - assert raylib_process.starts == 1 - - params.put_bool("UseOldUI", True) - assert ui_process.should_run(True, params, car.CarParams.new_message(), SimpleNamespace()) - ui_process.start() - assert ui_process.proc is raylib_process.proc - assert qt_process.stops == 0 - assert qt_process.starts == 0 - - assert ui_process.should_run(False, params, car.CarParams.new_message(), SimpleNamespace()) - ui_process.start() - assert raylib_process.stops == 1 - assert qt_process.starts == 1 - assert ui_process.proc is qt_process.proc - def test_blacklisted_procs(self): # TODO: ensure there are blacklisted procs until we have a dedicated test assert len(BLACKLIST_PROCS), "No blacklisted procs to test not_run" diff --git a/system/ui/README.md b/system/ui/README.md index 3c42622ad..15594930d 100644 --- a/system/ui/README.md +++ b/system/ui/README.md @@ -21,5 +21,5 @@ Quick start: Style guide: * All graphical elements should subclass [`Widget`](/system/ui/widgets/__init__.py). - * Prefer a stateful widget over a function for easy migration from QT + * Prefer a stateful widget over a function when it simplifies lifecycle management * All internal class variables and functions should be prefixed with `_` diff --git a/system/ui/lib/application.py b/system/ui/lib/application.py index 60d66fd47..cacc59869 100644 --- a/system/ui/lib/application.py +++ b/system/ui/lib/application.py @@ -141,7 +141,7 @@ void main() { DEFAULT_TEXT_SIZE = 60 DEFAULT_TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) -# Qt draws fonts accounting for ascent/descent differently, so compensate to match old styles +# Compensate for ascent/descent so migrated layouts keep their established alignment. # The real scales for the fonts below range from 1.212 to 1.266 FONT_SCALE = 1.242 if BIG_UI else 1.16 @@ -624,7 +624,7 @@ class GuiApplication: self._render_texture_width = max(1, int(round(self._scaled_width * self._pixel_scale_x))) self._render_texture_height = max(1, int(round(self._scaled_height * self._pixel_scale_y))) - # Keep raybig burn-in movement in final-frame composition. Translating the live EGL + # Keep big-UI burn-in movement in final-frame composition. Translating the live EGL # camera/widget pass can corrupt the camera presentation instead of shifting the UI. needs_render_texture = ((self._scale != 1.0 and not PC) or BURN_IN_MODE or RECORD or MICI_FORCE_RENDER_TEXTURE or @@ -1199,7 +1199,7 @@ class GuiApplication: rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BASE_COLOR_NORMAL, rl.color_to_int(rl.Color(50, 50, 50, 255))) def _patch_text_functions(self): - # Wrap pyray text APIs to apply a global text size scale so our px sizes match Qt + # Wrap pyray text APIs to apply a global text size scale. if not hasattr(rl, "_orig_draw_text_ex"): rl._orig_draw_text_ex = rl.draw_text_ex diff --git a/system/ui/widgets/__init__.py b/system/ui/widgets/__init__.py index 17e1aac1c..c3a8b8f82 100644 --- a/system/ui/widgets/__init__.py +++ b/system/ui/widgets/__init__.py @@ -57,7 +57,7 @@ class Widget(abc.ABC): self._update_layout_rects() def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: - """Can be used like size hint in QT""" + """Return the widget's preferred dimensions.""" self._parent_rect = parent_rect @property diff --git a/system/ui/widgets/html_render.py b/system/ui/widgets/html_render.py index 77fca9fe3..6a794ea57 100644 --- a/system/ui/widgets/html_render.py +++ b/system/ui/widgets/html_render.py @@ -52,7 +52,7 @@ class HtmlElement: font_weight: FontWeight margin_top: int margin_bottom: int - line_height: float = 0.9 # matches Qt visually, unsure why not default 1.2 + line_height: float = 0.9 indent_level: int = 0 @@ -72,7 +72,7 @@ class HtmlRenderer(Widget): self._cached_height: float | None = None self._cached_width: int = -1 - # Base paragraph size (Qt stylesheet default is 48px in offroad alerts) + # Base paragraph size for offroad alerts. base_p_size = int(text_size.get(ElementType.P, 48)) # Untagged text defaults to

diff --git a/tools/CTF.md b/tools/CTF.md index 32891cd38..167f9eaad 100644 --- a/tools/CTF.md +++ b/tools/CTF.md @@ -15,6 +15,6 @@ getting started cd tools/replay ./replay '0c7f0c7f0c7f0c7f|2021-10-13--13-00-00' --dcam --ecam -# start the UI in another terminal -selfdrive/ui/ui +# start the C3 UI in another terminal +./c3 ``` diff --git a/tools/README.md b/tools/README.md index cdd5b3030..60f582ab6 100644 --- a/tools/README.md +++ b/tools/README.md @@ -41,7 +41,7 @@ scons -u -j$(nproc) Follow [these instructions](https://docs.microsoft.com/en-us/windows/wsl/install) to setup the WSL and install the `Ubuntu-24.04` distribution. Once your Ubuntu WSL environment is setup, follow the Linux setup instructions to finish setting up your environment. See [these instructions](https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps) for running GUI apps. -**NOTE**: If you are running WSL and any GUIs are failing (segfaulting or other strange issues) even after following the steps above, you may need to enable software rendering with `LIBGL_ALWAYS_SOFTWARE=1`, e.g. `LIBGL_ALWAYS_SOFTWARE=1 selfdrive/ui/ui`. +**NOTE**: If you are running WSL and any GUIs are failing (segfaulting or other strange issues) even after following the steps above, you may need to enable software rendering with `LIBGL_ALWAYS_SOFTWARE=1`, e.g. `LIBGL_ALWAYS_SOFTWARE=1 ./c3`. ## CTF Learn about the openpilot ecosystem and tools by playing our [CTF](/tools/CTF.md). diff --git a/tools/STARPILOT_DEVELOPMENT.md b/tools/STARPILOT_DEVELOPMENT.md index 1b57bddd2..b34d3cd09 100644 --- a/tools/STARPILOT_DEVELOPMENT.md +++ b/tools/STARPILOT_DEVELOPMENT.md @@ -3,7 +3,7 @@ This branch uses a split development flow: - `./build` keeps producing device-target (`larch64`) artifacts for comma runtime compatibility. -- `./dev`, `./tool`, `./tools/host`, `./c3`, `./c4`, and `./raybig` use an isolated host cache under `.host_runtime/` for native macOS/Linux tooling. +- `./dev`, `./tool`, `./tools/host`, `./c3`, and `./c4` use an isolated host cache under `.host_runtime/` for native macOS/Linux tooling. The goal is simple: keep the device build intact, keep host tools consistent with runtime behavior, and stop polluting the repo with host-only `.so`, `.o`, and desktop UI artifacts. @@ -14,7 +14,6 @@ The goal is simple: keep the device build intact, keep host tools consistent wit - Run `tools/install_python_dependencies.sh` - Have `uv` available in your shell - For device-target builds, install Docker Desktop or Podman with Linux/aarch64 support -- For macOS Qt UI (`./c3`), install the Qt 5/Homebrew dependencies already expected by the repo ## One-time device build setup @@ -75,7 +74,7 @@ All three entrypoints do the same thing. `./dev` is the shortest general-purpose ### Available host commands - `./dev replay [args...]` -- `./onroad [jobs] (--c3 | --c4 | --raybig | --all | --replay-only) ` +- `./onroad [jobs] (--c3 | --c4 | --all | --replay-only) ` - `./dev cabana [args...]` - `./dev plotjuggler [args...]` - `./dev juggle [args...]` @@ -89,7 +88,6 @@ watching it in real time, use `tools/clip/run.py` (see [tools/clip/README.md](cl - `./c3 [jobs] [args...]` - `./c4 [jobs] [args...]` -- `./raybig [jobs] [args...]` These are wrappers around the same isolated host runner used by `./dev`. @@ -104,7 +102,6 @@ Examples: ./dev cabana ./c3 8 ./c4 8 -./raybig 8 ./dev shell ``` @@ -149,7 +146,7 @@ That means: Current bucket split: -- shared bucket: `./c3`, `./c4`, `./raybig`, `./dev replay`, `./dev plotjuggler`, `./dev juggle`, `./dev shell` +- shared bucket: `./c3`, `./c4`, `./dev replay`, `./dev plotjuggler`, `./dev juggle`, `./dev shell` - cabana bucket: `./dev cabana` This prevents one command from syncing or rebuilding over another live host session while still allowing the common Cabana + PlotJuggler pairing. @@ -174,7 +171,7 @@ Use `./onroad ...` when: - you need replay and UI to share the same isolated host runtime and messaging prefix - you want the default side-by-side desktop UI launch without running separate replay/UI commands -Use `./c3`, `./c4`, or `./raybig` when: +Use `./c3` or `./c4` when: - you want the desktop UI variants - you want them to build/run from the isolated host cache instead of touching tracked files @@ -217,5 +214,5 @@ To refresh one bucket only: 1. Use `./build` when you need the real device-target build. 2. Use `./dev replay`, `./dev cabana`, or `./dev plotjuggler` for host-side tooling. -3. Use `./c3`, `./c4`, or `./raybig` for desktop UI work. +3. Use `./c3` or `./c4` for desktop UI work. 4. Let `.host_runtime` keep host artifacts out of the repo. diff --git a/tools/StarPilot/generate_galaxy_layout.py b/tools/StarPilot/generate_galaxy_layout.py deleted file mode 100755 index 28ddf7cab..000000000 --- a/tools/StarPilot/generate_galaxy_layout.py +++ /dev/null @@ -1,721 +0,0 @@ -import os -import re -import sys -import json -import ast - -REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')) - -CATEGORIES = [ - {"file": "lateral_settings.cc", "name": "Lateral (Steering)", "icon": "bi-arrows-move"}, - {"file": "longitudinal_settings.cc", "name": "Longitudinal (Speed & Following)", "icon": "bi-speedometer2"}, - {"file": "visual_settings.cc", "name": "Visual (Display & UI)", "icon": "bi-eye"}, - {"file": "sounds_settings.cc", "name": "Sounds & Alerts", "icon": "bi-volume-up"}, - {"file": "vehicle_settings.cc", "name": "Vehicle", "icon": "bi-car-front"}, - {"file": "device_settings.cc", "name": "Device & Data", "icon": "bi-hdd"}, -] - -DROPDOWN_MAPPING = { - "SelectModel": { - "key": "DrivingModel", - "options_endpoint": "/api/models/installed" - } -} - -# Custom controls implemented outside the tuple vectors in Qt settings panels. -# Inject these so regenerated galaxy layouts retain equivalent functionality. -INJECTED_SECTION_PARAMS = { - "Longitudinal (Speed & Following)": [ - { - "key": "CEOpenRoad", - "label": "Open Road", - "description": "Keep Experimental Mode active on an open road after reaching the set speed when no lead vehicle is detected. This can help the model anticipate braking sooner.", - "data_type": "bool", - "ui_type": "toggle", - "parent_key": "ConditionalExperimental", - }, - ], - "Vehicle": [ - { - "key": "CarMake", - "label": "Car Make", - "description": "Select your car make.", - "data_type": "string", - "ui_type": "dropdown", - "options_endpoint": "/api/fingerprints/makes", - }, - { - "key": "CarModel", - "label": "Car Model (Fingerprint)", - "description": "Choose the fingerprint platform to use when automatic detection is disabled.", - "data_type": "string", - "ui_type": "dropdown", - "options_endpoint": "/api/fingerprints/models?make={CarMake}", - }, - { - "key": "ForceFingerprint", - "label": "Disable Automatic Fingerprint Detection", - "description": "Force the selected fingerprint and prevent it from changing automatically.", - "data_type": "bool", - "ui_type": "toggle", - }, - { - "key": "IsRHD", - "label": "Right Hand Driving", - "description": "Use right-hand-drive driver monitoring. This follows the auto-detected side until changed manually.", - "data_type": "bool", - "ui_type": "toggle", - }, - ], -} - -# Keys explicitly hidden from The Galaxy's generic settings UI. -HIDDEN_KEYS = { - "CustomAlerts", - "HumanAcceleration", - "HideLeadMarker", - "HideSpeedLimit", - "LockDoorsTimer", - "NewLongAPI", - "ToyotaDoors", - "ReverseCruise", -} - -HIDDEN_SECTION_NAMES = {"Model & Customization"} - -# Keys that are boolean toggles despite ambiguous defaults in starpilot_variables.py. -FORCE_BOOL_KEYS = {"EVTuning"} - -# These fields are intentionally allowed to differ from the Qt source. Galaxy -# has its own copy, nesting, and browser-only behavior for otherwise shared -# params, so regeneration must not discard those overrides. -GALAXY_OVERRIDE_FIELDS = { - "label", - "description", - "parent_key", - "is_parent_toggle", - "disabled_when_key_true", - "disabled_reason", -} - - -def get_param_settings_tiers(): - params_path = os.path.join(REPO_ROOT, "common/params_keys.h") - tiers = {} - with open(params_path, "r", encoding="utf-8") as params_file: - for line in params_file: - match = re.match(r'\s*\{"([^"]+)",', line) - if match: - tiers[match.group(1)] = "simple" if "SETTINGS_SIMPLE" in line else "advanced" - return tiers - - -PARAM_SETTINGS_TIERS = get_param_settings_tiers() - - -def apply_settings_tiers(layout): - for section in layout: - params = section.get("params", []) - params_by_key = {param["key"]: param for param in params if "key" in param} - resolved = {} - - def resolve_tier(key, resolving=None): - if key in resolved: - return resolved[key] - - resolving = set(resolving or ()) - if key in resolving: - return "advanced" - resolving.add(key) - - parent_key = params_by_key.get(key, {}).get("parent_key") - if parent_key == "GalaxyDeveloperMode": - resolved[key] = "advanced" - return resolved[key] - own_tier = PARAM_SETTINGS_TIERS.get(key) - if parent_key: - parent_tier = resolve_tier(parent_key, resolving) - resolved[key] = parent_tier if own_tier is None else ( - "advanced" if "advanced" in (parent_tier, own_tier) else "simple" - ) - else: - resolved[key] = own_tier or "advanced" - return resolved[key] - - for param in params: - key = param.get("key") - if key: - param["settings_tier"] = resolve_tier(key) - - return layout - -DEVELOPER_SIDEBAR_METRIC_KEYS = { - "DeveloperSidebarMetric1", - "DeveloperSidebarMetric2", - "DeveloperSidebarMetric3", - "DeveloperSidebarMetric4", - "DeveloperSidebarMetric5", - "DeveloperSidebarMetric6", - "DeveloperSidebarMetric7", -} - -DEVELOPER_SIDEBAR_METRIC_OPTIONS = [ - {"value": 0, "label": "None"}, - {"value": 1, "label": "Acceleration: Current"}, - {"value": 2, "label": "Acceleration: Max"}, - {"value": 3, "label": "Auto Tune: Actuator Delay"}, - {"value": 4, "label": "Auto Tune: Friction"}, - {"value": 5, "label": "Auto Tune: Lateral Acceleration"}, - {"value": 6, "label": "Auto Tune: Steer Ratio"}, - {"value": 7, "label": "Auto Tune: Stiffness Factor"}, - {"value": 8, "label": "Engagement %: Lateral"}, - {"value": 9, "label": "Engagement %: Longitudinal"}, - {"value": 10, "label": "Lateral Control: Steering Angle"}, - {"value": 11, "label": "Lateral Control: Torque % Used"}, - {"value": 12, "label": "Longitudinal Control: Actuator Acceleration Output"}, - {"value": 13, "label": "Longitudinal MPC Jerk: Acceleration"}, - {"value": 14, "label": "Longitudinal MPC Jerk: Danger Zone"}, - {"value": 15, "label": "Longitudinal MPC Jerk: Speed Control"}, - {"value": 16, "label": "Driving Model: Current"}, -] - -PARENT_KEYS_MAPPING = { - "device_settings.cc": { - "deviceManagementKeys": "DeviceManagement", - "screenKeys": "ScreenManagement" - }, - "lateral_settings.cc": { - "advancedLateralTuneKeys": "AdvancedLateralTune", - "aolKeys": "AlwaysOnLateral", - "laneChangeKeys": "LaneChanges", - "lateralTuneKeys": "LateralTune", - "qolKeys": "QOLLateral" - }, - "longitudinal_settings.cc": { - "advancedLongitudinalTuneKeys": "AdvancedLongitudinalTune", - "aggressivePersonalityKeys": "AggressivePersonalityProfile", - "conditionalChillKeys": "ConditionalChill", - "conditionalExperimentalKeys": "ConditionalExperimental", - "curveSpeedKeys": "CurveSpeedController", - "customDrivingPersonalityKeys": "CustomPersonalities", - "longitudinalTuneKeys": "LongitudinalTune", - "qolKeys": "QOLLongitudinal", - "relaxedPersonalityKeys": "RelaxedPersonalityProfile", - "speedLimitControllerKeys": "SpeedLimitController", - "speedLimitControllerOffsetsKeys": "SpeedLimitController", - "speedLimitControllerQOLKeys": "SpeedLimitController", - "speedLimitControllerVisualKeys": "SpeedLimitController", - "standardPersonalityKeys": "StandardPersonalityProfile", - "trafficPersonalityKeys": "TrafficPersonalityProfile" - }, - "sounds_settings.cc": { - "alertVolumeControlKeys": "AlertVolumeControl", - }, - "theme_settings.cc": { - "customThemeKeys": "CustomTheme" - }, - "visual_settings.cc": { - "advancedCustomOnroadUIKeys": "AdvancedCustomUI", - "customOnroadUIKeys": "CustomUI", - "developerMetricKeys": "DeveloperMetrics", - "developerSidebarKeys": "DeveloperSidebar", - "developerUIKeys": "DeveloperUI", - "developerWidgetKeys": "DeveloperWidgets", - "modelUIKeys": "ModelUI", - "navigationUIKeys": "NavigationUI", - "qualityOfLifeKeys": "QOLVisuals" - }, - "vehicle_settings.cc": {} -} - -ALL_PARENT_KEYS = set() -for cmap in PARENT_KEYS_MAPPING.values(): - for parent in cmap.values(): - ALL_PARENT_KEYS.add(parent) - -def get_variables_data(): - filepath = os.path.join(REPO_ROOT, "starpilot/common/starpilot_variables.py") - excluded = set() - defaults = {} - if not os.path.exists(filepath): - return excluded, defaults - - with open(filepath, 'r', encoding='utf-8') as f: - tree = ast.parse(f.read()) - - def parse_params_list(value_node): - try: - if isinstance(value_node, ast.List): - for elt in value_node.elts: - if isinstance(elt, ast.Tuple) and len(elt.elts) >= 2: - key_node = elt.elts[0] - val_node = elt.elts[1] - if isinstance(key_node, ast.Constant): - key = key_node.value - if isinstance(val_node, ast.Constant): - val = val_node.value - if isinstance(val, (str, bytes)): - v = val.decode('utf-8') if isinstance(val, bytes) else str(val) - if v in ("0", "1"): - defaults[key] = "bool" - elif "." in v and v.replace(".", "", 1).isdigit(): - defaults[key] = "float" - elif v.isdigit(): - defaults[key] = "int" - else: - defaults[key] = "string" - else: - defaults[key] = "unknown" - elif isinstance(val_node, ast.Call) and isinstance(val_node.func, ast.Name) and val_node.func.id == "str": - # str() is used for several numeric defaults. - defaults[key] = "float" - else: - defaults[key] = "unknown" - except: - pass - - for node in tree.body: - if isinstance(node, ast.Assign): - for target in node.targets: - if getattr(target, 'id', '') == 'EXCLUDED_KEYS': - try: - excluded = ast.literal_eval(node.value) - except: - pass - elif getattr(target, 'id', '') in ('starpilot_default_params', 'misc_tuning_levels'): - parse_params_list(node.value) - elif isinstance(node, ast.AnnAssign): - if getattr(node.target, 'id', '') in ('starpilot_default_params', 'misc_tuning_levels'): - parse_params_list(node.value) - - return excluded, defaults - -EXCLUDED_KEYS, DEFAULT_TYPES = get_variables_data() - -def get_editable_keys(): - filepath = os.path.join(REPO_ROOT, "starpilot/common/starpilot_variables.py") - editable = set() - if not os.path.exists(filepath): - return editable - - with open(filepath, 'r', encoding='utf-8') as f: - tree = ast.parse(f.read()) - - for node in tree.body: - value_node = None - if isinstance(node, ast.Assign): - for target in node.targets: - if getattr(target, 'id', '') == 'starpilot_default_params': - value_node = node.value - break - elif isinstance(node, ast.AnnAssign): - if getattr(node.target, 'id', '') == 'starpilot_default_params': - value_node = node.value - - if isinstance(value_node, ast.List): - for elt in value_node.elts: - if isinstance(elt, ast.Tuple) and elt.elts and isinstance(elt.elts[0], ast.Constant): - editable.add(elt.elts[0].value) - - return editable - -EDITABLE_KEYS = get_editable_keys() - - -def parse_params_keys_h(): - filepath = os.path.join(REPO_ROOT, "common/params_keys.h") - keys = set() - types = {} - if not os.path.exists(filepath): - return keys, types - - type_map = { - "BOOL": "bool", - "INT": "int", - "FLOAT": "float", - "STRING": "string", - "JSON": "string", - "BYTES": "string", - } - pattern = re.compile(r'\{"([A-Za-z0-9_]+)",\s*\{[^,]+,\s*([A-Z]+)') - - with open(filepath, 'r', encoding='utf-8') as f: - for line in f: - match = pattern.search(line) - if not match: - continue - key, ptype = match.groups() - keys.add(key) - types[key] = type_map.get(ptype, "unknown") - - return keys, types - - -if not DEFAULT_TYPES or not EDITABLE_KEYS: - parsed_keys, parsed_types = parse_params_keys_h() - if not EDITABLE_KEYS: - EDITABLE_KEYS = parsed_keys - for key, value in parsed_types.items(): - DEFAULT_TYPES.setdefault(key, value) - -def get_param_type(key): - return DEFAULT_TYPES.get(key, "unknown") - -def extract_bracket_block(text, start_idx): - if text[start_idx] != '{': return "" - depth = 0 - in_str = False - escape = False - for i in range(start_idx, len(text)): - char = text[i] - if escape: - escape = False - continue - if char == '\\': - escape = True - continue - if char == '"': - in_str = not in_str - continue - if not in_str: - if char == '{': depth += 1 - elif char == '}': - depth -= 1 - if depth == 0: - return text[start_idx:i+1] - return "" - -def parse_cpp_file(filename): - filepath = os.path.join(REPO_ROOT, "starpilot/ui/qt/offroad", filename) - if not os.path.exists(filepath): return [] - - with open(filepath, 'r', encoding='utf-8') as f: - content = f.read() - - vector_match = re.search( - r'(?:const\s+)?std::vector<\s*std::tuple\s*>\s*\w+\s*\{', - content, - re.DOTALL, - ) - if not vector_match: return [] - - start_idx = vector_match.end() - 1 - vector_content = extract_bracket_block(content, start_idx) - - local_parent_map = PARENT_KEYS_MAPPING.get(filename, {}) - child_to_parent = {} - child_to_qsets = {} - - header_filename = filename.replace(".cc", ".h") - header_filepath = os.path.join(REPO_ROOT, "starpilot/ui/qt/offroad", header_filename) - full_source = content - if os.path.exists(header_filepath): - with open(header_filepath, 'r', encoding='utf-8') as fh: - full_source += "\n" + fh.read() - - for qset_match in re.finditer(r'QSet\s+(\w+)\s*(?:=\s*)?\{([^}]+)\};', full_source): - qset_name = qset_match.group(1) - if qset_name in local_parent_map: - parent_key = local_parent_map[qset_name] - children_str = qset_match.group(2) - children = [c.strip().strip('"') for c in children_str.split(',') if c.strip()] - for child in children: - child_to_parent[child] = parent_key - child_to_qsets.setdefault(child, []).append(qset_name) - - items = [] - - idx = 0 - while True: - idx = vector_content.find('{"', idx) - if idx == -1: break - - block = extract_bracket_block(vector_content, idx) - if not block: - idx += 1 - continue - - row_match = re.search(r'\{"([A-Za-z0-9_]+)"\s*,\s*(.*?)\s*\}$', block, re.DOTALL) - if not row_match: - idx += len(block) - continue - - key = row_match.group(1) - rest = row_match.group(2) - idx += len(block) - - if key in HIDDEN_KEYS or key in EXCLUDED_KEYS or key.startswith("IgnoreMe"): - continue - - strings = re.findall(r'tr\("((?:[^"\\]|\\.)+)"\)|"((?:[^"\\]|\\.)+)"', rest) - valid_strings = [s[0] or s[1] for s in strings if s[0] or s[1]] - - if not valid_strings: continue - - title = valid_strings[0] - desc = valid_strings[1] if len(valid_strings) > 1 else "" - options_endpoint = None - dropdown_options = None - - if key in DEVELOPER_SIDEBAR_METRIC_KEYS: - if key not in EDITABLE_KEYS: - continue - widget_type = "dropdown" - data_type = "int" - dropdown_options = DEVELOPER_SIDEBAR_METRIC_OPTIONS - elif key in DROPDOWN_MAPPING: - m = DROPDOWN_MAPPING[key] - key = m["key"] - widget_type = "dropdown" - options_endpoint = m["options_endpoint"] - data_type = "string" - else: - if key not in EDITABLE_KEYS: - continue - data_type = get_param_type(key) - if data_type == "unknown": continue - widget_type = "toggle" - min_val, max_val, step = None, None, None - - for i in range(1, 10): - placeholder = f"%{i}" - if placeholder in desc and len(valid_strings) > i + 1: - desc = desc.replace(placeholder, valid_strings[i + 1]) - - desc = re.sub(r'', '\n', desc, flags=re.IGNORECASE) - desc = re.sub(r'<[^>]+>', '', desc) - desc = desc.replace('\\"', '"').strip() - title = re.sub(r'\s*\(\s*Default:\s*%\d\s*\)', '', title) - title = re.sub(r'%\d', '', title).strip() - desc = re.sub(r'\s*\(\s*Default:\s*%\d\s*\)', '', desc) - desc = re.sub(r'%\d', '', desc).strip() - - if widget_type == "toggle": - snippet_match = None - - # Let's match the original's regex for finding the Toggle = assignment line - search_patterns = [r'param\s*==\s*"' + key + r'"'] - for qset_name in child_to_qsets.get(key, []): - search_patterns.append(r'(?:' + qset_name + r'\.contains\(param\))') - - for pattern in search_patterns: - match = re.search(pattern + r'.*?[a-zA-Z]+Toggle\s*=\s*(.*?);', content, re.DOTALL) - if match: - snippet_match = match - break - - if snippet_match: - assignment = snippet_match.group(1) - if "StarPilotParamValueControl" in assignment or "StarPilotParamValueButtonControl" in assignment: - widget_type = "numeric" - if data_type in ("string", "bool", "unknown"): - data_type = "float" - - if "alertVolumeControlKeys" in child_to_qsets.get(key, []): - if key in ["WarningImmediateVolume", "WarningSoftVolume"]: - min_val, max_val, step = "25", "101", "1" - else: - min_val, max_val, step = "0", "101", "1" - else: - args_match = re.search(r'Control[^(]*\(([^;]+)\)', assignment) - if args_match: - args_str = args_match.group(1) - num_match = re.search(r'icon\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,(?:[^,]*,){2}\s*([-\d.]+)', args_str) - if num_match: - min_val, max_val, step = num_match.group(1), num_match.group(2), num_match.group(3) - else: - num_match = re.search(r'icon\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)', args_str) - if num_match: - min_val, max_val = num_match.group(1), num_match.group(2) - step_match = re.search(r'(?:std::map\(\)|[a-zA-Z0-9_]+Labels)\s*,\s*([-\d.]+)', args_str) - if step_match: - step = step_match.group(1) - - # CESpeed/CCMSpeed are rendered in Qt with dual numeric controls, - # so the generic assignment matcher cannot infer it reliably. - if key in {"CESpeed", "CCMSpeed"}: - widget_type = "numeric" - data_type = "int" - min_val, max_val, step = "0", "99", "1" - - if key in FORCE_BOOL_KEYS: - data_type = "bool" - - precision = None - precision_match = re.search(r"QString::number\([^,]+,\s*'f'\s*,\s*(\d+)\)", rest) - if precision_match: - precision = int(precision_match.group(1)) - - if data_type == "float" and step and float(step).is_integer(): - data_type = "int" - - # Generic galaxy UI can't faithfully represent non-boolean button/multi-option controls. - if widget_type == "toggle" and data_type != "bool": - continue - - s = { - "key": key, - "label": title, - "description": desc, - "data_type": data_type, - "ui_type": widget_type - } - if widget_type == "numeric": - if min_val is not None: s["min"] = float(min_val) - if max_val is not None: s["max"] = float(max_val) - if step is not None: s["step"] = float(step) - if precision is not None: s["precision"] = precision - elif widget_type == "dropdown": - if options_endpoint: s["options_endpoint"] = options_endpoint - if dropdown_options: s["options"] = dropdown_options - if key in child_to_parent: s["parent_key"] = child_to_parent[key] - if key in ALL_PARENT_KEYS: s["is_parent_toggle"] = True - - if key == "CELead": - s["is_parent_toggle"] = True - - items.append(s) - - # Mirror CELead's split sub-toggles from StarPilotButtonToggleControl. - if key == "CELead": - items.extend([ - { - "key": "CESlowerLead", - "label": "Slower Lead", - "description": "Switch to \"Experimental Mode\" when a slower lead vehicle is detected ahead.", - "data_type": "bool", - "ui_type": "toggle", - "parent_key": "CELead", - }, - { - "key": "CEStoppedLead", - "label": "Stopped Lead", - "description": "Switch to \"Experimental Mode\" when a stopped lead vehicle is detected ahead.", - "data_type": "bool", - "ui_type": "toggle", - "parent_key": "CELead", - }, - ]) - - # Mirror CESpeed/CCMSpeed's dual sliders (with-lead variants) from Qt. - if key == "CESpeed": - items.append({ - "key": "CESpeedLead", - "label": "Below (With Lead)", - "description": "Switch to \"Experimental Mode\" when driving below this speed with a lead.", - "data_type": "int", - "ui_type": "numeric", - "min": 0.0, - "max": 99.0, - "step": 1.0, - "parent_key": "ConditionalExperimental", - }) - elif key == "CCMSpeed": - items.append({ - "key": "CCMSpeedLead", - "label": "Above (With Lead)", - "description": "Switch to \"Chill Mode\" when following a stable lead above this speed.", - "data_type": "int", - "ui_type": "numeric", - "min": 0.0, - "max": 99.0, - "step": 1.0, - "parent_key": "ConditionalChill", - }) - - return items - - -def merge_layouts(existing_layout, generated_layout): - generated_sections = {section["name"]: section for section in generated_layout} - existing_keys = { - param["key"] - for section in existing_layout - for param in section.get("params", []) - if "key" in param - } - merged_keys = set(existing_keys) - - merged_layout = [] - - for section in existing_layout: - name = section["name"] - if name in HIDDEN_SECTION_NAMES: - continue - generated = generated_sections.get(name) - if generated is None: - merged_layout.append(section) - continue - - existing_params = section.get("params", []) - generated_params = generated.get("params", []) - generated_by_key = {param["key"]: param for param in generated_params} - - merged_params = [] - seen_keys = set() - - for param in existing_params: - key = param["key"] - if key in generated_by_key: - merged_param = dict(param) - for field, value in generated_by_key[key].items(): - if field not in GALAXY_OVERRIDE_FIELDS and field != "settings_tier": - merged_param[field] = value - merged_params.append(merged_param) - else: - merged_params.append(param) - seen_keys.add(key) - - for param in generated_params: - key = param["key"] - if key not in seen_keys and key not in merged_keys: - merged_params.append(param) - seen_keys.add(key) - merged_keys.add(key) - - merged_section = dict(section) - merged_section["icon"] = generated.get("icon", section.get("icon")) - merged_section["params"] = merged_params - merged_layout.append(merged_section) - - existing_names = {section["name"] for section in existing_layout} - for section in generated_layout: - if section["name"] not in existing_names: - merged_layout.append(section) - - return merged_layout - - -def generate_layout(existing_layout=None): - generated_layout = [] - for cat in CATEGORIES: - items = parse_cpp_file(cat["file"]) - injected = INJECTED_SECTION_PARAMS.get(cat["name"], []) - if injected: - existing_keys = {item["key"] for item in items} - items = [dict(item) for item in injected if item["key"] not in existing_keys] + items - if items: - generated_layout.append({ - "name": cat["name"], - "icon": cat["icon"], - "params": items - }) - - layout = generated_layout if existing_layout is None else merge_layouts(existing_layout, generated_layout) - return apply_settings_tiers(layout) - -def main(): - output_path = os.path.join(REPO_ROOT, "starpilot/system/the_galaxy/assets/components/tools/device_settings_layout.json") - existing_layout = None - if os.path.exists(output_path): - with open(output_path, 'r', encoding='utf-8') as f: - existing_layout = json.load(f) - layout = generate_layout(existing_layout) - if layout == existing_layout: - return - with open(output_path, 'w', encoding='utf-8') as f: - json.dump(layout, f, indent=2, ensure_ascii=False) - f.write("\n") - -if __name__ == '__main__': - main() diff --git a/tools/clip/README.md b/tools/clip/README.md index 22b505ce5..863feba07 100644 --- a/tools/clip/README.md +++ b/tools/clip/README.md @@ -18,7 +18,7 @@ python3 tools/lib/auth.py Public routes and `--demo` need no authentication. -`replay` and the raybig UI runtime are built automatically on first run, so expect the first +`replay` and the c3 UI runtime are built automatically on first run, so expect the first clip to take a few extra minutes. ## Usage @@ -36,22 +36,16 @@ python3 tools/clip/run.py 78511c37de32c375/00000958--8cb1d3e165 -s 140 -e 260 -o Recording happens in real time, so a 120s clip takes about 120s to produce. -## Choosing a UI +## UI -`-u/--ui` selects which desktop UI to record. The default is `c3`. +Clips use the c3 raylib UI. ```bash -python3 tools/clip/run.py --demo -u raybig -o output.mp4 +python3 tools/clip/run.py --demo -u c3 -o output.mp4 ``` -- `c3` renders the Qt UI into a virtual Xvfb display and screen captures it with `ffmpeg`. -- `raybig` runs the raylib UI, which exports its own frames straight to `ffmpeg`. This bypasses - screen capture entirely, so it also works where a compositor hides window contents from - `x11grab` (notably WSLg). - -Note that `raybig` clips do not get the title, metadata, or route timer overlays that `c3` -clips get: those are `ffmpeg` `drawtext` filters applied during screen capture, and the raylib -UI's own export path does not run them. +The UI exports its frames straight to `ffmpeg`. This bypasses screen capture, so it also works +where a compositor hides window contents from `x11grab` (notably WSLg). ## Options @@ -59,11 +53,10 @@ UI's own export path does not run them. | --- | --- | | `-o, --output` | Output path, must be `.mp4` (default `output.mp4`) | | `-s, --start` / `-e, --end` | Clip window in seconds; omit if timing is in the route ID | -| `-u, --ui` | `c3` (default) or `raybig` | +| `-u, --ui` | `c3` (default) | | `-f, --file-size` | Target size in MB (default 9, sized for Discord/GitHub) | | `-q, --quality` | `high` (hevc, default) or `low` (qcam) | | `-x, --speed` | Record at this speed multiple | -| `-t, --title` | Burn a title into the video (`c3` only) | | `-d, --data-dir` | Use local route data instead of downloading | | `-p, --prefix` | openpilot prefix to isolate the run | @@ -72,11 +65,10 @@ The default 9MB target suits short clips. For anything longer than about a minut ## WSL -Recording works on WSL2 under Windows 11, which supplies a display through WSLg. Use -`-u raybig`; `-u c3` relies on screen capture and can produce black frames there. +Recording works on WSL2 under Windows 11, which supplies a display through WSLg. ```bash -python3 tools/clip/run.py -u raybig -f 250 -o ~/clips/foo.mp4 78511c37de32c375/00000958--8cb1d3e165/140/260 +python3 tools/clip/run.py -u c3 -f 250 -o ~/clips/foo.mp4 78511c37de32c375/00000958--8cb1d3e165/140/260 ``` Running the tool rebuilds native extensions, and this repo tracks those build artifacts in git, diff --git a/tools/clip/run.py b/tools/clip/run.py index 3d49c0391..9f5452568 100755 --- a/tools/clip/run.py +++ b/tools/clip/run.py @@ -20,8 +20,8 @@ from openpilot.common.utils import managed_proc from openpilot.tools.lib.route import Route from openpilot.tools.lib.logreader import LogReader -# cereal.messaging, common.params and common.prefix load native extensions that the raybig path -# builds at runtime (prepare_raybig_runtime), so they're imported at point of use instead - at +# cereal.messaging, common.params and common.prefix load native extensions that the c3 path +# builds at runtime (prepare_c3_runtime), so they're imported at point of use instead - at # module scope they'd fail before that build ever runs. DEFAULT_OUTPUT = 'output.mp4' @@ -32,18 +32,15 @@ FRAMERATE = 20 PIXEL_DEPTH = '24' RESOLUTION = '2160x1080' SECONDS_TO_WARM = 2 -PROC_WAIT_SECONDS = 30*10 -RECORD_TAIL_MARGIN = 5 # extra seconds recorded past the requested end, see record_raybig +RECORD_TAIL_MARGIN = 5 # extra seconds recorded past the requested end, see record_c3 MAX_CACHED_SEGMENTS = 5 # replay's own default, see tools/replay/main.cc -MAX_PLAYBACK = 10 # upper bound for --playback, see record_raybig +MAX_PLAYBACK = 10 # upper bound for --playback, see record_c3 PROGRESS_INTERVAL = 30 # seconds between progress lines while recording STALL_WARN_SECONDS = 60 # warn if the output file stops growing for this long -OPENPILOT_FONT = str(Path(BASEDIR, 'selfdrive/assets/fonts/Inter-Regular.ttf').resolve()) REPLAY = str(Path(BASEDIR, 'tools/replay/replay').resolve()) -UI = str(Path(BASEDIR, 'selfdrive/ui/ui').resolve()) -RAYBIG_UI = str(Path(BASEDIR, 'selfdrive/ui/ui.py').resolve()) -RAYBIG_PREPARE_SCRIPT = str(Path(BASEDIR, 'scripts/launch_ui_raybig_desktop.sh').resolve()) +C3_UI = str(Path(BASEDIR, 'selfdrive/ui/ui.py').resolve()) +C3_PREPARE_SCRIPT = str(Path(BASEDIR, 'scripts/launch_ui_c3_desktop.sh').resolve()) WSLG_X11_DIR = '/mnt/wslg/.X11-unix' logger = logging.getLogger('clip.py') @@ -78,34 +75,10 @@ def check_for_failure(procs: list[Popen]): raise ChildProcessError(msg) -def escape_ffmpeg_text(value: str): - special_chars = {',': '\\,', ':': '\\:', '=': '\\=', '[': '\\[', ']': '\\]'} - value = value.replace('\\', '\\\\\\\\\\\\\\\\') - for char, escaped in special_chars.items(): - value = value.replace(char, escaped) - return value - - def get_logreader(route: Route): return LogReader(route.qlog_paths()[0] if len(route.qlog_paths()) else route.name.canonical_name) -def get_meta_text(lr: LogReader, route: Route): - init_data = lr.first('initData') - car_params = lr.first('carParams') - origin_parts = init_data.gitRemote.split('/') - origin = origin_parts[3] if len(origin_parts) > 3 else 'unknown' - return ', '.join([ - f"openpilot v{init_data.version}", - f"route: {route.name.canonical_name}", - f"car: {car_params.carFingerprint}", - f"origin: {origin}", - f"branch: {init_data.gitBranch}", - f"commit: {init_data.gitCommit[:7]}", - f"modified: {str(init_data.dirty).lower()}", - ]) - - def parse_args(parser: ArgumentParser): args = parser.parse_args() if args.demo: @@ -169,17 +142,15 @@ def wslg_available() -> bool: return os.path.isdir(WSLG_X11_DIR) -def validate_env(parser: ArgumentParser, ui: Literal['c3', 'raybig']): +def validate_env(parser: ArgumentParser, ui: Literal['c3']): if platform.system() not in ['Linux']: parser.exit(1, f'clip.py: error: {platform.system()} is not a supported operating system\n') - use_wslg = ui == 'raybig' and wslg_available() + use_wslg = wslg_available() - required_bins = ['ffmpeg'] - if ui == 'raybig': - required_bins.append('ffprobe') # used to retime the export, see retime_to_wall_clock + required_bins = ['ffmpeg', 'ffprobe'] if not use_wslg: - # Under WSLg, raybig renders against the existing live :0 display instead of a virtual Xvfb one. + # Under WSLg, c3 renders against the existing live :0 display instead of a virtual Xvfb one. required_bins.append('Xvfb') for proc in required_bins: if shutil.which(proc) is None: @@ -187,14 +158,10 @@ def validate_env(parser: ArgumentParser, ui: Literal['c3', 'raybig']): # REPLAY is not checked here; prepare_replay() builds it on demand - if ui == 'c3': - if shutil.which(UI) is None: - parser.exit(1, f'clip.py: error: missing {UI} command, did you build openpilot yet?\n') - elif ui == 'raybig': - if not os.path.isfile(RAYBIG_UI): - parser.exit(1, f'clip.py: error: missing {RAYBIG_UI}\n') - if not os.access(RAYBIG_PREPARE_SCRIPT, os.X_OK): - parser.exit(1, f'clip.py: error: missing or non-executable {RAYBIG_PREPARE_SCRIPT}\n') + if not os.path.isfile(C3_UI): + parser.exit(1, f'clip.py: error: missing {C3_UI}\n') + if not os.access(C3_PREPARE_SCRIPT, os.X_OK): + parser.exit(1, f'clip.py: error: missing or non-executable {C3_PREPARE_SCRIPT}\n') def validate_output_file(output_file: str): @@ -209,12 +176,6 @@ def validate_route(route: str): return route -def validate_title(title: str): - if len(title) > 80: - raise ArgumentTypeError('title must be no longer than 80 chars') - return title - - def validate_scale(scale: str): value = float(scale) if not 0 < value <= 1: @@ -266,58 +227,15 @@ def prepare_replay(jobs: int | None = None): raise ChildProcessError('failed to build replay, see output above') -def prepare_raybig_runtime(): - logger.info('preparing raybig host runtime (this can take a while the first time)...') +def prepare_c3_runtime(): + logger.info('preparing c3 host runtime (this can take a while the first time)...') env = os.environ.copy() - env['SP_RAYBIG_COMPILE_ONLY'] = '1' + env['SP_C3_COMPILE_ONLY'] = '1' # Without this, the script's own cleanup trap restores/deletes the .so files it just built. env['SP_KEEP_DESKTOP_RUNTIME_ARTIFACTS'] = '1' - result = Popen([RAYBIG_PREPARE_SCRIPT], env=env) + result = Popen([C3_PREPARE_SCRIPT], env=env) if result.wait() != 0: - raise ChildProcessError('failed to prepare raybig host runtime, see output above') - - -def make_ffmpeg_cmd(display: str, out: str, duration: int, bit_rate_kbps: int, overlays: list[str]): - return [ - 'ffmpeg', '-y', - '-video_size', RESOLUTION, - '-framerate', str(FRAMERATE), - '-f', 'x11grab', - '-rtbufsize', '100M', - '-draw_mouse', '0', - '-i', display, - '-c:v', 'libx264', - '-maxrate', f'{bit_rate_kbps}k', - '-bufsize', f'{bit_rate_kbps*2}k', - '-crf', '23', - '-filter:v', ','.join(overlays), - '-preset', 'ultrafast', - '-tune', 'zerolatency', - '-pix_fmt', 'yuv420p', - '-movflags', '+faststart', - '-f', 'mp4', - '-t', str(duration), - out, - ] - - -def record(procs: list[Popen], env: dict[str, str], display: str, out: str, duration: int, - bit_rate_kbps: int, overlays: list[str]): - # c3 has no frame export of its own, so screen capture its Xvfb display. raybig uses - # record_raybig instead. - logger.info('waiting for replay to begin (loading segments, may take a while)...') - wait_for_frames(procs) - logger.debug(f'letting UI warm up ({SECONDS_TO_WARM}s)...') - time.sleep(SECONDS_TO_WARM) - check_for_failure(procs) - - ffmpeg_cmd = make_ffmpeg_cmd(display, out, duration, bit_rate_kbps, overlays) - with managed_proc(ffmpeg_cmd, env) as ffmpeg_proc: - all_procs = procs + [ffmpeg_proc] - logger.info(f'recording in progress ({duration}s)...') - ffmpeg_proc.wait(duration + PROC_WAIT_SECONDS) - check_for_failure(all_procs) - logger.info(f'recording complete: {Path(out).resolve()}') + raise ChildProcessError('failed to prepare c3 host runtime, see output above') def probe_video(path: str) -> tuple[float, float]: @@ -367,7 +285,7 @@ def retime_to_wall_clock(out: str, recorded_seconds: float, tolerance: float = 0 retimed.unlink(missing_ok=True) -def record_raybig(ui_proc: Popen, replay_proc: Popen, duration: int, out: str, playback: float = 1.0): +def record_c3(ui_proc: Popen, replay_proc: Popen, duration: int, out: str, playback: float = 1.0): # the UI records from the moment its window opens, so the export leads with some offroad # frames. tail margin covers replay not being exactly at `start` on the first onroad frame. # at playback > 1 the route advances faster than the clock, so we wait proportionally less. @@ -441,8 +359,7 @@ def clip( end: int, speed: int, target_mb: int, - title: str | None, - ui: Literal['c3', 'raybig'], + ui: Literal['c3'], scale: float | None, playback: float, ): @@ -454,9 +371,9 @@ def clip( duration = end - start bit_rate_kbps = int(round(target_mb * 8 * 1024 * 1024 / duration / 1000)) - # raybig exports its own frames (RECORD, below) rather than being screen captured, so under + # c3 exports its own frames (RECORD, below) rather than being screen captured, so under # WSLg it can just render against the live desktop instead of needing its own Xvfb. - use_wslg = ui == 'raybig' and wslg_available() + use_wslg = wslg_available() if use_wslg: display = os.environ.get('DISPLAY', ':0') else: @@ -465,23 +382,6 @@ def clip( display = f':{display_num}' xvfb_cmd = ['Xvfb', display, '-terminate', '-screen', '0', f'{RESOLUTION}x{PIXEL_DEPTH}'] - box_style = 'box=1:boxcolor=black@0.33:boxborderw=7' - meta_text = get_meta_text(lr, route) - overlays = [ - # metadata overlay - f"drawtext=text='{escape_ffmpeg_text(meta_text)}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=15:{box_style}:x=(w-text_w)/2:y=5.5:enable='between(t,1,5)'", - # route time overlay - f"drawtext=text='%{{eif\\:floor(({start}+t)/60)\\:d\\:2}}\\:%{{eif\\:mod({start}+t\\,60)\\:d\\:2}}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=24:{box_style}:x=w-text_w-38:y=38" - ] - if title: - overlays.append(f"drawtext=text='{escape_ffmpeg_text(title)}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=32:{box_style}:x=(w-text_w)/2:y=53") - - if speed > 1: - overlays += [ - f"setpts=PTS/{speed}", - "fps=60", - ] - # read far enough ahead that replay doesn't run dry partway through and loop back on itself, # repeating earlier footage. capped because each cached ~60s segment holds its logs and camera # video in memory, and a long clip would otherwise try to hold the whole route at once. @@ -497,61 +397,44 @@ def clip( prepare_replay() - if ui == 'raybig': - prepare_raybig_runtime() - ui_cmd = [sys.executable, RAYBIG_UI] - else: - ui_cmd = [UI, '-platform', 'xcb'] + prepare_c3_runtime() + ui_cmd = [sys.executable, C3_UI] - # imported here, after prepare_raybig_runtime() has built the native extensions it needs + # imported here, after prepare_c3_runtime() has built the native extensions it needs from openpilot.common.prefix import OpenpilotPrefix with OpenpilotPrefix(prefix, shared_download_cache=True): populate_car_params(lr) env = os.environ.copy() env['DISPLAY'] = display - if ui == 'raybig': - env['BIG'] = '1' - env.setdefault('PRIME_TYPE', '0') - # use the real replayed drive stats instead of raybig's desktop fake-data demo - env['SP_RAYBIG_FAKE_DRIVE_STATS'] = '0' - pythonpath_extra = f"{BASEDIR}{os.pathsep}{Path(BASEDIR, 'starpilot/third_party')}" - env['PYTHONPATH'] = f"{pythonpath_extra}{os.pathsep}{env['PYTHONPATH']}" if env.get('PYTHONPATH') else pythonpath_extra - # the raylib UI pipes its own frames to ffmpeg (system/ui/lib/application.py). no drawtext - # overlays on this path, unlike c3. - env['RECORD'] = '1' - env['RECORD_OUTPUT'] = out - env['RECORD_BITRATE'] = f'{bit_rate_kbps}k' - if speed > 1: - env['RECORD_SPEED'] = str(speed) - # the UI defaults to 60fps and tags the export as such, but the per-frame GPU readback - # can't sustain that and the clip plays fast. ask for a rate it can actually hit. at - # playback > 1 it has to render proportionally faster to still cover FRAMERATE frames - # per second of route. - env['FPS'] = str(int(round(FRAMERATE * playback))) - # sets the render texture size, which is what gets piped to ffmpeg. left unset, the UI - # picks a scale that fits the screen. - if scale is not None: - env['SCALE'] = str(scale) + env['BIG'] = '1' + env.setdefault('PRIME_TYPE', '0') + env['SP_C3_FAKE_DRIVE_STATS'] = '0' + pythonpath_extra = f"{BASEDIR}{os.pathsep}{Path(BASEDIR, 'starpilot/third_party')}" + env['PYTHONPATH'] = f"{pythonpath_extra}{os.pathsep}{env['PYTHONPATH']}" if env.get('PYTHONPATH') else pythonpath_extra + env['RECORD'] = '1' + env['RECORD_OUTPUT'] = out + env['RECORD_BITRATE'] = f'{bit_rate_kbps}k' + if speed > 1: + env['RECORD_SPEED'] = str(speed) + env['FPS'] = str(int(round(FRAMERATE * playback))) + if scale is not None: + env['SCALE'] = str(scale) - if use_wslg: - logger.info('WSLg detected: rendering against the live desktop display.') - with managed_proc(ui_cmd, env) as ui_proc, managed_proc(replay_cmd, env) as replay_proc: - record_raybig(ui_proc, replay_proc, duration, out, playback) - else: - with managed_proc(xvfb_cmd, env) as xvfb_proc: - wait_for_xvfb(display_num, xvfb_proc) - with managed_proc(ui_cmd, env) as ui_proc, managed_proc(replay_cmd, env) as replay_proc: - record_raybig(ui_proc, replay_proc, duration, out, playback) + if use_wslg: + logger.info('WSLg detected: rendering against the live desktop display.') + with managed_proc(ui_cmd, env) as ui_proc, managed_proc(replay_cmd, env) as replay_proc: + record_c3(ui_proc, replay_proc, duration, out, playback) else: with managed_proc(xvfb_cmd, env) as xvfb_proc: wait_for_xvfb(display_num, xvfb_proc) with managed_proc(ui_cmd, env) as ui_proc, managed_proc(replay_cmd, env) as replay_proc: - record([xvfb_proc, ui_proc, replay_proc], env, display, out, duration, bit_rate_kbps, overlays) + record_c3(ui_proc, replay_proc, duration, out, playback) def main(): p = ArgumentParser(prog='clip.py', description='clip your openpilot route.', epilog='comma.ai') + playback_help = "Replay faster than real time; the clip stays at normal speed but drops frames if the UI cannot keep up." route_group = p.add_mutually_exclusive_group(required=True) route_group.add_argument('route', nargs='?', type=validate_route, help=f'The route (e.g. {DEMO_ROUTE} or {DEMO_ROUTE}/{DEMO_START}/{DEMO_END})') route_group.add_argument('--demo', help='use the demo route', action='store_true') @@ -563,14 +446,10 @@ def main(): p.add_argument('-q', '--quality', help='quality of camera (low = qcam, high = hevc)', choices=['low', 'high'], default='high') p.add_argument('-x', '--speed', help='record the clip at this speed multiple', type=int, default=1) p.add_argument('-s', '--start', help='start clipping at seconds', type=int) - p.add_argument('-t', '--title', help='overlay this title on the video (e.g. "Chill driving across the Golden Gate Bridge")', type=validate_title) - p.add_argument('-u', '--ui', help='desktop UI to record. raybig exports its own frames, so it also works where screen capture ' - 'cannot see the window (e.g. WSLg), but gets no title/metadata overlays', - choices=['c3', 'raybig'], default='c3') - p.add_argument('--scale', help='scale the recorded resolution, e.g. 0.5 for half size (raybig only, default is to fit the screen)', + p.add_argument('-u', '--ui', help='desktop UI to record', choices=['c3'], default='c3') + p.add_argument('--scale', help='scale the recorded resolution, e.g. 0.5 for half size (default is to fit the screen)', type=validate_scale) - p.add_argument('--playback', help='replay faster than real time to finish sooner, e.g. 2 for twice as fast (raybig only). ' - 'the clip still plays at normal speed, but drops frames if the UI cannot keep up', + p.add_argument('--playback', help=playback_help, type=validate_playback, default=1.0) args = parse_args(p) validate_env(p, args.ui) @@ -586,7 +465,6 @@ def main(): end=args.end, speed=args.speed, target_mb=args.file_size, - title=args.title, ui=args.ui, scale=args.scale, playback=args.playback, diff --git a/tools/laptop_device_build/Dockerfile b/tools/laptop_device_build/Dockerfile index 8a4cf86c4..0cf253289 100644 --- a/tools/laptop_device_build/Dockerfile +++ b/tools/laptop_device_build/Dockerfile @@ -19,7 +19,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ gcc-aarch64-linux-gnu \ g++-aarch64-linux-gnu \ cmake \ - qtbase5-private-dev \ python3-pip \ xz-utils \ git \ diff --git a/tools/laptop_device_build/extract_sysroot_from_agnos.py b/tools/laptop_device_build/extract_sysroot_from_agnos.py index 0096857d8..a5b8bb51d 100644 --- a/tools/laptop_device_build/extract_sysroot_from_agnos.py +++ b/tools/laptop_device_build/extract_sysroot_from_agnos.py @@ -20,9 +20,6 @@ REQUIRED_DIRS = [ ("usr/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu"), ("usr/include", "/usr/include"), ] -OPTIONAL_DIRS = [ - ("usr/lib/qt5/bin", "/usr/lib/qt5/bin"), -] VENDOR_CANDIDATES = ["/system/vendor/lib64", "/vendor/lib64"] OPTIONAL_INCLUDE_DIRS: list[str] = [] DEBUGFS_NOT_FOUND_MARKERS = ( @@ -237,14 +234,6 @@ def main() -> int: print(f"Extracting {src_path} -> {dst}", flush=True) run_debugfs(image_path, src_path, dst) - for rel_dst, src_path in OPTIONAL_DIRS: - dst = output_dir / rel_dst - try: - print(f"Extracting {src_path} -> {dst}", flush=True) - run_debugfs(image_path, src_path, dst) - except RuntimeError: - print(f"WARN: optional path not found in AGNOS image: {src_path}", flush=True) - vendor_ok = False vendor_dst = output_dir / "system/vendor/lib64" for src_path in VENDOR_CANDIDATES: diff --git a/tools/replay/onroad_config.py b/tools/replay/onroad_config.py index b1599286f..27615a357 100644 --- a/tools/replay/onroad_config.py +++ b/tools/replay/onroad_config.py @@ -217,16 +217,13 @@ def logged_params(init_data: Any | None) -> dict[str, bytes]: def select_ui_target(init_data: Any | None) -> str: if init_data is None: - return "raybig" + return "c3" device_type = str(getattr(init_data, "deviceType", "")).lower() if device_type in {"mici", "c4"}: return "c4" - if device_type in {"tici", "tizi"} and logged_params(init_data).get("UseOldUI") == b"1": - return "c3" - - return "raybig" + return "c3" def seed_logged_params(init_data: Any | None, params: Params) -> int: diff --git a/tools/replay/tests/test_onroad_config.py b/tools/replay/tests/test_onroad_config.py index aa09acddb..ad5eb60eb 100644 --- a/tools/replay/tests/test_onroad_config.py +++ b/tools/replay/tests/test_onroad_config.py @@ -74,10 +74,11 @@ def test_select_ui_uses_c4_for_mici_routes(): assert onroad_config.select_ui_target(_init_data("mici")) == "c4" -def test_select_ui_uses_old_qt_only_when_big_route_logged_use_old_ui(): +def test_select_ui_uses_c3_for_all_big_routes(): assert onroad_config.select_ui_target(_init_data("tici", {"UseOldUI": b"1"})) == "c3" - assert onroad_config.select_ui_target(_init_data("tici", {"TryRaylibUI": b"0"})) == "raybig" - assert onroad_config.select_ui_target(_init_data("tizi")) == "raybig" + assert onroad_config.select_ui_target(_init_data("tici", {"TryRaylibUI": b"0"})) == "c3" + assert onroad_config.select_ui_target(_init_data("tizi")) == "c3" + assert onroad_config.select_ui_target(None) == "c3" def test_seed_onroad_params_uses_logged_disabled_bool_and_desktop_overrides(monkeypatch):