diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_always_on_lateral.png b/selfdrive/frogpilot/assets/toggle_icons/icon_always_on_lateral.png new file mode 100644 index 0000000000..1e55e3feb9 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_always_on_lateral.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_conditional.png b/selfdrive/frogpilot/assets/toggle_icons/icon_conditional.png new file mode 100644 index 0000000000..18ec179d6e Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_conditional.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_device.png b/selfdrive/frogpilot/assets/toggle_icons/icon_device.png new file mode 100644 index 0000000000..2275347c45 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_device.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_green_light.png b/selfdrive/frogpilot/assets/toggle_icons/icon_green_light.png new file mode 100644 index 0000000000..cb47d7a81d Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_green_light.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_lane.png b/selfdrive/frogpilot/assets/toggle_icons/icon_lane.png new file mode 100644 index 0000000000..eea1440c70 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_lane.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_lateral_tune.png b/selfdrive/frogpilot/assets/toggle_icons/icon_lateral_tune.png new file mode 100644 index 0000000000..3dcd9c7fc5 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_lateral_tune.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_light.png b/selfdrive/frogpilot/assets/toggle_icons/icon_light.png new file mode 100644 index 0000000000..043b5c03d4 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_light.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_longitudinal_tune.png b/selfdrive/frogpilot/assets/toggle_icons/icon_longitudinal_tune.png new file mode 100644 index 0000000000..7648a38b2b Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_longitudinal_tune.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_mute.png b/selfdrive/frogpilot/assets/toggle_icons/icon_mute.png new file mode 100644 index 0000000000..487ceae5d4 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_mute.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_personality.png b/selfdrive/frogpilot/assets/toggle_icons/icon_personality.png new file mode 100644 index 0000000000..97c1d7fe5f Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_personality.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_speed_map.png b/selfdrive/frogpilot/assets/toggle_icons/icon_speed_map.png new file mode 100644 index 0000000000..4557dd5fad Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_speed_map.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/icon_vtc.png b/selfdrive/frogpilot/assets/toggle_icons/icon_vtc.png new file mode 100644 index 0000000000..269ba1ea58 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/icon_vtc.png differ diff --git a/selfdrive/frogpilot/assets/toggle_icons/quality_of_life.png b/selfdrive/frogpilot/assets/toggle_icons/quality_of_life.png new file mode 100644 index 0000000000..5130f15275 Binary files /dev/null and b/selfdrive/frogpilot/assets/toggle_icons/quality_of_life.png differ diff --git a/selfdrive/frogpilot/ui/qt/offroad/control_settings.cc b/selfdrive/frogpilot/ui/qt/offroad/control_settings.cc new file mode 100644 index 0000000000..cead13a42f --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/control_settings.cc @@ -0,0 +1,1453 @@ +#include +#include + +#include "selfdrive/frogpilot/ui/qt/offroad/control_settings.h" + +bool checkCommaNNFFSupport(const std::string &carFingerprint) { + std::ifstream file("../car/torque_data/neural_ff_weights.json"); + for (std::string line; std::getline(file, line);) { + if (line.find(carFingerprint) != std::string::npos) { + std::cout << "comma's NNFF supports fingerprint: " << carFingerprint << std::endl; + return true; + } + } + return false; +} + +bool checkNNFFLogFileExists(const std::string &carFingerprint) { + for (const auto &entry : std::filesystem::directory_iterator("../car/torque_data/lat_models")) { + if (entry.path().filename().string().find(carFingerprint) == 0) { + std::cout << "NNFF supports fingerprint: " << entry.path().filename() << std::endl; + return true; + } + } + return false; +} + +FrogPilotControlsPanel::FrogPilotControlsPanel(SettingsWindow *parent) : FrogPilotListWidget(parent) { + std::string branch = params.get("GitBranch"); + isRelease = branch == "FrogPilot"; + + const std::vector> controlToggles { + {"AlwaysOnLateral", tr("Always on Lateral"), tr("Maintain openpilot lateral control when the brake or gas pedals are used.\n\nDeactivation occurs only through the 'Cruise Control' button."), "../frogpilot/assets/toggle_icons/icon_always_on_lateral.png"}, + {"AlwaysOnLateralLKAS", tr("Control Via LKAS Button"), tr("Enable or disable 'Always On Lateral' by clicking your 'LKAS' button."), ""}, + {"AlwaysOnLateralMain", tr("Enable On Cruise Main"), tr("Enable 'Always On Lateral' by clicking your 'Cruise Control' button without requiring openpilot to be enabled first."), ""}, + {"PauseAOLOnBrake", tr("Pause On Brake Below"), tr("Pause 'Always On Lateral' when the brake pedal is being pressed below the set speed."), ""}, + {"HideAOLStatusBar", tr("Hide the Status Bar"), tr("Don't use the status bar for 'Always On Lateral'."), ""}, + + {"ConditionalExperimental", tr("Conditional Experimental Mode"), tr("Automatically switches to 'Experimental Mode' under predefined conditions."), "../frogpilot/assets/toggle_icons/icon_conditional.png"}, + {"CESpeed", tr("Below"), tr("Switch to 'Experimental Mode' below this speed when not following a lead vehicle."), ""}, + {"CECurves", tr("Curve Detected Ahead"), tr("Switch to 'Experimental Mode' when a curve is detected."), ""}, + {"CELead", tr("Lead Detected Ahead"), tr("Switch to 'Experimental Mode' when a slower or stopped lead vehicle is detected ahead."), ""}, + {"CENavigation", tr("Navigation Based"), tr("Switch to 'Experimental Mode' based on navigation data. (i.e. Intersections, stop signs, upcoming turns, etc.)"), ""}, + {"CEStopLights", tr("Stop Lights and Stop Signs"), tr("Switch to 'Experimental Mode' when a stop light or stop sign is detected."), ""}, + {"CESignal", tr("Turn Signal When Below Highway Speeds"), tr("Switch to 'Experimental Mode' when using turn signals below highway speeds to help assist with turns."), ""}, + {"HideCEMStatusBar", tr("Hide the Status Bar"), tr("Don't use the status bar for 'Conditional Experimental Mode'."), ""}, + + {"DeviceManagement", tr("Device Management"), tr("Tweak your device's behaviors to your personal preferences."), "../frogpilot/assets/toggle_icons/icon_device.png"}, + {"DeviceShutdown", tr("Device Shutdown Timer"), tr("Configure how quickly the device shuts down after going offroad."), ""}, + {"NoLogging", tr("Disable Logging"), tr("Turn off all data tracking to enhance privacy or reduce thermal load."), ""}, + {"NoUploads", tr("Disable Uploads"), tr("Turn off all data uploads to comma's servers."), ""}, + {"IncreaseThermalLimits", tr("Increase Thermal Safety Limit"), tr("Allow the device to run at a temperature above comma's recommended thermal limits."), ""}, + {"LowVoltageShutdown", tr("Low Voltage Shutdown Threshold"), tr("Automatically shut the device down when your battery reaches a specific voltage level to prevent killing your battery."), ""}, + {"OfflineMode", tr("Offline Mode"), tr("Allow the device to be offline indefinitely."), ""}, + + {"DrivingPersonalities", tr("Driving Personalities"), tr("Manage the driving behaviors of comma's 'Personality Profiles'."), "../frogpilot/assets/toggle_icons/icon_personality.png"}, + {"CustomPersonalities", tr("Customize Personalities"), tr("Customize the driving personality profiles to your driving style."), ""}, + {"PersonalityInfo", tr("What Do All These Do"), tr("Learn what all the values in 'Custom Personality Profiles' do on openpilot's driving behaviors."), ""}, + {"TrafficPersonalityProfile", tr("Traffic Personality"), tr("Customize the 'Traffic' personality profile."), "../frogpilot/assets/other_images/traffic.png"}, + {"TrafficFollow", tr("Following Distance"), tr("Set the minimum following distance when using 'Traffic Mode'. Your following distance will dynamically adjust between this distance and the following distance from the 'Aggressive' profile when driving between 0 and %1.\n\nFor example:\n\nTraffic Mode: 0.5s\nAggressive: 1.0s\n\n0%2 = 0.5s\n%3 = 0.75s\n%1 = 1.0s"), ""}, + {"TrafficJerkAcceleration", tr("Acceleration Jerk"), tr("Customize the acceleration jerk when using 'Traffic Mode'."), ""}, + {"TrafficJerkDanger", tr("Danger Zone Jerk"), tr("Customize the danger zone jerk when using the 'Traffic' personality."), ""}, + {"TrafficJerkSpeed", tr("Speed Control Jerk"), tr("Customize the speed control jerk when using 'Traffic Mode'."), ""}, + {"ResetTrafficPersonality", tr("Reset Settings"), tr("Reset the values for the 'Traffic Mode' personality back to stock."), ""}, + {"AggressivePersonalityProfile", tr("Aggressive Personality"), tr("Customize the 'Aggressive' personality profile."), "../frogpilot/assets/other_images/aggressive.png"}, + {"AggressiveFollow", tr("Following Distance"), tr("Set the 'Aggressive' personality following distance. Represents seconds to follow behind the lead vehicle.\n\nStock: 1.25 seconds."), ""}, + {"AggressiveJerkAcceleration", tr("Acceleration Jerk"), tr("Customize the acceleration jerk when using the 'Aggressive' personality."), ""}, + {"AggressiveJerkDanger", tr("Danger Zone Jerk"), tr("Customize the danger zone jerk when using the 'Aggressive' personality."), ""}, + {"AggressiveJerkSpeed", tr("Speed Control Jerk"), tr("Customize the speed control jerk when using the 'Aggressive' personality."), ""}, + {"ResetAggressivePersonality", tr("Reset Settings"), tr("Reset the values for the 'Aggressive' personality back to stock."), ""}, + {"StandardPersonalityProfile", tr("Standard Personality"), tr("Customize the 'Standard' personality profile."), "../frogpilot/assets/other_images/standard.png"}, + {"StandardFollow", tr("Following Distance"), tr("Set the 'Standard' personality following distance. Represents seconds to follow behind the lead vehicle.\n\nStock: 1.45 seconds."), ""}, + {"StandardJerkAcceleration", tr("Acceleration Jerk"), tr("Customize the acceleration jerk when using the 'Standard' personality."), ""}, + {"StandardJerkDanger", tr("Danger Zone Jerk"), tr("Customize the danger zone jerk when using the 'Standard' personality."), ""}, + {"StandardJerkSpeed", tr("Speed Control Jerk"), tr("Customize the speed control jerk when using the 'Standard' personality."), ""}, + {"ResetStandardPersonality", tr("Reset Settings"), tr("Reset the values for the 'Standard' personality back to stock."), ""}, + {"RelaxedPersonalityProfile", tr("Relaxed Personality"), tr("Customize the 'Relaxed' personality profile."), "../frogpilot/assets/other_images/relaxed.png"}, + {"RelaxedFollow", tr("Following Distance"), tr("Set the 'Relaxed' personality following distance. Represents seconds to follow behind the lead vehicle.\n\nStock: 1.75 seconds."), ""}, + {"RelaxedJerkAcceleration", tr("Acceleration Jerk"), tr("Customize the acceleration jerk when using the 'Relaxed' personality."), ""}, + {"RelaxedJerkDanger", tr("Danger Zone Jerk"), tr("Customize the danger zone jerk when using the 'Relaxed' personality."), ""}, + {"RelaxedJerkSpeed", tr("Speed Control Jerk"), tr("Customize the speed control jerk when using the 'Relaxed' personality."), ""}, + {"ResetRelaxedPersonality", tr("Reset Settings"), tr("Reset the values for the 'Relaxed' personality back to stock."), ""}, + {"OnroadDistanceButton", tr("Onroad Distance Button"), tr("Simulate a distance button via the onroad UI to control personalities, 'Experimental Mode', and 'Traffic Mode'."), ""}, + + {"ExperimentalModeActivation", tr("Experimental Mode Activation"), tr("Toggle Experimental Mode with either buttons on the steering wheel or the screen. \n\nOverrides 'Conditional Experimental Mode'."), "../assets/img_experimental_white.svg"}, + {"ExperimentalModeViaLKAS", tr("Click LKAS Button"), tr("Enable/disable 'Experimental Mode' by clicking the 'LKAS' button on your steering wheel."), ""}, + {"ExperimentalModeViaTap", tr("Double Tap the UI"), tr("Enable/disable 'Experimental Mode' by double tapping the onroad UI within a 0.5 second time frame."), ""}, + {"ExperimentalModeViaDistance", tr("Long Press Distance"), tr("Enable/disable 'Experimental Mode' by holding down the 'distance' button on your steering wheel for 0.5 seconds."), ""}, + + {"LaneChangeCustomizations", tr("Lane Change Customizations"), tr("Customize the lane change behaviors in openpilot."), "../frogpilot/assets/toggle_icons/icon_lane.png"}, + {"LaneChangeTime", tr("Lane Change Timer"), tr("Set a delay before executing a lane change."), ""}, + {"LaneDetectionWidth", tr("Lane Detection Threshold"), tr("Set the required lane width to be qualified as a lane."), ""}, + {"MinimumLaneChangeSpeed", tr("Minimum Lane Change Speed"), tr("Customize the minimum driving speed to allow openpilot to change lanes."), ""}, + {"NudgelessLaneChange", tr("Nudgeless Lane Change"), tr("Enable lane changes without requiring manual steering input."), ""}, + {"OneLaneChange", tr("One Lane Change Per Signal"), tr("Only allow one lane change per turn signal activation."), ""}, + + {"LateralTune", tr("Lateral Tuning"), tr("Modify openpilot's steering behavior."), "../frogpilot/assets/toggle_icons/icon_lateral_tune.png"}, + {"ForceAutoTune", tr("Force Auto Tune"), tr("Forces comma's auto lateral tuning for unsupported vehicles."), ""}, + {"NNFF", tr("NNFF"), tr("Use Twilsonco's Neural Network Feedforward for enhanced precision in lateral control."), ""}, + {"NNFFLite", tr("NNFF-Lite"), tr("Use Twilsonco's Neural Network Feedforward for enhanced precision in lateral control for cars without available NNFF logs."), ""}, + {"SteerRatio", steerRatioStock != 0 ? QString(tr("Steer Ratio (Default: %1)")).arg(QString::number(steerRatioStock, 'f', 2)) : tr("Steer Ratio"), tr("Use a custom steer ratio as opposed to comma's auto tune value."), ""}, + {"TacoTune", tr("Taco Tune"), tr("Use comma's 'Taco Tune' designed for handling left and right turns."), ""}, + {"TurnDesires", tr("Use Turn Desires"), tr("Use turn desires for greater precision in turns below the minimum lane change speed."), ""}, + + {"LongitudinalTune", tr("Longitudinal Tuning"), tr("Modify openpilot's acceleration and braking behavior."), "../frogpilot/assets/toggle_icons/icon_longitudinal_tune.png"}, + {"AccelerationProfile", tr("Acceleration Profile"), tr("Change the acceleration rate to be either sporty or eco-friendly."), ""}, + {"DecelerationProfile", tr("Deceleration Profile"), tr("Change the deceleration rate to be either sporty or eco-friendly."), ""}, + {"AggressiveAcceleration", tr("Increase Acceleration Behind Lead"), tr("Increase aggressiveness when following a faster lead."), ""}, + {"StoppingDistance", tr("Increase Stop Distance Behind Lead"), tr("Increase the stopping distance for a more comfortable stop from lead vehicles."), ""}, + {"LeadDetectionThreshold", tr("Lead Detection Threshold"), tr("Increase or decrease the lead detection threshold to either detect leads sooner, or increase model confidence."), ""}, + {"SmoothBraking", tr("Smoother Braking"), tr("Smoothen out the braking behavior when approaching slower vehicles."), ""}, + {"TrafficMode", tr("Traffic Mode"), tr("Enable the ability to activate 'Traffic Mode' by holding down the 'distance' button for 2.5 seconds. When 'Traffic Mode' is active the onroad UI will turn red and openpilot will drive catered towards stop and go traffic."), ""}, + + {"MTSCEnabled", tr("Map Turn Speed Control"), tr("Slow down for anticipated curves detected by the downloaded maps."), "../frogpilot/assets/toggle_icons/icon_speed_map.png"}, + {"DisableMTSCSmoothing", tr("Disable MTSC UI Smoothing"), tr("Disables the smoothing for the requested speed in the onroad UI to show exactly what speed MTSC is currently requesting."), ""}, + {"MTSCCurvatureCheck", tr("Model Curvature Detection Failsafe"), tr("Only trigger MTSC when the model detects a curve in the road. Purely used as a failsafe to prevent false positives. Leave this off if you never experience false positives."), ""}, + {"MTSCAggressiveness", tr("Turn Speed Aggressiveness"), tr("Set turn speed aggressiveness. Higher values result in faster turns, lower values yield gentler turns. \n\nA change of +- 1% results in the speed being raised or lowered by about 1 mph."), ""}, + + {"ModelManagement", tr("Model Management"), tr("Manage openpilot's driving models."), "../assets/offroad/icon_calibration.png"}, + {"AutomaticallyUpdateModels", tr("Automatically Update Models"), tr("Automatically download models as they're updated or added to the model list."), ""}, + {"ModelRandomizer", tr("Model Randomizer"), tr("Have a random model be selected each drive that can be reviewed at the end of each drive to find your preferred model."), ""}, + {"ManageBlacklistedModels", tr("Manage Model Blacklist"), "Manage the models on your blacklist.", ""}, + {"ResetScores", tr("Reset Model Scores"), tr("Reset the scores you have rated the openpilot models."), ""}, + {"ReviewScores", tr("Review Model Scores"), tr("View the scores FrogPilot and yourself have rated the openpilot models."), ""}, + {"DeleteModel", tr("Delete Model"), "", ""}, + {"DownloadModel", tr("Download Model"), "", ""}, + {"DownloadAllModels", tr("Download All Models"), "", ""}, + {"SelectModel", tr("Select Model"), "", ""}, + {"ResetCalibrations", tr("Reset Model Calibrations"), tr("Reset the driving model calibrations."), ""}, + + {"QOLControls", tr("Quality of Life"), tr("Miscellaneous quality of life changes to improve your overall openpilot experience."), "../frogpilot/assets/toggle_icons/quality_of_life.png"}, + {"CustomCruise", tr("Cruise Increase Interval"), tr("Set a custom interval to increase the max set speed by."), ""}, + {"CustomCruiseLong", tr("Cruise Increase Interval (Long Press)"), tr("Set a custom interval to increase the max set speed by when holding down the cruise increase button."), ""}, + {"ForceStandstill", tr("Force Standstill State"), tr("Keeps openpilot in the 'standstill' state until the gas pedal is pressed."), ""}, + {"MapGears", tr("Map Accel/Decel To Gears"), tr("Map your acceleration/deceleration profile to your 'Eco' and/or 'Sport' gears."), ""}, + {"PauseLateralSpeed", tr("Pause Lateral Below"), tr("Pause lateral control on all speeds below the set speed."), ""}, + {"ReverseCruise", tr("Reverse Cruise Increase"), tr("Reverses the 'long press' functionality logic to increase the max set speed by 5 instead of 1. Useful to increase the max speed quickly."), ""}, + {"SetSpeedOffset", tr("Set Speed Offset"), tr("Set an offset for your desired set speed."), ""}, + + {"SpeedLimitController", tr("Speed Limit Controller"), tr("Automatically adjust the max speed to match the current speed limit using 'Open Street Maps', 'Navigate On openpilot', or your car's dashboard (Toyotas/Lexus/HKG only)."), "../assets/offroad/icon_speed_limit.png"}, + {"SLCControls", tr("Controls Settings"), tr("Manage toggles related to 'Speed Limit Controller's controls."), ""}, + {"Offset1", tr("Speed Limit Offset (0-34 mph)"), tr("Speed limit offset for speed limits between 0-34 mph."), ""}, + {"Offset2", tr("Speed Limit Offset (35-54 mph)"), tr("Speed limit offset for speed limits between 35-54 mph."), ""}, + {"Offset3", tr("Speed Limit Offset (55-64 mph)"), tr("Speed limit offset for speed limits between 55-64 mph."), ""}, + {"Offset4", tr("Speed Limit Offset (65-99 mph)"), tr("Speed limit offset for speed limits between 65-99 mph."), ""}, + {"SLCFallback", tr("Fallback Method"), tr("Choose your fallback method when there is no speed limit available."), ""}, + {"SLCOverride", tr("Override Method"), tr("Choose your preferred method to override the current speed limit."), ""}, + {"SLCPriority", tr("Priority Order"), tr("Configure the speed limit priority order."), ""}, + {"SLCQOL", tr("Quality of Life"), tr("Manage toggles related to 'Speed Limit Controller's quality of life features."), ""}, + {"SLCConfirmation", tr("Confirm New Speed Limits"), tr("Don't automatically start using the new speed limit until it's been manually confirmed."), ""}, + {"ForceMPHDashboard", tr("Force MPH From Dashboard Readings"), tr("Force MPH readings from the dashboard. Only use this if you live in an area where the speed limits from your dashboard are in KPH, but you use MPH."), ""}, + {"SLCLookaheadHigher", tr("Prepare For Higher Speed Limits"), tr("Set a 'lookahead' value to prepare for upcoming speed limits higher than your current speed limit using the data stored in 'Open Street Maps'."), ""}, + {"SLCLookaheadLower", tr("Prepare For Lower Speed Limits"), tr("Set a 'lookahead' value to prepare for upcoming speed limits lower than your current speed limit using the data stored in 'Open Street Maps'."), ""}, + {"SetSpeedLimit", tr("Use Current Speed Limit As Set Speed"), tr("Sets your max speed to the current speed limit if one is populated when you initially enable openpilot."), ""}, + {"SLCVisuals", tr("Visuals Settings"), tr("Manage toggles related to 'Speed Limit Controller's visuals."), ""}, + {"ShowSLCOffset", tr("Show Speed Limit Offset"), tr("Show the speed limit offset separated from the speed limit in the onroad UI when using 'Speed Limit Controller'."), ""}, + {"SpeedLimitChangedAlert", tr("Speed Limit Changed Alert"), tr("Trigger an alert whenever the speed limit changes."), ""}, + {"UseVienna", tr("Use Vienna Speed Limit Signs"), tr("Use the Vienna (EU) speed limit style signs as opposed to MUTCD (US)."), ""}, + + {"VisionTurnControl", tr("Vision Turn Speed Controller"), tr("Slow down for detected curves in the road."), "../frogpilot/assets/toggle_icons/icon_vtc.png"}, + {"DisableVTSCSmoothing", tr("Disable VTSC UI Smoothing"), tr("Disables the smoothing for the requested speed in the onroad UI."), ""}, + {"CurveSensitivity", tr("Curve Detection Sensitivity"), tr("Set curve detection sensitivity. Higher values prompt earlier responses, lower values lead to smoother but later reactions."), ""}, + {"TurnAggressiveness", tr("Turn Speed Aggressiveness"), tr("Set turn speed aggressiveness. Higher values result in faster turns, lower values yield gentler turns."), ""}, + }; + + for (const auto &[param, title, desc, icon] : controlToggles) { + AbstractControl *controlToggle; + + if (param == "AlwaysOnLateral") { + FrogPilotParamManageControl *aolToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(aolToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(aolKeys.find(key.c_str()) != aolKeys.end()); + } + openParentToggle(); + }); + controlToggle = aolToggle; + } else if (param == "PauseAOLOnBrake") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph")); + + } else if (param == "ConditionalExperimental") { + FrogPilotParamManageControl *conditionalExperimentalToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(conditionalExperimentalToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(conditionalExperimentalKeys.find(key.c_str()) != conditionalExperimentalKeys.end()); + } + openParentToggle(); + }); + controlToggle = conditionalExperimentalToggle; + } else if (param == "CESpeed") { + FrogPilotParamValueControl *CESpeed = new FrogPilotParamValueControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph")); + FrogPilotParamValueControl *CESpeedLead = new FrogPilotParamValueControl("CESpeedLead", tr(" With Lead"), tr("Switch to 'Experimental Mode' below this speed when following a lead vehicle."), icon, 0, 99, std::map(), this, false, tr("mph")); + FrogPilotDualParamControl *conditionalSpeeds = new FrogPilotDualParamControl(CESpeed, CESpeedLead, this); + controlToggle = reinterpret_cast(conditionalSpeeds); + } else if (param == "CECurves") { + std::vector curveToggles{"CECurvesLead"}; + std::vector curveToggleNames{tr("With Lead")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, curveToggles, curveToggleNames); + } else if (param == "CELead") { + std::vector leadToggles{"CESlowerLead", "CEStoppedLead"}; + std::vector leadToggleNames{tr("Slower Lead"), tr("Stopped Lead")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, leadToggles, leadToggleNames); + } else if (param == "CENavigation") { + std::vector navigationToggles{"CENavigationIntersections", "CENavigationTurns", "CENavigationLead"}; + std::vector navigationToggleNames{tr("Intersections"), tr("Turns"), tr("With Lead")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, navigationToggles, navigationToggleNames); + } else if (param == "CEStopLights") { + std::vector stopLightsToggles{"CEStopLightsLessSensitive"}; + std::vector stopLightsToggleNames{tr("Decrease Sensitivity")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, stopLightsToggles, stopLightsToggleNames); + + } else if (param == "DeviceManagement") { + FrogPilotParamManageControl *deviceManagementToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(deviceManagementToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(deviceManagementKeys.find(key.c_str()) != deviceManagementKeys.end()); + } + openParentToggle(); + }); + controlToggle = 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")); + } + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 33, shutdownLabels, this, false); + } else if (param == "NoUploads") { + std::vector uploadsToggles{"DisableOnroadUploads"}; + std::vector uploadsToggleNames{tr("Only Onroad")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, uploadsToggles, uploadsToggleNames); + } else if (param == "LowVoltageShutdown") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 11.8, 12.5, std::map(), this, false, tr(" volts"), 1, 0.01); + + } else if (param == "DrivingPersonalities") { + FrogPilotParamManageControl *drivingPersonalitiesToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(drivingPersonalitiesToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(drivingPersonalityKeys.find(key.c_str()) != drivingPersonalityKeys.end()); + } + openParentToggle(); + }); + controlToggle = drivingPersonalitiesToggle; + } else if (param == "CustomPersonalities") { + FrogPilotParamManageControl *customPersonalitiesToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(customPersonalitiesToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + customPersonalitiesOpen = true; + for (auto &[key, toggle] : toggles) { + toggle->setVisible(customdrivingPersonalityKeys.find(key.c_str()) != customdrivingPersonalityKeys.end()); + } + openSubParentToggle(); + }); + controlToggle = customPersonalitiesToggle; + } else if (param == "PersonalityInfo") { + ButtonControl *personalitiesInfoBtn = new ButtonControl(title, tr("VIEW"), desc); + QObject::connect(personalitiesInfoBtn, &ButtonControl::clicked, [=]() { + const std::string txt = util::read_file("../frogpilot/ui/qt/offroad/personalities_info.txt"); + ConfirmationDialog::rich(QString::fromStdString(txt), this); + }); + controlToggle = reinterpret_cast(personalitiesInfoBtn); + } else if (param == "ResetTrafficPersonality" || param == "ResetAggressivePersonality" || param == "ResetStandardPersonality" || param == "ResetRelaxedPersonality") { + std::vector personalityOptions{tr("Reset")}; + FrogPilotButtonsControl *profileBtn = new FrogPilotButtonsControl(title, desc, icon, personalityOptions); + controlToggle = profileBtn; + } else if (param == "TrafficPersonalityProfile") { + FrogPilotParamManageControl *trafficPersonalityToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(trafficPersonalityToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(trafficPersonalityKeys.find(key.c_str()) != trafficPersonalityKeys.end()); + } + openSubSubParentToggle(); + }); + controlToggle = trafficPersonalityToggle; + } else if (param == "AggressivePersonalityProfile") { + FrogPilotParamManageControl *aggressivePersonalityToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(aggressivePersonalityToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(aggressivePersonalityKeys.find(key.c_str()) != aggressivePersonalityKeys.end()); + } + openSubSubParentToggle(); + }); + controlToggle = aggressivePersonalityToggle; + } else if (param == "StandardPersonalityProfile") { + FrogPilotParamManageControl *standardPersonalityToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(standardPersonalityToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(standardPersonalityKeys.find(key.c_str()) != standardPersonalityKeys.end()); + } + openSubSubParentToggle(); + }); + controlToggle = standardPersonalityToggle; + } else if (param == "RelaxedPersonalityProfile") { + FrogPilotParamManageControl *relaxedPersonalityToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(relaxedPersonalityToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(relaxedPersonalityKeys.find(key.c_str()) != relaxedPersonalityKeys.end()); + } + openSubSubParentToggle(); + }); + controlToggle = relaxedPersonalityToggle; + } else if (trafficPersonalityKeys.find(param) != trafficPersonalityKeys.end() || + aggressivePersonalityKeys.find(param) != aggressivePersonalityKeys.end() || + standardPersonalityKeys.find(param) != standardPersonalityKeys.end() || + relaxedPersonalityKeys.find(param) != relaxedPersonalityKeys.end()) { + if (param == "TrafficFollow" || param == "AggressiveFollow" || param == "StandardFollow" || param == "RelaxedFollow") { + if (param == "TrafficFollow") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0.5, 5, std::map(), this, false, tr(" seconds"), 1, 0.01); + } else { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 5, std::map(), this, false, tr(" seconds"), 1, 0.01); + } + } else { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 500, std::map(), this, false, "%"); + } + } else if (param == "OnroadDistanceButton") { + std::vector onroadDistanceToggles{"KaofuiIcons"}; + std::vector onroadDistanceToggleNames{tr("Kaofui's Icons")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, onroadDistanceToggles, onroadDistanceToggleNames); + + } else if (param == "ExperimentalModeActivation") { + FrogPilotParamManageControl *experimentalModeActivationToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(experimentalModeActivationToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + std::set modifiedExperimentalModeActivationKeys = experimentalModeActivationKeys; + + if (params.getBool("AlwaysOnLateralLKAS")) { + modifiedExperimentalModeActivationKeys.erase("ExperimentalModeViaLKAS"); + } + + toggle->setVisible(modifiedExperimentalModeActivationKeys.find(key.c_str()) != modifiedExperimentalModeActivationKeys.end()); + } + openParentToggle(); + }); + controlToggle = experimentalModeActivationToggle; + + } else if (param == "LateralTune") { + FrogPilotParamManageControl *lateralTuneToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(lateralTuneToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + std::set modifiedLateralTuneKeys = lateralTuneKeys; + + if (hasAutoTune || params.getBool("LateralTune") && params.getBool("NNFF")) { + modifiedLateralTuneKeys.erase("ForceAutoTune"); + } + + if (hasCommaNNFFSupport || !hasNNFFLog) { + modifiedLateralTuneKeys.erase("NNFF"); + } else { + modifiedLateralTuneKeys.erase("NNFFLite"); + } + + toggle->setVisible(modifiedLateralTuneKeys.find(key.c_str()) != modifiedLateralTuneKeys.end()); + } + openParentToggle(); + }); + controlToggle = lateralTuneToggle; + } else if (param == "SteerRatio") { + std::vector steerRatioToggles{"ResetSteerRatio"}; + std::vector steerRatioToggleNames{"Reset"}; + controlToggle = new FrogPilotParamValueToggleControl(param, title, desc, icon, steerRatioStock * 0.75, steerRatioStock * 1.25, std::map(), this, false, "", 1, 0.01, steerRatioToggles, steerRatioToggleNames); + + } else if (param == "LongitudinalTune") { + FrogPilotParamManageControl *longitudinalTuneToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(longitudinalTuneToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + std::set modifiedLongitudinalTuneKeys = longitudinalTuneKeys; + + if (!isRelease && params.get("Model") == "radical-turtle") { + modifiedLongitudinalTuneKeys.erase("LeadDetectionThreshold"); + } + + toggle->setVisible(modifiedLongitudinalTuneKeys.find(key.c_str()) != modifiedLongitudinalTuneKeys.end()); + } + openParentToggle(); + }); + controlToggle = longitudinalTuneToggle; + } else if (param == "AccelerationProfile") { + std::vector profileOptions{tr("Standard"), tr("Eco"), tr("Sport"), tr("Sport+")}; + FrogPilotButtonParamControl *profileSelection = new FrogPilotButtonParamControl(param, title, desc, icon, profileOptions); + controlToggle = profileSelection; + } else if (param == "DecelerationProfile") { + std::vector profileOptions{tr("Standard"), tr("Eco"), tr("Sport")}; + FrogPilotButtonParamControl *profileSelection = new FrogPilotButtonParamControl(param, title, desc, icon, profileOptions); + controlToggle = profileSelection; + } else if (param == "StoppingDistance") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 10, std::map(), this, false, tr(" feet")); + } else if (param == "LeadDetectionThreshold") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 99, std::map(), this, false, "%"); + + } else if (param == "MTSCEnabled") { + FrogPilotParamManageControl *mtscToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(mtscToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(mtscKeys.find(key.c_str()) != mtscKeys.end()); + } + openParentToggle(); + }); + controlToggle = mtscToggle; + } else if (param == "MTSCAggressiveness") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 200, std::map(), this, false, "%"); + + } else if (param == "ModelManagement") { + FrogPilotParamManageControl *modelManagementToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(modelManagementToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + availableModelNames = QString::fromStdString(params.get("AvailableModelsNames")).split(","); + availableModels = QString::fromStdString(params.get("AvailableModels")).split(","); + experimentalModels = QString::fromStdString(params.get("ExperimentalModels")).split(","); + + modelManagementOpen = true; + for (auto &[key, toggle] : toggles) { + toggle->setVisible(modelManagementKeys.find(key.c_str()) != modelManagementKeys.end()); + } + + std::string currentModel = params.get("Model") + ".thneed"; + QStringList modelFiles = modelDir.entryList({"*.thneed"}, QDir::Files); + modelFiles.removeAll(QString::fromStdString(currentModel)); + haveModelsDownloaded = modelFiles.size() > 1; + modelsDownloaded = params.getBool("ModelsDownloaded"); + + openParentToggle(); + }); + controlToggle = modelManagementToggle; + } else if (param == "ModelRandomizer") { + FrogPilotParamManageControl *modelRandomizerToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(modelRandomizerToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(modelRandomizerKeys.find(key.c_str()) != modelRandomizerKeys.end()); + } + openSubParentToggle(); + }); + controlToggle = modelRandomizerToggle; + } else if (param == "ManageBlacklistedModels") { + std::vector blacklistOptions{tr("ADD"), tr("REMOVE")}; + FrogPilotButtonsControl *manageModelsBlacklistBtn = new FrogPilotButtonsControl(title, desc, "", blacklistOptions); + QObject::connect(manageModelsBlacklistBtn, &FrogPilotButtonsControl::buttonClicked, [=](int id) { + QStringList blacklistedModels = QString::fromStdString(params.get("BlacklistedModels")).split(",", QString::SkipEmptyParts); + QMap labelToModelMap; + QStringList selectableModels, deletableModels; + + for (int i = 0; i < availableModels.size(); ++i) { + QString modelFileName = availableModels[i]; + QString readableName = availableModelNames[i]; + if (!blacklistedModels.contains(modelFileName)) { + selectableModels.append(readableName); + } else { + deletableModels.append(readableName); + } + labelToModelMap[readableName] = modelFileName; + } + + if (id == 0) { + if (selectableModels.size() == 1) { + QString onlyModel = selectableModels.first(); + FrogPilotConfirmationDialog::toggleAlert( + tr("There's no more models to blacklist! The only available model is \"%1\"!").arg(onlyModel), + tr("OK"), this); + } else { + QString selectedModel = MultiOptionDialog::getSelection(tr("Select a model to add to the blacklist"), selectableModels, "", this); + if (!selectedModel.isEmpty() && ConfirmationDialog::confirm(tr("Are you sure you want to add this model to the blacklist?"), tr("Add"), this)) { + QString modelToAdd = labelToModelMap[selectedModel]; + if (!blacklistedModels.contains(modelToAdd)) { + blacklistedModels.append(modelToAdd); + params.putNonBlocking("BlacklistedModels", blacklistedModels.join(",").toStdString()); + } + } + } + } else if (id == 1) { + QString selectedModel = MultiOptionDialog::getSelection(tr("Select a model to remove from the blacklist"), deletableModels, "", this); + if (!selectedModel.isEmpty() && ConfirmationDialog::confirm(tr("Are you sure you want to remove this model from the blacklist?"), tr("Remove"), this)) { + QString modelToRemove = labelToModelMap[selectedModel]; + if (blacklistedModels.contains(modelToRemove)) { + blacklistedModels.removeAll(modelToRemove); + params.putNonBlocking("BlacklistedModels", blacklistedModels.join(",").toStdString()); + paramsStorage.put("BlacklistedModels", blacklistedModels.join(",").toStdString()); + } + } + } + }); + controlToggle = reinterpret_cast(manageModelsBlacklistBtn); + } else if (param == "ResetScores") { + ButtonControl *resetScoresBtn = new ButtonControl(title, tr("RESET"), desc); + QObject::connect(resetScoresBtn, &ButtonControl::clicked, [=]() { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset all of your model scores?"), this)) { + for (QString model : availableModelNames) { + QString cleanedModelName = processModelName(model); + params.remove(QString("%1Drives").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1Drives").arg(cleanedModelName).toStdString()); + params.remove(QString("%1Score").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1Score").arg(cleanedModelName).toStdString()); + } + + updateModelLabels(); + } + }); + controlToggle = reinterpret_cast(resetScoresBtn); + } else if (param == "ReviewScores") { + ButtonControl *reviewScoresBtn = new ButtonControl(title, tr("VIEW"), desc); + QObject::connect(reviewScoresBtn, &ButtonControl::clicked, [=]() { + for (LabelControl *label : labelControls) { + label->setVisible(true); + } + for (auto &[key, toggle] : toggles) { + toggle->setVisible(false); + } + openSubSubParentToggle(); + }); + controlToggle = reinterpret_cast(reviewScoresBtn); + } else if (param == "DeleteModel") { + deleteModelBtn = new ButtonControl(title, tr("DELETE"), desc); + QObject::connect(deleteModelBtn, &ButtonControl::clicked, [=]() { + std::string currentModel = params.get("Model") + ".thneed"; + QMap labelToFileMap; + + QStringList existingModelFiles = modelDir.entryList({"*.thneed"}, QDir::Files); + QStringList deletableModelLabels; + + for (int i = 0; i < availableModels.size(); ++i) { + QString modelFileName = availableModels[i] + ".thneed"; + if (existingModelFiles.contains(modelFileName) && modelFileName != QString::fromStdString(currentModel) && !availableModelNames[i].contains(" (Default)")) { + deletableModelLabels.append(availableModelNames[i]); + labelToFileMap[availableModelNames[i]] = modelFileName; + } + } + + QString selectedModel = MultiOptionDialog::getSelection(tr("Select a model to delete"), deletableModelLabels, "", this); + if (!selectedModel.isEmpty() && ConfirmationDialog::confirm(tr("Are you sure you want to delete this model?"), tr("Delete"), this)) { + std::thread([=]() { + modelDeleting = true; + modelsDownloaded = false; + update(); + + params.putBoolNonBlocking("ModelsDownloaded", false); + + deleteModelBtn->setValue(tr("Deleting...")); + + QFile::remove(modelDir.absoluteFilePath(labelToFileMap[selectedModel])); + + deleteModelBtn->setValue(tr("Deleted!")); + + std::this_thread::sleep_for(std::chrono::seconds(2)); + deleteModelBtn->setValue(""); + modelDeleting = false; + + std::string currentModel = params.get("Model") + ".thneed"; + QStringList modelFiles = modelDir.entryList({"*.thneed"}, QDir::Files); + modelFiles.removeAll(QString::fromStdString(currentModel)); + + haveModelsDownloaded = modelFiles.size() > 1; + update(); + }).detach(); + } + }); + controlToggle = reinterpret_cast(deleteModelBtn); + } else if (param == "DownloadModel") { + downloadModelBtn = new ButtonControl(title, tr("DOWNLOAD"), desc); + QObject::connect(downloadModelBtn, &ButtonControl::clicked, [=]() { + QMap labelToModelMap; + QStringList existingModelFiles = modelDir.entryList({"*.thneed"}, QDir::Files); + QStringList downloadableModelLabels; + + for (int i = 0; i < availableModels.size(); ++i) { + QString modelFileName = availableModels[i] + ".thneed"; + if (!existingModelFiles.contains(modelFileName) && !availableModelNames[i].contains("(Default)")) { + downloadableModelLabels.append(availableModelNames[i]); + labelToModelMap.insert(availableModelNames[i], availableModels[i]); + } + } + + QString modelToDownload = MultiOptionDialog::getSelection(tr("Select a driving model to download"), downloadableModelLabels, "", this); + if (!modelToDownload.isEmpty()) { + modelDownloading = true; + paramsMemory.put("ModelToDownload", labelToModelMap.value(modelToDownload).toStdString()); + paramsMemory.put("ModelDownloadProgress", "0%"); + + downloadModelBtn->setValue(tr("Downloading %1...").arg(modelToDownload.remove(QRegularExpression("[πŸ—ΊοΈπŸ‘€πŸ“‘]")).trimmed())); + + QTimer *progressTimer = new QTimer(this); + progressTimer->setInterval(100); + + QObject::connect(progressTimer, &QTimer::timeout, this, [=]() { + QString progress = QString::fromStdString(paramsMemory.get("ModelDownloadProgress")); + bool downloadFailed = progress.contains(QRegularExpression("exists|Failed|offline", QRegularExpression::CaseInsensitiveOption)); + + if (progress != "0%") { + downloadModelBtn->setValue(progress); + } + + if (progress == "Downloaded!" || downloadFailed) { + bool lastModelDownloaded = !downloadFailed; + + if (!downloadFailed) { + haveModelsDownloaded = true; + update(); + } + + if (lastModelDownloaded) { + for (const QString &model : availableModels) { + if (!QFile::exists(modelDir.filePath(model + ".thneed"))) { + lastModelDownloaded = false; + break; + } + } + } + + downloadModelBtn->setValue(progress); + paramsMemory.remove("ModelDownloadProgress"); + + progressTimer->stop(); + progressTimer->deleteLater(); + + QTimer::singleShot(downloadFailed ? 10000 : 2000, this, [=]() { + modelDownloading = false; + downloadModelBtn->setValue(""); + + if (lastModelDownloaded) { + modelsDownloaded = true; + update(); + + params.putBoolNonBlocking("ModelsDownloaded", modelsDownloaded); + } + }); + } + }); + progressTimer->start(); + } + }); + controlToggle = reinterpret_cast(downloadModelBtn); + } else if (param == "DownloadAllModels") { + downloadAllModelsBtn = new ButtonControl(title, tr("DOWNLOAD"), desc); + QObject::connect(downloadAllModelsBtn, &ButtonControl::clicked, [=]() { + startDownloadAllModels(); + }); + controlToggle = reinterpret_cast(downloadAllModelsBtn); + } else if (param == "SelectModel") { + selectModelBtn = new ButtonControl(title, tr("SELECT"), desc); + QObject::connect(selectModelBtn, &ButtonControl::clicked, [=]() { + QSet modelFilesBaseNames = QSet::fromList( + modelDir.entryList({"*.thneed"}, QDir::Files).replaceInStrings(QRegExp("\\.thneed$"), "") + ); + + QStringList selectableModelLabels; + for (int i = 0; i < availableModels.size(); ++i) { + if (modelFilesBaseNames.contains(availableModels[i]) || availableModelNames[i].contains("(Default)")) { + selectableModelLabels.append(availableModelNames[i]); + } + } + + QString modelToSelect = MultiOptionDialog::getSelection(tr("Select a model - πŸ—ΊοΈ = Navigation | πŸ“‘ = Radar | πŸ‘€ = VOACC"), selectableModelLabels, "", this); + if (!modelToSelect.isEmpty()) { + selectModelBtn->setValue(modelToSelect); + int modelIndex = availableModelNames.indexOf(modelToSelect); + + params.putNonBlocking("Model", availableModels.at(modelIndex).toStdString()); + params.putNonBlocking("ModelName", modelToSelect.toStdString()); + + if (experimentalModels.contains(availableModels.at(modelIndex))) { + FrogPilotConfirmationDialog::toggleAlert( + tr("WARNING: This is a very experimental model and may drive dangerously!"), + tr("I understand the risks."), this); + } + + QString model = availableModelNames.at(modelIndex); + QString part_model_param = processModelName(model); + + if (!params.checkKey(part_model_param.toStdString() + "CalibrationParams") || !params.checkKey(part_model_param.toStdString() + "LiveTorqueParameters")) { + if (FrogPilotConfirmationDialog::yesorno(tr("Do you want to start with a fresh calibration for the newly selected model?"), this)) { + params.remove("CalibrationParams"); + params.remove("LiveTorqueParameters"); + } + } + + if (started) { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } + } + }); + selectModelBtn->setValue(QString::fromStdString(params.get("ModelName"))); + controlToggle = reinterpret_cast(selectModelBtn); + } else if (param == "ResetCalibrations") { + std::vector resetOptions{tr("RESET ALL"), tr("RESET ONE")}; + FrogPilotButtonsControl *resetCalibrationsBtn = new FrogPilotButtonsControl(title, desc, "", resetOptions); + QObject::connect(resetCalibrationsBtn, &FrogPilotButtonsControl::showDescriptionEvent, this, &FrogPilotControlsPanel::updateCalibrationDescription); + QObject::connect(resetCalibrationsBtn, &FrogPilotButtonsControl::buttonClicked, [=](int id) { + if (id == 0) { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset all of your model calibrations?"), this)) { + for (QString model : availableModelNames) { + QString cleanedModelName = processModelName(model); + params.remove(QString("%1CalibrationParams").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1CalibrationParams").arg(cleanedModelName).toStdString()); + params.remove(QString("%1LiveTorqueParameters").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1LiveTorqueParameters").arg(cleanedModelName).toStdString()); + } + } + } else if (id == 1) { + QStringList selectableModelLabels; + for (int i = 0; i < availableModels.size(); ++i) { + selectableModelLabels.append(availableModelNames[i]); + } + + QString modelToReset = MultiOptionDialog::getSelection(tr("Select a model to reset"), selectableModelLabels, "", this); + if (!modelToReset.isEmpty()) { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset this model's calibrations?"), this)) { + QString cleanedModelName = processModelName(modelToReset); + params.remove(QString("%1CalibrationParams").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1CalibrationParams").arg(cleanedModelName).toStdString()); + params.remove(QString("%1LiveTorqueParameters").arg(cleanedModelName).toStdString()); + paramsStorage.remove(QString("%1LiveTorqueParameters").arg(cleanedModelName).toStdString()); + } + } + } + }); + controlToggle = reinterpret_cast(resetCalibrationsBtn); + + } else if (param == "QOLControls") { + FrogPilotParamManageControl *qolToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(qolToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + std::set modifiedQolKeys = qolKeys; + + if (!hasPCMCruise) { + modifiedQolKeys.erase("ReverseCruise"); + } else { + modifiedQolKeys.erase("CustomCruise"); + modifiedQolKeys.erase("CustomCruiseLong"); + modifiedQolKeys.erase("SetSpeedOffset"); + } + + if (!isToyota && !isGM && !isHKGCanFd) { + modifiedQolKeys.erase("MapGears"); + } + + toggle->setVisible(modifiedQolKeys.find(key.c_str()) != modifiedQolKeys.end()); + } + openParentToggle(); + }); + controlToggle = qolToggle; + } else if (param == "CustomCruise") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 99, std::map(), this, false, tr("mph")); + } else if (param == "CustomCruiseLong") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 99, std::map(), this, false, tr("mph")); + } else if (param == "ForceStandstill") { + std::vector forceStopToggles{"ForceStops"}; + std::vector forceStopToggleNames{tr("Only For Stop Lights/Stop Signs")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, forceStopToggles, forceStopToggleNames); + } else if (param == "MapGears") { + std::vector mapGearsToggles{"MapAcceleration", "MapDeceleration"}; + std::vector mapGearsToggleNames{tr("Acceleration"), tr("Deceleration")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, mapGearsToggles, mapGearsToggleNames); + } else if (param == "PauseLateralSpeed") { + std::vector pauseLateralToggles{"PauseLateralOnSignal"}; + std::vector pauseLateralToggleNames{"Turn Signal Only"}; + controlToggle = new FrogPilotParamValueToggleControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph"), 1, 1, pauseLateralToggles, pauseLateralToggleNames); + } else if (param == "PauseLateralOnSignal") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph")); + } else if (param == "ReverseCruise") { + std::vector reverseCruiseToggles{"ReverseCruiseUI"}; + std::vector reverseCruiseNames{tr("Control Via UI")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, reverseCruiseToggles, reverseCruiseNames); + } else if (param == "SetSpeedOffset") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph")); + + } else if (param == "LaneChangeCustomizations") { + FrogPilotParamManageControl *laneChangeToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(laneChangeToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(laneChangeKeys.find(key.c_str()) != laneChangeKeys.end()); + } + openParentToggle(); + }); + controlToggle = laneChangeToggle; + } else if (param == "LaneChangeTime") { + std::map laneChangeTimeLabels; + for (int i = 0; i <= 10; ++i) { + laneChangeTimeLabels[i] = i == 0 ? "Instant" : QString::number(i / 2.0) + " seconds"; + } + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 10, laneChangeTimeLabels, this, false); + } else if (param == "LaneDetectionWidth") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 100, std::map(), this, false, " feet", 10); + } else if (param == "MinimumLaneChangeSpeed") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 99, std::map(), this, false, tr("mph")); + + } else if (param == "SpeedLimitController") { + FrogPilotParamManageControl *speedLimitControllerToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(speedLimitControllerToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + slcOpen = true; + for (auto &[key, toggle] : toggles) { + toggle->setVisible(speedLimitControllerKeys.find(key.c_str()) != speedLimitControllerKeys.end()); + } + openParentToggle(); + }); + controlToggle = speedLimitControllerToggle; + } else if (param == "SLCControls") { + FrogPilotParamManageControl *manageSLCControlsToggle = new FrogPilotParamManageControl(param, title, desc, icon, this, true); + QObject::connect(manageSLCControlsToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(speedLimitControllerControlsKeys.find(key.c_str()) != speedLimitControllerControlsKeys.end()); + } + openSubParentToggle(); + }); + controlToggle = manageSLCControlsToggle; + } else if (param == "SLCQOL") { + FrogPilotParamManageControl *manageSLCQOLToggle = new FrogPilotParamManageControl(param, title, desc, icon, this, true); + QObject::connect(manageSLCQOLToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + std::set modifiedSpeedLimitControllerQOLKeys = speedLimitControllerQOLKeys; + + if (hasPCMCruise) { + modifiedSpeedLimitControllerQOLKeys.erase("SetSpeedLimit"); + } + + if (!isToyota) { + modifiedSpeedLimitControllerQOLKeys.erase("ForceMPHDashboard"); + } + + toggle->setVisible(modifiedSpeedLimitControllerQOLKeys.find(key.c_str()) != modifiedSpeedLimitControllerQOLKeys.end()); + } + openSubParentToggle(); + }); + controlToggle = manageSLCQOLToggle; + } else if (param == "SLCConfirmation") { + std::vector slcConfirmationToggles{"SLCConfirmationLower", "SLCConfirmationHigher"}; + std::vector slcConfirmationNames{tr("Lower Limits"), tr("Higher Limits")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, slcConfirmationToggles, slcConfirmationNames); + } else if (param == "SLCLookaheadHigher" || param == "SLCLookaheadLower") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 60, std::map(), this, false, " seconds"); + } else if (param == "SLCVisuals") { + FrogPilotParamManageControl *manageSLCVisualsToggle = new FrogPilotParamManageControl(param, title, desc, icon, this, true); + QObject::connect(manageSLCVisualsToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(speedLimitControllerVisualsKeys.find(key.c_str()) != speedLimitControllerVisualsKeys.end()); + } + openSubParentToggle(); + }); + controlToggle = manageSLCVisualsToggle; + } else if (param == "Offset1" || param == "Offset2" || param == "Offset3" || param == "Offset4") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, -99, 99, std::map(), this, false, tr("mph")); + } else if (param == "ShowSLCOffset") { + std::vector slcOffsetToggles{"ShowSLCOffsetUI"}; + std::vector slcOffsetToggleNames{tr("Control Via UI")}; + controlToggle = new FrogPilotParamToggleControl(param, title, desc, icon, slcOffsetToggles, slcOffsetToggleNames); + } else if (param == "SLCFallback") { + std::vector fallbackOptions{tr("Set Speed"), tr("Experimental Mode"), tr("Previous Limit")}; + FrogPilotButtonParamControl *fallbackSelection = new FrogPilotButtonParamControl(param, title, desc, icon, fallbackOptions); + controlToggle = fallbackSelection; + } else if (param == "SLCOverride") { + std::vector overrideOptions{tr("None"), tr("Manual Set Speed"), tr("Set Speed")}; + FrogPilotButtonParamControl *overrideSelection = new FrogPilotButtonParamControl(param, title, desc, icon, overrideOptions); + controlToggle = overrideSelection; + } else if (param == "SLCPriority") { + ButtonControl *slcPriorityButton = new ButtonControl(title, tr("SELECT"), desc); + QStringList primaryPriorities = {tr("None"), tr("Dashboard"), tr("Navigation"), tr("Offline Maps"), tr("Highest"), tr("Lowest")}; + QStringList secondaryTertiaryPriorities = {tr("None"), tr("Dashboard"), tr("Navigation"), tr("Offline Maps")}; + QStringList priorityPrompts = {tr("Select your primary priority"), tr("Select your secondary priority"), tr("Select your tertiary priority")}; + + QObject::connect(slcPriorityButton, &ButtonControl::clicked, [=]() { + QStringList selectedPriorities; + + for (int i = 1; i <= 3; ++i) { + QStringList currentPriorities = (i == 1) ? primaryPriorities : secondaryTertiaryPriorities; + QStringList prioritiesToDisplay = currentPriorities; + for (const auto &selectedPriority : qAsConst(selectedPriorities)) { + prioritiesToDisplay.removeAll(selectedPriority); + } + + if (!hasDashSpeedLimits) { + prioritiesToDisplay.removeAll(tr("Dashboard")); + } + + if (prioritiesToDisplay.size() == 1 && prioritiesToDisplay.contains(tr("None"))) { + break; + } + + QString priorityKey = QString("SLCPriority%1").arg(i); + QString selection = MultiOptionDialog::getSelection(priorityPrompts[i - 1], prioritiesToDisplay, "", this); + + if (selection.isEmpty()) break; + + params.putNonBlocking(priorityKey.toStdString(), selection.toStdString()); + selectedPriorities.append(selection); + + if (selection == tr("Lowest") || selection == tr("Highest") || selection == tr("None")) break; + + updateFrogPilotToggles(); + } + + selectedPriorities.removeAll(tr("None")); + slcPriorityButton->setValue(selectedPriorities.join(", ")); + }); + + QStringList initialPriorities; + for (int i = 1; i <= 3; ++i) { + QString priorityKey = QString("SLCPriority%1").arg(i); + QString priority = QString::fromStdString(params.get(priorityKey.toStdString())); + + if (!priority.isEmpty() && primaryPriorities.contains(priority) && priority != tr("None")) { + initialPriorities.append(priority); + } + } + slcPriorityButton->setValue(initialPriorities.join(", ")); + controlToggle = slcPriorityButton; + + } else if (param == "VisionTurnControl") { + FrogPilotParamManageControl *visionTurnControlToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(visionTurnControlToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + for (auto &[key, toggle] : toggles) { + toggle->setVisible(visionTurnControlKeys.find(key.c_str()) != visionTurnControlKeys.end()); + } + openParentToggle(); + }); + controlToggle = visionTurnControlToggle; + } else if (param == "CurveSensitivity" || param == "TurnAggressiveness") { + controlToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 200, std::map(), this, false, "%"); + + } else { + controlToggle = new ParamControl(param, title, desc, icon, this); + } + + addItem(controlToggle); + toggles[param.toStdString()] = controlToggle; + + QObject::connect(static_cast(controlToggle), &ToggleControl::toggleFlipped, &updateFrogPilotToggles); + QObject::connect(static_cast(controlToggle), &FrogPilotParamToggleControl::buttonTypeClicked, &updateFrogPilotToggles); + QObject::connect(static_cast(controlToggle), &FrogPilotParamValueControl::valueChanged, &updateFrogPilotToggles); + + QObject::connect(controlToggle, &AbstractControl::showDescriptionEvent, [this]() { + update(); + }); + + QObject::connect(static_cast(controlToggle), &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + update(); + }); + } + + QObject::connect(static_cast(toggles["IncreaseThermalLimits"]), &ToggleControl::toggleFlipped, [this](bool state) { + if (state) { + FrogPilotConfirmationDialog::toggleAlert( + tr("WARNING: This can cause premature wear or damage by running the device over comma's recommended temperature limits!"), + tr("I understand the risks."), this); + } + }); + + QObject::connect(static_cast(toggles["NoLogging"]), &ToggleControl::toggleFlipped, [this](bool state) { + if (state) { + FrogPilotConfirmationDialog::toggleAlert( + tr("WARNING: This will prevent your drives from being recorded and the data will be unobtainable!"), + tr("I understand the risks."), this); + } + }); + + QObject::connect(static_cast(toggles["NoUploads"]), &ToggleControl::toggleFlipped, [this](bool state) { + if (state) { + FrogPilotConfirmationDialog::toggleAlert( + tr("WARNING: This will prevent your drives from appearing on comma connect which may impact debugging and support!"), + tr("I understand the risks."), this); + } + }); + + QObject::connect(static_cast(toggles["TrafficMode"]), &ToggleControl::toggleFlipped, [this](bool state) { + if (state) { + FrogPilotConfirmationDialog::toggleAlert( + tr("To activate 'Traffic Mode' you hold down the 'distance' button on your steering wheel for 2.5 seconds."), + tr("Sounds good!"), this); + } + }); + + std::set rebootKeys = {"AlwaysOnLateral", "NNFF", "NNFFLite"}; + for (const QString &key : rebootKeys) { + QObject::connect(static_cast(toggles[key.toStdString().c_str()]), &ToggleControl::toggleFlipped, [this, key](bool state) { + if (started) { + if (key == "AlwaysOnLateral" && state) { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } else if (key != "AlwaysOnLateral") { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } + } + }); + } + + QObject::connect(static_cast(toggles["ModelRandomizer"]), &ToggleControl::toggleFlipped, [this](bool state) { + modelRandomizer = state; + if (state && !modelsDownloaded) { + if (FrogPilotConfirmationDialog::yesorno(tr("The 'Model Randomizer' only works with downloaded models. Do you want to download all the driving models?"), this)) { + startDownloadAllModels(); + } + } + }); + + FrogPilotParamValueControl *trafficFollowToggle = static_cast(toggles["TrafficFollow"]); + FrogPilotParamValueControl *trafficAccelerationToggle = static_cast(toggles["TrafficJerkAcceleration"]); + FrogPilotParamValueControl *trafficDangerToggle = static_cast(toggles["TrafficJerkDanger"]); + FrogPilotParamValueControl *trafficSpeedToggle = static_cast(toggles["TrafficJerkSpeed"]); + FrogPilotButtonsControl *trafficResetButton = static_cast(toggles["ResetTrafficPersonality"]); + + QObject::connect(trafficResetButton, &FrogPilotButtonsControl::buttonClicked, this, [=]() { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the 'Traffic Mode' personality?"), this)) { + params.putFloat("TrafficFollow", 0.5); + params.putFloat("TrafficJerkAcceleration", 50); + params.putFloat("TrafficJerkDanger", 100); + params.putFloat("TrafficJerkSpeed", 50); + trafficFollowToggle->refresh(); + trafficAccelerationToggle->refresh(); + trafficDangerToggle->refresh(); + trafficSpeedToggle->refresh(); + updateFrogPilotToggles(); + } + }); + + FrogPilotParamValueControl *aggressiveFollowToggle = static_cast(toggles["AggressiveFollow"]); + FrogPilotParamValueControl *aggressiveAccelerationToggle = static_cast(toggles["AggressiveJerkAcceleration"]); + FrogPilotParamValueControl *aggressiveDangerToggle = static_cast(toggles["AggressiveJerkDanger"]); + FrogPilotParamValueControl *aggressiveSpeedToggle = static_cast(toggles["AggressiveJerkSpeed"]); + FrogPilotButtonsControl *aggressiveResetButton = static_cast(toggles["ResetAggressivePersonality"]); + + QObject::connect(aggressiveResetButton, &FrogPilotButtonsControl::buttonClicked, this, [=]() { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the 'Aggressive' personality?"), this)) { + params.putFloat("AggressiveFollow", 1.25); + params.putFloat("AggressiveJerkAcceleration", 50); + params.putFloat("AggressiveJerkDanger", 100); + params.putFloat("AggressiveJerkSpeed", 50); + aggressiveFollowToggle->refresh(); + aggressiveAccelerationToggle->refresh(); + aggressiveDangerToggle->refresh(); + aggressiveSpeedToggle->refresh(); + updateFrogPilotToggles(); + } + }); + + FrogPilotParamValueControl *standardFollowToggle = static_cast(toggles["StandardFollow"]); + FrogPilotParamValueControl *standardAccelerationToggle = static_cast(toggles["StandardJerkAcceleration"]); + FrogPilotParamValueControl *standardDangerToggle = static_cast(toggles["StandardJerkDanger"]); + FrogPilotParamValueControl *standardSpeedToggle = static_cast(toggles["StandardJerkSpeed"]); + FrogPilotButtonsControl *standardResetButton = static_cast(toggles["ResetStandardPersonality"]); + + QObject::connect(standardResetButton, &FrogPilotButtonsControl::buttonClicked, this, [=]() { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the 'Standard' personality?"), this)) { + params.putFloat("StandardFollow", 1.45); + params.putFloat("StandardJerkAcceleration", 100); + params.putFloat("StandardJerkDanger", 100); + params.putFloat("StandardJerkSpeed", 100); + standardFollowToggle->refresh(); + standardAccelerationToggle->refresh(); + standardDangerToggle->refresh(); + standardSpeedToggle->refresh(); + updateFrogPilotToggles(); + } + }); + + FrogPilotParamValueControl *relaxedFollowToggle = static_cast(toggles["RelaxedFollow"]); + FrogPilotParamValueControl *relaxedAccelerationToggle = static_cast(toggles["RelaxedJerkAcceleration"]); + FrogPilotParamValueControl *relaxedDangerToggle = static_cast(toggles["RelaxedJerkDanger"]); + FrogPilotParamValueControl *relaxedSpeedToggle = static_cast(toggles["RelaxedJerkSpeed"]); + FrogPilotButtonsControl *relaxedResetButton = static_cast(toggles["ResetRelaxedPersonality"]); + + QObject::connect(relaxedResetButton, &FrogPilotButtonsControl::buttonClicked, this, [=]() { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely reset your settings for the 'Relaxed' personality?"), this)) { + params.putFloat("RelaxedFollow", 1.75); + params.putFloat("RelaxedJerkAcceleration", 100); + params.putFloat("RelaxedJerkDanger", 100); + params.putFloat("RelaxedJerkSpeed", 100); + relaxedFollowToggle->refresh(); + relaxedAccelerationToggle->refresh(); + relaxedDangerToggle->refresh(); + relaxedSpeedToggle->refresh(); + updateFrogPilotToggles(); + } + }); + + steerRatioToggle = static_cast(toggles["SteerRatio"]); + + QObject::connect(steerRatioToggle, &FrogPilotParamValueToggleControl::buttonClicked, this, [this]() { + params.putFloat("SteerRatio", steerRatioStock); + steerRatioToggle->refresh(); + updateFrogPilotToggles(); + }); + + QObject::connect(parent, &SettingsWindow::closeParentToggle, this, &FrogPilotControlsPanel::hideToggles); + QObject::connect(parent, &SettingsWindow::closeSubParentToggle, this, &FrogPilotControlsPanel::hideSubToggles); + QObject::connect(parent, &SettingsWindow::closeSubSubParentToggle, this, &FrogPilotControlsPanel::hideSubSubToggles); + QObject::connect(parent, &SettingsWindow::updateMetric, this, &FrogPilotControlsPanel::updateMetric); + QObject::connect(uiState(), &UIState::driveRated, this, &FrogPilotControlsPanel::updateModelLabels); + QObject::connect(uiState(), &UIState::offroadTransition, this, &FrogPilotControlsPanel::updateCarToggles); + QObject::connect(uiState(), &UIState::uiUpdate, this, &FrogPilotControlsPanel::updateState); + + updateMetric(); + updateModelLabels(); +} + +void FrogPilotControlsPanel::showEvent(QShowEvent *event) { + disableOpenpilotLongitudinal = params.getBool("DisableOpenpilotLongitudinal"); + modelRandomizer = params.getBool("ModelRandomizer"); +} + +void FrogPilotControlsPanel::updateState(const UIState &s) { + if (!isVisible()) return; + + if (modelManagementOpen) { + deleteModelBtn->setEnabled(!modelDeleting && !modelDownloading); + downloadAllModelsBtn->setEnabled(s.scene.online && !modelDeleting && !modelDownloading && !modelsDownloaded); + downloadModelBtn->setEnabled(s.scene.online && !modelDeleting && !modelDownloading && !modelsDownloaded); + selectModelBtn->setEnabled(!modelDeleting && !modelDownloading && !modelRandomizer); + } + + started = s.scene.started; +} + +void FrogPilotControlsPanel::updateCarToggles() { + auto 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(); + auto carFingerprint = CP.getCarFingerprint(); + auto carName = CP.getCarName(); + auto safetyConfigs = CP.getSafetyConfigs(); + auto safetyModel = safetyConfigs[0].getSafetyModel(); + + hasAutoTune = (carName == "hyundai" || carName == "toyota") && CP.getLateralTuning().which() == cereal::CarParams::LateralTuning::TORQUE; + bool forcingAutoTune = params.getBool("LateralTune") && params.getBool("ForceAutoTune"); + uiState()->scene.has_auto_tune = hasAutoTune || forcingAutoTune; + hasCommaNNFFSupport = checkCommaNNFFSupport(carFingerprint); + hasDashSpeedLimits = carName == "hyundai" || carName == "toyota"; + hasNNFFLog = checkNNFFLogFileExists(carFingerprint); + hasOpenpilotLongitudinal = hasLongitudinalControl(CP); + hasPCMCruise = CP.getPcmCruise(); + isGM = carName == "gm"; + isHKGCanFd = carName == "hyundai" && safetyModel == cereal::CarParams::SafetyModel::HYUNDAI_CANFD; + isToyota = carName == "toyota"; + steerRatioStock = CP.getSteerRatio(); + + steerRatioToggle->setTitle(QString(tr("Steer Ratio (Default: %1)")).arg(QString::number(steerRatioStock, 'f', 2))); + steerRatioToggle->updateControl(steerRatioStock * 0.75, steerRatioStock * 1.25, "", 0.01); + steerRatioToggle->refresh(); + } else { + hasAutoTune = false; + hasCommaNNFFSupport = false; + hasDashSpeedLimits = true; + hasNNFFLog = true; + hasOpenpilotLongitudinal = true; + hasPCMCruise = true; + isGM = true; + isHKGCanFd = true; + isToyota = true; + } + + hideToggles(); +} + +void FrogPilotControlsPanel::updateMetric() { + bool previousIsMetric = isMetric; + isMetric = params.getBool("IsMetric"); + + if (isMetric != previousIsMetric) { + double distanceConversion = isMetric ? FOOT_TO_METER : METER_TO_FOOT; + double speedConversion = isMetric ? MILE_TO_KM : KM_TO_MILE; + + params.putIntNonBlocking("LaneDetectionWidth", std::nearbyint(params.getInt("LaneDetectionWidth") * distanceConversion)); + params.putIntNonBlocking("StoppingDistance", std::nearbyint(params.getInt("StoppingDistance") * distanceConversion)); + + params.putIntNonBlocking("CESpeed", std::nearbyint(params.getInt("CESpeed") * speedConversion)); + params.putIntNonBlocking("CESpeedLead", std::nearbyint(params.getInt("CESpeedLead") * speedConversion)); + params.putIntNonBlocking("CustomCruise", std::nearbyint(params.getInt("CustomCruise") * speedConversion)); + params.putIntNonBlocking("CustomCruiseLong", std::nearbyint(params.getInt("CustomCruiseLong") * speedConversion)); + params.putIntNonBlocking("MinimumLaneChangeSpeed", std::nearbyint(params.getInt("MinimumLaneChangeSpeed") * speedConversion)); + params.putIntNonBlocking("Offset1", std::nearbyint(params.getInt("Offset1") * speedConversion)); + params.putIntNonBlocking("Offset2", std::nearbyint(params.getInt("Offset2") * speedConversion)); + params.putIntNonBlocking("Offset3", std::nearbyint(params.getInt("Offset3") * speedConversion)); + params.putIntNonBlocking("Offset4", std::nearbyint(params.getInt("Offset4") * speedConversion)); + params.putIntNonBlocking("PauseAOLOnBrake", std::nearbyint(params.getInt("PauseAOLOnBrake") * speedConversion)); + params.putIntNonBlocking("PauseLateralOnSignal", std::nearbyint(params.getInt("PauseLateralOnSignal") * speedConversion)); + params.putIntNonBlocking("PauseLateralSpeed", std::nearbyint(params.getInt("PauseLateralSpeed") * speedConversion)); + params.putIntNonBlocking("SetSpeedOffset", std::nearbyint(params.getInt("SetSpeedOffset") * speedConversion)); + } + + FrogPilotDualParamControl *ceSpeedToggle = reinterpret_cast(toggles["CESpeed"]); + FrogPilotParamValueControl *customCruiseToggle = static_cast(toggles["CustomCruise"]); + FrogPilotParamValueControl *customCruiseLongToggle = static_cast(toggles["CustomCruiseLong"]); + FrogPilotParamValueControl *laneWidthToggle = static_cast(toggles["LaneDetectionWidth"]); + FrogPilotParamValueControl *minimumLaneChangeSpeedToggle = static_cast(toggles["MinimumLaneChangeSpeed"]); + FrogPilotParamValueControl *offset1Toggle = static_cast(toggles["Offset1"]); + FrogPilotParamValueControl *offset2Toggle = static_cast(toggles["Offset2"]); + FrogPilotParamValueControl *offset3Toggle = static_cast(toggles["Offset3"]); + FrogPilotParamValueControl *offset4Toggle = static_cast(toggles["Offset4"]); + FrogPilotParamValueControl *pauseAOLOnBrakeToggle = static_cast(toggles["PauseAOLOnBrake"]); + FrogPilotParamValueControl *pauseLateralToggle = static_cast(toggles["PauseLateralSpeed"]); + FrogPilotParamValueControl *setSpeedOffsetToggle = static_cast(toggles["SetSpeedOffset"]); + FrogPilotParamValueControl *stoppingDistanceToggle = static_cast(toggles["StoppingDistance"]); + + if (isMetric) { + offset1Toggle->setTitle(tr("Speed Limit Offset (0-34 kph)")); + offset2Toggle->setTitle(tr("Speed Limit Offset (35-54 kph)")); + offset3Toggle->setTitle(tr("Speed Limit Offset (55-64 kph)")); + offset4Toggle->setTitle(tr("Speed Limit Offset (65-99 kph)")); + + offset1Toggle->setDescription(tr("Set speed limit offset for limits between 0-34 kph.")); + offset2Toggle->setDescription(tr("Set speed limit offset for limits between 35-54 kph.")); + offset3Toggle->setDescription(tr("Set speed limit offset for limits between 55-64 kph.")); + offset4Toggle->setDescription(tr("Set speed limit offset for limits between 65-99 kph.")); + + ceSpeedToggle->updateControl(0, 150, tr("kph")); + customCruiseToggle->updateControl(1, 150, tr("kph")); + customCruiseLongToggle->updateControl(1, 150, tr("kph")); + minimumLaneChangeSpeedToggle->updateControl(0, 150, tr("kph")); + offset1Toggle->updateControl(-99, 99, tr("kph")); + offset2Toggle->updateControl(-99, 99, tr("kph")); + offset3Toggle->updateControl(-99, 99, tr("kph")); + offset4Toggle->updateControl(-99, 99, tr("kph")); + pauseAOLOnBrakeToggle->updateControl(0, 99, tr("kph")); + pauseLateralToggle->updateControl(0, 99, tr("kph")); + setSpeedOffsetToggle->updateControl(0, 150, tr("kph")); + + laneWidthToggle->updateControl(0, 30, tr(" meters"), 10); + stoppingDistanceToggle->updateControl(0, 5, tr(" meters")); + } else { + offset1Toggle->setTitle(tr("Speed Limit Offset (0-34 mph)")); + offset2Toggle->setTitle(tr("Speed Limit Offset (35-54 mph)")); + offset3Toggle->setTitle(tr("Speed Limit Offset (55-64 mph)")); + offset4Toggle->setTitle(tr("Speed Limit Offset (65-99 mph)")); + + offset1Toggle->setDescription(tr("Set speed limit offset for limits between 0-34 mph.")); + offset2Toggle->setDescription(tr("Set speed limit offset for limits between 35-54 mph.")); + offset3Toggle->setDescription(tr("Set speed limit offset for limits between 55-64 mph.")); + offset4Toggle->setDescription(tr("Set speed limit offset for limits between 65-99 mph.")); + + ceSpeedToggle->updateControl(0, 99, tr("mph")); + customCruiseToggle->updateControl(1, 99, tr("mph")); + customCruiseLongToggle->updateControl(1, 99, tr("mph")); + minimumLaneChangeSpeedToggle->updateControl(0, 99, tr("mph")); + offset1Toggle->updateControl(-99, 99, tr("mph")); + offset2Toggle->updateControl(-99, 99, tr("mph")); + offset3Toggle->updateControl(-99, 99, tr("mph")); + offset4Toggle->updateControl(-99, 99, tr("mph")); + pauseAOLOnBrakeToggle->updateControl(0, 99, tr("mph")); + pauseLateralToggle->updateControl(0, 99, tr("mph")); + setSpeedOffsetToggle->updateControl(0, 99, tr("mph")); + + laneWidthToggle->updateControl(0, 100, tr(" feet"), 10); + stoppingDistanceToggle->updateControl(0, 10, tr(" feet")); + } + + ceSpeedToggle->refresh(); + customCruiseToggle->refresh(); + customCruiseLongToggle->refresh(); + laneWidthToggle->refresh(); + minimumLaneChangeSpeedToggle->refresh(); + offset1Toggle->refresh(); + offset2Toggle->refresh(); + offset3Toggle->refresh(); + offset4Toggle->refresh(); + pauseAOLOnBrakeToggle->refresh(); + pauseLateralToggle->refresh(); + setSpeedOffsetToggle->refresh(); + stoppingDistanceToggle->refresh(); +} + +void FrogPilotControlsPanel::startDownloadAllModels() { + modelDownloading = true; + + paramsMemory.putBoolNonBlocking("DownloadAllModels", true); + + downloadAllModelsBtn->setValue(tr("Downloading models...")); + + QTimer *checkDownloadTimer = new QTimer(this); + checkDownloadTimer->setInterval(100); + + QObject::connect(checkDownloadTimer, &QTimer::timeout, this, [=]() { + QString progress = QString::fromStdString(paramsMemory.get("ModelDownloadProgress")); + bool downloadFailed = progress.contains(QRegularExpression("exists|Failed|offline", QRegularExpression::CaseInsensitiveOption)); + + if (!progress.isEmpty() && progress != "0%") { + downloadAllModelsBtn->setValue(progress); + } + + if (progress == "All models downloaded!" || downloadFailed) { + if (!downloadFailed) { + haveModelsDownloaded = true; + update(); + } + + QTimer::singleShot(2000, this, [=]() { + modelDownloading = false; + downloadAllModelsBtn->setValue(""); + modelsDownloaded = params.getBool("ModelsDownloaded"); + update(); + }); + + paramsMemory.remove("ModelDownloadProgress"); + + checkDownloadTimer->stop(); + checkDownloadTimer->deleteLater(); + } + }); + + checkDownloadTimer->start(); +} + +QString FrogPilotControlsPanel::processModelName(const QString &modelName) { + QString modelCleaned = modelName; + modelCleaned = modelCleaned.remove(QRegularExpression("[πŸ—ΊοΈπŸ‘€πŸ“‘]")).simplified(); + QString scoreParam = modelCleaned.remove(QRegularExpression("[^a-zA-Z0-9()-]")).replace(" ", "").simplified(); + scoreParam = scoreParam.replace("(Default)", "").replace("-", ""); + return scoreParam; +} + +void FrogPilotControlsPanel::updateCalibrationDescription() { + QString model = QString::fromStdString(params.get("ModelName")); + QString part_model_param = processModelName(model); + + QString desc = + tr("openpilot requires the device to be mounted within 4Β° left or right and " + "within 5Β° up or 9Β° down. openpilot is continuously calibrating, resetting is rarely required."); + std::string calib_bytes = params.get(part_model_param.toStdString() + "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"; + } + } + qobject_cast(sender())->setDescription(desc); +} + +void FrogPilotControlsPanel::updateModelLabels() { + QVector> modelScores; + availableModelNames = QString::fromStdString(params.get("AvailableModelsNames")).split(","); + + for (const QString &model : availableModelNames) { + QString cleanedModel = processModelName(model); + int score = params.getInt((cleanedModel + "Score").toStdString()); + + if (model.contains("(Default)")) { + modelScores.prepend(qMakePair(model, score)); + } else { + modelScores.append(qMakePair(model, score)); + } + } + + labelControls.clear(); + + for (const auto &pair : modelScores) { + QString scoreDisplay = pair.second == 0 ? "N/A" : QString::number(pair.second) + "%"; + LabelControl *labelControl = new LabelControl(pair.first, scoreDisplay, "", this); + addItem(labelControl); + labelControls.append(labelControl); + } + + for (LabelControl *label : labelControls) { + label->setVisible(false); + } +} + +void FrogPilotControlsPanel::hideToggles() { + customPersonalitiesOpen = false; + modelManagementOpen = false; + slcOpen = false; + + for (LabelControl *label : labelControls) { + label->setVisible(false); + } + + std::set longitudinalKeys = {"ConditionalExperimental", "DrivingPersonalities", "ExperimentalModeActivation", + "LongitudinalTune", "MTSCEnabled", "SpeedLimitController", "VisionTurnControl"}; + + for (auto &[key, toggle] : toggles) { + toggle->setVisible(false); + + if ((!hasOpenpilotLongitudinal || disableOpenpilotLongitudinal) && longitudinalKeys.find(key.c_str()) != longitudinalKeys.end()) { + continue; + } + + bool subToggles = aggressivePersonalityKeys.find(key.c_str()) != aggressivePersonalityKeys.end() || + aolKeys.find(key.c_str()) != aolKeys.end() || + conditionalExperimentalKeys.find(key.c_str()) != conditionalExperimentalKeys.end() || + customdrivingPersonalityKeys.find(key.c_str()) != customdrivingPersonalityKeys.end() || + deviceManagementKeys.find(key.c_str()) != deviceManagementKeys.end() || + drivingPersonalityKeys.find(key.c_str()) != drivingPersonalityKeys.end() || + experimentalModeActivationKeys.find(key.c_str()) != experimentalModeActivationKeys.end() || + laneChangeKeys.find(key.c_str()) != laneChangeKeys.end() || + lateralTuneKeys.find(key.c_str()) != lateralTuneKeys.end() || + longitudinalTuneKeys.find(key.c_str()) != longitudinalTuneKeys.end() || + modelManagementKeys.find(key.c_str()) != modelManagementKeys.end() || + modelRandomizerKeys.find(key.c_str()) != modelRandomizerKeys.end() || + mtscKeys.find(key.c_str()) != mtscKeys.end() || + qolKeys.find(key.c_str()) != qolKeys.end() || + relaxedPersonalityKeys.find(key.c_str()) != relaxedPersonalityKeys.end() || + speedLimitControllerKeys.find(key.c_str()) != speedLimitControllerKeys.end() || + speedLimitControllerControlsKeys.find(key.c_str()) != speedLimitControllerControlsKeys.end() || + speedLimitControllerQOLKeys.find(key.c_str()) != speedLimitControllerQOLKeys.end() || + speedLimitControllerVisualsKeys.find(key.c_str()) != speedLimitControllerVisualsKeys.end() || + standardPersonalityKeys.find(key.c_str()) != standardPersonalityKeys.end() || + trafficPersonalityKeys.find(key.c_str()) != trafficPersonalityKeys.end() || + visionTurnControlKeys.find(key.c_str()) != visionTurnControlKeys.end(); + toggle->setVisible(!subToggles); + } + + update(); +} + +void FrogPilotControlsPanel::hideSubToggles() { + if (customPersonalitiesOpen) { + for (auto &[key, toggle] : toggles) { + bool isVisible = drivingPersonalityKeys.find(key.c_str()) != drivingPersonalityKeys.end(); + toggle->setVisible(isVisible); + } + } else if (slcOpen) { + for (auto &[key, toggle] : toggles) { + bool isVisible = speedLimitControllerKeys.find(key.c_str()) != speedLimitControllerKeys.end(); + toggle->setVisible(isVisible); + } + } else if (modelManagementOpen) { + for (LabelControl *label : labelControls) { + label->setVisible(false); + } + + for (auto &[key, toggle] : toggles) { + bool isVisible = modelManagementKeys.find(key.c_str()) != modelManagementKeys.end(); + toggle->setVisible(isVisible); + } + } + + update(); +} + +void FrogPilotControlsPanel::hideSubSubToggles() { + if (customPersonalitiesOpen) { + for (auto &[key, toggle] : toggles) { + bool isVisible = customdrivingPersonalityKeys.find(key.c_str()) != customdrivingPersonalityKeys.end(); + toggle->setVisible(isVisible); + } + } else if (modelManagementOpen) { + for (LabelControl *label : labelControls) { + label->setVisible(false); + } + + for (auto &[key, toggle] : toggles) { + bool isVisible = modelRandomizerKeys.find(key.c_str()) != modelRandomizerKeys.end(); + toggle->setVisible(isVisible); + } + } + + update(); +} diff --git a/selfdrive/frogpilot/ui/qt/offroad/control_settings.h b/selfdrive/frogpilot/ui/qt/offroad/control_settings.h new file mode 100644 index 0000000000..5899982856 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/control_settings.h @@ -0,0 +1,100 @@ +#pragma once + +#include + +#include "selfdrive/ui/qt/offroad/settings.h" +#include "selfdrive/ui/ui.h" + +class FrogPilotControlsPanel : public FrogPilotListWidget { + Q_OBJECT + +public: + explicit FrogPilotControlsPanel(SettingsWindow *parent); + +signals: + void openParentToggle(); + void openSubParentToggle(); + void openSubSubParentToggle(); + +private: + QString processModelName(const QString &modelName); + + void hideSubToggles(); + void hideSubSubToggles(); + void hideToggles(); + void showEvent(QShowEvent *event) override; + void startDownloadAllModels(); + void updateCalibrationDescription(); + void updateCarToggles(); + void updateMetric(); + void updateModelLabels(); + void updateState(const UIState &s); + + ButtonControl *deleteModelBtn; + ButtonControl *downloadAllModelsBtn; + ButtonControl *downloadModelBtn; + ButtonControl *selectModelBtn; + + FrogPilotParamValueToggleControl *steerRatioToggle; + + std::set aggressivePersonalityKeys = {"PersonalityInfo", "AggressiveFollow", "AggressiveJerkAcceleration", "AggressiveJerkDanger", "AggressiveJerkSpeed", "ResetAggressivePersonality"}; + std::set aolKeys = {"AlwaysOnLateralLKAS", "AlwaysOnLateralMain", "HideAOLStatusBar", "PauseAOLOnBrake"}; + std::set conditionalExperimentalKeys = {"CESpeed", "CESpeedLead", "CECurves", "CELead", "CENavigation", "CESignal", "CEStopLights", "HideCEMStatusBar"}; + std::set customdrivingPersonalityKeys = {"AggressivePersonalityProfile", "RelaxedPersonalityProfile", "StandardPersonalityProfile", "TrafficPersonalityProfile"}; + std::set deviceManagementKeys = {"DeviceShutdown", "IncreaseThermalLimits", "LowVoltageShutdown", "NoLogging", "NoUploads", "OfflineMode"}; + std::set drivingPersonalityKeys = {"CustomPersonalities", "OnroadDistanceButton"}; + std::set experimentalModeActivationKeys = {"ExperimentalModeViaDistance", "ExperimentalModeViaLKAS", "ExperimentalModeViaTap"}; + std::set laneChangeKeys = {"LaneChangeTime", "LaneDetectionWidth", "MinimumLaneChangeSpeed", "NudgelessLaneChange", "OneLaneChange"}; + std::set lateralTuneKeys = {"ForceAutoTune", "NNFF", "NNFFLite", "SteerRatio", "TacoTune", "TurnDesires"}; + std::set longitudinalTuneKeys = {"AccelerationProfile", "AggressiveAcceleration", "DecelerationProfile", "LeadDetectionThreshold", "SmoothBraking", "StoppingDistance", "TrafficMode"}; + std::set modelManagementKeys = {"AutomaticallyUpdateModels", "ModelRandomizer", "DeleteModel", "DownloadModel", "DownloadAllModels", "SelectModel", "ResetCalibrations"}; + std::set modelRandomizerKeys = {"ManageBlacklistedModels", "ResetScores", "ReviewScores"}; + std::set mtscKeys = {"DisableMTSCSmoothing", "MTSCAggressiveness", "MTSCCurvatureCheck"}; + std::set qolKeys = {"CustomCruise", "CustomCruiseLong", "ForceStandstill", "MapGears", "PauseLateralSpeed", "ReverseCruise", "SetSpeedOffset"}; + std::set relaxedPersonalityKeys = {"PersonalityInfo", "RelaxedFollow", "RelaxedJerkAcceleration", "RelaxedJerkDanger", "RelaxedJerkSpeed", "ResetRelaxedPersonality"}; + std::set speedLimitControllerKeys = {"SLCControls", "SLCQOL", "SLCVisuals"}; + std::set speedLimitControllerControlsKeys = {"Offset1", "Offset2", "Offset3", "Offset4", "SLCFallback", "SLCOverride", "SLCPriority"}; + std::set speedLimitControllerQOLKeys = {"ForceMPHDashboard", "SetSpeedLimit", "SLCConfirmation", "SLCLookaheadHigher", "SLCLookaheadLower"}; + std::set speedLimitControllerVisualsKeys = {"ShowSLCOffset", "SpeedLimitChangedAlert", "UseVienna"}; + std::set standardPersonalityKeys = {"PersonalityInfo", "StandardFollow", "StandardJerkAcceleration", "StandardJerkDanger", "StandardJerkSpeed", "ResetStandardPersonality"}; + std::set trafficPersonalityKeys = {"PersonalityInfo", "TrafficFollow", "TrafficJerkAcceleration", "TrafficJerkDanger", "TrafficJerkSpeed", "ResetTrafficPersonality"}; + std::set visionTurnControlKeys = {"CurveSensitivity", "DisableVTSCSmoothing", "TurnAggressiveness"}; + + std::map toggles; + + QList labelControls; + + QDir modelDir{"/data/models/"}; + + Params params; + Params paramsMemory{"/dev/shm/params"}; + Params paramsStorage{"/persist/params"}; + + bool customPersonalitiesOpen; + bool disableOpenpilotLongitudinal; + bool hasAutoTune; + bool hasCommaNNFFSupport; + bool hasNNFFLog; + bool hasOpenpilotLongitudinal; + bool hasPCMCruise; + bool hasDashSpeedLimits; + bool haveModelsDownloaded; + bool isGM; + bool isHKGCanFd; + bool isMetric = params.getBool("IsMetric"); + bool isRelease; + bool isToyota; + bool modelDeleting; + bool modelDownloading; + bool modelManagementOpen; + bool modelRandomizer; + bool modelsDownloaded; + bool slcOpen; + bool started; + + float steerRatioStock; + + QStringList availableModelNames; + QStringList availableModels; + QStringList experimentalModels; +}; diff --git a/selfdrive/frogpilot/ui/qt/offroad/personalities_info.txt b/selfdrive/frogpilot/ui/qt/offroad/personalities_info.txt new file mode 100644 index 0000000000..9d12b8eb09 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/personalities_info.txt @@ -0,0 +1,26 @@ +Following Distance: +Represents the desired time-based distance from the lead vehicle in seconds. This value adjusts how closely openpilot follows the car in front. It is not an exact value but a more representative value. + +Real-World Example: If this value is set to 1.5 seconds, and you’re driving at 50 mph (80 kph), openpilot aims to keep a distance of about 110 feet (33.5 meters) from the car in front. It means if the car in front suddenly stops, you have 1.5 seconds to react and stop safely. + +Acceleration Jerk: +Controls how quickly the car speeds up or slows down. + +Real-World Example: If you like your rides to be smooth and gentle, you can set this value higher. So, if the car in front speeds up or slows down suddenly, openpilot will change its speed more slowly to avoid jerky movements. + +Danger Zone Jerk: +How careful the car is when it gets close to other cars or obstacles. + +Real-World Example: If there’s a much slower car ahead of you, setting a higher danger zone will make openpilot more cautious. It will brake sooner and harder if the speed difference is big or the distance is small, making sure you don’t get too close too quickly. + +Speed Control Jerk: +How smoothly the car changes its speed overall. + +Real-World Example: If you set this value higher, openpilot will change the car's speed more gradually to adjust to higher/lower speed limits and other speed change conditions where there's no lead. So, when you need to speed up to match the set cruise speed or slow down because of traffic, openpilot will do it gently, making the ride smoother. + +In Summary: + +Following Distance: Sets how far to stay behind the car in front, based on time. +Acceleration Jerk: Controls how smoothly the car changes speed. +Danger Zone Jerk: Adjusts how cautious the car is when getting close to other cars or obstacles. +Speed Control Jerk: Controls the overall smoothness of speed changes when there's no lead in front. \ No newline at end of file diff --git a/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.cc b/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.cc new file mode 100644 index 0000000000..a4fb412006 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.cc @@ -0,0 +1,313 @@ +#include +#include +#include + +#include "selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.h" + +QStringList getCarNames(const QString &carMake, QMap &carModels) { + QMap makeMap; + makeMap["acura"] = "honda"; + makeMap["audi"] = "volkswagen"; + makeMap["buick"] = "gm"; + makeMap["cadillac"] = "gm"; + makeMap["chevrolet"] = "gm"; + makeMap["chrysler"] = "chrysler"; + makeMap["dodge"] = "chrysler"; + makeMap["ford"] = "ford"; + makeMap["genesis"] = "hyundai"; + makeMap["gmc"] = "gm"; + makeMap["holden"] = "gm"; + makeMap["honda"] = "honda"; + makeMap["hyundai"] = "hyundai"; + makeMap["jeep"] = "chrysler"; + makeMap["kia"] = "hyundai"; + makeMap["lexus"] = "toyota"; + makeMap["lincoln"] = "ford"; + makeMap["man"] = "volkswagen"; + makeMap["mazda"] = "mazda"; + makeMap["nissan"] = "nissan"; + makeMap["ram"] = "chrysler"; + makeMap["seat"] = "volkswagen"; + makeMap["Ε‘koda"] = "volkswagen"; + makeMap["subaru"] = "subaru"; + makeMap["tesla"] = "tesla"; + makeMap["toyota"] = "toyota"; + makeMap["volkswagen"] = "volkswagen"; + + QString targetFolder = makeMap.value(carMake, carMake); + QFile file(QString("../car/%1/values.py").arg(targetFolder)); + QStringList names; + QSet uniqueNames; + + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return names; + + QTextStream in(&file); + QString fileContent = in.readAll(); + file.close(); + + fileContent.remove(QRegularExpression("#[^\n]*")); + + QRegularExpression carModelRegex(R"delimiter((\w+)\s*=\s*\w+\s*\(\s*\[([\s\S]*?)\]\s*,)delimiter"); + QRegularExpression carDocsRegex(R"delimiter(CarDocs\(\s*"([^"]+)"[^)]*\))delimiter"); + + QRegularExpressionMatchIterator carModelIt = carModelRegex.globalMatch(fileContent); + while (carModelIt.hasNext()) { + QRegularExpressionMatch carModelMatch = carModelIt.next(); + QString platform = carModelMatch.captured(1); + QString platformSection = carModelMatch.captured(2); + + QRegularExpressionMatchIterator carDocsIt = carDocsRegex.globalMatch(platformSection); + while (carDocsIt.hasNext()) { + QRegularExpressionMatch match = carDocsIt.next(); + QString carName = match.captured(1); + + if (carName.contains(QRegularExpression("^[A-Za-z0-9 Ε .()-]+$")) && carName.count(" ") >= 1) { + QStringList nameParts = carName.split(" "); + if (nameParts.contains(carMake, Qt::CaseInsensitive)) { + if (!uniqueNames.contains(carName)) { + names << carName; + carModels[carName] = platform; + uniqueNames.insert(carName); + } + } + } + } + } + + std::sort(names.begin(), names.end()); + return names; +} + +FrogPilotVehiclesPanel::FrogPilotVehiclesPanel(SettingsWindow *parent) : FrogPilotListWidget(parent) { + selectMakeButton = new ButtonControl(tr("Select Make"), tr("SELECT")); + QObject::connect(selectMakeButton, &ButtonControl::clicked, [this]() { + QStringList makes = { + "Acura", "Audi", "Buick", "Cadillac", "Chevrolet", "Chrysler", "Dodge", "Ford", "Genesis", + "GMC", "Holden", "Honda", "Hyundai", "Jeep", "Kia", "Lexus", "Lincoln", "MAN", "Mazda", + "Nissan", "Ram", "SEAT", "Ε koda", "Subaru", "Tesla", "Toyota", "Volkswagen", + }; + + QString newMakeSelection = MultiOptionDialog::getSelection(tr("Select a Make"), makes, "", this); + if (!newMakeSelection.isEmpty()) { + carMake = newMakeSelection; + params.putNonBlocking("CarMake", carMake.toStdString()); + selectMakeButton->setValue(newMakeSelection); + setModels(); + } + }); + addItem(selectMakeButton); + + selectModelButton = new ButtonControl(tr("Select Model"), tr("SELECT")); + QObject::connect(selectModelButton, &ButtonControl::clicked, [this]() { + QString newModelSelection = MultiOptionDialog::getSelection(tr("Select a Model"), models, "", this); + if (!newModelSelection.isEmpty()) { + carModel = newModelSelection; + QString modelIdentifier = carModels.value(newModelSelection); + params.putNonBlocking("CarModel", modelIdentifier.toStdString()); + params.putNonBlocking("CarModelName", newModelSelection.toStdString()); + selectModelButton->setValue(newModelSelection); + } + }); + addItem(selectModelButton); + selectModelButton->setVisible(false); + + ParamControl *forceFingerprint = new ParamControl("ForceFingerprint", tr("Disable Automatic Fingerprint Detection"), tr("Forces the selected fingerprint and prevents it from ever changing."), "", this); + addItem(forceFingerprint); + + bool disableOpenpilotLongState = params.getBool("DisableOpenpilotLongitudinal"); + disableOpenpilotLong = new ToggleControl(tr("Disable openpilot Longitudinal Control"), tr("Disable openpilot longitudinal control and use stock ACC instead."), "", disableOpenpilotLongState); + QObject::connect(disableOpenpilotLong, &ToggleControl::toggleFlipped, [this](bool state) { + if (state) { + if (FrogPilotConfirmationDialog::yesorno(tr("Are you sure you want to completely disable openpilot longitudinal control?"), this)) { + params.putBool("DisableOpenpilotLongitudinal", state); + if (started) { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } + } else { + disableOpenpilotLong->refresh(); + } + } else { + params.putBool("DisableOpenpilotLongitudinal", state); + } + updateCarToggles(); + }); + addItem(disableOpenpilotLong); + + std::vector> vehicleToggles { + {"LongPitch", tr("Long Pitch Compensation"), tr("Smoothen out the gas and pedal controls."), ""}, + {"VoltSNG", tr("2017 Volt SNG"), tr("Enable the 'Stop and Go' hack for 2017 Chevy Volts."), ""}, + + {"CrosstrekTorque", tr("Subaru Crosstrek Torque Increase"), tr("Increases the maximum allowed torque for the Subaru Crosstrek."), ""}, + + {"ToyotaDoors", tr("Automatically Lock/Unlock Doors"), tr("Automatically lock the doors when in drive and unlock when in park."), ""}, + {"ClusterOffset", tr("Cluster Offset"), tr("Set the cluster offset openpilot uses to try and match the speed displayed on the dash."), ""}, + {"SNGHack", tr("Stop and Go Hack"), tr("Enable the 'Stop and Go' hack for vehicles without stock stop and go functionality."), ""}, + {"ToyotaTune", tr("Toyota Tune"), tr("Use a custom Toyota longitudinal tune.\n\nCydia = More focused on TSS-P vehicles but works for all Toyotas\n\nDragonPilot = Focused on TSS2 vehicles\n\nFrogPilot = Takes the best of both worlds with some personal tweaks focused around FrogsGoMoo's 2019 Lexus ES 350"), ""}, + }; + + for (const auto &[param, title, desc, icon] : vehicleToggles) { + AbstractControl *vehicleToggle; + + if (param == "ToyotaDoors") { + std::vector lockToggles{"LockDoors", "UnlockDoors"}; + std::vector lockToggleNames{tr("Lock"), tr("Unlock")}; + vehicleToggle = new FrogPilotParamToggleControl(param, title, desc, icon, lockToggles, lockToggleNames); + + } else if (param == "ClusterOffset") { + vehicleToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1.000, 1.050, std::map(), this, false, "x", 1, 0.001); + + } else if (param == "ToyotaTune") { + std::vector> tuneOptions{ + {"StockTune", tr("Stock")}, + {"CydiaTune", tr("Cydia")}, + {"FrogsGoMooTune", tr("FrogPilot")}, + }; + + FrogPilotButtonsParamControl *toyotaTuneToggle = new FrogPilotButtonsParamControl(param, title, desc, icon, tuneOptions); + vehicleToggle = toyotaTuneToggle; + + QObject::connect(toyotaTuneToggle, &FrogPilotButtonsParamControl::buttonClicked, [this]() { + if (started) { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } + }); + + } else { + vehicleToggle = new ParamControl(param, title, desc, icon, this); + } + + vehicleToggle->setVisible(false); + addItem(vehicleToggle); + toggles[param.toStdString()] = vehicleToggle; + + QObject::connect(static_cast(vehicleToggle), &ToggleControl::toggleFlipped, &updateFrogPilotToggles); + QObject::connect(static_cast(vehicleToggle), &FrogPilotParamToggleControl::buttonTypeClicked, &updateFrogPilotToggles); + + QObject::connect(vehicleToggle, &AbstractControl::showDescriptionEvent, [this]() { + update(); + }); + } + + std::set rebootKeys = {"CrosstrekTorque"}; + for (const QString &key : rebootKeys) { + QObject::connect(static_cast(toggles[key.toStdString().c_str()]), &ToggleControl::toggleFlipped, [this]() { + if (started) { + if (FrogPilotConfirmationDialog::toggle(tr("Reboot required to take effect."), tr("Reboot Now"), this)) { + Hardware::reboot(); + } + } + }); + } + + QObject::connect(uiState(), &UIState::offroadTransition, [this]() { + std::thread([this]() { + while (carMake.isEmpty()) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + carMake = QString::fromStdString(params.get("CarMake")); + carModel = QString::fromStdString(params.get(params.get("CarModelName").empty() ? "CarModel" : "CarModelName")); + } + setModels(); + updateCarToggles(); + }).detach(); + }); + + QObject::connect(uiState(), &UIState::uiUpdate, this, &FrogPilotVehiclesPanel::updateState); + + carMake = QString::fromStdString(params.get("CarMake")); + carModel = QString::fromStdString(params.get(params.get("CarModelName").empty() ? "CarModel" : "CarModelName")); + + if (!carMake.isEmpty()) { + setModels(); + } +} + +void FrogPilotVehiclesPanel::updateState(const UIState &s) { + if (!isVisible()) return; + + started = s.scene.started; +} + +void FrogPilotVehiclesPanel::updateCarToggles() { + auto 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(); + + auto carFingerprint = CP.getCarFingerprint(); + + hasExperimentalOpenpilotLongitudinal = CP.getExperimentalLongitudinalAvailable(); + hasOpenpilotLongitudinal = hasLongitudinalControl(CP); + hasSNG = CP.getMinEnableSpeed() <= 0; + isGMPCMCruise = CP.getCarName() == "gm" && CP.getPcmCruise(); + isImpreza = carFingerprint == "SUBARU_IMPREZA"; + isVolt = carFingerprint == "CHEVROLET_VOLT"; + } else { + hasExperimentalOpenpilotLongitudinal = false; + hasOpenpilotLongitudinal = true; + hasSNG = false; + isImpreza = true; + isVolt = true; + } + + hideToggles(); +} + +void FrogPilotVehiclesPanel::setModels() { + models = getCarNames(carMake.toLower(), carModels); + hideToggles(); +} + +void FrogPilotVehiclesPanel::hideToggles() { + disableOpenpilotLong->setVisible(hasOpenpilotLongitudinal && !hasExperimentalOpenpilotLongitudinal && !isGMPCMCruise || params.getBool("DisableOpenpilotLongitudinal")); + + selectMakeButton->setValue(carMake); + selectModelButton->setValue(carModel); + selectModelButton->setVisible(!carMake.isEmpty()); + + bool gm = carMake == "Buick" || carMake == "Cadillac" || carMake == "Chevrolet" || carMake == "GM" || carMake == "GMC"; + bool subaru = carMake == "Subaru"; + bool toyota = carMake == "Lexus" || carMake == "Toyota"; + + std::set imprezaKeys = {"CrosstrekTorque"}; + std::set longitudinalKeys = {"ToyotaTune", "LongPitch", "SNGHack"}; + std::set sngKeys = {"SNGHack"}; + std::set voltKeys = {"VoltSNG"}; + + for (auto &[key, toggle] : toggles) { + if (toggle) { + toggle->setVisible(false); + + if ((!hasOpenpilotLongitudinal || params.getBool("DisableOpenpilotLongitudinal")) && longitudinalKeys.find(key.c_str()) != longitudinalKeys.end()) { + continue; + } + + if (hasSNG && sngKeys.find(key.c_str()) != sngKeys.end()) { + continue; + } + + if (!isImpreza && imprezaKeys.find(key.c_str()) != imprezaKeys.end()) { + continue; + } + + if (!isVolt && voltKeys.find(key.c_str()) != voltKeys.end()) { + continue; + } + + if (gm) { + toggle->setVisible(gmKeys.find(key.c_str()) != gmKeys.end()); + } else if (subaru) { + toggle->setVisible(subaruKeys.find(key.c_str()) != subaruKeys.end()); + } else if (toyota) { + toggle->setVisible(toyotaKeys.find(key.c_str()) != toyotaKeys.end()); + } + } + } + + update(); +} diff --git a/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.h b/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.h new file mode 100644 index 0000000000..57f61d2b31 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.h @@ -0,0 +1,49 @@ +#pragma once + +#include + +#include + +#include "selfdrive/ui/qt/offroad/settings.h" +#include "selfdrive/ui/ui.h" + +class FrogPilotVehiclesPanel : public FrogPilotListWidget { + Q_OBJECT + +public: + explicit FrogPilotVehiclesPanel(SettingsWindow *parent); + +private: + void hideToggles(); + void setModels(); + void updateCarToggles(); + void updateState(const UIState &s); + + ButtonControl *selectMakeButton; + ButtonControl *selectModelButton; + + ToggleControl *disableOpenpilotLong; + + QString carMake; + QString carModel; + + QStringList models; + + QMap carModels; + + std::set gmKeys = {"LongPitch", "VoltSNG"}; + std::set subaruKeys = {"CrosstrekTorque"}; + std::set toyotaKeys = {"ClusterOffset", "SNGHack", "ToyotaDoors", "ToyotaTune"}; + + std::map toggles; + + Params params; + + bool hasExperimentalOpenpilotLongitudinal; + bool hasOpenpilotLongitudinal; + bool hasSNG; + bool isGMPCMCruise; + bool isImpreza; + bool isVolt; + bool started; +}; diff --git a/selfdrive/frogpilot/ui/qt/offroad/visual_settings.cc b/selfdrive/frogpilot/ui/qt/offroad/visual_settings.cc new file mode 100644 index 0000000000..47a47130f4 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/visual_settings.cc @@ -0,0 +1,449 @@ +#include "selfdrive/frogpilot/ui/qt/offroad/visual_settings.h" + +FrogPilotVisualsPanel::FrogPilotVisualsPanel(SettingsWindow *parent) : FrogPilotListWidget(parent) { + std::string branch = params.get("GitBranch"); + isRelease = branch == "FrogPilot"; + + const std::vector> visualToggles { + {"AlertVolumeControl", tr("Alert Volume Controller"), tr("Control the volume level for each individual sound in openpilot."), "../frogpilot/assets/toggle_icons/icon_mute.png"}, + {"DisengageVolume", tr("Disengage Volume"), tr("Related alerts:\n\nAdaptive Cruise Disabled\nParking Brake Engaged\nBrake Pedal Pressed\nSpeed too Low"), ""}, + {"EngageVolume", tr("Engage Volume"), tr("Related alerts:\n\nNNFF Torque Controller loaded\nopenpilot engaged"), ""}, + {"PromptVolume", tr("Prompt Volume"), tr("Related alerts:\n\nCar Detected in Blindspot\nSpeed too Low\nSteer Unavailable Below 'X'\nTake Control, Turn Exceeds Steering Limit"), ""}, + {"PromptDistractedVolume", tr("Prompt Distracted Volume"), tr("Related alerts:\n\nPay Attention, Driver Distracted\nTouch Steering Wheel, Driver Unresponsive"), ""}, + {"RefuseVolume", tr("Refuse Volume"), tr("Related alerts:\n\nopenpilot Unavailable"), ""}, + {"WarningSoftVolume", tr("Warning Soft Volume"), tr("Related alerts:\n\nBRAKE!, Risk of Collision\nTAKE CONTROL IMMEDIATELY"), ""}, + {"WarningImmediateVolume", tr("Warning Immediate Volume"), tr("Related alerts:\n\nDISENGAGE IMMEDIATELY, Driver Distracted\nDISENGAGE IMMEDIATELY, Driver Unresponsive"), ""}, + + {"CustomAlerts", tr("Custom Alerts"), tr("Enable custom alerts for openpilot events."), "../frogpilot/assets/toggle_icons/icon_green_light.png"}, + {"GreenLightAlert", tr("Green Light Alert"), tr("Get an alert when a traffic light changes from red to green."), ""}, + {"LeadDepartingAlert", tr("Lead Departing Alert"), tr("Get an alert when the lead vehicle starts departing when at a standstill."), ""}, + {"LoudBlindspotAlert", tr("Loud Blindspot Alert"), tr("Enable a louder alert for when a vehicle is detected in the blindspot when attempting to change lanes."), ""}, + + {"CustomUI", tr("Custom Onroad UI"), tr("Customize the Onroad UI."), "../assets/offroad/icon_road.png"}, + {"Compass", tr("Compass"), tr("Add a compass to the onroad UI."), ""}, + {"CustomPaths", tr("Paths"), tr("Show your projected acceleration on the driving path, detected adjacent lanes, or when a vehicle is detected in your blindspot."), ""}, + {"PedalsOnUI", tr("Pedals Being Pressed"), tr("Display the brake and gas pedals on the onroad UI below the steering wheel icon."), ""}, + {"RoadNameUI", tr("Road Name"), tr("Display the current road's name at the bottom of the screen. Sourced from OpenStreetMap."), ""}, + {"WheelIcon", tr("Steering Wheel Icon"), tr("Replace the default steering wheel icon with a custom icon."), ""}, + {"ShowStoppingPoint", tr("Stopping Points"), tr("Display the point where openpilot wants to stop for red lights/stop signs."), ""}, + + {"CustomTheme", tr("Custom Themes"), tr("Enable the ability to use custom themes."), "../frogpilot/assets/wheel_images/frog.png"}, + {"CustomColors", tr("Color Theme"), tr("Switch out the standard openpilot color scheme with themed colors.\n\nWant to submit your own color scheme? Post it in the 'feature-request' channel in the FrogPilot Discord!"), ""}, + {"CustomIcons", tr("Icon Pack"), tr("Switch out the standard openpilot icons with a set of themed icons.\n\nWant to submit your own icon pack? Post it in the 'feature-request' channel in the FrogPilot Discord!"), ""}, + {"CustomSounds", tr("Sound Pack"), tr("Switch out the standard openpilot sounds with a set of themed sounds.\n\nWant to submit your own sound pack? Post it in the 'feature-request' channel in the FrogPilot Discord!"), ""}, + {"CustomSignals", tr("Turn Signals"), tr("Add themed animation for your turn signals.\n\nWant to submit your own turn signal animation? Post it in the 'feature-request' channel in the FrogPilot Discord!"), ""}, + {"HolidayThemes", tr("Holiday Themes"), tr("The openpilot theme changes according to the current/upcoming holiday. Minor holidays last a day, while major holidays (Easter, Christmas, Halloween, etc.) last a week."), ""}, + {"RandomEvents", tr("Random Events"), tr("Enjoy a bit of unpredictability with random events that can occur during certain driving conditions. This is purely cosmetic and has no impact on driving controls!"), ""}, + + {"DeveloperUI", tr("Developer UI"), tr("Get various detailed information of what openpilot is doing behind the scenes."), "../frogpilot/assets/toggle_icons/icon_device.png"}, + {"BorderMetrics", tr("Border Metrics"), tr("Display metrics in onroad UI border."), ""}, + {"FPSCounter", tr("FPS Counter"), tr("Display the 'Frames Per Second' (FPS) of your onroad UI for monitoring system performance."), ""}, + {"LateralMetrics", tr("Lateral Metrics"), tr("Display various metrics related to the lateral performance of openpilot."), ""}, + {"LongitudinalMetrics", tr("Longitudinal Metrics"), tr("Display various metrics related to the longitudinal performance of openpilot."), ""}, + {"NumericalTemp", tr("Numerical Temperature Gauge"), tr("Replace the 'GOOD', 'OK', and 'HIGH' temperature statuses with a numerical temperature gauge based on the highest temperature between the memory, CPU, and GPU."), ""}, + {"SidebarMetrics", tr("Sidebar"), tr("Display various custom metrics on the sidebar for the CPU, GPU, RAM, IP, and storage used/left."), ""}, + {"UseSI", tr("Use International System of Units"), tr("Display relevant metrics in the SI format."), ""}, + + {"ModelUI", tr("Model UI"), tr("Customize the model visualizations on the screen."), "../assets/offroad/icon_calibration.png"}, + {"DynamicPathWidth", tr("Dynamic Path Width"), tr("Have the path width dynamically adjust based on the current engagement state of openpilot."), ""}, + {"HideLeadMarker", tr("Hide Lead Marker"), tr("Hide the lead marker from the onroad UI."), ""}, + {"LaneLinesWidth", tr("Lane Lines"), tr("Adjust the visual thickness of lane lines on your display.\n\nDefault matches the MUTCD average of 4 inches."), ""}, + {"PathEdgeWidth", tr("Path Edges"), tr("Adjust the width of the path edges shown on your UI to represent different driving modes and statuses.\n\nDefault is 20% of the total path.\n\nBlue = Navigation\nLight Blue = 'Always On Lateral'\nGreen = Default\nOrange = 'Experimental Mode'\nRed = 'Traffic Mode'\nYellow = 'Conditional Experimental Mode' Overridden"), ""}, + {"PathWidth", tr("Path Width"), tr("Customize the width of the driving path shown on your UI.\n\nDefault matches the width of a 2019 Lexus ES 350."), ""}, + {"RoadEdgesWidth", tr("Road Edges"), tr("Adjust the visual thickness of road edges on your display.\n\nDefault is 1/2 of the MUTCD average lane line width of 4 inches."), ""}, + {"UnlimitedLength", tr("'Unlimited' Road UI Length"), tr("Extend the display of the path, lane lines, and road edges out as far as the model can see."), ""}, + + {"QOLVisuals", tr("Quality of Life"), tr("Miscellaneous quality of life changes to improve your overall openpilot experience."), "../frogpilot/assets/toggle_icons/quality_of_life.png"}, + {"BigMap", tr("Big Map"), tr("Increase the size of the map in the onroad UI."), ""}, + {"CameraView", tr("Camera View"), tr("Choose your preferred camera view for the onroad UI. This is purely a visual change and doesn't impact how openpilot drives."), ""}, + {"DriverCamera", tr("Driver Camera On Reverse"), tr("Show the driver camera feed when in reverse."), ""}, + {"HideSpeed", tr("Hide Speed"), tr("Hide the speed indicator in the onroad UI. Additional toggle allows it to be hidden/shown via tapping the speed itself."), ""}, + {"MapStyle", tr("Map Style"), tr("Select a map style to use with navigation."), ""}, + {"StoppedTimer", tr("Stopped Timer"), tr("Display a timer in the onroad UI that indicates how long you've been stopped for."), ""}, + {"WheelSpeed", tr("Use Wheel Speed"), tr("Use the wheel speed instead of the cluster speed in the onroad UI."), ""}, + + {"ScreenManagement", tr("Screen Management"), tr("Manage your screen's brightness, timeout settings, and hide onroad UI elements."), "../frogpilot/assets/toggle_icons/icon_light.png"}, + {"HideUIElements", tr("Hide UI Elements"), tr("Hide the selected UI elements from the onroad screen."), ""}, + {"ScreenBrightness", tr("Screen Brightness"), tr("Customize your screen brightness when offroad."), ""}, + {"ScreenBrightnessOnroad", tr("Screen Brightness (Onroad)"), tr("Customize your screen brightness when onroad."), ""}, + {"ScreenRecorder", tr("Screen Recorder"), tr("Enable the ability to record the screen while onroad."), ""}, + {"ScreenTimeout", tr("Screen Timeout"), tr("Customize how long it takes for your screen to turn off."), ""}, + {"ScreenTimeoutOnroad", tr("Screen Timeout (Onroad)"), tr("Customize how long it takes for your screen to turn off when onroad."), ""}, + {"StandbyMode", tr("Standby Mode"), tr("Turn the screen off after your screen times out when onroad, but wake it back up when engagement state changes or important alerts are triggered."), ""}, + }; + + for (const auto &[param, title, desc, icon] : visualToggles) { + AbstractControl *visualToggle; + + if (param == "AlertVolumeControl") { + FrogPilotParamManageControl *alertVolumeControlToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(alertVolumeControlToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + toggle->setVisible(alertVolumeControlKeys.find(key.c_str()) != alertVolumeControlKeys.end()); + } + }); + visualToggle = alertVolumeControlToggle; + } else if (alertVolumeControlKeys.find(param) != alertVolumeControlKeys.end()) { + if (param == "WarningImmediateVolume") { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 25, 100, std::map(), this, false, "%"); + } else { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 100, std::map(), this, false, "%"); + } + + } else if (param == "CustomAlerts") { + FrogPilotParamManageControl *customAlertsToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(customAlertsToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + std::set modifiedCustomAlertsKeys = customAlertsKeys; + + if (!hasBSM) { + modifiedCustomAlertsKeys.erase("LoudBlindspotAlert"); + } + + toggle->setVisible(modifiedCustomAlertsKeys.find(key.c_str()) != modifiedCustomAlertsKeys.end()); + } + }); + visualToggle = customAlertsToggle; + + } else if (param == "CustomTheme") { + FrogPilotParamManageControl *customThemeToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(customThemeToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + toggle->setVisible(customThemeKeys.find(key.c_str()) != customThemeKeys.end()); + } + }); + visualToggle = customThemeToggle; + } else if (param == "CustomColors" || param == "CustomIcons" || param == "CustomSignals" || param == "CustomSounds") { + std::vector themeOptions{tr("Stock"), tr("Frog"), tr("Tesla"), tr("Stalin")}; + FrogPilotButtonParamControl *themeSelection = new FrogPilotButtonParamControl(param, title, desc, icon, themeOptions); + visualToggle = themeSelection; + + if (param == "CustomSounds") { + QObject::connect(themeSelection, &FrogPilotButtonParamControl::buttonClicked, [this](int id) { + if (id == 1) { + if (FrogPilotConfirmationDialog::yesorno(tr("Do you want to enable the bonus 'Goat' sound effect?"), this)) { + params.putBoolNonBlocking("GoatScream", true); + } else { + params.putBoolNonBlocking("GoatScream", false); + } + } + }); + } + + } else if (param == "CustomUI") { + FrogPilotParamManageControl *customUIToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(customUIToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + toggle->setVisible(customOnroadUIKeys.find(key.c_str()) != customOnroadUIKeys.end()); + } + }); + visualToggle = customUIToggle; + } else if (param == "CustomPaths") { + std::vector pathToggles{"AccelerationPath", "AdjacentPath", "BlindSpotPath", "AdjacentPathMetrics"}; + std::vector pathToggleNames{tr("Acceleration"), tr("Adjacent"), tr("Blind Spot"), tr("Metrics")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, pathToggles, pathToggleNames); + } else if (param == "PedalsOnUI") { + std::vector pedalsToggles{"DynamicPedalsOnUI", "StaticPedalsOnUI"}; + std::vector pedalsToggleNames{tr("Dynamic"), tr("Static")}; + FrogPilotParamToggleControl *pedalsToggle = new FrogPilotParamToggleControl(param, title, desc, icon, pedalsToggles, pedalsToggleNames); + QObject::connect(pedalsToggle, &FrogPilotParamToggleControl::buttonTypeClicked, this, [this, pedalsToggle](int index) { + if (index == 0) { + params.putBool("StaticPedalsOnUI", false); + } else if (index == 1) { + params.putBool("DynamicPedalsOnUI", false); + } + + pedalsToggle->updateButtonStates(); + }); + visualToggle = pedalsToggle; + } else if (param == "WheelIcon") { + std::vector wheelToggles{"RotatingWheel"}; + std::vector wheelToggleNames{"Live Rotation"}; + std::map steeringWheelLabels = {{-1, tr("None")}, {0, tr("Stock")}, {1, tr("Lexus")}, {2, tr("Toyota")}, {3, tr("Frog")}, {4, tr("Rocket")}, {5, tr("Hyundai")}, {6, tr("Stalin")}}; + visualToggle = new FrogPilotParamValueToggleControl(param, title, desc, icon, -1, 6, steeringWheelLabels, this, true, "", 1, 1, wheelToggles, wheelToggleNames); + } else if (param == "ShowStoppingPoint") { + std::vector stoppingPointToggles{"ShowStoppingPointMetrics"}; + std::vector stoppingPointToggleNames{tr("Show Distance")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, stoppingPointToggles, stoppingPointToggleNames); + + } else if (param == "DeveloperUI") { + FrogPilotParamManageControl *developerUIToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(developerUIToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + std::set modifiedDeveloperUIKeys = developerUIKeys ; + + toggle->setVisible(modifiedDeveloperUIKeys.find(key.c_str()) != modifiedDeveloperUIKeys.end()); + } + }); + visualToggle = developerUIToggle; + } else if (param == "BorderMetrics") { + std::vector borderToggles{"BlindSpotMetrics", "ShowSteering", "SignalMetrics"}; + std::vector borderToggleNames{tr("Blind Spot"), tr("Steering Torque"), tr("Turn Signal")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, borderToggles, borderToggleNames); + } else if (param == "LateralMetrics") { + std::vector lateralToggles{"TuningInfo"}; + std::vector lateralToggleNames{tr("Auto Tune")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, lateralToggles, lateralToggleNames); + } else if (param == "LongitudinalMetrics") { + std::vector longitudinalToggles{"LeadInfo", "JerkInfo"}; + std::vector longitudinalToggleNames{tr("Lead Info"), tr("Longitudinal Jerk")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, longitudinalToggles, longitudinalToggleNames); + } else if (param == "NumericalTemp") { + std::vector temperatureToggles{"Fahrenheit"}; + std::vector temperatureToggleNames{tr("Fahrenheit")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, temperatureToggles, temperatureToggleNames); + } else if (param == "SidebarMetrics") { + std::vector sidebarMetricsToggles{"ShowCPU", "ShowGPU", "ShowIP", "ShowMemoryUsage", "ShowStorageLeft", "ShowStorageUsed"}; + std::vector sidebarMetricsToggleNames{tr("CPU"), tr("GPU"), tr("IP"), tr("RAM"), tr("SSD Left"), tr("SSD Used")}; + FrogPilotParamToggleControl *sidebarMetricsToggle = new FrogPilotParamToggleControl(param, title, desc, icon, sidebarMetricsToggles, sidebarMetricsToggleNames, this, 125); + QObject::connect(sidebarMetricsToggle, &FrogPilotParamToggleControl::buttonTypeClicked, this, [this, sidebarMetricsToggle](int index) { + if (index == 0) { + params.putBool("ShowGPU", false); + } else if (index == 1) { + params.putBool("ShowCPU", false); + } else if (index == 3) { + params.putBool("ShowStorageLeft", false); + params.putBool("ShowStorageUsed", false); + } else if (index == 4) { + params.putBool("ShowMemoryUsage", false); + params.putBool("ShowStorageUsed", false); + } else if (index == 5) { + params.putBool("ShowMemoryUsage", false); + params.putBool("ShowStorageLeft", false); + } + + sidebarMetricsToggle->updateButtonStates(); + }); + visualToggle = sidebarMetricsToggle; + + } else if (param == "ModelUI") { + FrogPilotParamManageControl *modelUIToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(modelUIToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + std::set modifiedModelUIKeysKeys = modelUIKeys; + + if (!hasOpenpilotLongitudinal || disableOpenpilotLongitudinal) { + modifiedModelUIKeysKeys.erase("HideLeadMarker"); + } + + toggle->setVisible(modifiedModelUIKeysKeys.find(key.c_str()) != modifiedModelUIKeysKeys.end()); + } + }); + visualToggle = modelUIToggle; + } else if (param == "LaneLinesWidth" || param == "RoadEdgesWidth") { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 24, std::map(), this, false, tr(" inches")); + } else if (param == "PathEdgeWidth") { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 100, std::map(), this, false, tr("%")); + } else if (param == "PathWidth") { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 100, std::map(), this, false, tr(" feet"), 10); + + } else if (param == "QOLVisuals") { + FrogPilotParamManageControl *qolToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(qolToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + toggle->setVisible(qolKeys.find(key.c_str()) != qolKeys.end()); + } + }); + visualToggle = qolToggle; + } else if (param == "CameraView") { + std::vector cameraOptions{tr("Auto"), tr("Driver"), tr("Standard"), tr("Wide")}; + FrogPilotButtonParamControl *preferredCamera = new FrogPilotButtonParamControl(param, title, desc, icon, cameraOptions); + visualToggle = preferredCamera; + } else if (param == "BigMap") { + std::vector mapToggles{"FullMap"}; + std::vector mapToggleNames{tr("Full Map")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, mapToggles, mapToggleNames); + } else if (param == "HideSpeed") { + std::vector hideSpeedToggles{"HideSpeedUI"}; + std::vector hideSpeedToggleNames{tr("Control Via UI")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, hideSpeedToggles, hideSpeedToggleNames); + } else if (param == "MapStyle") { + QMap styleMap = { + {0, tr("Stock openpilot")}, + {1, tr("Mapbox Streets")}, + {2, tr("Mapbox Outdoors")}, + {3, tr("Mapbox Light")}, + {4, tr("Mapbox Dark")}, + {5, tr("Mapbox Satellite")}, + {6, tr("Mapbox Satellite Streets")}, + {7, tr("Mapbox Navigation Day")}, + {8, tr("Mapbox Navigation Night")}, + {9, tr("Mapbox Traffic Night")}, + {10, tr("mike854's (Satellite hybrid)")}, + }; + + QStringList styles = styleMap.values(); + ButtonControl *mapStyleButton = new ButtonControl(title, tr("SELECT"), desc); + QObject::connect(mapStyleButton, &ButtonControl::clicked, [=]() { + QStringList styles = styleMap.values(); + QString selection = MultiOptionDialog::getSelection(tr("Select a map style"), styles, "", this); + if (!selection.isEmpty()) { + int selectedStyle = styleMap.key(selection); + params.putIntNonBlocking("MapStyle", selectedStyle); + mapStyleButton->setValue(selection); + updateFrogPilotToggles(); + } + }); + + int currentStyle = params.getInt("MapStyle"); + mapStyleButton->setValue(styleMap[currentStyle]); + + visualToggle = mapStyleButton; + + } else if (param == "ScreenManagement") { + FrogPilotParamManageControl *screenToggle = new FrogPilotParamManageControl(param, title, desc, icon, this); + QObject::connect(screenToggle, &FrogPilotParamManageControl::manageButtonClicked, this, [this]() { + openParentToggle(); + for (auto &[key, toggle] : toggles) { + toggle->setVisible(screenKeys.find(key.c_str()) != screenKeys.end()); + } + }); + visualToggle = screenToggle; + } else if (param == "HideUIElements") { + std::vector uiElementsToggles{"HideAlerts", "HideMapIcon", "HideMaxSpeed"}; + std::vector uiElementsToggleNames{tr("Alerts"), tr("Map Icon"), tr("Max Speed")}; + visualToggle = new FrogPilotParamToggleControl(param, title, desc, icon, uiElementsToggles, uiElementsToggleNames); + } else if (param == "ScreenBrightness" || param == "ScreenBrightnessOnroad") { + std::map brightnessLabels; + if (param == "ScreenBrightnessOnroad") { + for (int i = 0; i <= 101; i++) { + brightnessLabels[i] = (i == 0) ? tr("Screen Off") : (i == 101) ? tr("Auto") : QString::number(i) + "%"; + } + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 0, 101, brightnessLabels, this, false); + } else { + for (int i = 1; i <= 101; i++) { + brightnessLabels[i] = (i == 101) ? tr("Auto") : QString::number(i) + "%"; + } + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 1, 101, brightnessLabels, this, false); + } + } else if (param == "ScreenTimeout" || param == "ScreenTimeoutOnroad") { + visualToggle = new FrogPilotParamValueControl(param, title, desc, icon, 5, 60, std::map(), this, false, tr(" seconds")); + + } else { + visualToggle = new ParamControl(param, title, desc, icon, this); + } + + addItem(visualToggle); + toggles[param.toStdString()] = visualToggle; + + QObject::connect(static_cast(visualToggle), &ToggleControl::toggleFlipped, &updateFrogPilotToggles); + QObject::connect(static_cast(visualToggle), &FrogPilotParamToggleControl::buttonTypeClicked, &updateFrogPilotToggles); + QObject::connect(static_cast(visualToggle), &FrogPilotParamValueControl::valueChanged, [this]() { + bool screen_management = params.getBool("ScreenManagement"); + if (!started) { + uiState()->scene.screen_brightness = screen_management ? params.getInt("ScreenBrightness") : 101; + } else { + uiState()->scene.screen_brightness_onroad = screen_management ? params.getInt("ScreenBrightnessOnroad") : 101; + } + updateFrogPilotToggles(); + }); + + QObject::connect(visualToggle, &AbstractControl::showDescriptionEvent, [this]() { + update(); + }); + + QObject::connect(static_cast(visualToggle), &FrogPilotParamManageControl::manageButtonClicked, [this]() { + update(); + }); + } + + QObject::connect(parent, &SettingsWindow::closeParentToggle, this, &FrogPilotVisualsPanel::hideToggles); + QObject::connect(parent, &SettingsWindow::updateMetric, this, &FrogPilotVisualsPanel::updateMetric); + QObject::connect(uiState(), &UIState::offroadTransition, this, &FrogPilotVisualsPanel::updateCarToggles); + QObject::connect(uiState(), &UIState::uiUpdate, this, &FrogPilotVisualsPanel::updateState); + + updateMetric(); +} + +void FrogPilotVisualsPanel::showEvent(QShowEvent *event) { + disableOpenpilotLongitudinal = params.getBool("DisableOpenpilotLongitudinal"); +} + +void FrogPilotVisualsPanel::updateState(const UIState &s) { + if (!isVisible()) return; + + started = s.scene.started; +} + +void FrogPilotVisualsPanel::updateCarToggles() { + auto 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(); + auto carName = CP.getCarName(); + + hasAutoTune = (carName == "hyundai" || carName == "toyota") && CP.getLateralTuning().which() == cereal::CarParams::LateralTuning::TORQUE; + hasBSM = CP.getEnableBsm(); + hasOpenpilotLongitudinal = hasLongitudinalControl(CP); + } else { + hasAutoTune = true; + hasBSM = true; + hasOpenpilotLongitudinal = true; + } + + hideToggles(); +} + +void FrogPilotVisualsPanel::updateMetric() { + bool previousIsMetric = isMetric; + isMetric = params.getBool("IsMetric"); + + if (isMetric != previousIsMetric) { + double distanceConversion = isMetric ? INCH_TO_CM : CM_TO_INCH; + double speedConversion = isMetric ? FOOT_TO_METER : METER_TO_FOOT; + + params.putIntNonBlocking("LaneLinesWidth", std::nearbyint(params.getInt("LaneLinesWidth") * distanceConversion)); + params.putIntNonBlocking("RoadEdgesWidth", std::nearbyint(params.getInt("RoadEdgesWidth") * distanceConversion)); + + params.putIntNonBlocking("PathWidth", std::nearbyint(params.getInt("PathWidth") * speedConversion)); + } + + FrogPilotParamValueControl *laneLinesWidthToggle = static_cast(toggles["LaneLinesWidth"]); + FrogPilotParamValueControl *roadEdgesWidthToggle = static_cast(toggles["RoadEdgesWidth"]); + FrogPilotParamValueControl *pathWidthToggle = static_cast(toggles["PathWidth"]); + + if (isMetric) { + laneLinesWidthToggle->setDescription(tr("Customize the lane line width.\n\nDefault matches the Vienna average of 10 centimeters.")); + roadEdgesWidthToggle->setDescription(tr("Customize the road edges width.\n\nDefault is 1/2 of the Vienna average lane line width of 10 centimeters.")); + + laneLinesWidthToggle->updateControl(0, 60, tr(" centimeters")); + roadEdgesWidthToggle->updateControl(0, 60, tr(" centimeters")); + + pathWidthToggle->updateControl(0, 30, tr(" meters"), 10); + } else { + laneLinesWidthToggle->setDescription(tr("Customize the lane line width.\n\nDefault matches the MUTCD average of 4 inches.")); + roadEdgesWidthToggle->setDescription(tr("Customize the road edges width.\n\nDefault is 1/2 of the MUTCD average lane line width of 4 inches.")); + + laneLinesWidthToggle->updateControl(0, 24, tr(" inches")); + roadEdgesWidthToggle->updateControl(0, 24, tr(" inches")); + + pathWidthToggle->updateControl(0, 100, tr(" feet"), 10); + } + + laneLinesWidthToggle->refresh(); + roadEdgesWidthToggle->refresh(); +} + +void FrogPilotVisualsPanel::hideToggles() { + for (auto &[key, toggle] : toggles) { + bool subToggles = alertVolumeControlKeys.find(key.c_str()) != alertVolumeControlKeys.end() || + customAlertsKeys.find(key.c_str()) != customAlertsKeys.end() || + customOnroadUIKeys.find(key.c_str()) != customOnroadUIKeys.end() || + customThemeKeys.find(key.c_str()) != customThemeKeys.end() || + developerUIKeys.find(key.c_str()) != developerUIKeys.end() || + modelUIKeys.find(key.c_str()) != modelUIKeys.end() || + qolKeys.find(key.c_str()) != qolKeys.end() || + screenKeys.find(key.c_str()) != screenKeys.end(); + toggle->setVisible(!subToggles); + } + + update(); +} diff --git a/selfdrive/frogpilot/ui/qt/offroad/visual_settings.h b/selfdrive/frogpilot/ui/qt/offroad/visual_settings.h new file mode 100644 index 0000000000..4726ab69a4 --- /dev/null +++ b/selfdrive/frogpilot/ui/qt/offroad/visual_settings.h @@ -0,0 +1,44 @@ +#pragma once + +#include + +#include "selfdrive/ui/qt/offroad/settings.h" +#include "selfdrive/ui/ui.h" + +class FrogPilotVisualsPanel : public FrogPilotListWidget { + Q_OBJECT + +public: + explicit FrogPilotVisualsPanel(SettingsWindow *parent); + +signals: + void openParentToggle(); + +private: + void hideToggles(); + void showEvent(QShowEvent *event) override; + void updateCarToggles(); + void updateMetric(); + void updateState(const UIState &s); + + std::set alertVolumeControlKeys = {"DisengageVolume", "EngageVolume", "PromptDistractedVolume", "PromptVolume", "RefuseVolume", "WarningImmediateVolume", "WarningSoftVolume"}; + std::set customAlertsKeys = {"GreenLightAlert", "LeadDepartingAlert", "LoudBlindspotAlert"}; + std::set customOnroadUIKeys = {"Compass", "CustomPaths", "PedalsOnUI", "RoadNameUI", "ShowStoppingPoint", "WheelIcon"}; + std::set customThemeKeys = {"CustomColors", "CustomIcons", "CustomSignals", "CustomSounds", "HolidayThemes", "RandomEvents"}; + std::set developerUIKeys = {"BorderMetrics", "FPSCounter", "LateralMetrics", "LongitudinalMetrics", "NumericalTemp", "SidebarMetrics", "UseSI"}; + std::set modelUIKeys = {"DynamicPathWidth", "HideLeadMarker", "LaneLinesWidth", "PathEdgeWidth", "PathWidth", "RoadEdgesWidth", "UnlimitedLength"}; + std::set qolKeys = {"BigMap", "CameraView", "DriverCamera", "FullMap", "HideSpeed", "MapStyle", "StoppedTimer", "WheelSpeed"}; + std::set screenKeys = {"HideUIElements", "ScreenBrightness", "ScreenBrightnessOnroad", "ScreenRecorder", "ScreenTimeout", "ScreenTimeoutOnroad", "StandbyMode"}; + + std::map toggles; + + Params params; + + bool disableOpenpilotLongitudinal; + bool hasAutoTune; + bool hasBSM; + bool hasOpenpilotLongitudinal; + bool isMetric = params.getBool("IsMetric"); + bool isRelease; + bool started; +}; diff --git a/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.cc b/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.cc index ee2bceed8a..63cf81ba19 100644 --- a/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.cc +++ b/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.cc @@ -14,3 +14,41 @@ void updateFrogPilotToggles() { } }).detach(); } + +bool FrogPilotConfirmationDialog::toggle(const QString &prompt_text, const QString &confirm_text, QWidget *parent) { + ConfirmationDialog d = ConfirmationDialog(prompt_text, confirm_text, tr("Reboot Later"), false, parent); + return d.exec(); +} + +bool FrogPilotConfirmationDialog::toggleAlert(const QString &prompt_text, const QString &button_text, QWidget *parent) { + ConfirmationDialog d = ConfirmationDialog(prompt_text, button_text, "", false, parent); + return d.exec(); +} + +bool FrogPilotConfirmationDialog::yesorno(const QString &prompt_text, QWidget *parent) { + ConfirmationDialog d = ConfirmationDialog(prompt_text, tr("Yes"), tr("No"), false, parent); + return d.exec(); +} + +FrogPilotButtonIconControl::FrogPilotButtonIconControl(const QString &title, const QString &text, const QString &desc, const QString &icon, QWidget *parent) : AbstractControl(title, desc, icon, 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, &FrogPilotButtonIconControl::clicked); + hlayout->addWidget(&btn); +} diff --git a/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.h b/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.h index 3364551509..cf5e547027 100644 --- a/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.h +++ b/selfdrive/frogpilot/ui/qt/widgets/frogpilot_controls.h @@ -1,3 +1,731 @@ #pragma once +#include + +#include + +#include "selfdrive/ui/qt/widgets/controls.h" + void updateFrogPilotToggles(); + +class FrogPilotConfirmationDialog : public ConfirmationDialog { + Q_OBJECT + +public: + explicit FrogPilotConfirmationDialog(const QString &prompt_text, const QString &confirm_text, + const QString &cancel_text, const bool rich, QWidget *parent); + static bool toggle(const QString &prompt_text, const QString &confirm_text, QWidget *parent); + static bool toggleAlert(const QString &prompt_text, const QString &button_text, QWidget *parent); + static bool yesorno(const QString &prompt_text, QWidget *parent); +}; + +class FrogPilotListWidget : public QWidget { + Q_OBJECT +public: + explicit FrogPilotListWidget(QWidget *parent = nullptr) : 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 + } + + inline void addItem(QWidget *w) { + inner_layout.addWidget(w); + adjustStretch(); + } + + inline void addItem(QLayout *layout) { + inner_layout.addLayout(layout); + adjustStretch(); + } + + inline void setSpacing(int spacing) { + inner_layout.setSpacing(spacing); + adjustStretch(); + } + +private: + void adjustStretch() { + if (inner_layout.stretch(inner_layout.count() - 1) > 0) { + inner_layout.setStretch(inner_layout.count() - 1, 0); + } + if (inner_layout.count() > 3) { + outer_layout.addStretch(); + } + } + + void paintEvent(QPaintEvent *event) override { + QPainter p(this); + p.setPen(Qt::gray); + + int visibleWidgetCount = 0; + std::vector visibleRects; + + for (int i = 0; i < inner_layout.count(); ++i) { + QWidget *widget = inner_layout.itemAt(i)->widget(); + if (widget && widget->isVisible()) { + visibleWidgetCount++; + visibleRects.push_back(inner_layout.itemAt(i)->geometry()); + } + } + + for (int i = 0; i < visibleWidgetCount - 1; ++i) { + int bottom = visibleRects[i].bottom() + inner_layout.spacing() / 2; + p.drawLine(visibleRects[i].left() + 40, bottom, visibleRects[i].right() - 40, bottom); + } + } + + QVBoxLayout outer_layout; + QVBoxLayout inner_layout; +}; + +class FrogPilotButtonControl : public AbstractControl { + Q_OBJECT + +public: + FrogPilotButtonControl(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 FrogPilotButtonIconControl : public AbstractControl { + Q_OBJECT + +public: + FrogPilotButtonIconControl(const QString &title, const QString &text, const QString &desc = "", const QString &icon = "", 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 FrogPilotButtonParamControl : public ParamControl { + Q_OBJECT +public: + FrogPilotButtonParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, + const std::vector &button_texts, const int minimum_button_width = 225) + : ParamControl(param, 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:disabled { + color: #33E4E4E4; + } + )"; + + key = param.toStdString(); + int value = atoi(params.get(key).c_str()); + + button_group = new QButtonGroup(this); + button_group->setExclusive(true); + for (size_t i = 0; i < button_texts.size(); i++) { + QPushButton *button = new QPushButton(button_texts[i], this); + button->setCheckable(true); + button->setChecked(i == value); + button->setStyleSheet(style); + button->setMinimumWidth(minimum_button_width); + hlayout->addWidget(button); + button_group->addButton(button, i); + } + + QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonToggled), [=](int id, bool checked) { + if (checked) { + params.put(key, std::to_string(id)); + refresh(); + emit buttonClicked(id); + } + }); + + toggle.hide(); + } + + void setEnabled(bool enable) { + for (auto btn : button_group->buttons()) { + btn->setEnabled(enable); + } + } + +signals: + void buttonClicked(int id); + +private: + std::string key; + Params params; + QButtonGroup *button_group; +}; + +class FrogPilotButtonsControl : public ParamControl { + Q_OBJECT +public: + FrogPilotButtonsControl(const QString &title, const QString &desc, const QString &icon, + const std::vector &button_texts, const bool checkable = false, const int minimum_button_width = 225) + : ParamControl("", title, desc, icon) { + const QString style = R"( + QPushButton { + border-radius: 50px; + font-size: 40px; + font-weight: 500; + height: 100px; + padding: 0 25px 0 25px; + color: #E4E4E4; + background-color: #393939; + } + QPushButton:checked { + background-color: #33Ab4C; + } + QPushButton:pressed { + background-color: #33Ab4C; + } + QPushButton:disabled { + color: #33E4E4E4; + } + )"; + + button_group = new QButtonGroup(this); + + for (size_t i = 0; i < button_texts.size(); i++) { + QPushButton *button = new QPushButton(button_texts[i], this); + button->setStyleSheet(style); + button->setCheckable(checkable); + button->setMinimumWidth(minimum_button_width); + hlayout->addWidget(button); + button_group->addButton(button, static_cast(i)); + + connect(button, &QPushButton::clicked, this, [this, i]() { + emit buttonClicked(static_cast(i)); + }); + } + + toggle.hide(); + } + + void updateButtonStyles(int id) { + for (auto button : button_group->buttons()) { + button->setChecked(button_group->id(button) == id); + } + } + + void setEnabled(bool enable) { + for (auto btn : button_group->buttons()) { + btn->setEnabled(enable); + } + } + +signals: + void buttonClicked(int id); + +private: + QButtonGroup *button_group; +}; + +class FrogPilotButtonsParamControl : public ParamControl { + Q_OBJECT +public: + FrogPilotButtonsParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, + const std::vector> &button_params) + : ParamControl(param, 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:disabled { + color: #33E4E4E4; + } + )"; + + button_group = new QButtonGroup(this); + button_group->setExclusive(true); + + for (const auto ¶m_pair : button_params) { + const QString ¶m_toggle = param_pair.first; + const QString &button_text = param_pair.second; + + QPushButton *button = new QPushButton(button_text, this); + button->setCheckable(true); + + bool value = params.getBool(param_toggle.toStdString()); + button->setChecked(value); + button->setStyleSheet(style); + button->setMinimumWidth(225); + hlayout->addWidget(button); + + QObject::connect(button, &QPushButton::toggled, this, [=](bool checked) { + if (checked) { + for (const auto &inner_param_pair : button_params) { + const QString &inner_param = inner_param_pair.first; + params.putBool(inner_param.toStdString(), inner_param == param_toggle); + } + refresh(); + emit buttonClicked(); + } + }); + + button_group->addButton(button); + } + + toggle.hide(); + } + + void setEnabled(bool enable) { + for (auto btn : button_group->buttons()) { + btn->setEnabled(enable); + } + } + +signals: + void buttonClicked(); + +private: + Params params; + QButtonGroup *button_group; +}; + +class FrogPilotParamManageControl : public ParamControl { + Q_OBJECT + +public: + FrogPilotParamManageControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr, bool hideToggle = false) + : ParamControl(param, title, desc, icon, parent), + hideToggle(hideToggle), + key(param.toStdString()), + manageButton(new ButtonControl(tr(""), tr("MANAGE"), tr(""))) { + hlayout->insertWidget(hlayout->indexOf(&toggle) - 1, manageButton); + + connect(this, &ToggleControl::toggleFlipped, this, [this](bool state) { + refresh(); + }); + + connect(manageButton, &ButtonControl::clicked, this, &FrogPilotParamManageControl::manageButtonClicked); + + if (hideToggle) { + toggle.hide(); + } + } + + void refresh() { + ParamControl::refresh(); + manageButton->setVisible(params.getBool(key) || hideToggle); + } + + void setEnabled(bool enabled) { + manageButton->setEnabled(enabled); + toggle.setEnabled(enabled); + toggle.update(); + } + + void showEvent(QShowEvent *event) override { + ParamControl::showEvent(event); + refresh(); + } + +signals: + void manageButtonClicked(); + +private: + bool hideToggle; + std::string key; + Params params; + ButtonControl *manageButton; +}; + +class FrogPilotParamToggleControl : public ParamControl { + Q_OBJECT +public: + FrogPilotParamToggleControl(const QString ¶m, const QString &title, const QString &desc, + const QString &icon, const std::vector &button_params, + const std::vector &button_texts, QWidget *parent = nullptr, + const int minimum_button_width = 225) + : ParamControl(param, title, desc, icon, parent) { + + key = param.toStdString(); + + connect(this, &ToggleControl::toggleFlipped, this, [this](bool state) { + refreshButtons(state); + }); + + 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:disabled { + color: #33E4E4E4; + } + )"; + + button_group = new QButtonGroup(this); + button_group->setExclusive(false); + this->button_params = button_params; + + for (int i = 0; i < button_texts.size(); ++i) { + QPushButton *button = new QPushButton(button_texts[i], this); + button->setCheckable(true); + button->setStyleSheet(style); + button->setMinimumWidth(minimum_button_width); + button_group->addButton(button, i); + + connect(button, &QPushButton::clicked, [this, i](bool checked) { + params.putBool(this->button_params[i].toStdString(), checked); + button_group->button(i)->setChecked(checked); + emit buttonClicked(checked); + emit buttonTypeClicked(i); + }); + + hlayout->insertWidget(hlayout->indexOf(&toggle) - 1, button); + } + } + + void refresh() { + bool state = params.getBool(key); + if (state != toggle.on) { + toggle.togglePosition(); + } + + refreshButtons(state); + updateButtonStates(); + } + + void refreshButtons(bool state) { + for (QAbstractButton *button : button_group->buttons()) { + button->setVisible(state); + } + } + + void updateButtonStates() { + for (int i = 0; i < button_group->buttons().size(); ++i) { + bool checked = params.getBool(button_params[i].toStdString()); + QAbstractButton *button = button_group->button(i); + if (button) { + button->setChecked(checked); + } + } + } + + void showEvent(QShowEvent *event) override { + refresh(); + QWidget::showEvent(event); + } + +signals: + void buttonClicked(const bool checked); + void buttonTypeClicked(int i); + +private: + std::string key; + Params params; + QButtonGroup *button_group; + std::vector button_params; +}; + +class FrogPilotParamValueControl : public ParamControl { + Q_OBJECT + +public: + FrogPilotParamValueControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, + const float &minValue, const float &maxValue, const std::map &valueLabels, + QWidget *parent = nullptr, const bool &loop = true, const QString &label = "", + const float &division = 1.0f, const float &interval = 1.0f) + : ParamControl(param, title, desc, icon, parent), + minValue(minValue), maxValue(maxValue), valueLabelMappings(valueLabels), loop(loop), labelText(label), + division(division), interval(interval), previousValue(0.0f), value(0.0f) { + key = param.toStdString(); + + valueLabel = new QLabel(this); + hlayout->addWidget(valueLabel); + + QPushButton *decrementButton = createButton("-", this); + QPushButton *incrementButton = createButton("+", this); + + hlayout->addWidget(decrementButton); + hlayout->addWidget(incrementButton); + + countdownTimer = new QTimer(this); + countdownTimer->setInterval(150); + countdownTimer->setSingleShot(true); + + connect(countdownTimer, &QTimer::timeout, this, &FrogPilotParamValueControl::handleTimeout); + + connect(decrementButton, &QPushButton::pressed, this, [=]() { updateValue(-interval); }); + connect(incrementButton, &QPushButton::pressed, this, [=]() { updateValue(interval); }); + + connect(decrementButton, &QPushButton::released, this, &FrogPilotParamValueControl::restartTimer); + connect(incrementButton, &QPushButton::released, this, &FrogPilotParamValueControl::restartTimer); + + toggle.hide(); + } + + void restartTimer() { + countdownTimer->stop(); + countdownTimer->start(); + + emit valueChanged(value); + } + + void handleTimeout() { + previousValue = value; + } + + void updateValue(float intervalChange) { + int previousValueAdjusted = round(previousValue * 100) / 100 / intervalChange; + int valueAdjusted = round(value * 100) / 100 / intervalChange; + + if (std::fabs(previousValueAdjusted - valueAdjusted) > 5 && std::fmod(valueAdjusted, 5) == 0) { + intervalChange *= 5; + } + + value += intervalChange; + + if (loop) { + if (value < minValue) { + value = maxValue; + } else if (value > maxValue) { + value = minValue; + } + } else { + value = std::max(minValue, std::min(maxValue, value)); + } + + params.putFloat(key, value); + refresh(); + } + + void refresh() { + value = params.getFloat(key); + + QString text; + auto it = valueLabelMappings.find(value); + int decimals = interval < 1.0f ? static_cast(-std::log10(interval)) : 2; + + if (division > 1.0f) { + text = QString::number(value / division, 'g', division >= 10.0f ? 4 : 3); + } else { + if (it != valueLabelMappings.end()) { + text = it->second; + } else { + if (value >= 100.0f) { + text = QString::number(value, 'f', 0); + } else { + text = QString::number(value, interval < 1.0f ? 'f' : 'g', decimals); + } + } + } + + if (!labelText.isEmpty()) { + text += labelText; + } + + valueLabel->setText(text); + valueLabel->setStyleSheet("QLabel { color: #E0E879; }"); + } + + void updateControl(float newMinValue, float newMaxValue, const QString &newLabel, float newDivision = 1.0f) { + minValue = newMinValue; + maxValue = newMaxValue; + labelText = newLabel; + division = newDivision; + } + + void showEvent(QShowEvent *event) override { + refresh(); + previousValue = value; + } + +signals: + void valueChanged(float value); + +private: + Params params; + + bool loop; + + float division; + float interval; + float maxValue; + float minValue; + float previousValue; + float value; + + QLabel *valueLabel; + QString labelText; + + std::map valueLabelMappings; + std::string key; + + QTimer *countdownTimer; + + QPushButton *createButton(const QString &text, QWidget *parent) { + QPushButton *button = new QPushButton(text, parent); + button->setFixedSize(150, 100); + button->setAutoRepeat(true); + button->setAutoRepeatInterval(150); + button->setAutoRepeatDelay(500); + button->setStyleSheet(R"( + QPushButton { + border-radius: 50px; + font-size: 50px; + font-weight: 500; + height: 100px; + padding: 0 25 0 25; + color: #E4E4E4; + background-color: #393939; + } + QPushButton:pressed { + background-color: #4a4a4a; + } + )"); + return button; + } +}; + +class FrogPilotParamValueToggleControl : public FrogPilotParamValueControl { + Q_OBJECT + +public: + FrogPilotParamValueToggleControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, + const float &minValue, const float &maxValue, const std::map &valueLabels, + QWidget *parent = nullptr, const bool &loop = true, const QString &label = "", + const float &division = 1.0f, const float &interval = 1.0f, + const std::vector &button_params = std::vector(), const std::vector &button_texts = std::vector(), + const int minimum_button_width = 225) + : FrogPilotParamValueControl(param, title, desc, icon, minValue, maxValue, valueLabels, parent, loop, label, division, interval) { + + 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:disabled { + color: #33E4E4E4; + } + )"; + + 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(true); + button->setChecked(params.getBool(button_params[i].toStdString())); + button->setStyleSheet(style); + button->setMinimumWidth(minimum_button_width); + button_group->addButton(button, i); + + connect(button, &QPushButton::clicked, [this, button_params, i](bool checked) { + params.putBool(button_params[i].toStdString(), checked); + emit buttonClicked(); + refresh(); + }); + + buttons[button_params[i]] = button; + hlayout->insertWidget(3, button); + } + } + + void refresh() { + FrogPilotParamValueControl::refresh(); + + auto keys = buttons.keys(); + for (const QString ¶m : keys) { + QPushButton *button = buttons.value(param); + button->setChecked(params.getBool(param.toStdString())); + } + } + +signals: + void buttonClicked(); + +private: + Params params; + QButtonGroup *button_group; + QMap buttons; +}; + +class FrogPilotDualParamControl : public QFrame { + Q_OBJECT + +public: + FrogPilotDualParamControl(FrogPilotParamValueControl *control1, FrogPilotParamValueControl *control2, QWidget *parent = nullptr) + : QFrame(parent), control1(control1), control2(control2) { + QHBoxLayout *hlayout = new QHBoxLayout(this); + hlayout->addWidget(control1); + hlayout->addWidget(control2); + } + + void updateControl(float newMinValue, float newMaxValue, const QString &newLabel, float newDivision = 1.0f) { + control1->updateControl(newMinValue, newMaxValue, newLabel, newDivision); + control2->updateControl(newMinValue, newMaxValue, newLabel, newDivision); + } + + void refresh() { + control1->refresh(); + control2->refresh(); + } + +private: + FrogPilotParamValueControl *control1; + FrogPilotParamValueControl *control2; +}; diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript index e181cb9abd..29e1638429 100644 --- a/selfdrive/ui/SConscript +++ b/selfdrive/ui/SConscript @@ -22,7 +22,10 @@ widgets_src = ["ui.cc", "qt/widgets/input.cc", "qt/widgets/wifi.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"] + "qt/request_repeater.cc", "qt/qt_window.cc", "qt/network/networking.cc", "qt/network/wifi_manager.cc", + "../frogpilot/ui/qt/widgets/frogpilot_controls.cc", + "../frogpilot/ui/qt/offroad/control_settings.cc", "../frogpilot/ui/qt/offroad/vehicle_settings.cc", + "../frogpilot/ui/qt/offroad/visual_settings.cc"] qt_env['CPPDEFINES'] = [] if maps: diff --git a/selfdrive/ui/qt/offroad/settings.cc b/selfdrive/ui/qt/offroad/settings.cc index 5aa33974ac..063ae4817f 100644 --- a/selfdrive/ui/qt/offroad/settings.cc +++ b/selfdrive/ui/qt/offroad/settings.cc @@ -5,6 +5,7 @@ #include #include +#include #include "common/watchdog.h" #include "common/util.h" @@ -15,6 +16,10 @@ #include "selfdrive/ui/qt/widgets/scrollview.h" #include "selfdrive/ui/qt/widgets/ssh_keys.h" +#include "selfdrive/frogpilot/ui/qt/offroad/control_settings.h" +#include "selfdrive/frogpilot/ui/qt/offroad/vehicle_settings.h" +#include "selfdrive/frogpilot/ui/qt/offroad/visual_settings.h" + TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { // param, title, desc, icon std::vector> toggle_defs{ @@ -114,6 +119,11 @@ TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { connect(toggles["ExperimentalLongitudinalEnabled"], &ToggleControl::toggleFlipped, [=]() { updateToggles(); }); + + // FrogPilot signals + connect(toggles["IsMetric"], &ToggleControl::toggleFlipped, [=]() { + updateMetric(); + }); } void TogglesPanel::updateState(const UIState &s) { @@ -348,6 +358,16 @@ void DevicePanel::showEvent(QShowEvent *event) { ListWidget::showEvent(event); } +void SettingsWindow::hideEvent(QHideEvent *event) { + closeParentToggle(); + + parentToggleOpen = false; + subParentToggleOpen = false; + subSubParentToggleOpen = false; + + previousScrollPosition = 0; +} + void SettingsWindow::showEvent(QShowEvent *event) { setCurrentPanel(0); } @@ -384,7 +404,20 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { close_btn->setFixedSize(200, 200); sidebar_layout->addSpacing(45); sidebar_layout->addWidget(close_btn, 0, Qt::AlignCenter); - QObject::connect(close_btn, &QPushButton::clicked, this, &SettingsWindow::closeSettings); + QObject::connect(close_btn, &QPushButton::clicked, [this]() { + if (subSubParentToggleOpen) { + closeSubSubParentToggle(); + subSubParentToggleOpen = false; + } else if (subParentToggleOpen) { + closeSubParentToggle(); + subParentToggleOpen = false; + } else if (parentToggleOpen) { + closeParentToggle(); + parentToggleOpen = false; + } else { + closeSettings(); + } + }); // setup panels DevicePanel *device = new DevicePanel(this); @@ -393,12 +426,24 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { TogglesPanel *toggles = new TogglesPanel(this); QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); + QObject::connect(toggles, &TogglesPanel::updateMetric, this, &SettingsWindow::updateMetric); + + FrogPilotControlsPanel *frogpilotControls = new FrogPilotControlsPanel(this); + QObject::connect(frogpilotControls, &FrogPilotControlsPanel::openParentToggle, this, [this]() {parentToggleOpen=true;}); + QObject::connect(frogpilotControls, &FrogPilotControlsPanel::openSubParentToggle, this, [this]() {subParentToggleOpen=true;}); + QObject::connect(frogpilotControls, &FrogPilotControlsPanel::openSubSubParentToggle, this, [this]() {subSubParentToggleOpen=true;}); + + FrogPilotVisualsPanel *frogpilotVisuals = new FrogPilotVisualsPanel(this); + QObject::connect(frogpilotVisuals, &FrogPilotVisualsPanel::openParentToggle, this, [this]() {parentToggleOpen=true;}); QList> panels = { {tr("Device"), device}, {tr("Network"), new Networking(this)}, {tr("Toggles"), toggles}, {tr("Software"), new SoftwarePanel(this)}, + {tr("Controls"), frogpilotControls}, + {tr("Vehicles"), new FrogPilotVehiclesPanel(this)}, + {tr("Visuals"), frogpilotVisuals}, }; nav_btns = new QButtonGroup(this); @@ -431,7 +476,25 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { ScrollView *panel_frame = new ScrollView(panel, this); panel_widget->addWidget(panel_frame); + if (name == tr("Controls") || name == tr("Visuals")) { + QScrollBar *scrollbar = panel_frame->verticalScrollBar(); + + QObject::connect(scrollbar, &QScrollBar::valueChanged, this, [this](int value) { + if (!parentToggleOpen) { + previousScrollPosition = value; + } + }); + + QObject::connect(scrollbar, &QScrollBar::rangeChanged, this, [this, panel_frame]() { + if (!parentToggleOpen) { + panel_frame->restorePosition(previousScrollPosition); + } + }); + } + QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { + closeParentToggle(); + previousScrollPosition = 0; btn->setChecked(true); panel_widget->setCurrentWidget(w); }); diff --git a/selfdrive/ui/qt/offroad/settings.h b/selfdrive/ui/qt/offroad/settings.h index 8b1ae8ceee..9b680723f3 100644 --- a/selfdrive/ui/qt/offroad/settings.h +++ b/selfdrive/ui/qt/offroad/settings.h @@ -25,17 +25,33 @@ public: protected: void showEvent(QShowEvent *event) override; + // FrogPilot widgets + void hideEvent(QHideEvent *event) override; + signals: void closeSettings(); void reviewTrainingGuide(); void showDriverView(); void expandToggleDescription(const QString ¶m); + // FrogPilot signals + void closeParentToggle(); + void closeSubParentToggle(); + void closeSubSubParentToggle(); + void updateMetric(); + private: QPushButton *sidebar_alert_widget; QWidget *sidebar_widget; QButtonGroup *nav_btns; QStackedWidget *panel_widget; + + // FrogPilot variables + bool parentToggleOpen; + bool subParentToggleOpen; + bool subSubParentToggleOpen; + + int previousScrollPosition; }; class DevicePanel : public ListWidget { @@ -64,6 +80,10 @@ public: explicit TogglesPanel(SettingsWindow *parent); void showEvent(QShowEvent *event) override; +signals: + // FrogPilot signals + void updateMetric(); + public slots: void expandToggleDescription(const QString ¶m); diff --git a/selfdrive/ui/qt/widgets/controls.h b/selfdrive/ui/qt/widgets/controls.h index aa304e0df6..4a2c7f3fdc 100644 --- a/selfdrive/ui/qt/widgets/controls.h +++ b/selfdrive/ui/qt/widgets/controls.h @@ -132,6 +132,10 @@ public: toggle.update(); } + void refresh() { + toggle.togglePosition(); + } + signals: void toggleFlipped(bool state); diff --git a/selfdrive/ui/qt/widgets/scrollview.cc b/selfdrive/ui/qt/widgets/scrollview.cc index 978bf83a63..28460078af 100644 --- a/selfdrive/ui/qt/widgets/scrollview.cc +++ b/selfdrive/ui/qt/widgets/scrollview.cc @@ -44,6 +44,10 @@ ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { scroller->setScrollerProperties(sp); } +void ScrollView::restorePosition(int previousScrollPosition) { + verticalScrollBar()->setValue(previousScrollPosition); +} + void ScrollView::hideEvent(QHideEvent *e) { verticalScrollBar()->setValue(0); } diff --git a/selfdrive/ui/qt/widgets/scrollview.h b/selfdrive/ui/qt/widgets/scrollview.h index 024331aa39..51acc4c432 100644 --- a/selfdrive/ui/qt/widgets/scrollview.h +++ b/selfdrive/ui/qt/widgets/scrollview.h @@ -7,6 +7,10 @@ class ScrollView : public QScrollArea { public: explicit ScrollView(QWidget *w = nullptr, QWidget *parent = nullptr); + + // FrogPilot functions + void restorePosition(int previousScrollPosition); + protected: void hideEvent(QHideEvent *e) override; }; diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc index f37ee0b0f2..4ea9740eb6 100644 --- a/selfdrive/ui/ui.cc +++ b/selfdrive/ui/ui.cc @@ -216,6 +216,7 @@ static void update_state(UIState *s) { } if (sm.updated("deviceState")) { auto deviceState = sm["deviceState"].getDeviceState(); + scene.online = deviceState.getNetworkType() != cereal::DeviceState::NetworkType::NONE; } if (sm.updated("frogpilotCarControl")) { auto frogpilotCarControl = sm["frogpilotCarControl"].getFrogpilotCarControl(); diff --git a/selfdrive/ui/ui.h b/selfdrive/ui/ui.h index 38c1ff02ee..47b5c8d1cf 100644 --- a/selfdrive/ui/ui.h +++ b/selfdrive/ui/ui.h @@ -117,6 +117,7 @@ typedef struct UIScene { bool enabled; bool experimental_mode; bool map_open; + bool online; bool right_hand_drive; int alert_size;