diff --git a/core/main.gd b/core/main.gd index 5afd83997..f7742b560 100644 --- a/core/main.gd +++ b/core/main.gd @@ -1,10 +1,14 @@ extends Node var args := OS.get_cmdline_args() +var feature_flags := load("res://core/systems/features/feature_flags.tres") as FeatureFlags # Called when the node enters the scene tree for the first time. func _ready() -> void: + # Resolve feature flags from launch arguments and the environment + feature_flags.load_from_os() + # Display a custom help if 'help' in args if "help" in args: _show_help() @@ -51,4 +55,13 @@ func _show_help() -> void: print("Environment Variables:") print(" LOG_LEVEL Set the global log level (debug,info,warn,error)") print(" LOG_LEVEL_ Set the log level for one logger (debug,info,warn,error)") + print(" OGUI_FEATURES Comma-separated list of features to enable") + print(" OGUI_DISABLED_FEATURES Comma-separated list of features to disable") + print("") + print("Features (--feature- / --feature-no-):") + for feature in feature_flags.get_features(): + var description := feature.description + if description == "": + description = "Feature flag" + print(" ", feature.id, " ", description) print("") diff --git a/core/systems/features/feature.gd b/core/systems/features/feature.gd new file mode 100644 index 000000000..034b46cf2 --- /dev/null +++ b/core/systems/features/feature.gd @@ -0,0 +1,30 @@ +extends Resource +class_name Feature + +## Definition of a single feature flag +## +## A Feature describes one toggleable behavior: its id, description, and default +## state. Feature objects hold no logic and are registered with [FeatureFlags]. + +## The normalized identifier of this feature (lowercase, hyphen-separated). +@export var id: String = "" + +## Human-readable description, used by help output and settings UI. +@export var description: String = "" + +## The state this feature has when no source overrides it. +@export var default: bool = false + + +## Creates a new feature with a normalized id. +static func create(feature_id: String, feature_default: bool = false, feature_description: String = "") -> Feature: + var feature := Feature.new() + feature.id = normalize(feature_id) + feature.description = feature_description + feature.default = feature_default + return feature + + +## Normalizes a feature id: lowercase, with underscores and spaces replaced by hyphens. +static func normalize(feature_id: String) -> String: + return feature_id.to_lower().replace("_", "-").replace(" ", "-") diff --git a/core/systems/features/feature.gd.uid b/core/systems/features/feature.gd.uid new file mode 100644 index 000000000..9d7ff4ba0 --- /dev/null +++ b/core/systems/features/feature.gd.uid @@ -0,0 +1 @@ +uid://bpubgh1iqco41 diff --git a/core/systems/features/feature_flags.gd b/core/systems/features/feature_flags.gd new file mode 100644 index 000000000..2877f1a40 --- /dev/null +++ b/core/systems/features/feature_flags.gd @@ -0,0 +1,268 @@ +extends Resource +class_name FeatureFlags + +## Registry of feature flags +## +## FeatureFlags parses command-line arguments and environment variables to turn +## features on or off, and allows features to be toggled at runtime by plugins and +## platform classes. Signals are emitted when a feature changes so the UI can react. + +signal feature_registered(feature: Feature) +signal feature_changed(feature: Feature, enabled: bool) +signal feature_enabled(feature: Feature) +signal feature_disabled(feature: Feature) + +## Where the current value of a feature came from. +enum Source { DEFAULT, ENV, ARG, RUNTIME } + +## Environment variable prefix for a single feature, e.g. OGUI_FEATURE_UPDATER=0. +const ENV_PREFIX := "OGUI_FEATURE_" + +## Environment variable containing a list of features to enable. +const ENV_LIST := "OGUI_FEATURES" + +## Environment variable containing a list of features to disable. +const ENV_DISABLED_LIST := "OGUI_DISABLED_FEATURES" + +## Command-line argument prefix for a single feature, e.g. --feature-no-updater. +const ARG_PREFIX := "--feature-" + +const TRUTHY := ["1", "true", "yes", "on", "enable", "enabled"] +const FALSY := ["0", "false", "no", "off", "disable", "disabled"] + +## The registered features. +@export var features: Array[Feature] = [] + +var _env: Dictionary = {} +var _env_overrides: Dictionary[String, bool] = {} +var _arg_overrides: Dictionary[String, bool] = {} +var _runtime_overrides: Dictionary[String, bool] = {} +var logger: CustomLogger = Log.get_logger("FeatureFlags") + + +func _init() -> void: + load_from_os() + + +## Registers a feature. Returns OK if the feature was newly registered. +func register_feature(feature: Feature) -> Error: + if not feature or feature.id == "": + logger.warn("Cannot register a feature without an id") + return Error.ERR_INVALID_PARAMETER + feature.id = Feature.normalize(feature.id) + if get_feature(feature.id): + return Error.ERR_ALREADY_EXISTS + features.append(feature) + feature_registered.emit(feature) + var value := _resolve(feature.id) + if value != feature.default: + _emit_change(feature, value) + return Error.OK + + +## Returns the registered feature with the given id, or null if it is not registered. +func get_feature(id: String) -> Feature: + var normalized := Feature.normalize(id) + for feature in features: + if feature and Feature.normalize(feature.id) == normalized: + return feature + return null + + +## Returns all registered features. +func get_features() -> Array[Feature]: + return features + + +## Returns whether the given feature is enabled. Unknown features return false. +func is_enabled(id: String) -> bool: + var normalized := Feature.normalize(id) + var feature := get_feature(normalized) + if not feature: + logger.warn("Unknown feature: " + normalized) + return false + return _resolve(normalized) + + +## Sets a feature at runtime. The runtime value takes precedence over all sources. +func set_feature(id: String, enabled: bool) -> void: + var normalized := Feature.normalize(id) + if not get_feature(normalized): + logger.warn("Cannot set unknown feature: " + normalized) + return + _apply(normalized, enabled, Source.RUNTIME) + + +## Turns the given feature on at runtime. Shortcut for set_feature(id, true). +func enable(id: String) -> void: + set_feature(id, true) + + +## Turns the given feature off at runtime. Shortcut for set_feature(id, false). +func disable(id: String) -> void: + set_feature(id, false) + + +## Flips the given feature to the opposite of its current state at runtime. +func toggle(id: String) -> void: + set_feature(id, not is_enabled(id)) + + +## Clears the runtime override so the feature resolves from its sources again. +func reset(id: String) -> void: + var normalized := Feature.normalize(id) + if not _runtime_overrides.has(normalized): + return + var before := _resolve(normalized) + _runtime_overrides.erase(normalized) + var feature := get_feature(normalized) + if not feature or before == _resolve(normalized): + return + _emit_change(feature, _resolve(normalized)) + + +## Returns which source produced the current value of the given feature. +func get_source(id: String) -> int: + var normalized := Feature.normalize(id) + if _runtime_overrides.has(normalized): + return Source.RUNTIME + if _arg_overrides.has(normalized): + return Source.ARG + if _has_env_value(normalized): + return Source.ENV + return Source.DEFAULT + + +## Clears all parsed values so the sources can be applied again. +func clear_sources() -> void: + _env = {} + _env_overrides.clear() + _arg_overrides.clear() + _runtime_overrides.clear() + + +## Applies the given command-line arguments. Testable entrypoint. +func parse_args(args: Array[String]) -> void: + for arg in args: + if not arg.begins_with(ARG_PREFIX): + continue + var id := arg.trim_prefix(ARG_PREFIX) + var enabled := true + if id.begins_with("no-"): + enabled = false + id = id.trim_prefix("no-") + if id == "": + continue + _apply(Feature.normalize(id), enabled, Source.ARG) + + +## Applies the given environment variables. Testable entrypoint. +func parse_env(env: Dictionary) -> void: + _env = env + # Bulk lists are applied first so per-feature variables take precedence. + for id in _parse_list(str(env.get(ENV_LIST, ""))): + _apply(id, true, Source.ENV) + for id in _parse_list(str(env.get(ENV_DISABLED_LIST, ""))): + _apply(id, false, Source.ENV) + for key in env: + var name := str(key) + if not name.begins_with(ENV_PREFIX): + continue + var raw := str(env[key]) + if not _is_bool_string(raw): + logger.warn("Unable to parse value for " + name + ", using default") + continue + _apply(Feature.normalize(name.trim_prefix(ENV_PREFIX)), _to_bool(raw), Source.ENV) + + +## Parses the process command-line arguments and environment. +func load_from_os() -> void: + parse_args(OS.get_cmdline_args()) + parse_env(_collect_env()) + + +func _resolve(id: String) -> bool: + if _runtime_overrides.has(id): + return _runtime_overrides[id] + if _arg_overrides.has(id): + return _arg_overrides[id] + if _has_env_value(id): + return _env_value(id) + var feature := get_feature(id) + if not feature: + return false + return feature.default + + +func _has_env_value(id: String) -> bool: + return _env_overrides.has(id) or _is_bool_string(_read_env(ENV_PREFIX + _env_key(id))) + + +func _env_value(id: String) -> bool: + if _env_overrides.has(id): + return _env_overrides[id] + return _to_bool(_read_env(ENV_PREFIX + _env_key(id))) + + +func _apply(id: String, value: bool, source: int) -> void: + var before := _resolve(id) + if source == Source.RUNTIME: + _runtime_overrides[id] = value + elif source == Source.ARG: + _arg_overrides[id] = value + elif source == Source.ENV: + _env_overrides[id] = value + if before == value: + return + var feature := get_feature(id) + if not feature: + return + _emit_change(feature, value) + + +func _emit_change(feature: Feature, value: bool) -> void: + feature_changed.emit(feature, value) + if value: + feature_enabled.emit(feature) + else: + feature_disabled.emit(feature) + + +func _read_env(name: String) -> String: + if _env.has(name): + return str(_env[name]) + return OS.get_environment(name) + + +func _collect_env() -> Dictionary: + var env := {} + env[ENV_LIST] = OS.get_environment(ENV_LIST) + env[ENV_DISABLED_LIST] = OS.get_environment(ENV_DISABLED_LIST) + for feature in features: + if not feature: + continue + var name := ENV_PREFIX + _env_key(feature.id) + env[name] = OS.get_environment(name) + return env + + +func _env_key(id: String) -> String: + return id.replace("-", "_").to_upper() + + +func _is_bool_string(raw: String) -> bool: + var value := raw.to_lower() + return value in TRUTHY or value in FALSY + + +func _to_bool(raw: String) -> bool: + return raw.to_lower() in TRUTHY + + +func _parse_list(raw: String) -> Array[String]: + var ids: Array[String] = [] + for part in raw.replace(",", " ").split(" "): + if part == "": + continue + ids.append(Feature.normalize(part)) + return ids diff --git a/core/systems/features/feature_flags.gd.uid b/core/systems/features/feature_flags.gd.uid new file mode 100644 index 000000000..fbeec5ced --- /dev/null +++ b/core/systems/features/feature_flags.gd.uid @@ -0,0 +1 @@ +uid://b6lv3knr8wjqx diff --git a/core/systems/features/feature_flags.tres b/core/systems/features/feature_flags.tres new file mode 100644 index 000000000..1ef6b9cc9 --- /dev/null +++ b/core/systems/features/feature_flags.tres @@ -0,0 +1,20 @@ +[gd_resource type="Resource" script_class="FeatureFlags" format=3 uid="uid://cfb4ht3s2u5ox"] + +[ext_resource type="Script" uid="uid://bpubgh1iqco41" path="res://core/systems/features/feature.gd" id="1_feature"] +[ext_resource type="Script" uid="uid://b6lv3knr8wjqx" path="res://core/systems/features/feature_flags.gd" id="2_feature_flags"] + +[sub_resource type="Resource" id="Feature_updater"] +script = ExtResource("1_feature") +id = "updater" +description = "Allow checking for and installing app updates" +default = true + +[sub_resource type="Resource" id="Feature_tdp"] +script = ExtResource("1_feature") +id = "tdp" +description = "Allow managing TDP settings" +default = true + +[resource] +script = ExtResource("2_feature_flags") +features = Array[ExtResource("1_feature")]([SubResource("Feature_updater"), SubResource("Feature_tdp")]) diff --git a/core/systems/features/feature_flags_test.gd b/core/systems/features/feature_flags_test.gd new file mode 100644 index 000000000..511709fcc --- /dev/null +++ b/core/systems/features/feature_flags_test.gd @@ -0,0 +1,75 @@ +extends GutTest + +var feature_flags: FeatureFlags + + +func before_each() -> void: + feature_flags = FeatureFlags.new() + feature_flags.clear_sources() + feature_flags.register_feature(Feature.create("updater", true, "Allow checking for updates")) + watch_signals(feature_flags) + + +func test_default_value_and_unknown_feature() -> void: + assert_true(feature_flags.is_enabled("updater")) + assert_eq(feature_flags.get_source("updater"), FeatureFlags.Source.DEFAULT) + var offline := Feature.create("offline", false) + feature_flags.register_feature(offline) + assert_false(feature_flags.is_enabled("offline")) + assert_false(feature_flags.is_enabled("nope")) + assert_null(feature_flags.get_feature("nope")) + + +func test_normalizes_feature_ids() -> void: + var feature := Feature.create("Steam_Deck Mode") + assert_eq(feature.id, "steam-deck-mode") + feature_flags.register_feature(feature) + feature_flags.parse_args(["--feature-STEAM-DECK-MODE"]) + assert_true(feature_flags.is_enabled("Steam_Deck_Mode")) + + +func test_args_enable_and_disable() -> void: + feature_flags.parse_args(["--feature-offline", "--feature-no-updater"]) + feature_flags.register_feature(Feature.create("offline", false)) + assert_true(feature_flags.is_enabled("offline")) + assert_false(feature_flags.is_enabled("updater")) + assert_eq(feature_flags.get_source("updater"), FeatureFlags.Source.ARG) + + +func test_env_bulk_lists() -> void: + feature_flags.parse_env({ + "OGUI_FEATURES": "offline, steam-deck-mode", + "OGUI_DISABLED_FEATURES": "updater", + }) + feature_flags.register_feature(Feature.create("offline", false)) + feature_flags.register_feature(Feature.create("steam_deck_mode", false)) + assert_true(feature_flags.is_enabled("offline")) + assert_true(feature_flags.is_enabled("steam-deck-mode")) + assert_false(feature_flags.is_enabled("updater")) + + +func test_precedence() -> void: + feature_flags.parse_env({"OGUI_FEATURE_UPDATER": "0"}) + assert_false(feature_flags.is_enabled("updater")) + assert_eq(feature_flags.get_source("updater"), FeatureFlags.Source.ENV) + feature_flags.parse_args(["--feature-updater"]) + assert_true(feature_flags.is_enabled("updater")) + feature_flags.set_feature("updater", false) + assert_false(feature_flags.is_enabled("updater")) + assert_eq(feature_flags.get_source("updater"), FeatureFlags.Source.RUNTIME) + + +func test_reset_clears_runtime_override() -> void: + feature_flags.parse_env({"OGUI_FEATURE_UPDATER": "0"}) + feature_flags.set_feature("updater", true) + assert_true(feature_flags.is_enabled("updater")) + feature_flags.reset("updater") + assert_false(feature_flags.is_enabled("updater")) + assert_eq(feature_flags.get_source("updater"), FeatureFlags.Source.ENV) + + +func test_signal_on_registration_when_overridden() -> void: + feature_flags.parse_env({"OGUI_FEATURE_OFFLINE": "1"}) + var offline := Feature.create("offline", false) + feature_flags.register_feature(offline) + assert_signal_emitted_with_parameters(feature_flags, "feature_changed", [offline, true]) diff --git a/core/systems/features/feature_flags_test.gd.uid b/core/systems/features/feature_flags_test.gd.uid new file mode 100644 index 000000000..e67a3641c --- /dev/null +++ b/core/systems/features/feature_flags_test.gd.uid @@ -0,0 +1 @@ +uid://kfsmnp1yoon0 diff --git a/core/ui/card_ui/settings/general_settings_menu.gd b/core/ui/card_ui/settings/general_settings_menu.gd index 7c697ef01..dc4b2cebf 100644 --- a/core/ui/card_ui/settings/general_settings_menu.gd +++ b/core/ui/card_ui/settings/general_settings_menu.gd @@ -9,12 +9,14 @@ var NotificationManager := load("res://core/global/notification_manager.tres") a var Version := load("res://core/global/version.tres") as Version var platform := load("res://core/global/platform.tres") as Platform var hardware_manager := load("res://core/systems/hardware/hardware_manager.tres") as HardwareManager +var feature_flags := load("res://core/systems/features/feature_flags.tres") as FeatureFlags var update_available := false var update_installed := false var logger := Log.get_logger("GeneralSettings") @onready var updater := $SoftwareUpdater as SoftwareUpdater @onready var update_timer := $UpdateTimer as Timer +@onready var update_section := $%UpdateSection as VBoxContainer @onready var auto_update_toggle := $%AutoUpdateToggle @onready var check_update_button := $%CheckUpdateButton @onready var update_button := $%UpdateButton @@ -109,9 +111,13 @@ func _ready() -> void: update_timer.stop() auto_update_toggle.toggled.connect(on_auto_update_toggled) update_timer.timeout.connect(_on_autoupdate) - if auto_update: + if auto_update and feature_flags.is_enabled("updater"): update_timer.start() + # Hide the update section when the updater feature is disabled + feature_flags.feature_changed.connect(_on_feature_changed) + _update_update_section(feature_flags.is_enabled("updater")) + # Configure the language dropdown var current_locale := SettingsManager.get_value("general", "locale", "en_US") as String lang_dropdown.clear() @@ -179,6 +185,21 @@ func _add_user_themes() -> void: logger.debug("Add user theme: " + theme_name) +# Shows or hides the update section for the updater feature +func _update_update_section(enabled: bool) -> void: + update_section.visible = enabled + + +# Reacts to a feature flag being toggled at runtime +func _on_feature_changed(feature: Feature, enabled: bool) -> void: + if feature.id != "updater": + return + _update_update_section(enabled) + update_timer.stop() + if enabled and SettingsManager.get_value("general.updates", "auto_update", false) as bool: + update_timer.start() + + func _on_autoupdate() -> void: logger.info("Automatically checking for updates...") check_update_button.disabled = true diff --git a/core/ui/card_ui/settings/general_settings_menu.tscn b/core/ui/card_ui/settings/general_settings_menu.tscn index 0d93f5f46..bcd96ad68 100644 --- a/core/ui/card_ui/settings/general_settings_menu.tscn +++ b/core/ui/card_ui/settings/general_settings_menu.tscn @@ -51,7 +51,7 @@ state = ExtResource("6_vwiy7") [node name="FocusGroupSetter" type="Node" parent="StateWatcher" node_paths=PackedStringArray("target")] script = ExtResource("7_sb10a") -target = NodePath("../../MarginContainer/VBoxContainer/VBoxContainer/FocusGroup") +target = NodePath("../../MarginContainer/VBoxContainer/UpdateSection/FocusGroup") on_signal = "state_entered" [node name="SoftwareUpdater" parent="." instance=ExtResource("2_ogwq4")] @@ -74,54 +74,55 @@ size_flags_horizontal = 3 size_flags_vertical = 3 theme_override_constants/separation = 10 -[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/VBoxContainer"] +[node name="UpdateSection" type="VBoxContainer" parent="MarginContainer/VBoxContainer"] +unique_name_in_owner = true layout_mode = 2 theme_override_constants/separation = 10 -[node name="FocusGroup" parent="MarginContainer/VBoxContainer/VBoxContainer" node_paths=PackedStringArray("current_focus", "focus_neighbor_bottom") instance=ExtResource("3_36sdt")] +[node name="FocusGroup" parent="MarginContainer/VBoxContainer/UpdateSection" node_paths=PackedStringArray("current_focus", "focus_neighbor_bottom") instance=ExtResource("3_36sdt")] current_focus = NodePath("../AutoUpdateToggle") wrap_focus = false focus_neighbor_bottom = NodePath("../../ThemeButtonContainer/FocusGroup") -[node name="UpdatesLabel" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("5_caxj0")] +[node name="UpdatesLabel" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("5_caxj0")] layout_mode = 2 text = "Updates" -[node name="AutoUpdateToggle" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("6_ghdw1")] +[node name="AutoUpdateToggle" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("6_ghdw1")] unique_name_in_owner = true layout_mode = 2 text = "Automatic Updates" separator_visible = false description = "Automatically download and apply updates in the background when they are available" -[node name="CheckUpdateButton" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("12_3b8j5")] +[node name="CheckUpdateButton" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("12_3b8j5")] unique_name_in_owner = true layout_mode = 2 text = "Check for updates" button_text = "Check for updates" disabled = false -[node name="UpdateButton" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("12_3b8j5")] +[node name="UpdateButton" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("12_3b8j5")] unique_name_in_owner = true layout_mode = 2 text = "Install Updates" button_text = "Update" disabled = false -[node name="HSeparator2" type="HSeparator" parent="MarginContainer/VBoxContainer/VBoxContainer"] +[node name="HSeparator2" type="HSeparator" parent="MarginContainer/VBoxContainer/UpdateSection"] layout_mode = 2 -[node name="Appearance" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("5_caxj0")] +[node name="Appearance" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("5_caxj0")] layout_mode = 2 text = "Appearance" -[node name="LanguageDropdown" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("8_r15pa")] +[node name="LanguageDropdown" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("8_r15pa")] unique_name_in_owner = true layout_mode = 2 title = "Language" description = "System language" -[node name="ThemeLabel" parent="MarginContainer/VBoxContainer/VBoxContainer" instance=ExtResource("8_2m3jw")] +[node name="ThemeLabel" parent="MarginContainer/VBoxContainer/UpdateSection" instance=ExtResource("8_2m3jw")] layout_mode = 2 text = "Theme" diff --git a/docs/class-reference/Feature.md b/docs/class-reference/Feature.md new file mode 100644 index 000000000..da735f559 --- /dev/null +++ b/docs/class-reference/Feature.md @@ -0,0 +1,70 @@ +# Feature + +**Inherits:** [Resource](https://docs.godotengine.org/en/stable/classes/class_resource.html) + +Definition of a single feature flag +## Description + +A Feature describes one toggleable behavior: its id, description, and default state. Feature objects hold no logic and are registered with [FeatureFlags](../FeatureFlags). +## Properties + +| Type | Name | Default | +| ---- | ---- | ------- | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [id](./#id) | "" | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [description](./#description) | "" | +| [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) | [default](./#default) | false | + +## Methods + +| Returns | Signature | +| ------- | --------- | +| [Feature](../Feature) | [create](./#create)(feature_id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html), feature_default: [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) = false, feature_description: [String](https://docs.godotengine.org/en/stable/classes/class_string.html) = "") | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [normalize](./#normalize)(feature_id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | + + +------------------ + +## Property Descriptions + +### `id` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) id = "" + + +The normalized identifier of this feature (lowercase, hyphen-separated). +### `description` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) description = "" + + +Human-readable description, used by help output and settings UI. +### `default` + + +[bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) default = false + + +The state this feature has when no source overrides it. + + + +------------------ + +## Method Descriptions + +### `create()` + + +[Feature](../Feature) **create**(feature_id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html), feature_default: [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) = false, feature_description: [String](https://docs.godotengine.org/en/stable/classes/class_string.html) = "") + + +Creates a new feature with a normalized id. +### `normalize()` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) **normalize**(feature_id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Normalizes a feature id: lowercase, with underscores and spaces replaced by hyphens. diff --git a/docs/class-reference/FeatureFlags.md b/docs/class-reference/FeatureFlags.md new file mode 100644 index 000000000..e286b7908 --- /dev/null +++ b/docs/class-reference/FeatureFlags.md @@ -0,0 +1,158 @@ +# FeatureFlags + +**Inherits:** [Resource](https://docs.godotengine.org/en/stable/classes/class_resource.html) + +Registry of feature flags +## Description + +FeatureFlags parses command-line arguments and environment variables to turn features on or off, and allows features to be toggled at runtime by plugins and platform classes. Signals are emitted when a feature changes so the UI can react. +## Properties + +| Type | Name | Default | +| ---- | ---- | ------- | +| [Feature[]](../Feature) | [features](./#features) | [] | +| [CustomLogger](../CustomLogger) | [logger](./#logger) | | + +## Methods + +| Returns | Signature | +| ------- | --------- | +| [int](https://docs.godotengine.org/en/stable/classes/class_int.html) | [register_feature](./#register_feature)(feature: [Feature](../Feature)) | +| [Feature](../Feature) | [get_feature](./#get_feature)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| [Feature[]](../Feature) | [get_features](./#get_features)() | +| [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) | [is_enabled](./#is_enabled)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [set_feature](./#set_feature)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html), enabled: [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html)) | +| void | [enable](./#enable)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [disable](./#disable)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [toggle](./#toggle)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [reset](./#reset)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| [int](https://docs.godotengine.org/en/stable/classes/class_int.html) | [get_source](./#get_source)(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [clear_sources](./#clear_sources)() | +| void | [parse_args](./#parse_args)(args: [String[]](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| void | [parse_env](./#parse_env)(env: [Dictionary](https://docs.godotengine.org/en/stable/classes/class_dictionary.html)) | +| void | [load_from_os](./#load_from_os)() | + + +------------------ + +## Property Descriptions + +### `features` + + +[Feature[]](../Feature) features = [] + + +The registered features. +### `logger` + + +[CustomLogger](../CustomLogger) logger + + +Reports unknown features, invalid registrations, and unparseable values. + + + +------------------ + +## Method Descriptions + +### `register_feature()` + + +[int](https://docs.godotengine.org/en/stable/classes/class_int.html) **register_feature**(feature: [Feature](../Feature)) + + +Registers a feature. Returns OK if the feature was newly registered. +### `get_feature()` + + +[Feature](../Feature) **get_feature**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Returns the registered feature with the given id, or null if it is not registered. +### `get_features()` + + +[Feature[]](../Feature) **get_features**() + + +Returns all registered features. +### `is_enabled()` + + +[bool](https://docs.godotengine.org/en/stable/classes/class_bool.html) **is_enabled**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Returns whether the given feature is enabled. Unknown features return false. +### `set_feature()` + + +void **set_feature**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html), enabled: [bool](https://docs.godotengine.org/en/stable/classes/class_bool.html)) + + +Sets a feature at runtime. The runtime value takes precedence over all sources. +### `enable()` + + +void **enable**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Turns the given feature on at runtime. Shortcut for set_feature(id, true). +### `disable()` + + +void **disable**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Turns the given feature off at runtime. Shortcut for set_feature(id, false). +### `toggle()` + + +void **toggle**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Flips the given feature to the opposite of its current state at runtime. +### `reset()` + + +void **reset**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Clears the runtime override so the feature resolves from its sources again. +### `get_source()` + + +[int](https://docs.godotengine.org/en/stable/classes/class_int.html) **get_source**(id: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Returns which source produced the current value of the given feature. +### `clear_sources()` + + +void **clear_sources**() + + +Clears all parsed values so the sources can be applied again. +### `parse_args()` + + +void **parse_args**(args: [String[]](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +Applies the given command-line arguments. Testable entrypoint. +### `parse_env()` + + +void **parse_env**(env: [Dictionary](https://docs.godotengine.org/en/stable/classes/class_dictionary.html)) + + +Applies the given environment variables. Testable entrypoint. +### `load_from_os()` + + +void **load_from_os**() + + +Parses the process command-line arguments and environment. diff --git a/docs/documentation/plugins/feature_flags.md b/docs/documentation/plugins/feature_flags.md new file mode 100644 index 000000000..b2c5cc157 --- /dev/null +++ b/docs/documentation/plugins/feature_flags.md @@ -0,0 +1,135 @@ +# Feature Flags + +Feature flags are named boolean switches that can be turned on or off from the +command line, the environment, or at runtime by plugins and platform classes. +They are useful for enabling experimental features, disabling subsystems that do +not apply to a device, or letting a plugin opt into behavior. + +Flags are managed by the +[FeatureFlags](../../class-reference/FeatureFlags.md) resource, which is shared +across the whole application. A single feature is described by a +[Feature](../../class-reference/Feature.md) resource containing its `id`, +`description`, and `default` state. + +## Resolving a flag + +The value of a feature is resolved from the first source that provides one: + +1. A runtime override set with `set_feature()` +2. A command-line argument +3. An environment variable +4. The feature's `default` + +Feature ids are normalized to lowercase with hyphens, so `Updater`, `updater`, +`UPDATER`, and `updater_mode` all refer to the same feature. + +## Command line and environment + +```bash +# Enable a feature +opengamepad-ui --feature-updater + +# Disable a feature +opengamepad-ui --feature-no-updater + +# Per-feature environment variable +OGUI_FEATURE_UPDATER=0 opengamepad-ui + +# Bulk lists, comma or space separated +OGUI_FEATURES=offline,steam-deck-mode opengamepad-ui +OGUI_DISABLED_FEATURES=updater opengamepad-ui +``` + +Values are read as booleans: `1`, `true`, `yes`, and `on` enable a feature, and +`0`, `false`, `no`, and `off` disable it. The environment key for a feature is +derived from its id, so `steam-deck-mode` becomes `OGUI_FEATURE_STEAM_DECK_MODE`. + +Bulk lists are applied before per-feature variables, so a per-feature variable +wins when both name the same feature. Values that are not boolean strings are +ignored and the feature keeps its default. + +## Using flags in a plugin + +Plugins can register their own features and read them anywhere in the codebase: + +```gdscript +extends Plugin + +var feature_flags := load("res://core/systems/features/feature_flags.tres") as FeatureFlags +var logger := Log.get_logger("MyPlugin") + + +func _ready() -> void: + # Connect signals before registering, so a change emitted during registration is not missed. + feature_flags.feature_changed.connect(_on_feature_changed) + + var feature := Feature.create("my-plugin-voice-chat", false, "Voice chat support") + var err := feature_flags.register_feature(feature) + if err == Error.ERR_ALREADY_EXISTS: + # Another plugin owns this id already; use the registered feature instead of overriding it. + feature = feature_flags.get_feature("my-plugin-voice-chat") + elif err != Error.OK: + logger.warn("Cannot register feature: " + str(err)) + return + + if feature_flags.is_enabled(feature.id): + logger.info("Voice chat is enabled") + + +func _on_feature_changed(feature: Feature, enabled: bool) -> void: + if feature.id != "my-plugin-voice-chat": + return + print("Voice chat is now ", "on" if enabled else "off") +``` + +`register_feature()` returns `Error`: `Error.OK` when the feature was newly +registered, `Error.ERR_INVALID_PARAMETER` when it has no id, and +`Error.ERR_ALREADY_EXISTS` when the id is already registered. It never replaces +an existing feature, so a duplicate registration leaves the first feature's +`default` in place. + +## Unknown feature ids + +Reading or setting an id that is not registered logs a warning and does nothing +else: + +- `is_enabled()` warns and returns `false` +- `set_feature()` warns and returns without storing an override +- `get_feature()` returns `null` + +Register the feature first, then read it. Warnings are written to the +`FeatureFlags` logger, so they can be raised or silenced with +`LOG_LEVEL_FEATUREFLAGS` (see the log level environment variables). The logger is +not created inside the editor, so warnings are skipped there. + +## Signals + +Signals are only emitted when the value actually changes. `feature_changed` +passes the `Feature` object, so handlers can read its `id`, `description`, and +`default` without a second lookup. `feature_enabled` and `feature_disabled` are +convenience signals for the two directions. `feature_registered` is emitted once +per successful registration. + +## Sources and clearing + +Use `feature_flags.get_source("my-plugin-voice-chat")` to find out which source +produced the current value. It returns one of `FeatureFlags.Source` +(`DEFAULT`, `ENV`, `ARG`, or `RUNTIME`). + +Use `feature_flags.reset(id)` to drop a single runtime override so the feature +resolves from its sources again, or `feature_flags.clear_sources()` to drop every +parsed value at once. + +`parse_args()` and `parse_env()` take explicit arguments instead of reading the +process, which makes them the entrypoints to use in tests; `load_from_os()` is the +convenience wrapper that reads the real command line and environment. + +## Shared features + +Features defined in `core/systems/features/feature_flags.tres` are available to +everything: + +| id | default | behavior | +| --- | --- | --- | +| `updater` | `true` | Allows checking for and installing app updates. The settings menu hides its update section when it is off. | +| `tdp` | `true` | Allows managing TDP settings. |