Files
coffee-crisis-ae/source/ui/action_list_option.cpp
T

95 lines
2.4 KiB
C++

#include "action_list_option.h"
#include <algorithm>
#include "text.h"
ActionListOption::ActionListOption(
const std::string& caption,
ServiceMenu::SettingsGroup group,
std::vector<std::string> options,
ValueGetter getter,
ValueSetter setter,
ActionExecutor action_executor,
bool hidden) : MenuOption(caption, group, hidden),
options_(std::move(options)),
value_getter_(std::move(getter)),
value_setter_(std::move(setter)),
action_executor_(std::move(action_executor)),
current_index_(0) {
updateCurrentIndex();
}
auto ActionListOption::getBehavior() const -> Behavior {
// Puede tanto ajustar valor (lista) como ejecutar acción (botón)
return Behavior::BOTH;
}
auto ActionListOption::getValueAsString() const -> std::string {
if (value_getter_) {
return value_getter_();
}
if (current_index_ < options_.size()) {
return options_[current_index_];
}
return options_.empty() ? "" : options_[0];
}
auto ActionListOption::getMaxValueWidth(Text* text) const -> int {
int max_width = 0;
for (const auto& option : options_) {
int width = text->lenght(option, -2);
if (width > max_width) {
max_width = width;
}
}
return max_width;
}
void ActionListOption::adjustValue(bool up) {
if (options_.empty()) {
return;
}
if (up) {
current_index_ = (current_index_ + 1) % options_.size();
} else {
current_index_ = (current_index_ == 0) ? options_.size() - 1 : current_index_ - 1;
}
// Aplicar el cambio usando el setter
if (value_setter_ && current_index_ < options_.size()) {
value_setter_(options_[current_index_]);
}
}
void ActionListOption::executeAction() {
if (action_executor_) {
action_executor_();
}
}
void ActionListOption::sync() {
updateCurrentIndex();
}
void ActionListOption::updateCurrentIndex() {
current_index_ = findCurrentIndex();
}
auto ActionListOption::findCurrentIndex() const -> size_t {
if (!value_getter_ || options_.empty()) {
return 0;
}
const std::string current_value = value_getter_();
auto it = std::find(options_.begin(), options_.end(), current_value);
if (it != options_.end()) {
return static_cast<size_t>(std::distance(options_.begin(), it));
}
return 0; // Valor por defecto si no se encuentra
}