renombrades extensions .h a .hpp

This commit is contained in:
2025-10-17 21:45:19 +02:00
parent 50ccb2ccc2
commit 46974ef2eb
144 changed files with 1758 additions and 1783 deletions

View File

@@ -1,70 +0,0 @@
#pragma once
#include <iostream>
#include <string>
namespace Logger {
// Colores ANSI
inline constexpr const char* RESET = "\033[0m";
inline constexpr const char* RED = "\033[31m";
inline constexpr const char* GREEN = "\033[32m";
inline constexpr const char* YELLOW = "\033[33m";
inline constexpr const char* BLUE = "\033[34m";
inline constexpr const char* MAGENTA = "\033[35m";
inline constexpr const char* CYAN = "\033[36m";
inline constexpr const char* WHITE = "\033[37m";
// Ancho total global para alineación
inline constexpr size_t TOTAL_WIDTH = 52;
// Sección
inline void section(const std::string& title, const std::string& color = CYAN) {
std::cout << "\n" << color
<< "========================================\n"
<< " " << title << "\n"
<< "========================================"
<< RESET << "\n";
}
// Info
inline void info(const std::string& msg, const std::string& color = WHITE) {
std::cout << " " << color << msg << RESET << "\n";
}
// Dots genérico
inline void dots(const std::string& prefix,
const std::string& middle,
const std::string& suffix,
const std::string& suffixColor = GREEN)
{
size_t field_width = TOTAL_WIDTH > (prefix.size() + suffix.size())
? TOTAL_WIDTH - prefix.size() - suffix.size()
: 0;
std::string field_text;
if (middle.size() < field_width) {
field_text = middle + std::string(field_width - middle.size(), '.');
} else {
field_text = middle.substr(0, field_width);
}
std::cout << prefix << field_text
<< suffixColor << suffix << RESET
<< "\n";
}
// Status con true/false, usando dots y sufijos fijos
inline void status(const std::string& name, bool ok) {
// Ambos sufijos tienen 9 caracteres → alineación perfecta
constexpr const char* OK_LABEL = "[ OK ]";
constexpr const char* ERROR_LABEL = "[ ERROR ]";
if (ok) {
dots(" ", name, OK_LABEL, GREEN);
} else {
dots(" ", name, ERROR_LABEL, RED);
}
}
} // namespace Logger

70
source/ui/logger.hpp Normal file
View File

@@ -0,0 +1,70 @@
#pragma once
#include <iostream>
#include <string>
namespace Logger {
// Colores ANSI
inline constexpr const char* RESET = "\033[0m";
inline constexpr const char* RED = "\033[31m";
inline constexpr const char* GREEN = "\033[32m";
inline constexpr const char* YELLOW = "\033[33m";
inline constexpr const char* BLUE = "\033[34m";
inline constexpr const char* MAGENTA = "\033[35m";
inline constexpr const char* CYAN = "\033[36m";
inline constexpr const char* WHITE = "\033[37m";
// Ancho total global para alineación
inline constexpr size_t TOTAL_WIDTH = 52;
// Sección
inline void section(const std::string& title, const std::string& color = CYAN) {
std::cout << "\n"
<< color
<< "========================================\n"
<< " " << title << "\n"
<< "========================================"
<< RESET << "\n";
}
// Info
inline void info(const std::string& msg, const std::string& color = WHITE) {
std::cout << " " << color << msg << RESET << "\n";
}
// Dots genérico
inline void dots(const std::string& prefix,
const std::string& middle,
const std::string& suffix,
const std::string& suffixColor = GREEN) {
size_t field_width = TOTAL_WIDTH > (prefix.size() + suffix.size())
? TOTAL_WIDTH - prefix.size() - suffix.size()
: 0;
std::string field_text;
if (middle.size() < field_width) {
field_text = middle + std::string(field_width - middle.size(), '.');
} else {
field_text = middle.substr(0, field_width);
}
std::cout << prefix << field_text
<< suffixColor << suffix << RESET
<< "\n";
}
// Status con true/false, usando dots y sufijos fijos
inline void status(const std::string& name, bool ok) {
// Ambos sufijos tienen 9 caracteres → alineación perfecta
constexpr const char* OK_LABEL = "[ OK ]";
constexpr const char* ERROR_LABEL = "[ ERROR ]";
if (ok) {
dots(" ", name, OK_LABEL, GREEN);
} else {
dots(" ", name, ERROR_LABEL, RED);
}
}
} // namespace Logger

View File

