diff --git a/controller-bridge/.gitignore b/controller-bridge/.gitignore new file mode 100644 index 0000000..b5b5cb9 --- /dev/null +++ b/controller-bridge/.gitignore @@ -0,0 +1,24 @@ +# Build directory +build/ + +# Objetos +*.o +*.d + +# Bibliotecas +*.a +*.so + +# Binário gerado +controller-bridge + +# Core dumps +core +core.* + +# Editor +.vscode/ +.idea/ + +# Sistema +.DS_Store diff --git a/controller-bridge/LICENSE b/controller-bridge/LICENSE new file mode 100644 index 0000000..cb028a0 --- /dev/null +++ b/controller-bridge/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Alberto Biason and Steam Media Pack contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/controller-bridge/Makefile b/controller-bridge/Makefile new file mode 100644 index 0000000..409d594 --- /dev/null +++ b/controller-bridge/Makefile @@ -0,0 +1,48 @@ +CC := gcc + +TARGET := controller-bridge + +SRC_DIR := src +INC_DIR := include +BUILD_DIR := build + +SOURCES := $(wildcard $(SRC_DIR)/*.c) +OBJECTS := $(patsubst $(SRC_DIR)/%.c,$(BUILD_DIR)/%.o,$(SOURCES)) +DEPENDENCIES := $(OBJECTS:.o=.d) + +SDL2_CFLAGS := $(shell pkg-config --cflags sdl2) +SDL2_LIBS := $(shell pkg-config --libs sdl2) + +CPPFLAGS := -I$(INC_DIR) $(SDL2_CFLAGS) +CFLAGS := -std=c11 -O2 -Wall -Wextra -Wpedantic +LDFLAGS := +LDLIBS := $(SDL2_LIBS) -lm + +.PHONY: all clean debug release install uninstall + +all: $(TARGET) + +$(TARGET): $(OBJECTS) + $(CC) $(LDFLAGS) $(OBJECTS) -o $@ $(LDLIBS) + +$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c $< -o $@ + +debug: CFLAGS := -std=c11 -O0 -g3 -Wall -Wextra -Wpedantic +debug: clean all + +release: CFLAGS := -std=c11 -O2 -DNDEBUG -Wall -Wextra -Wpedantic +release: clean all + +install: $(TARGET) + install -Dm755 $(TARGET) \ + $(DESTDIR)/usr/local/bin/$(TARGET) + +uninstall: + rm -f $(DESTDIR)/usr/local/bin/$(TARGET) + +clean: + rm -rf $(BUILD_DIR) $(TARGET) + +-include $(DEPENDENCIES) diff --git a/controller-bridge/README.pt-BR.md b/controller-bridge/README.pt-BR.md new file mode 100644 index 0000000..9643fed --- /dev/null +++ b/controller-bridge/README.pt-BR.md @@ -0,0 +1,35 @@ +# Steam Media Pack Controller Bridge + +## Objetivo + +O Controller Bridge é um componente experimental do Steam Media Pack responsável por criar um mouse virtual utilizando `uinput` e controlar esse mouse através de um controle compatível com SDL2. + +A motivação deste projeto é eliminar a dependência do Steam Input para navegação nas plataformas de streaming, proporcionando um comportamento consistente entre serviços como Netflix, Disney+, Max, Prime Video, Spotify e YouTube. + +## Funcionalidades previstas + +- Mouse virtual via Linux uinput +- Compatibilidade com SDL2 GameController API +- Reconexão automática de controles +- Movimento do cursor pelo analógico direito +- Clique esquerdo, direito e botão do meio +- Rolagem utilizando os gatilhos +- Execução em segundo plano como serviço de usuário (systemd) + +## Status + +**Experimental** + +Este componente ainda está em desenvolvimento e não faz parte da versão estável do Steam Media Pack. + +## Compilação + +```bash +make +``` + +## Limpeza + +```bash +make clean +``` diff --git a/controller-bridge/controller.conf.example b/controller-bridge/controller.conf.example new file mode 100644 index 0000000..f0b5094 --- /dev/null +++ b/controller-bridge/controller.conf.example @@ -0,0 +1,9 @@ +cursor.deadzone=8000 +cursor.max_speed=20 +cursor.exponent=2.2 +cursor.sensitivity=1.0 +cursor.smoothing=0.75 + +scroll.initial_delay=250 +scroll.repeat_interval=75 +scroll.step=1 diff --git a/controller-bridge/include/cli.h b/controller-bridge/include/cli.h new file mode 100644 index 0000000..c174b41 --- /dev/null +++ b/controller-bridge/include/cli.h @@ -0,0 +1,61 @@ +#ifndef CLI_H +#define CLI_H + +#include + +/* + * Opções obtidas a partir da linha de comando. + */ +typedef struct +{ + /* + * Caminho do arquivo de configuração. + * + * Quando NULL, o programa utilizará + * CONFIG_DEFAULT_PATH. + */ + const char *config_path; + + /* + * Exibe a ajuda. + */ + bool show_help; + + /* + * Exibe a versão. + */ + bool show_version; + +} CliOptions; + +/* + * Inicializa a estrutura com os valores padrão. + */ +void cli_init( + CliOptions *options); + +/* + * Processa os argumentos da linha de comando. + * + * Retorna: + * + * true -> argumentos válidos. + * false -> argumento inválido. + */ +bool cli_parse( + CliOptions *options, + int argc, + char **argv); + +/* + * Exibe a ajuda do programa. + */ +void cli_print_help( + const char *program_name); + +/* + * Exibe a versão do programa. + */ +void cli_print_version(void); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/clock.h b/controller-bridge/include/clock.h new file mode 100644 index 0000000..5706759 --- /dev/null +++ b/controller-bridge/include/clock.h @@ -0,0 +1,10 @@ +#ifndef SMP_CLOCK_H +#define SMP_CLOCK_H + +#include + +uint64_t clock_now_ms(void); + +void clock_sleep_ms(uint32_t ms); + +#endif /* SMP_CLOCK_H */ \ No newline at end of file diff --git a/controller-bridge/include/config.h b/controller-bridge/include/config.h new file mode 100644 index 0000000..92f5a3e --- /dev/null +++ b/controller-bridge/include/config.h @@ -0,0 +1,22 @@ +#ifndef SMP_CONFIG_H +#define SMP_CONFIG_H + +typedef struct +{ + int cursor_deadzone; + int cursor_max_speed; + + float cursor_exponent; + float cursor_sensitivity; + float cursor_smoothing; + + unsigned int scroll_initial_delay_ms; + unsigned int scroll_repeat_interval_ms; + int scroll_step; +} ControllerConfig; + +extern ControllerConfig g_config; + +void config_set_defaults(void); + +#endif /* SMP_CONFIG_H */ \ No newline at end of file diff --git a/controller-bridge/include/config_parser.h b/controller-bridge/include/config_parser.h new file mode 100644 index 0000000..01a537f --- /dev/null +++ b/controller-bridge/include/config_parser.h @@ -0,0 +1,36 @@ +#ifndef CONFIG_PARSER_H +#define CONFIG_PARSER_H + +#include + +/* + * Arquivo de configuração padrão. + */ +#define CONFIG_DEFAULT_PATH "controller.conf" + +/* + * Tamanho máximo de uma linha do arquivo + * de configuração. + */ +#define CONFIG_MAX_LINE_LENGTH 256 + +/* + * Carrega as configurações do arquivo informado. + * + * As configurações válidas são aplicadas diretamente + * à estrutura global g_config. + * + * Retorna: + * + * true: + * O arquivo foi aberto e processado. + * + * false: + * O caminho é inválido ou o arquivo não pôde ser aberto. + * + * Linhas inválidas são ignoradas e registradas no log, + * mantendo os valores atuais de g_config. + */ +bool config_load(const char *path); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/controller.h b/controller-bridge/include/controller.h new file mode 100644 index 0000000..0bc903b --- /dev/null +++ b/controller-bridge/include/controller.h @@ -0,0 +1,22 @@ +#ifndef SMP_CONTROLLER_H +#define SMP_CONTROLLER_H + +#include "cursor.h" + +#include +#include +#include + +#include "input.h" + +SDL_GameController *controller_open_first(void); + +void controller_close(SDL_GameController *); + +bool controller_is_connected(SDL_GameController *); + +void controller_poll( + SDL_GameController *, + InputState *); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/cursor.h b/controller-bridge/include/cursor.h new file mode 100644 index 0000000..0467c6b --- /dev/null +++ b/controller-bridge/include/cursor.h @@ -0,0 +1,17 @@ +#ifndef SMP_CURSOR_H +#define SMP_CURSOR_H + +#include + +typedef struct +{ + int delta_x; + int delta_y; +} CursorState; + +void cursor_update( + Sint16 axis_x, + Sint16 axis_y, + CursorState *state); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/input.h b/controller-bridge/include/input.h new file mode 100644 index 0000000..f4aad5e --- /dev/null +++ b/controller-bridge/include/input.h @@ -0,0 +1,32 @@ +#ifndef SMP_INPUT_H +#define SMP_INPUT_H + +#include + +#include "cursor.h" + +typedef enum +{ + INPUT_NONE = 0, + + INPUT_LEFT_CLICK = 1 << 0, + INPUT_RIGHT_CLICK = 1 << 1, + INPUT_MIDDLE_CLICK = 1 << 2, + + INPUT_SCROLL_UP = 1 << 3, + INPUT_SCROLL_DOWN = 1 << 4 + +} InputActions; + +typedef struct +{ + uint32_t actions; +} ButtonState; + +typedef struct +{ + CursorState cursor; + ButtonState buttons; +} InputState; + +#endif /* SMP_INPUT_H */ \ No newline at end of file diff --git a/controller-bridge/include/log.h b/controller-bridge/include/log.h new file mode 100644 index 0000000..39d4df8 --- /dev/null +++ b/controller-bridge/include/log.h @@ -0,0 +1,50 @@ +#ifndef SMP_LOG_H +#define SMP_LOG_H + +#include + +typedef enum +{ + LOG_LEVEL_DEBUG = 0, + LOG_LEVEL_INFO, + LOG_LEVEL_WARN, + LOG_LEVEL_ERROR, + LOG_LEVEL_NONE +} LogLevel; + +/* + * Define o nível mínimo exibido. + * + * Exemplo: + * log_set_level(LOG_LEVEL_INFO); + * + * Nesse caso, mensagens DEBUG serão ignoradas. + */ +void log_set_level(LogLevel level); + +LogLevel log_get_level(void); + +/* + * Função interna utilizada pelas macros. + * Normalmente não deve ser chamada diretamente. + */ +void log_write( + LogLevel level, + const char *file, + int line, + const char *format, + ...); + +#define LOG_DEBUG(...) \ + log_write(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) + +#define LOG_INFO(...) \ + log_write(LOG_LEVEL_INFO, __FILE__, __LINE__, __VA_ARGS__) + +#define LOG_WARN(...) \ + log_write(LOG_LEVEL_WARN, __FILE__, __LINE__, __VA_ARGS__) + +#define LOG_ERROR(...) \ + log_write(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__) + +#endif \ No newline at end of file diff --git a/controller-bridge/include/mapping.h b/controller-bridge/include/mapping.h new file mode 100644 index 0000000..6b26877 --- /dev/null +++ b/controller-bridge/include/mapping.h @@ -0,0 +1,17 @@ +#ifndef SMP_MAPPING_H +#define SMP_MAPPING_H + +#include +#include + +bool mapping_left_click(SDL_GameController *controller); + +bool mapping_right_click(SDL_GameController *controller); + +bool mapping_middle_click(SDL_GameController *controller); + +bool mapping_scroll_up(SDL_GameController *controller); + +bool mapping_scroll_down(SDL_GameController *controller); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/scroll.h b/controller-bridge/include/scroll.h new file mode 100644 index 0000000..b1589d7 --- /dev/null +++ b/controller-bridge/include/scroll.h @@ -0,0 +1,12 @@ +#ifndef SMP_SCROLL_H +#define SMP_SCROLL_H + +#include + +void scroll_reset(void); + +void scroll_update( + int mouse_fd, + uint32_t actions); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/signals.h b/controller-bridge/include/signals.h new file mode 100644 index 0000000..a31a454 --- /dev/null +++ b/controller-bridge/include/signals.h @@ -0,0 +1,10 @@ +#ifndef SMP_SIGNALS_H +#define SMP_SIGNALS_H + +#include + +extern volatile sig_atomic_t running; + +void signals_install(void); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/uinput.h b/controller-bridge/include/uinput.h new file mode 100644 index 0000000..0125a7e --- /dev/null +++ b/controller-bridge/include/uinput.h @@ -0,0 +1,36 @@ +#ifndef SMP_UINPUT_H +#define SMP_UINPUT_H + +#include + +#define DEVICE_NAME "Steam Media Pack Controller Bridge" +#define DEVICE_VENDOR 0x1209 +#define DEVICE_PRODUCT 0x0001 +#define DEVICE_VERSION 0x0001 + +int uinput_create(void); + +void uinput_destroy(int file_descriptor); + +void uinput_move( + int file_descriptor, + int delta_x, + int delta_y); + +void uinput_left_button( + int file_descriptor, + bool pressed); + +void uinput_right_button( + int file_descriptor, + bool pressed); + +void uinput_middle_button( + int file_descriptor, + bool pressed); + +void uinput_scroll( + int file_descriptor, + int direction); + +#endif \ No newline at end of file diff --git a/controller-bridge/include/version.h b/controller-bridge/include/version.h new file mode 100644 index 0000000..84ba21d --- /dev/null +++ b/controller-bridge/include/version.h @@ -0,0 +1,7 @@ +#ifndef VERSION_H +#define VERSION_H + +#define SMP_CONTROLLER_NAME "Steam Media Pack Controller Bridge" +#define SMP_CONTROLLER_VERSION "1.0.0" + +#endif \ No newline at end of file diff --git a/controller-bridge/src/cli.c b/controller-bridge/src/cli.c new file mode 100644 index 0000000..47c1f41 --- /dev/null +++ b/controller-bridge/src/cli.c @@ -0,0 +1,87 @@ +#include "cli.h" + +#include +#include + +#include "config_parser.h" +#include "version.h" + +void cli_init(CliOptions *options) +{ + if (options == NULL) + { + return; + } + + options->config_path = CONFIG_DEFAULT_PATH; + options->show_help = false; + options->show_version = false; +} + +bool cli_parse( + CliOptions *options, + int argc, + char **argv) +{ + int i; + + if (options == NULL) + { + return false; + } + + for (i = 1; i < argc; i++) + { + const char *arg = argv[i]; + + if (strcmp(arg, "--help") == 0 || + strcmp(arg, "-h") == 0) + { + options->show_help = true; + } + else if (strcmp(arg, "--version") == 0 || + strcmp(arg, "-v") == 0) + { + options->show_version = true; + } + else if (strcmp(arg, "--config") == 0 || + strcmp(arg, "-c") == 0) + { + if (i + 1 >= argc) + { + fprintf(stderr, + "Missing value for option '%s'.\n", + arg); + return false; + } + + options->config_path = argv[++i]; + } + else + { + fprintf(stderr, + "Unknown option: %s\n", + arg); + return false; + } + } + + return true; +} + +void cli_print_help(const char *program_name) +{ + printf( + "Usage: %s [OPTIONS]\n" + "\n" + "Options:\n" + " -h, --help Show this help message\n" + " -v, --version Show program version\n" + " -c, --config Configuration file\n", + program_name); +} + +void cli_print_version(void) +{ + printf("%s\n", SMP_CONTROLLER_VERSION); +} \ No newline at end of file diff --git a/controller-bridge/src/clock.c b/controller-bridge/src/clock.c new file mode 100644 index 0000000..df86881 --- /dev/null +++ b/controller-bridge/src/clock.c @@ -0,0 +1,13 @@ +#include "clock.h" + +#include + +uint64_t clock_now_ms(void) +{ + return (uint64_t)SDL_GetTicks64(); +} + +void clock_sleep_ms(uint32_t ms) +{ + SDL_Delay(ms); +} \ No newline at end of file diff --git a/controller-bridge/src/config.c b/controller-bridge/src/config.c new file mode 100644 index 0000000..b9e440c --- /dev/null +++ b/controller-bridge/src/config.c @@ -0,0 +1,17 @@ +#include "config.h" + +ControllerConfig g_config; + +void config_set_defaults(void) +{ + g_config.cursor_deadzone = 8000; + g_config.cursor_max_speed = 20; + + g_config.cursor_exponent = 2.2f; + g_config.cursor_sensitivity = 1.0f; + g_config.cursor_smoothing = 0.75f; + + g_config.scroll_initial_delay_ms = 250; + g_config.scroll_repeat_interval_ms = 75; + g_config.scroll_step = 1; +} \ No newline at end of file diff --git a/controller-bridge/src/config_parser.c b/controller-bridge/src/config_parser.c new file mode 100644 index 0000000..4a696ca --- /dev/null +++ b/controller-bridge/src/config_parser.c @@ -0,0 +1,628 @@ +#include "config_parser.h" + +#include "config.h" +#include "log.h" + +#include +#include +#include +#include +#include +#include + +/* + * Remove espaços em branco do início e do final + * de uma string. + * + * A função altera a própria string recebida. + */ +static char *trim(char *text) +{ + if (text == NULL) + { + return NULL; + } + + while (isspace((unsigned char)*text)) + { + ++text; + } + + if (*text == '\0') + { + return text; + } + + char *end = text + strlen(text) - 1; + + while (end > text && + isspace((unsigned char)*end)) + { + --end; + } + + end[1] = '\0'; + + return text; +} + +/* + * Limita um valor inteiro ao intervalo informado. + */ +static int clamp_int( + int value, + int minimum, + int maximum) +{ + if (value < minimum) + { + return minimum; + } + + if (value > maximum) + { + return maximum; + } + + return value; +} + +/* + * Limita um valor de ponto flutuante + * ao intervalo informado. + */ +static float clamp_float( + float value, + float minimum, + float maximum) +{ + if (value < minimum) + { + return minimum; + } + + if (value > maximum) + { + return maximum; + } + + return value; +} + +/* + * Converte uma string para inteiro. + * + * Diferentemente de atoi(), esta função consegue + * detectar valores inválidos e estouro numérico. + */ +static bool parse_int( + const char *text, + int *result) +{ + if (text == NULL || + result == NULL || + *text == '\0') + { + return false; + } + + errno = 0; + + char *end = NULL; + + long value = strtol( + text, + &end, + 10); + + if (errno == ERANGE || + value < INT_MIN || + value > INT_MAX) + { + return false; + } + + if (end == text) + { + return false; + } + + while (isspace((unsigned char)*end)) + { + ++end; + } + + if (*end != '\0') + { + return false; + } + + *result = (int)value; + + return true; +} + +/* + * Converte uma string para float. + * + * Detecta texto inválido e valores fora + * do intervalo representável. + */ +static bool parse_float( + const char *text, + float *result) +{ + if (text == NULL || + result == NULL || + *text == '\0') + { + return false; + } + + errno = 0; + + char *end = NULL; + + float value = strtof( + text, + &end); + + if (errno == ERANGE) + { + return false; + } + + if (end == text) + { + return false; + } + + while (isspace((unsigned char)*end)) + { + ++end; + } + + if (*end != '\0') + { + return false; + } + + *result = value; + + return true; +} + +/* + * Registra quando um valor inteiro precisou + * ser limitado ao intervalo permitido. + */ +static void log_int_adjustment( + const char *key, + int original, + int adjusted) +{ + if (original == adjusted) + { + return; + } + + LOG_WARN( + "%s fora do intervalo permitido: %d. " + "Valor ajustado para %d.", + key, + original, + adjusted); +} + +/* + * Registra quando um valor float precisou + * ser limitado ao intervalo permitido. + */ +static void log_float_adjustment( + const char *key, + float original, + float adjusted) +{ + if (original == adjusted) + { + return; + } + + LOG_WARN( + "%s fora do intervalo permitido: %.3f. " + "Valor ajustado para %.3f.", + key, + original, + adjusted); +} + +/* + * Aplica uma propriedade inteira à configuração global. + * + * Retorna false quando a chave não pertence ao grupo + * de propriedades inteiras. + */ +static bool set_int( + const char *key, + int value) +{ + int validated = value; + + if (strcmp(key, "cursor.deadzone") == 0) + { + validated = + clamp_int(value, 0, 32767); + + log_int_adjustment( + key, + value, + validated); + + g_config.cursor_deadzone = validated; + + return true; + } + + if (strcmp(key, "cursor.max_speed") == 0) + { + validated = + clamp_int(value, 1, 100); + + log_int_adjustment( + key, + value, + validated); + + g_config.cursor_max_speed = validated; + + return true; + } + + if (strcmp(key, "scroll.initial_delay") == 0) + { + validated = + clamp_int(value, 0, 5000); + + log_int_adjustment( + key, + value, + validated); + + g_config.scroll_initial_delay_ms = + (unsigned int)validated; + + return true; + } + + if (strcmp(key, "scroll.repeat_interval") == 0) + { + validated = + clamp_int(value, 1, 1000); + + log_int_adjustment( + key, + value, + validated); + + g_config.scroll_repeat_interval_ms = + (unsigned int)validated; + + return true; + } + + if (strcmp(key, "scroll.step") == 0) + { + validated = + clamp_int(value, 1, 20); + + log_int_adjustment( + key, + value, + validated); + + g_config.scroll_step = validated; + + return true; + } + + return false; +} + +/* + * Aplica uma propriedade de ponto flutuante + * à configuração global. + * + * Retorna false quando a chave não pertence + * ao grupo de propriedades float. + */ +static bool set_float( + const char *key, + float value) +{ + float validated = value; + + if (strcmp(key, "cursor.exponent") == 0) + { + validated = + clamp_float(value, 1.0f, 5.0f); + + log_float_adjustment( + key, + value, + validated); + + g_config.cursor_exponent = validated; + + return true; + } + + if (strcmp(key, "cursor.sensitivity") == 0) + { + validated = + clamp_float(value, 0.1f, 10.0f); + + log_float_adjustment( + key, + value, + validated); + + g_config.cursor_sensitivity = validated; + + return true; + } + + if (strcmp(key, "cursor.smoothing") == 0) + { + validated = + clamp_float(value, 0.0f, 0.99f); + + log_float_adjustment( + key, + value, + validated); + + g_config.cursor_smoothing = validated; + + return true; + } + + return false; +} + +/* + * Verifica se a chave pertence às configurações + * de ponto flutuante. + */ +static bool is_float_key(const char *key) +{ + return + strcmp(key, "cursor.exponent") == 0 || + strcmp(key, "cursor.sensitivity") == 0 || + strcmp(key, "cursor.smoothing") == 0; +} + +/* + * Verifica se a chave pertence às configurações inteiras. + */ +static bool is_int_key(const char *key) +{ + return + strcmp(key, "cursor.deadzone") == 0 || + strcmp(key, "cursor.max_speed") == 0 || + strcmp(key, "scroll.initial_delay") == 0 || + strcmp(key, "scroll.repeat_interval") == 0 || + strcmp(key, "scroll.step") == 0; +} + +/* + * Descarta o restante de uma linha que excedeu + * CONFIG_MAX_LINE_LENGTH. + */ +static void discard_line_remainder(FILE *file) +{ + int character = 0; + + while ((character = fgetc(file)) != '\n' && + character != EOF) + { + /* + * Apenas descarta os caracteres restantes. + */ + } +} + +/* + * Processa uma única propriedade no formato: + * + * chave=valor + */ +static void process_property( + char *text, + unsigned int line_number) +{ + char *separator = strchr(text, '='); + + if (separator == NULL) + { + LOG_WARN( + "Linha %u inválida: separador '=' não encontrado.", + line_number); + + return; + } + + *separator = '\0'; + + char *key = trim(text); + char *value_text = trim(separator + 1); + + if (key == NULL || + value_text == NULL || + *key == '\0' || + *value_text == '\0') + { + LOG_WARN( + "Linha %u inválida: chave ou valor ausente.", + line_number); + + return; + } + + if (!is_int_key(key) && + !is_float_key(key)) + { + LOG_WARN( + "Linha %u: configuração desconhecida: %s.", + line_number, + key); + + return; + } + + if (is_int_key(key)) + { + int value = 0; + + if (!parse_int( + value_text, + &value)) + { + LOG_WARN( + "Linha %u: valor inteiro inválido para %s: %s.", + line_number, + key, + value_text); + + return; + } + + set_int( + key, + value); + + LOG_DEBUG( + "Configuração aplicada: %s = %d.", + key, + value); + + return; + } + + float value = 0.0f; + + if (!parse_float( + value_text, + &value)) + { + LOG_WARN( + "Linha %u: valor decimal inválido para %s: %s.", + line_number, + key, + value_text); + + return; + } + + set_float( + key, + value); + + LOG_DEBUG( + "Configuração aplicada: %s = %.3f.", + key, + value); +} + +bool config_load(const char *path) +{ + if (path == NULL || + *path == '\0') + { + LOG_ERROR( + "Caminho do arquivo de configuração inválido."); + + return false; + } + + FILE *file = fopen( + path, + "r"); + + if (file == NULL) + { + LOG_WARN( + "Não foi possível abrir o arquivo de configuração " + "%s: %s.", + path, + strerror(errno)); + + return false; + } + + LOG_INFO( + "Carregando configurações de: %s.", + path); + + char line[CONFIG_MAX_LINE_LENGTH]; + unsigned int line_number = 0; + + while (fgets( + line, + sizeof(line), + file) != NULL) + { + ++line_number; + + /* + * Se não houver quebra de linha e ainda não estivermos + * no final do arquivo, a linha excedeu o tamanho máximo. + */ + if (strchr(line, '\n') == NULL && + !feof(file)) + { + LOG_WARN( + "Linha %u excede o limite de %d caracteres " + "e será ignorada.", + line_number, + CONFIG_MAX_LINE_LENGTH - 1); + + discard_line_remainder(file); + + continue; + } + + char *text = trim(line); + + /* + * Ignora linhas vazias e comentários. + */ + if (text == NULL || + *text == '\0' || + *text == '#') + { + continue; + } + + process_property( + text, + line_number); + } + + if (ferror(file)) + { + LOG_ERROR( + "Erro durante a leitura do arquivo de configuração: %s.", + path); + + fclose(file); + + return false; + } + + fclose(file); + + LOG_INFO( + "Arquivo de configuração processado com sucesso."); + + return true; +} \ No newline at end of file diff --git a/controller-bridge/src/controller.c b/controller-bridge/src/controller.c new file mode 100644 index 0000000..84e3569 --- /dev/null +++ b/controller-bridge/src/controller.c @@ -0,0 +1,161 @@ +#include "controller.h" +#include "cursor.h" + +#include "config.h" +#include "log.h" +#include "mapping.h" + +#include + +#include +#include + +SDL_GameController *controller_open_first(void) +{ + int joystick_count = SDL_NumJoysticks(); + + if (joystick_count < 0) + { + LOG_ERROR( + "Falha ao consultar dispositivos SDL: %s", + SDL_GetError()); + + return NULL; + } + + LOG_DEBUG( + "Procurando controles. Dispositivos detectados: %d.", + joystick_count); + + for (int index = 0; index < joystick_count; ++index) + { + if (!SDL_IsGameController(index)) + { + LOG_DEBUG( + "Dispositivo no índice %d não é reconhecido " + "como SDL GameController.", + index); + + continue; + } + + SDL_GameController *controller = + SDL_GameControllerOpen(index); + + if (controller == NULL) + { + LOG_WARN( + "Não foi possível abrir o controle no índice %d: %s", + index, + SDL_GetError()); + + continue; + } + + const char *name = + SDL_GameControllerName(controller); + + SDL_Joystick *joystick = + SDL_GameControllerGetJoystick(controller); + + SDL_JoystickID instance_id = -1; + + if (joystick != NULL) + { + instance_id = + SDL_JoystickInstanceID(joystick); + } + + LOG_INFO( + "Controle conectado: %s — ID: %d.", + name != NULL + ? name + : "controle desconhecido", + (int)instance_id); + + return controller; + } + + return NULL; +} + +void controller_close(SDL_GameController *controller) +{ + if (controller == NULL) + { + return; + } + + const char *name = + SDL_GameControllerName(controller); + + LOG_DEBUG( + "Fechando controle: %s.", + name != NULL + ? name + : "controle desconhecido"); + + SDL_GameControllerClose(controller); +} + +bool controller_is_connected( + SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + return SDL_GameControllerGetAttached(controller) + == SDL_TRUE; +} + +void controller_poll( + SDL_GameController *controller, + InputState *state) +{ + if (controller == NULL || state == NULL) + { + return; + } + + Sint16 axis_x = SDL_GameControllerGetAxis( + controller, + SDL_CONTROLLER_AXIS_LEFTX); + + Sint16 axis_y = SDL_GameControllerGetAxis( + controller, + SDL_CONTROLLER_AXIS_LEFTY); + + cursor_update( + axis_x, + axis_y, + &state->cursor); + + state->buttons.actions = INPUT_NONE; + + if (mapping_left_click(controller)) + { + state->buttons.actions |= INPUT_LEFT_CLICK; + } + + if (mapping_right_click(controller)) + { + state->buttons.actions |= INPUT_RIGHT_CLICK; + } + + if (mapping_middle_click(controller)) + { + state->buttons.actions |= INPUT_MIDDLE_CLICK; + } + + if (mapping_scroll_up(controller)) + { + state->buttons.actions |= INPUT_SCROLL_UP; + } + + if (mapping_scroll_down(controller)) + { + state->buttons.actions |= INPUT_SCROLL_DOWN; + } +} \ No newline at end of file diff --git a/controller-bridge/src/cursor.c b/controller-bridge/src/cursor.c new file mode 100644 index 0000000..4088054 --- /dev/null +++ b/controller-bridge/src/cursor.c @@ -0,0 +1,122 @@ +#include "cursor.h" +#include "config.h" + +#include + +static int apply_smoothing( + float *history, + int current); + +static float smooth_x = 0.0f; +static float smooth_y = 0.0f; + +static float normalize_axis(Sint16 axis) +{ + if (axis >= 0) + { + return (float)axis / 32767.0f; + } + + return (float)axis / 32768.0f; +} + +static float apply_deadzone(float value) +{ + const float deadzone = + (float)g_config.cursor_deadzone / 32767.0f; + + float magnitude = fabsf(value); + + if (magnitude <= deadzone) + { + return 0.0f; + } + + magnitude = + (magnitude - deadzone) / + (1.0f - deadzone); + + return copysignf(magnitude, value); +} + +static float apply_curve(float value) +{ + float magnitude = powf( + fabsf(value), + g_config.cursor_exponent); + + return copysignf(magnitude, value); +} + +static int apply_speed(float value) +{ + float speed = + value * + g_config.cursor_max_speed * + g_config.cursor_sensitivity; + + if (speed > g_config.cursor_max_speed) + { + speed = g_config.cursor_max_speed; + } + else if (speed < -g_config.cursor_max_speed) + { + speed = -g_config.cursor_max_speed; + } + + if (speed > 0.0f && speed < 1.0f) + { + return 1; + } + + if (speed < 0.0f && speed > -1.0f) + { + return -1; + } + + return (int)lroundf(speed); +} + +void cursor_update( + Sint16 axis_x, + Sint16 axis_y, + CursorState *state) +{ + if (state == NULL) + { + return; + } + + float x = normalize_axis(axis_x); + float y = normalize_axis(axis_y); + + x = apply_deadzone(x); + y = apply_deadzone(y); + + x = apply_curve(x); + y = apply_curve(y); + + int speed_x = apply_speed(x); + int speed_y = apply_speed(y); + + state->delta_x = + apply_smoothing( + &smooth_x, + speed_x); + + state->delta_y = + apply_smoothing( + &smooth_y, + speed_y); +} + +static int apply_smoothing( + float *history, + int current) +{ + *history = + (*history * g_config.cursor_smoothing) + + ((float)current * (1.0f - g_config.cursor_smoothing)); + + return (int)lroundf(*history); +} \ No newline at end of file diff --git a/controller-bridge/src/log.c b/controller-bridge/src/log.c new file mode 100644 index 0000000..94f547b --- /dev/null +++ b/controller-bridge/src/log.c @@ -0,0 +1,137 @@ +#include "log.h" + +#include +#include + +static LogLevel current_level = LOG_LEVEL_INFO; + +static const char *log_level_to_string(LogLevel level) +{ + switch (level) + { + case LOG_LEVEL_DEBUG: + return "DEBUG"; + + case LOG_LEVEL_INFO: + return "INFO"; + + case LOG_LEVEL_WARN: + return "WARN"; + + case LOG_LEVEL_ERROR: + return "ERROR"; + + case LOG_LEVEL_NONE: + return "NONE"; + + default: + return "UNKNOWN"; + } +} + +static const char *get_filename(const char *path) +{ + const char *filename = path; + + if (path == NULL) + return "unknown"; + + for (const char *cursor = path; *cursor != '\0'; ++cursor) + { + if (*cursor == '/' || *cursor == '\\') + filename = cursor + 1; + } + + return filename; +} + +static void format_timestamp( + char *buffer, + size_t buffer_size) +{ + time_t now = time(NULL); + struct tm local_time; + + if (localtime_r(&now, &local_time) == NULL) + { + snprintf( + buffer, + buffer_size, + "0000-00-00 00:00:00"); + + return; + } + + if (strftime( + buffer, + buffer_size, + "%Y-%m-%d %H:%M:%S", + &local_time) == 0) + { + snprintf( + buffer, + buffer_size, + "0000-00-00 00:00:00"); + } +} + +void log_set_level(LogLevel level) +{ + if (level < LOG_LEVEL_DEBUG || + level > LOG_LEVEL_NONE) + { + return; + } + + current_level = level; +} + +LogLevel log_get_level(void) +{ + return current_level; +} + +void log_write( + LogLevel level, + const char *file, + int line, + const char *format, + ...) +{ + char timestamp[20]; + va_list arguments; + + if (format == NULL) + return; + + if (level < current_level || + current_level == LOG_LEVEL_NONE) + { + return; + } + + format_timestamp( + timestamp, + sizeof(timestamp)); + + /* + * Todos os logs usam stderr. + * + * Isso facilita a captura pelo systemd/journald + * e evita perda de mensagens devido ao buffering. + */ + fprintf( + stderr, + "[%s] [%-5s] [%s:%d] ", + timestamp, + log_level_to_string(level), + get_filename(file), + line); + + va_start(arguments, format); + vfprintf(stderr, format, arguments); + va_end(arguments); + + fputc('\n', stderr); + fflush(stderr); +} \ No newline at end of file diff --git a/controller-bridge/src/main.c b/controller-bridge/src/main.c new file mode 100644 index 0000000..7db9c66 --- /dev/null +++ b/controller-bridge/src/main.c @@ -0,0 +1,341 @@ +#include "cli.h" +#include "clock.h" +#include "config.h" +#include "config_parser.h" +#include "controller.h" +#include "log.h" +#include "scroll.h" +#include "signals.h" +#include "uinput.h" +#include "version.h" + +#include + +#include +#include +#include + +#define MAIN_LOOP_DELAY_MS 8 +#define CONTROLLER_RETRY_DELAY_MS 250 + +/* + * Envia o estado atual dos botões para o dispositivo + * virtual de mouse. + */ +static void update_mouse_buttons( + int mouse_fd, + const ButtonState *buttons) +{ + if (buttons == NULL) + { + return; + } + + const uint32_t actions = buttons->actions; + + uinput_left_button( + mouse_fd, + (actions & INPUT_LEFT_CLICK) != 0); + + uinput_right_button( + mouse_fd, + (actions & INPUT_RIGHT_CLICK) != 0); + + uinput_middle_button( + mouse_fd, + (actions & INPUT_MIDDLE_CLICK) != 0); +} + +/* + * Libera todos os botões do mouse virtual. + * + * Isso evita que algum botão permaneça pressionado + * depois de uma desconexão ou encerramento. + */ +static void release_mouse_buttons(int mouse_fd) +{ + uinput_left_button(mouse_fd, false); + uinput_right_button(mouse_fd, false); + uinput_middle_button(mouse_fd, false); +} + +/* + * Aguarda até que um controle compatível com SDL2 + * esteja disponível. + * + * SDL_PumpEvents() atualiza o estado interno da SDL, + * permitindo que dispositivos conectados novamente + * apareçam em SDL_NumJoysticks(). + */ +static SDL_GameController *wait_for_controller(void) +{ + bool waiting_logged = false; + + while (running) + { + /* + * Atualiza os dispositivos conhecidos pela SDL. + */ + SDL_PumpEvents(); + + /* + * Faz uma nova varredura nos dispositivos. + * + * Um controle reconectado pode receber um novo + * índice e uma nova instance ID. + */ + SDL_GameController *controller = + controller_open_first(); + + if (controller != NULL) + { + return controller; + } + + if (!waiting_logged) + { + LOG_INFO( + "Aguardando conexão de um controle compatível."); + + waiting_logged = true; + } + + clock_sleep_ms(CONTROLLER_RETRY_DELAY_MS); + } + + return NULL; +} + +int main(int argc, char *argv[]) +{ + CliOptions cli; + + cli_init(&cli); + + if (!cli_parse(&cli, argc, argv)) + { + return EXIT_FAILURE; + } + + if (cli.show_help) + { + cli_print_help(argv[0]); + return EXIT_SUCCESS; + } + + if (cli.show_version) + { + cli_print_version(); + return EXIT_SUCCESS; + } + + config_set_defaults(); + + if (!config_load(cli.config_path)) + { + return EXIT_FAILURE; + } + + LOG_INFO( + "Iniciando %s %s.", + SMP_CONTROLLER_NAME, + SMP_CONTROLLER_VERSION); + + /* + * Instala os manipuladores de SIGINT e SIGTERM. + * + * Isso permite encerrar corretamente com Ctrl+C + * ou através do systemd. + */ + signals_install(); + + /* + * Inicializa os subsistemas necessários da SDL2. + */ + if (SDL_Init( + SDL_INIT_GAMECONTROLLER | + SDL_INIT_JOYSTICK | + SDL_INIT_EVENTS) != 0) + { + LOG_ERROR( + "Falha ao inicializar SDL2: %s.", + SDL_GetError()); + + return EXIT_FAILURE; + } + + /* + * Mantém habilitada a atualização dos estados + * de controles e joysticks. + */ + SDL_GameControllerEventState(SDL_ENABLE); + SDL_JoystickEventState(SDL_ENABLE); + + /* + * Cria o dispositivo virtual de mouse através + * do uinput. + */ + int mouse_fd = uinput_create(); + + if (mouse_fd < 0) + { + LOG_ERROR( + "Não foi possível criar o dispositivo virtual."); + + SDL_Quit(); + + return EXIT_FAILURE; + } + + /* + * Inicializa o estado interno do módulo de scroll. + */ + scroll_reset(); + + /* + * Aguarda o primeiro controle. + */ + SDL_GameController *controller = + wait_for_controller(); + + if (controller == NULL) + { + /* + * Normalmente significa que o programa recebeu + * um sinal enquanto aguardava um controle. + */ + release_mouse_buttons(mouse_fd); + scroll_reset(); + + uinput_destroy(mouse_fd); + SDL_Quit(); + + LOG_INFO("Controller Bridge encerrado."); + + return EXIT_SUCCESS; + } + + /* + * Estado atual das entradas do controle. + */ + InputState state = {0}; + + while (running) + { + /* + * Atualiza internamente o estado dos dispositivos. + * + * Esta chamada também permite detectar quando + * o controle foi desconectado. + */ + SDL_PumpEvents(); + + /* + * Verifica se a instância atual ainda está conectada. + */ + if (!controller_is_connected(controller)) + { + LOG_WARN("Controle desconectado."); + + controller_close(controller); + controller = NULL; + + /* + * Limpa todos os estados associados ao controle + * anterior. + */ + state = (InputState){0}; + + scroll_reset(); + release_mouse_buttons(mouse_fd); + + LOG_INFO( + "Aguardando reconexão do controle."); + + /* + * Faz uma nova varredura até que outro controle + * compatível seja encontrado. + */ + controller = wait_for_controller(); + + if (controller == NULL) + { + break; + } + + LOG_INFO( + "Controle reconectado e pronto para uso."); + + continue; + } + + /* + * Atualiza: + * + * state.cursor.delta_x + * state.cursor.delta_y + * state.buttons.actions + */ + controller_poll( + controller, + &state); + + /* + * Envia movimento apenas quando existe + * deslocamento no cursor. + */ + if (state.cursor.delta_x != 0 || + state.cursor.delta_y != 0) + { + uinput_move( + mouse_fd, + state.cursor.delta_x, + state.cursor.delta_y); + } + + /* + * Atualiza clique esquerdo, direito e central. + */ + update_mouse_buttons( + mouse_fd, + &state.buttons); + + /* + * Atualiza o scroll e sua repetição. + */ + scroll_update( + mouse_fd, + state.buttons.actions); + + /* + * Aproximadamente 125 atualizações por segundo. + */ + clock_sleep_ms(MAIN_LOOP_DELAY_MS); + } + + LOG_INFO( + "Encerrando Controller Bridge."); + + /* + * Libera os estados virtuais antes de destruir + * o dispositivo. + */ + release_mouse_buttons(mouse_fd); + + scroll_reset(); + + if (controller != NULL) + { + controller_close(controller); + controller = NULL; + } + + uinput_destroy(mouse_fd); + + SDL_Quit(); + + LOG_INFO( + "Controller Bridge encerrado corretamente."); + + return EXIT_SUCCESS; +} \ No newline at end of file diff --git a/controller-bridge/src/mapping.c b/controller-bridge/src/mapping.c new file mode 100644 index 0000000..25eb45b --- /dev/null +++ b/controller-bridge/src/mapping.c @@ -0,0 +1,71 @@ +#include "mapping.h" + +#include + +#define TRIGGER_THRESHOLD 20000 + +bool mapping_left_click(SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + return SDL_GameControllerGetButton( + controller, + SDL_CONTROLLER_BUTTON_A) != 0; +} + +bool mapping_right_click(SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + return SDL_GameControllerGetButton( + controller, + SDL_CONTROLLER_BUTTON_B) != 0; +} + +bool mapping_middle_click(SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + return SDL_GameControllerGetButton( + controller, + SDL_CONTROLLER_BUTTON_X) != 0; +} + +bool mapping_scroll_up(SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + Sint16 trigger_value = + SDL_GameControllerGetAxis( + controller, + SDL_CONTROLLER_AXIS_TRIGGERLEFT); + + return trigger_value > TRIGGER_THRESHOLD; +} + +bool mapping_scroll_down(SDL_GameController *controller) +{ + if (controller == NULL) + { + return false; + } + + Sint16 trigger_value = + SDL_GameControllerGetAxis( + controller, + SDL_CONTROLLER_AXIS_TRIGGERRIGHT); + + return trigger_value > TRIGGER_THRESHOLD; +} \ No newline at end of file diff --git a/controller-bridge/src/scroll.c b/controller-bridge/src/scroll.c new file mode 100644 index 0000000..519ea50 --- /dev/null +++ b/controller-bridge/src/scroll.c @@ -0,0 +1,87 @@ +#include "scroll.h" + +#include "clock.h" +#include "config.h" +#include "controller.h" +#include "uinput.h" + +#include + +typedef struct +{ + bool pressed; + uint64_t pressed_at; + uint64_t last_repeat; +} ScrollButtonState; + +static ScrollButtonState scroll_up_state; +static ScrollButtonState scroll_down_state; + +static void update_direction( + int mouse_fd, + bool active, + int direction, + ScrollButtonState *state) +{ + uint64_t now = clock_now_ms(); + + if (!active) + { + state->pressed = false; + state->pressed_at = 0; + state->last_repeat = 0; + return; + } + + if (!state->pressed) + { + state->pressed = true; + state->pressed_at = now; + state->last_repeat = now; + + uinput_scroll( + mouse_fd, + direction * g_config.scroll_step); + + return; + } + + if ((now - state->pressed_at) < + g_config.scroll_initial_delay_ms) + { + return; + } + + if ((now - state->last_repeat) >= + g_config.scroll_repeat_interval_ms) + { + state->last_repeat = now; + + uinput_scroll( + mouse_fd, + direction * g_config.scroll_step); + } +} + +void scroll_reset(void) +{ + scroll_up_state = (ScrollButtonState){0}; + scroll_down_state = (ScrollButtonState){0}; +} + +void scroll_update( + int mouse_fd, + uint32_t actions) +{ + update_direction( + mouse_fd, + (actions & INPUT_SCROLL_UP) != 0, + 1, + &scroll_up_state); + + update_direction( + mouse_fd, + (actions & INPUT_SCROLL_DOWN) != 0, + -1, + &scroll_down_state); +} \ No newline at end of file diff --git a/controller-bridge/src/signals.c b/controller-bridge/src/signals.c new file mode 100644 index 0000000..60dcf5e --- /dev/null +++ b/controller-bridge/src/signals.c @@ -0,0 +1,15 @@ +#include "signals.h" + +volatile sig_atomic_t running = 1; + +static void handle_signal(int signal_number) +{ + (void)signal_number; + running = 0; +} + +void signals_install(void) +{ + signal(SIGINT, handle_signal); + signal(SIGTERM, handle_signal); +} \ No newline at end of file diff --git a/controller-bridge/src/uinput.c b/controller-bridge/src/uinput.c new file mode 100644 index 0000000..2d461ae --- /dev/null +++ b/controller-bridge/src/uinput.c @@ -0,0 +1,369 @@ +#include "uinput.h" + +#include "config.h" +#include "log.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static bool left_button_pressed = false; +static bool right_button_pressed = false; +static bool middle_button_pressed = false; + +static bool emit_event( + int file_descriptor, + uint16_t type, + uint16_t code, + int32_t value) +{ + struct input_event event; + + memset(&event, 0, sizeof(event)); + + event.type = type; + event.code = code; + event.value = value; + + ssize_t written = + write( + file_descriptor, + &event, + sizeof(event)); + + if (written != (ssize_t)sizeof(event)) + { + LOG_ERROR( + "Falha ao enviar evento uinput " + "(tipo=%u, código=%u, valor=%d): %s", + type, + code, + value, + strerror(errno)); + + return false; + } + + return true; +} + +static bool sync_events(int file_descriptor) +{ + return emit_event( + file_descriptor, + EV_SYN, + SYN_REPORT, + 0); +} + +static bool configure_event_type( + int file_descriptor, + unsigned long request, + int value, + const char *description) +{ + if (ioctl(file_descriptor, request, value) < 0) + { + LOG_ERROR( + "Falha ao configurar %s no uinput: %s", + description, + strerror(errno)); + + return false; + } + + return true; +} + +static void send_button_state( + int file_descriptor, + uint16_t button_code, + bool pressed, + bool *previous_state) +{ + if (file_descriptor < 0 || previous_state == NULL) + { + return; + } + + /* + * Evita reenviar o mesmo estado continuamente. + */ + if (*previous_state == pressed) + { + return; + } + + if (!emit_event( + file_descriptor, + EV_KEY, + button_code, + pressed ? 1 : 0)) + { + return; + } + + if (!sync_events(file_descriptor)) + { + return; + } + + *previous_state = pressed; +} + +int uinput_create(void) +{ + int file_descriptor = + open( + "/dev/uinput", + O_WRONLY | O_NONBLOCK); + + if (file_descriptor < 0) + { + LOG_ERROR( + "Não foi possível abrir /dev/uinput: %s", + strerror(errno)); + + return -1; + } + + if (!configure_event_type( + file_descriptor, + UI_SET_EVBIT, + EV_KEY, + "eventos de botão") || + + !configure_event_type( + file_descriptor, + UI_SET_KEYBIT, + BTN_LEFT, + "botão esquerdo") || + + !configure_event_type( + file_descriptor, + UI_SET_KEYBIT, + BTN_RIGHT, + "botão direito") || + + !configure_event_type( + file_descriptor, + UI_SET_KEYBIT, + BTN_MIDDLE, + "botão do meio") || + + !configure_event_type( + file_descriptor, + UI_SET_EVBIT, + EV_REL, + "eventos relativos") || + + !configure_event_type( + file_descriptor, + UI_SET_RELBIT, + REL_X, + "movimento horizontal") || + + !configure_event_type( + file_descriptor, + UI_SET_RELBIT, + REL_Y, + "movimento vertical") || + + !configure_event_type( + file_descriptor, + UI_SET_RELBIT, + REL_WHEEL, + "rolagem vertical")) + { + close(file_descriptor); + + return -1; + } + + struct uinput_setup setup; + + memset(&setup, 0, sizeof(setup)); + + setup.id.bustype = BUS_USB; + setup.id.vendor = DEVICE_VENDOR; + setup.id.product = DEVICE_PRODUCT; + setup.id.version = DEVICE_VERSION; + + snprintf( + setup.name, + sizeof(setup.name), + "%s", + DEVICE_NAME); + + if (ioctl( + file_descriptor, + UI_DEV_SETUP, + &setup) < 0) + { + LOG_ERROR( + "Falha ao configurar o dispositivo virtual: %s", + strerror(errno)); + + close(file_descriptor); + + return -1; + } + + if (ioctl(file_descriptor, UI_DEV_CREATE) < 0) + { + LOG_ERROR( + "Falha ao criar o dispositivo virtual: %s", + strerror(errno)); + + close(file_descriptor); + + return -1; + } + + /* + * Dá ao kernel um pequeno intervalo para registrar + * completamente o novo dispositivo. + */ + usleep(100000); + + left_button_pressed = false; + right_button_pressed = false; + middle_button_pressed = false; + + LOG_INFO( + "Dispositivo virtual criado: %s.", + DEVICE_NAME); + + return file_descriptor; +} + +void uinput_destroy(int file_descriptor) +{ + if (file_descriptor < 0) + { + return; + } + + if (ioctl(file_descriptor, UI_DEV_DESTROY) < 0) + { + LOG_WARN( + "Não foi possível destruir corretamente " + "o dispositivo virtual: %s", + strerror(errno)); + } + else + { + LOG_INFO( + "Dispositivo virtual removido."); + } + + close(file_descriptor); + + left_button_pressed = false; + right_button_pressed = false; + middle_button_pressed = false; +} + +void uinput_move( + int file_descriptor, + int delta_x, + int delta_y) +{ + if (file_descriptor < 0) + { + return; + } + + if (delta_x == 0 && delta_y == 0) + { + return; + } + + bool success = true; + + if (delta_x != 0) + { + success = emit_event( + file_descriptor, + EV_REL, + REL_X, + delta_x); + } + + if (success && delta_y != 0) + { + success = emit_event( + file_descriptor, + EV_REL, + REL_Y, + delta_y); + } + + if (success) + { + sync_events(file_descriptor); + } +} + +void uinput_left_button( + int file_descriptor, + bool pressed) +{ + send_button_state( + file_descriptor, + BTN_LEFT, + pressed, + &left_button_pressed); +} + +void uinput_right_button( + int file_descriptor, + bool pressed) +{ + send_button_state( + file_descriptor, + BTN_RIGHT, + pressed, + &right_button_pressed); +} + +void uinput_middle_button( + int file_descriptor, + bool pressed) +{ + send_button_state( + file_descriptor, + BTN_MIDDLE, + pressed, + &middle_button_pressed); +} + +void uinput_scroll( + int file_descriptor, + int direction) +{ + if (file_descriptor < 0 || direction == 0) + { + return; + } + + int value = direction > 0 ? 1 : -1; + + if (emit_event( + file_descriptor, + EV_REL, + REL_WHEEL, + value)) + { + sync_events(file_descriptor); + } +} \ No newline at end of file diff --git a/controller.conf.example b/controller.conf.example new file mode 100644 index 0000000..4879e6e --- /dev/null +++ b/controller.conf.example @@ -0,0 +1,18 @@ +# +# Steam Media Pack Controller Bridge +# Example configuration +# + +# Cursor + +cursor.deadzone=8000 +cursor.max_speed=20 +cursor.exponent=2.2 +cursor.sensitivity=1.0 +cursor.smoothing=0.75 + +# Scroll + +scroll.initial_delay=250 +scroll.repeat_interval=75 +scroll.step=1 \ No newline at end of file diff --git a/diagnostics.sh b/diagnostics.sh old mode 100644 new mode 100755 diff --git a/install.sh b/install.sh old mode 100644 new mode 100755 index 581e755..0bf359b --- a/install.sh +++ b/install.sh @@ -2,13 +2,76 @@ set -Eeuo pipefail BASE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +# Funções compartilhadas do instalador. +source "$BASE/scripts/common.sh" + DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" PACK_DIR="$DATA_HOME/steam-media-pack" APP_DIR="$DATA_HOME/applications" ICON_DIR="$DATA_HOME/icons/hicolor/scalable/apps" +CONTROLLER_BRIDGE_DIR="$BASE/controller-bridge" +CONTROLLER_BRIDGE_BIN="$CONTROLLER_BRIDGE_DIR/controller-bridge" +INSTALLED_BIN_DIR="$PACK_DIR/bin" +INSTALLED_CONTROLLER_BRIDGE="$INSTALLED_BIN_DIR/controller-bridge" +CONTROLLER_BRIDGE_CONFIG_SOURCE="$CONTROLLER_BRIDGE_DIR/controller.conf.example" +CONTROLLER_BRIDGE_CONFIG_DIR="$PACK_DIR/config" +CONTROLLER_BRIDGE_CONFIG_TARGET="$CONTROLLER_BRIDGE_CONFIG_DIR/controller.conf" +SYSTEMD_DIR="$BASE/packaging/systemd" +SYSTEMD_INSTALL_SCRIPT="$SYSTEMD_DIR/install-controller-bridge-service.sh" + +log_info "Criando diretórios de instalação..." + +ensure_directory "$PACK_DIR/launchers" +ensure_directory "$INSTALLED_BIN_DIR" +ensure_directory "$APP_DIR" +ensure_directory "$ICON_DIR" +ensure_directory "$CONFIG_HOME/steam-media-pack" +ensure_directory "$CONTROLLER_BRIDGE_CONFIG_DIR" + +log_info "Compilando o Controller Bridge..." + +if [[ ! -f "$CONTROLLER_BRIDGE_DIR/Makefile" ]]; then + log_error "Makefile não encontrado em: $CONTROLLER_BRIDGE_DIR" + exit 1 +fi + +make -C "$CONTROLLER_BRIDGE_DIR" + +if [[ ! -x "$CONTROLLER_BRIDGE_BIN" ]]; then + log_error "Binário não foi gerado: $CONTROLLER_BRIDGE_BIN" + exit 1 +fi + +log_success "Controller Bridge compilado." + +log_info "Instalando o Controller Bridge..." + +install_executable \ + "$CONTROLLER_BRIDGE_BIN" \ + "$INSTALLED_CONTROLLER_BRIDGE" -mkdir -p "$PACK_DIR/launchers" "$APP_DIR" "$ICON_DIR" "$CONFIG_HOME/steam-media-pack" +log_success "Controller Bridge instalado em: $INSTALLED_CONTROLLER_BRIDGE" + +log_info "Preparando a configuração do Controller Bridge..." + +if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_SOURCE" ]]; then + log_error "Configuração de exemplo não encontrada: $CONTROLLER_BRIDGE_CONFIG_SOURCE" + exit 1 +fi + +if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_TARGET" ]]; then + install_regular_file \ + "$CONTROLLER_BRIDGE_CONFIG_SOURCE" \ + "$CONTROLLER_BRIDGE_CONFIG_TARGET" + + log_success "Configuração criada em: $CONTROLLER_BRIDGE_CONFIG_TARGET" +else + log_info "Configuração existente preservada: $CONTROLLER_BRIDGE_CONFIG_TARGET" +fi + +log_success "Diretórios preparados." install -m 755 "$BASE/launchers/"*.sh "$PACK_DIR/launchers/" install -m 755 "$BASE/diagnostics.sh" "$PACK_DIR/diagnostics.sh" @@ -16,14 +79,31 @@ install -m 755 "$BASE/select-mode.sh" "$PACK_DIR/select-mode.sh" install -m 644 "$BASE/desktop/"*.desktop "$APP_DIR/" install -m 644 "$BASE/icons/"*.svg "$ICON_DIR/" -cat >"$CONFIG_HOME/steam-media-pack/mode.conf" <<'EOF' +MODE_CONFIG="$CONFIG_HOME/steam-media-pack/mode.conf" + +if [[ ! -f "$MODE_CONFIG" ]]; then + cat >"$MODE_CONFIG" <<'EOF' MODE=auto EOF + log_success "Configuração padrão criada: $MODE_CONFIG" +else + log_info "Configuração existente preservada: $MODE_CONFIG" +fi + if command -v update-desktop-database >/dev/null 2>&1; then update-desktop-database "$APP_DIR" || true fi +log_info "Instalando o serviço do Controller Bridge..." + +if [[ -x "$SYSTEMD_INSTALL_SCRIPT" ]]; then + "$SYSTEMD_INSTALL_SCRIPT" + log_success "Serviço instalado." +else + log_warning "Instalador do serviço não encontrado." +fi + cat </dev/null || true + +if [[ -f "${TARGET_FILE}" ]] +then + rm -f "${TARGET_FILE}" + echo "Serviço removido:" + echo "${TARGET_FILE}" +else + echo "Serviço não estava instalado." +fi + +systemctl --user daemon-reload +systemctl --user reset-failed "${SERVICE_NAME}" 2>/dev/null || true diff --git a/scripts/common.sh b/scripts/common.sh new file mode 100755 index 0000000..9c3eb83 --- /dev/null +++ b/scripts/common.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail + +log_info() +{ + printf '[INFO] %s\n' "$1" +} + +log_success() +{ + printf '[OK] %s\n' "$1" +} + +log_warning() +{ + printf '[AVISO] %s\n' "$1" >&2 +} + +log_error() +{ + printf '[ERRO] %s\n' "$1" >&2 +} + +command_exists() +{ + command -v "$1" >/dev/null 2>&1 +} + +ensure_directory() +{ + local directory="$1" + + mkdir -p "$directory" +} + +install_executable() +{ + local source_file="$1" + local target_file="$2" + + install -Dm755 "$source_file" "$target_file" +} + +install_regular_file() +{ + local source_file="$1" + local target_file="$2" + + install -Dm644 "$source_file" "$target_file" +} diff --git a/select-mode.sh b/select-mode.sh old mode 100644 new mode 100755 diff --git a/systemd/steam-media-controller-bridge.service b/systemd/steam-media-controller-bridge.service new file mode 100644 index 0000000..a70df14 --- /dev/null +++ b/systemd/steam-media-controller-bridge.service @@ -0,0 +1,15 @@ +[Unit] +Description=Steam Media Pack Controller Bridge +Documentation=https://github.com/abiason/Steam-Media-Pack +After=graphical-session.target + +[Service] +Type=simple + +ExecStart=%h/.local/share/steam-media-pack/controller-bridge/controller-bridge + +Restart=always +RestartSec=2 + +[Install] +WantedBy=default.target diff --git a/tools/build-controller-bridge.sh b/tools/build-controller-bridge.sh new file mode 100644 index 0000000..7b10607 --- /dev/null +++ b/tools/build-controller-bridge.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +BASE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +SOURCE_DIR="$BASE/controller-bridge" + +for command_name in cc make pkg-config; do + if ! command -v "$command_name" >/dev/null 2>&1; then + printf 'Dependência ausente: %s\n' "$command_name" >&2 + exit 1 + fi +done + +if ! pkg-config --exists sdl2; then + echo 'SDL2 de desenvolvimento não encontrado pelo pkg-config.' >&2 + echo 'No CachyOS/Arch, instale os pacotes base-devel e sdl2.' >&2 + exit 1 +fi + +make -C "$SOURCE_DIR" clean all diff --git a/tools/setup-controller-bridge.sh b/tools/setup-controller-bridge.sh new file mode 100644 index 0000000..43c84de --- /dev/null +++ b/tools/setup-controller-bridge.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" +PACK_DIR="$DATA_HOME/steam-media-pack" +RULE_SOURCE="$PACK_DIR/controller-bridge/99-steam-media-controller-bridge.rules" +RULE_DEST="/etc/udev/rules.d/99-steam-media-controller-bridge.rules" +SERVICE_NAME="steam-media-controller-bridge.service" + +if [[ ! -f "$RULE_SOURCE" ]]; then + printf 'Regra udev não encontrada: %s\n' "$RULE_SOURCE" >&2 + exit 1 +fi + +if ! command -v sudo >/dev/null 2>&1; then + echo "sudo não encontrado. Instale a regra udev manualmente em $RULE_DEST." >&2 + exit 1 +fi + +sudo install -Dm644 "$RULE_SOURCE" "$RULE_DEST" +sudo modprobe uinput +sudo udevadm control --reload-rules +sudo udevadm trigger --subsystem-match=misc --action=add + +systemctl --user daemon-reload +systemctl --user enable --now "$SERVICE_NAME" + +cat <<'MSG' + +Controller Bridge configurado. + +Controles: + Analógico direito -> mover cursor + A -> clique esquerdo + B -> clique direito + X -> clique do meio + Gatilho esquerdo -> rolar para cima + Gatilho direito -> rolar para baixo + +Confira o estado com: + systemctl --user status steam-media-controller-bridge.service +MSG diff --git a/udev/99-steam-media-controller-bridge.rules b/udev/99-steam-media-controller-bridge.rules new file mode 100644 index 0000000..c631253 --- /dev/null +++ b/udev/99-steam-media-controller-bridge.rules @@ -0,0 +1 @@ +KERNEL=="uinput", MODE="0660", GROUP="input", OPTIONS+="static_node=uinput" diff --git a/uninstall.sh b/uninstall.sh old mode 100644 new mode 100755 index 1edc5e9..05d9f33 --- a/uninstall.sh +++ b/uninstall.sh @@ -4,6 +4,22 @@ set -Eeuo pipefail DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +echo "Removendo Controller Bridge..." + +systemctl --user disable --now steam-media-controller-bridge.service 2>/dev/null || true + +rm -f "$HOME/.config/systemd/user/steam-media-controller-bridge.service" + +systemctl --user daemon-reload + +if [ -f /etc/udev/rules.d/99-steam-media-controller-bridge.rules ]; then + sudo rm -f /etc/udev/rules.d/99-steam-media-controller-bridge.rules + sudo udevadm control --reload-rules + sudo udevadm trigger +fi + +rm -rf "$HOME/.local/share/steam-media-pack/controller-bridge" + rm -rf "$DATA_HOME/steam-media-pack" rm -rf "$CONFIG_HOME/steam-media-pack" rm -f "$DATA_HOME/applications"/steam-media-*.desktop