@@ -1,10 +1,10 @@
#include "menu_option.h"
#include "menu_option.hpp"
#include <algorithm> // Para find
#include <iterator> // Para distance
#include <memory> // Para allocator
#include "text.h" // Para Text
#include "text.hpp" // Para Text
auto ActionListOption::getValueAsString() const -> std::string {
if (value_getter_) {

View File

@@ -7,9 +7,9 @@
#include <utility> // Para move
#include <vector> // Para vector
#include "lang.h" // Para getText
#include "text.h" // Para Text
#include "ui/service_menu.h" // Para ServiceMenu
#include "lang.hpp" // Para getText
#include "text.hpp" // Para Text
#include "ui/service_menu.hpp" // Para ServiceMenu
// --- Clase MenuOption: interfaz base para todas las opciones del menú ---
class MenuOption {
@@ -29,7 +29,7 @@ class MenuOption {
virtual ~MenuOption() = default;
// --- Getters ---
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
[[nodiscard]] auto getCaption() const -> const std::string& { return caption_; }
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
void setHidden(bool hidden) { hidden_ = hidden; }
@@ -40,7 +40,7 @@ class MenuOption {
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
virtual void executeAction() {}
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; } // Método virtual para que cada opción calcule el ancho de su valor más largo
virtual auto getMaxValueWidth(Text* text_renderer) const -> int { return 0; } // Método virtual para que cada opción calcule el ancho de su valor más largo
protected:
// --- Variables ---
@@ -53,7 +53,7 @@ class MenuOption {
class BoolOption : public MenuOption {
public:
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
BoolOption(const std::string& cap, ServiceMenu::SettingsGroup grp, bool* var)
: MenuOption(cap, grp),
linked_variable_(var) {}
@@ -64,19 +64,19 @@ class BoolOption : public MenuOption {
void adjustValue(bool /*adjust_up*/) override {
*linked_variable_ = !*linked_variable_;
}
auto getMaxValueWidth(Text *text_renderer) const -> int override {
auto getMaxValueWidth(Text* text_renderer) const -> int override {
return std::max(
text_renderer->length(Lang::getText("[SERVICE_MENU] ON"), -2),
text_renderer->length(Lang::getText("[SERVICE_MENU] OFF"), -2));
}
private:
bool *linked_variable_;
bool* linked_variable_;
};
class IntOption : public MenuOption {
public:
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
IntOption(const std::string& cap, ServiceMenu::SettingsGroup grp, int* var, int min, int max, int step)
: MenuOption(cap, grp),
linked_variable_(var),
min_value_(min),
@@ -89,7 +89,7 @@ class IntOption : public MenuOption {
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
}
auto getMaxValueWidth(Text *text_renderer) const -> int override {
auto getMaxValueWidth(Text* text_renderer) const -> int override {
int max_width = 0;
// Iterar por todos los valores posibles en el rango
@@ -102,13 +102,13 @@ class IntOption : public MenuOption {
}
private:
int *linked_variable_;
int* linked_variable_;
int min_value_, max_value_, step_value_;
};
class ListOption : public MenuOption {
public:
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
ListOption(const std::string& cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string&)> new_value_setter)
: MenuOption(cap, grp),
value_list_(std::move(values)),
getter_(std::move(current_value_getter)),
@@ -139,9 +139,9 @@ class ListOption : public MenuOption {
: (list_index_ + size - 1) % size;
setter_(value_list_[list_index_]);
}
auto getMaxValueWidth(Text *text_renderer) const -> int override {
auto getMaxValueWidth(Text* text_renderer) const -> int override {
int max_w = 0;
for (const auto &val : value_list_) {
for (const auto& val : value_list_) {
max_w = std::max(max_w, text_renderer->length(val, -2));
}
return max_w;
@@ -150,13 +150,13 @@ class ListOption : public MenuOption {
private:
std::vector<std::string> value_list_;
std::function<std::string()> getter_;
std::function<void(const std::string &)> setter_;
std::function<void(const std::string&)> setter_;
size_t list_index_{0};
};
class FolderOption : public MenuOption {
public:
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
FolderOption(const std::string& cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
: MenuOption(cap, grp),
target_group_(target) {}
@@ -169,7 +169,7 @@ class FolderOption : public MenuOption {
class ActionOption : public MenuOption {
public:
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
ActionOption(const std::string& cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
: MenuOption(cap, grp, hidden),
action_(std::move(action)) {}
@@ -188,10 +188,10 @@ class ActionOption : public MenuOption {
class ActionListOption : public MenuOption {
public:
using ValueGetter = std::function<std::string()>;
using ValueSetter = std::function<void(const std::string &)>;
using ValueSetter = std::function<void(const std::string&)>;
using ActionExecutor = std::function<void()>;
ActionListOption(const std::string &caption, ServiceMenu::SettingsGroup group, std::vector<std::string> options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false)
ActionListOption(const std::string& caption, ServiceMenu::SettingsGroup group, std::vector<std::string> options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false)
: MenuOption(caption, group, hidden),
options_(std::move(options)),
value_getter_(std::move(getter)),
@@ -202,7 +202,7 @@ class ActionListOption : public MenuOption {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::BOTH; }
[[nodiscard]] auto getValueAsString() const -> std::string override;
[[nodiscard]] auto getMaxValueWidth(Text *text) const -> int override;
[[nodiscard]] auto getMaxValueWidth(Text* text) const -> int override;
void adjustValue(bool up) override;
void executeAction() override;
void sync(); // Sincroniza con el valor actual

View File

@@ -1,14 +1,14 @@
#include "menu_renderer.h"
#include "menu_renderer.hpp"
#include <algorithm>
#include <utility>
#include "color.h"
#include "menu_option.h"
#include "param.h"
#include "screen.h"
#include "text.h"
#include "utils.h"
#include "color.hpp"
#include "menu_option.hpp"
#include "param.hpp"
#include "screen.hpp"
#include "text.hpp"
#include "utils.hpp"
// --- Implementación de las estructuras de animación ---
@@ -43,14 +43,14 @@ void MenuRenderer::ShowHideAnimation::stop() {
elapsed = 0.0F;
}
MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text)
MenuRenderer::MenuRenderer(const ServiceMenu* menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text)
: element_text_(std::move(element_text)),
title_text_(std::move(title_text)) {
initializeMaxSizes();
setPosition(param.game.game_area.center_x, param.game.game_area.center_y, PositionMode::CENTERED);
}
void MenuRenderer::render(const ServiceMenu *menu_state) {
void MenuRenderer::render(const ServiceMenu* menu_state) {
if (!visible_) {
return;
}
@@ -85,11 +85,11 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
// Dibuja las opciones
y = options_y_;
const auto &option_pairs = menu_state->getOptionPairs();
const auto& option_pairs = menu_state->getOptionPairs();
for (size_t i = 0; i < option_pairs.size(); ++i) {
const bool IS_SELECTED = (i == menu_state->getSelectedIndex());
const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
const Color& current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
const int AVAILABLE_WIDTH = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - element_text_->length(option_pairs.at(i).first, -2) - ServiceMenu::MIN_GAP_OPTION_VALUE;
@@ -107,7 +107,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
}
}
void MenuRenderer::update(const ServiceMenu *menu_state, float delta_time) {
void MenuRenderer::update(const ServiceMenu* menu_state, float delta_time) {
updateAnimations(delta_time);
if (visible_) {
@@ -118,7 +118,7 @@ void MenuRenderer::update(const ServiceMenu *menu_state, float delta_time) {
// --- Nuevos métodos de control ---
void MenuRenderer::show(const ServiceMenu *menu_state) {
void MenuRenderer::show(const ServiceMenu* menu_state) {
if (visible_) {
return;
}
@@ -162,13 +162,13 @@ void MenuRenderer::setPosition(float x, float y, PositionMode mode) {
// --- Métodos de layout ---
void MenuRenderer::onLayoutChanged(const ServiceMenu *menu_state) {
void MenuRenderer::onLayoutChanged(const ServiceMenu* menu_state) {
precalculateMenuWidths(menu_state->getAllOptions(), menu_state);
setAnchors(menu_state);
resize(menu_state);
}
void MenuRenderer::setLayout(const ServiceMenu *menu_state) {
void MenuRenderer::setLayout(const ServiceMenu* menu_state) {
precalculateMenuWidths(menu_state->getAllOptions(), menu_state);
setAnchors(menu_state);
setSize(menu_state);
@@ -179,7 +179,7 @@ void MenuRenderer::initializeMaxSizes() {
max_menu_height_ = static_cast<size_t>(param.game.game_area.rect.h * 0.9F);
}
void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
void MenuRenderer::setAnchors(const ServiceMenu* menu_state) {
size_t max_entries = 0;
for (int i = 0; i < 5; ++i) {
max_entries = std::max(max_entries, menu_state->countOptionsInGroup(static_cast<ServiceMenu::SettingsGroup>(i)));
@@ -197,9 +197,9 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
height_ = upper_height_ + lower_height_;
}
auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect {
auto MenuRenderer::calculateNewRect(const ServiceMenu* menu_state) -> SDL_FRect {
width_ = std::min(static_cast<size_t>(getMenuWidthForGroup(menu_state->getCurrentGroup())), max_menu_width_);
const auto &display_options = menu_state->getDisplayOptions();
const auto& display_options = menu_state->getDisplayOptions();
lower_height_ = ((!display_options.empty() ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
height_ = std::min(upper_height_ + lower_height_, max_menu_height_);
@@ -209,7 +209,7 @@ auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect
return new_rect;
}
void MenuRenderer::resize(const ServiceMenu *menu_state) {
void MenuRenderer::resize(const ServiceMenu* menu_state) {
SDL_FRect new_rect = calculateNewRect(menu_state);
if (rect_.w != new_rect.w || rect_.h != new_rect.h) {
@@ -222,7 +222,7 @@ void MenuRenderer::resize(const ServiceMenu *menu_state) {
options_y_ = rect_.y + upper_height_ + lower_padding_;
}
void MenuRenderer::setSize(const ServiceMenu *menu_state) {
void MenuRenderer::setSize(const ServiceMenu* menu_state) {
SDL_FRect new_rect = calculateNewRect(menu_state);
rect_.w = new_rect.w;
rect_.h = new_rect.h;
@@ -310,15 +310,15 @@ void MenuRenderer::updatePosition() {
// Resto de métodos (sin cambios significativos)
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
for (int &w : group_menu_widths_) {
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state) {
for (int& w : group_menu_widths_) {
w = ServiceMenu::MIN_WIDTH;
}
for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0;
int max_value_width = 0;
for (const auto &option : all_options) {
for (const auto& option : all_options) {
if (option->getGroup() != sg) {
continue;
}
@@ -361,7 +361,7 @@ auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect {
border_rect_ = {.x = rect.x - 1, .y = rect.y + 1, .w = rect.w + 2, .h = rect.h - 2};
return rect;
}
auto MenuRenderer::getTruncatedValueWidth(const std::string &value, int available_width) const -> int {
auto MenuRenderer::getTruncatedValueWidth(const std::string& value, int available_width) const -> int {
int value_width = element_text_->length(value, -2);
if (value_width <= available_width) {
return value_width;
@@ -385,7 +385,7 @@ auto MenuRenderer::getTruncatedValueWidth(const std::string &value, int availabl
return element_text_->length(truncated, -2);
}
auto MenuRenderer::getTruncatedValue(const std::string &value, int available_width) const -> std::string {
auto MenuRenderer::getTruncatedValue(const std::string& value, int available_width) const -> std::string {
int value_width = element_text_->length(value, -2);
if (value_width <= available_width) {
return value;

View File

@@ -8,8 +8,8 @@
#include <string>
#include <vector>
#include "color.h"
#include "ui/service_menu.h"
#include "color.hpp"
#include "ui/service_menu.hpp"
class MenuOption;
class Text;
@@ -22,14 +22,14 @@ class MenuRenderer {
FIXED // La esquina superior izquierda coincide con el punto
};
MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text);
MenuRenderer(const ServiceMenu* menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text);
// --- Métodos principales de la vista ---
void render(const ServiceMenu *menu_state);
void update(const ServiceMenu *menu_state, float delta_time);
void render(const ServiceMenu* menu_state);
void update(const ServiceMenu* menu_state, float delta_time);
// --- Nuevos: Métodos de control de visibilidad y animación ---
void show(const ServiceMenu *menu_state);
void show(const ServiceMenu* menu_state);
void hide();
[[nodiscard]] auto isVisible() const -> bool { return visible_; }
[[nodiscard]] auto isFullyVisible() const -> bool { return visible_ && !show_hide_animation_.active && !resize_animation_.active; }
@@ -39,11 +39,11 @@ class MenuRenderer {
void setPosition(float x, float y, PositionMode mode);
// Método para notificar al renderer que el layout puede haber cambiado
void onLayoutChanged(const ServiceMenu *menu_state);
void setLayout(const ServiceMenu *menu_state);
void onLayoutChanged(const ServiceMenu* menu_state);
void setLayout(const ServiceMenu* menu_state);
// Getters
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
[[nodiscard]] auto getRect() const -> const SDL_FRect& { return rect_; }
private:
// --- Referencias a los renderizadores de texto ---
@@ -107,23 +107,23 @@ class MenuRenderer {
// --- Métodos privados de la vista ---
void initializeMaxSizes();
void setAnchors(const ServiceMenu *menu_state);
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void setAnchors(const ServiceMenu* menu_state);
auto calculateNewRect(const ServiceMenu* menu_state) -> SDL_FRect;
void resize(const ServiceMenu* menu_state);
void setSize(const ServiceMenu* menu_state);
void updateAnimations(float delta_time);
void updateResizeAnimation(float delta_time);
void updateShowHideAnimation(float delta_time);
void updatePosition();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>>& all_options, const ServiceMenu* menu_state);
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
[[nodiscard]] auto getAnimatedSelectedColor() const -> Color;
void updateColorCounter();
auto setRect(SDL_FRect rect) -> SDL_FRect;
[[nodiscard]] auto getTruncatedValueWidth(const std::string &value, int available_width) const -> int;
[[nodiscard]] auto getTruncatedValue(const std::string &value, int available_width) const -> std::string;
[[nodiscard]] auto getTruncatedValueWidth(const std::string& value, int available_width) const -> int;
[[nodiscard]] auto getTruncatedValue(const std::string& value, int available_width) const -> std::string;
[[nodiscard]] static auto easeOut(float t) -> float;
[[nodiscard]] auto shouldShowContent() const -> bool;
};

View File

@@ -1,4 +1,4 @@
#include "notifier.h"
#include "notifier.hpp"
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_FRect, SDL_RenderClear
@@ -7,12 +7,12 @@
#include <utility>
#include <vector> // Para vector
#include "audio.h" // Para Audio
#include "param.h" // Para Param, param, ParamNotification, ParamGame
#include "screen.h" // Para Screen
#include "sprite.h" // Para Sprite
#include "text.h" // Para Text
#include "texture.h" // Para Texture
#include "audio.hpp" // Para Audio
#include "param.hpp" // Para Param, param, ParamNotification, ParamGame
#include "screen.hpp" // Para Screen
#include "sprite.hpp" // Para Sprite
#include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture
// Singleton
Notifier* Notifier::instance = nullptr;
@@ -142,7 +142,7 @@ void Notifier::transitionToStayState(int index) {
auto& notification = notifications_[index];
notification.state = State::STAY;
notification.texture->setAlpha(255);
notification.rect.y = static_cast<float>(notification.y); // Asegurar posición exacta
notification.rect.y = static_cast<float>(notification.y); // Asegurar posición exacta
notification.timer = 0.0f;
}

View File

@@ -6,8 +6,8 @@
#include <string> // Para basic_string, string
#include <vector> // Para vector
#include "color.h" // Para stringInVector, Color
#include "utils.h"
#include "color.hpp" // Para stringInVector, Color
#include "utils.hpp"
class Sprite;
class Text;
@@ -26,24 +26,24 @@ class Notifier {
};
// --- Métodos de singleton ---
static void init(const std::string &icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
static void init(const std::string& icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
static void destroy(); // Libera el singleton
static auto get() -> Notifier *; // Obtiene la instancia
static auto get() -> Notifier*; // Obtiene la instancia
// --- Métodos principales ---
void render(); // Dibuja las notificaciones por pantalla
void render(); // Dibuja las notificaciones por pantalla
void update(float delta_time); // Actualiza el estado de las notificaciones
// --- Gestión de notificaciones ---
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla
void show(std::vector<std::string> texts, int icon = -1, const std::string& code = std::string()); // Muestra una notificación de texto por pantalla
[[nodiscard]] auto isActive() const -> bool { return !notifications_.empty(); } // Indica si hay notificaciones activas
auto getCodes() -> std::vector<std::string>; // Obtiene los códigos de las notificaciones activas
auto checkCode(const std::string &code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
auto checkCode(const std::string& code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float STAY_DURATION_S = 2.5f; // Tiempo que se ve la notificación (150 frames @ 60fps)
static constexpr float ANIMATION_SPEED_PX_PER_S = 60.0f; // Velocidad de animación (1 pixel/frame @ 60fps)
static constexpr float STAY_DURATION_S = 2.5f; // Tiempo que se ve la notificación (150 frames @ 60fps)
static constexpr float ANIMATION_SPEED_PX_PER_S = 60.0f; // Velocidad de animación (1 pixel/frame @ 60fps)
// --- Enums privados ---
enum class State {
@@ -79,7 +79,7 @@ class Notifier {
};
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Renderer* renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
std::shared_ptr<Text> text_; // Objeto para dibujar texto
@@ -87,26 +87,26 @@ class Notifier {
std::vector<Notification> notifications_; // Lista de notificaciones activas
Color bg_color_; // Color de fondo de las notificaciones
// Nota: wait_time_ eliminado, ahora se usa STAY_DURATION_S
bool stack_; // Indica si las notificaciones se apilan
bool has_icons_; // Indica si el notificador tiene textura para iconos
bool stack_; // Indica si las notificaciones se apilan
bool has_icons_; // Indica si el notificador tiene textura para iconos
// --- Métodos internos ---
void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED
void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado
[[nodiscard]] auto shouldProcessNotification(int index) const -> bool; // Determina si una notificación debe ser procesada (según su estado y posición)
void processNotification(int index, float delta_time); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual
static void playNotificationSoundIfNeeded(const Notification &notification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido)
void updateNotificationState(int index, float delta_time); // Actualiza el estado interno de una notificación (ej. de RISING a STAY)
void handleRisingState(int index, float delta_time); // Lógica de animación para el estado RISING (apareciendo)
void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY
void handleVanishingState(int index, float delta_time); // Lógica de animación para el estado VANISHING (desapareciendo)
static void moveNotificationVertically(Notification &notification, float pixels_to_move); // Mueve verticalmente una notificación con la cantidad de pixels especificada
void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final
void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED
void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado
[[nodiscard]] auto shouldProcessNotification(int index) const -> bool; // Determina si una notificación debe ser procesada (según su estado y posición)
void processNotification(int index, float delta_time); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual
static void playNotificationSoundIfNeeded(const Notification& notification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido)
void updateNotificationState(int index, float delta_time); // Actualiza el estado interno de una notificación (ej. de RISING a STAY)
void handleRisingState(int index, float delta_time); // Lógica de animación para el estado RISING (apareciendo)
void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY
void handleVanishingState(int index, float delta_time); // Lógica de animación para el estado VANISHING (desapareciendo)
static void moveNotificationVertically(Notification& notification, float pixels_to_move); // Mueve verticalmente una notificación con la cantidad de pixels especificada
void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final
// --- Constructores y destructor privados (singleton) ---
Notifier(const std::string &icon_file, std::shared_ptr<Text> text); // Constructor privado
Notifier(const std::string& icon_file, std::shared_ptr<Text> text); // Constructor privado
~Notifier() = default; // Destructor privado
// --- Instancia singleton ---
static Notifier *instance; // Instancia única de Notifier
static Notifier* instance; // Instancia única de Notifier
};

View File

@@ -1,29 +1,29 @@
#include "ui/service_menu.h"
#include "ui/service_menu.hpp"
#include <utility>
#include "audio.h" // Para Audio
#include "define_buttons.h" // Para DefineButtons
#include "difficulty.h" // Para getCodeFromName, getNameFromCode
#include "input.h" // Para Input
#include "input_types.h" // Para InputAction
#include "lang.h" // Para getText, getCodeFromName, getNameFromCode
#include "menu_option.h" // Para MenuOption, ActionOption, BoolOption, ListOption, FolderOption, IntOption, ActionListOption
#include "menu_renderer.h" // Para MenuRenderer
#include "options.h" // Para GamepadManager, gamepad_manager, PendingChanges, Video, pending_changes, video, Audio, Gamepad, Settings, audio, checkPendingChanges, settings, Window, getPlayerWhoUsesKeyboard, playerIdToString, stringToPlayerId, window, Keyboard, Music, Sound, keyboard
#include "param.h" // Para Param, param, ParamGame, ParamServiceMenu
#include "player.h" // Para Player
#include "resource.h" // Para Resource
#include "screen.h" // Para Screen
#include "section.hpp" // Para Name, name, Options, options
#include "ui/ui_message.h" // Para UIMessage
#include "utils.h" // Para Zone
#include "audio.hpp" // Para Audio
#include "define_buttons.hpp" // Para DefineButtons
#include "difficulty.hpp" // Para getCodeFromName, getNameFromCode
#include "input.hpp" // Para Input
#include "input_types.hpp" // Para InputAction
#include "lang.hpp" // Para getText, getCodeFromName, getNameFromCode
#include "menu_option.hpp" // Para MenuOption, ActionOption, BoolOption, ListOption, FolderOption, IntOption, ActionListOption
#include "menu_renderer.hpp" // Para MenuRenderer
#include "options.hpp" // Para GamepadManager, gamepad_manager, PendingChanges, Video, pending_changes, video, Audio, Gamepad, Settings, audio, checkPendingChanges, settings, Window, getPlayerWhoUsesKeyboard, playerIdToString, stringToPlayerId, window, Keyboard, Music, Sound, keyboard
#include "param.hpp" // Para Param, param, ParamGame, ParamServiceMenu
#include "player.hpp" // Para Player
#include "resource.hpp" // Para Resource
#include "screen.hpp" // Para Screen
#include "section.hpp" // Para Name, name, Options, options
#include "ui/ui_message.hpp" // Para UIMessage
#include "utils.hpp" // Para Zone
// Singleton
ServiceMenu *ServiceMenu::instance = nullptr;
ServiceMenu* ServiceMenu::instance = nullptr;
void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance; }
auto ServiceMenu::get() -> ServiceMenu * { return ServiceMenu::instance; }
auto ServiceMenu::get() -> ServiceMenu* { return ServiceMenu::instance; }
// Constructor
ServiceMenu::ServiceMenu()
@@ -153,7 +153,7 @@ void ServiceMenu::adjustOption(bool adjust_up) {
if (display_options_.empty()) {
return;
}
auto &selected_option = display_options_.at(selected_);
auto& selected_option = display_options_.at(selected_);
if (selected_option->getBehavior() == MenuOption::Behavior::ADJUST) {
selected_option->adjustValue(adjust_up);
applySettings();
@@ -169,13 +169,13 @@ void ServiceMenu::selectOption() {
main_menu_selected_ = selected_;
}
auto *selected_option = display_options_.at(selected_);
auto* selected_option = display_options_.at(selected_);
if (selected_option == nullptr) {
// This shouldn't happen in normal operation, but protects against null pointer
return;
}
if (auto *folder = dynamic_cast<FolderOption *>(selected_option)) {
if (auto* folder = dynamic_cast<FolderOption*>(selected_option)) {
previous_settings_group_ = current_settings_group_;
current_settings_group_ = folder->getTargetGroup();
selected_ = 0;
@@ -190,7 +190,7 @@ void ServiceMenu::selectOption() {
void ServiceMenu::updateDisplayOptions() {
display_options_.clear();
for (auto &option : options_) {
for (auto& option : options_) {
if (option->getGroup() == current_settings_group_ && !option->isHidden()) {
display_options_.push_back(option.get());
}
@@ -200,7 +200,7 @@ void ServiceMenu::updateDisplayOptions() {
void ServiceMenu::updateOptionPairs() {
option_pairs_.clear();
for (const auto &option : display_options_) {
for (const auto& option : display_options_) {
option_pairs_.emplace_back(option->getCaption(), option->getValueAsString());
}
}
@@ -249,8 +249,8 @@ void ServiceMenu::applySettingsSettings() {
setHiddenOptions();
}
auto ServiceMenu::getOptionByCaption(const std::string &caption) const -> MenuOption * {
for (const auto &option : options_) {
auto ServiceMenu::getOptionByCaption(const std::string& caption) const -> MenuOption* {
for (const auto& option : options_) {
if (option->getCaption() == caption) {
return option.get();
}
@@ -274,7 +274,7 @@ auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignmen
auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t {
size_t count = 0;
for (const auto &option : options_) {
for (const auto& option : options_) {
if (option->getGroup() == group && !option->isHidden()) {
count++;
}
@@ -294,12 +294,12 @@ void ServiceMenu::initializeOptions() {
[]() {
return Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).name;
},
[](const std::string &val) {
[](const std::string& val) {
Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER1, Input::get()->getGamepadByName(val), val);
},
[this]() {
// Acción: configurar botones del mando del jugador 1
auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1);
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1);
if ((gamepad != nullptr) && gamepad->instance) {
define_buttons_->enable(gamepad);
}
@@ -312,12 +312,12 @@ void ServiceMenu::initializeOptions() {
[]() {
return Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).name;
},
[](const std::string &val) {
[](const std::string& val) {
Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER2, Input::get()->getGamepadByName(val), val);
},
[this]() {
// Acción: configurar botones del mando del jugador 2
auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2);
auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2);
if ((gamepad != nullptr) && gamepad->instance) {
define_buttons_->enable(gamepad);
}
@@ -334,7 +334,7 @@ void ServiceMenu::initializeOptions() {
// Devolver el jugador actual asignado al teclado
return Options::playerIdToString(Options::getPlayerWhoUsesKeyboard());
},
[](const std::string &val) {
[](const std::string& val) {
// Asignar el teclado al jugador seleccionado
Options::keyboard.assignTo(Options::stringToPlayerId(val));
}));
@@ -424,7 +424,7 @@ void ServiceMenu::initializeOptions() {
[]() {
return Lang::getNameFromCode(Options::pending_changes.new_language);
},
[](const std::string &val) {
[](const std::string& val) {
Options::pending_changes.new_language = Lang::getCodeFromName(val);
Options::checkPendingChanges();
}));
@@ -439,7 +439,7 @@ void ServiceMenu::initializeOptions() {
[]() {
return Difficulty::getNameFromCode(Options::pending_changes.new_difficulty);
},
[](const std::string &val) {
[](const std::string& val) {
Options::pending_changes.new_difficulty = Difficulty::getCodeFromName(val);
Options::checkPendingChanges();
}));
@@ -507,8 +507,8 @@ void ServiceMenu::initializeOptions() {
// Sincroniza los valores de las opciones tipo lista
void ServiceMenu::adjustListValues() {
for (auto &option : options_) {
if (auto *list_option = dynamic_cast<ListOption *>(option.get())) {
for (auto& option : options_) {
if (auto* list_option = dynamic_cast<ListOption*>(option.get())) {
list_option->sync();
}
}
@@ -543,14 +543,14 @@ auto ServiceMenu::settingsGroupToString(SettingsGroup group) -> std::string {
// Establece el estado de oculto de ciertas opciones
void ServiceMenu::setHiddenOptions() {
{
auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"));
auto* option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"));
if (option != nullptr) {
option->setHidden(Options::video.fullscreen);
}
}
{
auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN"));
auto* option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN"));
if (option != nullptr) {
option->setHidden(!Options::settings.shutdown_enabled);
}
@@ -559,7 +559,7 @@ void ServiceMenu::setHiddenOptions() {
updateMenu(); // El menú debe refrescarse si algo se oculta
}
void ServiceMenu::handleEvent(const SDL_Event &event) {
void ServiceMenu::handleEvent(const SDL_Event& event) {
if (!enabled_) {
return;
}
@@ -577,7 +577,7 @@ auto ServiceMenu::checkInput() -> bool {
return false;
}
static auto *input_ = Input::get();
static auto* input_ = Input::get();
using Action = Input::Action;
const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = {
@@ -590,7 +590,7 @@ auto ServiceMenu::checkInput() -> bool {
};
// Teclado
for (const auto &[action, func] : ACTIONS) {
for (const auto& [action, func] : ACTIONS) {
if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
func();
return true;
@@ -598,8 +598,8 @@ auto ServiceMenu::checkInput() -> bool {
}
// Mandos
for (const auto &gamepad : input_->getGamepads()) {
for (const auto &[action, func] : ACTIONS) {
for (const auto& gamepad : input_->getGamepads()) {
for (const auto& [action, func] : ACTIONS) {
if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
func();
return true;

View File

@@ -9,8 +9,8 @@
#include <utility> // Para pair
#include <vector> // Para vector
#include "define_buttons.h" // Para DefineButtons
#include "ui_message.h" // Para UIMessage
#include "define_buttons.hpp" // Para DefineButtons
#include "ui_message.hpp" // Para UIMessage
class MenuOption;
class MenuRenderer;
@@ -40,9 +40,9 @@ class ServiceMenu {
// --- Métodos de singleton ---
static void init();
static void destroy();
static auto get() -> ServiceMenu *;
ServiceMenu(const ServiceMenu &) = delete;
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
static auto get() -> ServiceMenu*;
ServiceMenu(const ServiceMenu&) = delete;
auto operator=(const ServiceMenu&) -> ServiceMenu& = delete;
// --- Métodos principales ---
void toggle();
@@ -58,7 +58,7 @@ class ServiceMenu {
void moveBack();
// --- Método para manejar eventos ---
void handleEvent(const SDL_Event &event);
void handleEvent(const SDL_Event& event);
auto checkInput() -> bool;
// --- Método principal para refresco externo ---
@@ -73,19 +73,19 @@ class ServiceMenu {
// --- Getters para que el Renderer pueda leer el estado ---
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
[[nodiscard]] auto getTitle() const -> const std::string& { return title_; }
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption*>& { return display_options_; }
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>>& { return options_; }
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>>& { return option_pairs_; }
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
private:
bool enabled_ = false;
std::vector<std::unique_ptr<MenuOption>> options_;
std::vector<MenuOption *> display_options_;
std::vector<MenuOption*> display_options_;
std::vector<std::pair<std::string, std::string>> option_pairs_;
SettingsGroup current_settings_group_;
SettingsGroup previous_settings_group_;
@@ -108,7 +108,7 @@ class ServiceMenu {
void applyVideoSettings();
static void applyAudioSettings();
void applySettingsSettings();
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
[[nodiscard]] auto getOptionByCaption(const std::string& caption) const -> MenuOption*;
void adjustListValues();
static void playMoveSound();
static void playAdjustSound();
@@ -123,5 +123,5 @@ class ServiceMenu {
~ServiceMenu() = default;
// --- Instancia singleton ---
static ServiceMenu *instance;
static ServiceMenu* instance;
};

View File

@@ -1,12 +1,12 @@
#include "ui_message.h"
#include "ui_message.hpp"
#include <cmath> // Para pow
#include <utility>
#include "text.h" // Para Text::CENTER, Text::COLOR, Text
#include "text.hpp" // Para Text::CENTER, Text::COLOR, Text
// Constructor: inicializa el renderizador, el texto y el color del mensaje
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color)
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color& color)
: text_renderer_(std::move(text_renderer)),
text_(std::move(message_text)),
color_(color) {}

View File

@@ -3,7 +3,7 @@
#include <memory> // Para shared_ptr
#include <string> // Para string
#include "color.h" // Para Color
#include "color.hpp" // Para Color
class Text;
@@ -11,7 +11,7 @@ class Text;
class UIMessage {
public:
// Constructor: recibe el renderizador de texto, el mensaje y el color
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color& color);
// Muestra el mensaje con animación de entrada
void show();
@@ -45,11 +45,11 @@ class UIMessage {
float y_offset_ = 0.0F; // Desplazamiento vertical actual del mensaje (para animación)
// --- Animación ---
float start_y_ = 0.0F; // Posición Y inicial de la animación
float target_y_ = 0.0F; // Posición Y objetivo de la animación
float animation_timer_ = 0.0F; // Timer actual de la animación en segundos
float start_y_ = 0.0F; // Posición Y inicial de la animación
float target_y_ = 0.0F; // Posición Y objetivo de la animación
float animation_timer_ = 0.0F; // Timer actual de la animación en segundos
static constexpr float ANIMATION_DURATION_S = 0.133f; // Duración total de la animación (8 frames @ 60fps)
static constexpr float DESP = -8.0F; // Distancia a desplazarse
static constexpr float DESP = -8.0F; // Distancia a desplazarse
// Actualiza la interpolación de la animación (ease out/in cubic)
void updateAnimation(float delta_time);

View File

@@ -1,11 +1,11 @@
#include "window_message.h"
#include "window_message.hpp"
#include <algorithm>
#include <utility>
#include "param.h"
#include "screen.h"
#include "text.h"
#include "param.hpp"
#include "screen.hpp"
#include "text.hpp"
WindowMessage::WindowMessage(
std::shared_ptr<Text> text_renderer,

View File

@@ -7,9 +7,9 @@
#include <string> // Para string
#include <vector> // Para vector
#include "color.h" // Para Color
#include "param.h" // Para param
#include "text.h" // Para Text
#include "color.hpp" // Para Color
#include "param.hpp" // Para param
#include "text.hpp" // Para Text
class WindowMessage {
public: