Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ Tools/compilar.sh simulador # abre el simulador en este escritorio (X11)
- **Ajustes del sistema**: el sistema es la fuente de verdad. `packaging/zeropower-helper`
(bash, se instala en `/usr/lib/zeropower/`): `status` sin root; `set <ajuste> <valor>` y
`restore` con root, por `sudo -n` con el sudo sin contraseña que trae el usuario del aparato
(`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). **La tienda no deja
(`bruno ALL=(ALL) NOPASSWD:ALL` en `90-cloud-init-users`, del Imager). Si sudo pide
contraseña (`classify_sudo` en `src/model/sudo_password.h`), `SettingsScreen` la pide encima
de la lista y `PowerControl::apply` repite con `sudo -S -p ""`, pasándola por la entrada
estándar de `run_process` y borrándola al acabar (`SecretInput`, `wipe`). En el simulador se
prueba con `ZEROPOWER_SIMULATE_SUDO=<clave>`. Para teclearla, `linux_input` entiende Shift
y la capa Sym del Cardputer (lee `/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map`), y
la T no cambia el tema mientras se escribe (`set_text_entry`). **La tienda no deja
instalar sudoers** (ni en `/etc/sudoers.d` ni desde los scripts: busca `/etc/sudoers`), ni
polkit. Guarda el original de cada ajuste en `/var/lib/zeropower/original/` y `restore`
(en el `prerm`) lo devuelve. **No hay servicio de root al arrancar** (la tienda rechaza
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@ volver a aplicarlo. **Al desinstalar ZeroPower, todo lo que cambió vuelve a com
`/usr/lib/zeropower/zeropower-helper status` (sin root).
- **Para cambiar algo** llama a `sudo -n /usr/lib/zeropower/zeropower-helper set <ajuste> <valor>`,
con el `sudo` sin contraseña que el usuario del aparato ya trae de fábrica (lo pone el
Raspberry Pi Imager). ZeroPower **no instala ningún fichero de sudoers** ni da permisos
nuevos; sin sudo sin contraseña, la app avisa y no cambia nada. El ayudante es un script de
Raspberry Pi Imager). Si tu usuario necesita contraseña para sudo, la app la pide en
pantalla y repite el cambio con `sudo -S`: la contraseña va por la entrada estándar (nunca
en la línea de órdenes), no se guarda y se borra de la memoria al acabar; sudo la recuerda
unos minutos, como en un terminal. ZeroPower **no instala ningún fichero de sudoers** ni da
permisos nuevos; un usuario sin sudo no puede cambiar nada. El ayudante es un script de
bash corto que acepta una lista cerrada de ajustes y valores; la primera vez que cambia
algo guarda su valor original en `/var/lib/zeropower/original/` para poder devolverlo
(`zeropower-helper restore`, que se ejecuta al desinstalar).
Expand Down
2 changes: 1 addition & 1 deletion app-builder.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"description": "Battery saver and power settings for the Cardputer Zero",
"store": {
"summary": "Battery saver: live power draw, turn off Ethernet, HDMI, BT, services",
"description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm) and the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM).\n- Services: Tailscale, background extras (NFS, rpcbind, avahi, apt timers) and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off pauses the launcher and parks its audio (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's passwordless sudo (as set up by Raspberry Pi Imager); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).",
"description": "Make the Cardputer Zero last longer. See the live power draw from the battery gauge, then turn off for good what a handheld does not need, and undo it just as easily.\n\n- Battery: average draw over the last 30 s, charge, voltage and time left, with the last minute as bars. R restarts the average, so you can see what each setting saves.\n- Hardware: internal USB Ethernet (On / Auto-suspend / Off, ~90 mA less), Wi-Fi, Bluetooth, the HDMI desktop (lightdm) and the GPU memory split (16 MB is enough for the built-in screen: 48 MB more RAM).\n- Services: Tailscale, background extras (NFS, rpcbind, avahi, apt timers) and system logs in RAM.\n- Power saving (zeropowerd, a service running as the device user, not root): screen off pauses the launcher and parks its audio (a key wakes it), quiet launcher (no key sounds), a clean power-off at low battery, and a screen timeout that turns the screen off after a few minutes without a key, as a safety net for when the launcher or an app leaves it on.\n\nSettings stay in the system itself and survive reboots. Uninstalling ZeroPower puts every changed setting back. System changes go through a small helper that accepts a fixed list of settings, run with the device user's sudo: passwordless as set up by Raspberry Pi Imager, or ZeroPower asks for the password on screen (never stored); no sudoers file is installed.\n\nMeasured on a Cardputer Zero with the screen off: 301 mA -> 209 mA just with Ethernet auto-suspend. Ideas and first measurements from cz-battery-saver by InstantComet (MIT).",
"categories": [
"System Tools"
],
Expand Down
6 changes: 3 additions & 3 deletions src/app/app.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class ShortcutController {
const auto result = platform::screenshot::capture_active_screen();
if (result.success) {
LOG_INFO("screenshot saved: {}", result.path);
toast_->show_highlighted("Guardada en ",
toast_->show_highlighted("Saved to ",
result.path,
"",
view::widgets::ToastTone::Success,
Expand All @@ -163,7 +163,7 @@ class ShortcutController {
}
else {
LOG_WARN("screenshot failed: {}", result.error);
toast_->show("No se pudo capturar: " + result.error,
toast_->show("Screenshot failed: " + result.error,
view::widgets::ToastTone::Error,
3200);
}
Expand Down Expand Up @@ -230,7 +230,7 @@ class ShortcutController {
if (!view_model_.back()) {
// Ya no hay adónde volver: se recuerda cómo se sale en vez de salir con
// una pulsación que pudo ser de más.
toast_->show_highlighted("Mantén ", "ESC", " para salir", view::widgets::ToastTone::Warning, 2200);
toast_->show_highlighted("Hold ", "ESC", " to exit", view::widgets::ToastTone::Warning, 2200);
}
}

Expand Down
95 changes: 95 additions & 0 deletions src/model/sudo_password.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* SPDX-License-Identifier: MIT
*/

#include "sudo_password.h"

namespace power {
namespace {

bool contains(const std::string& text, const char* what) {
return text.find(what) != std::string::npos;
}

} // namespace

SudoOutcome classify_sudo(int exit_code, const std::string& output) {
if (exit_code == 0) {
return SudoOutcome::Ok;
}
// "Sorry, try again." sale en cuanto una contraseña falla, aunque luego diga otra cosa.
if (contains(output, "incorrect password") || contains(output, "Sorry, try again")) {
return SudoOutcome::WrongPassword;
}
if (contains(output, "a password is required") || contains(output, "no password was provided")) {
return SudoOutcome::NeedsPassword;
}
if (contains(output, "is not in the sudoers") || contains(output, "is not allowed to") ||
contains(output, "may not run sudo")) {
return SudoOutcome::NotAllowed;
}
return SudoOutcome::Failed;
}

void wipe(std::string& text) {
volatile char* p = text.empty() ? nullptr : &text[0];
for (std::size_t i = 0; i < text.size(); ++i) {
p[i] = '\0';
}
text.clear();
}

SecretInput::SecretInput() {
text_.reserve(kMaxLength + 1); // +1: el salto de línea de take_line()
}

SecretInput::~SecretInput() {
clear();
}

bool SecretInput::add(std::uint32_t ch) {
if (ch < 0x20 || ch > 0x7E || text_.size() >= kMaxLength) {
return false;
}
text_.push_back(static_cast<char>(ch));
return true;
}

bool SecretInput::backspace() {
if (text_.empty()) {
return false;
}
text_.back() = '\0';
text_.pop_back();
return true;
}

void SecretInput::clear() {
wipe(text_);
}

std::string SecretInput::masked(std::size_t max_dots) const {
std::string out;
std::size_t dots = text_.size();
if (dots > max_dots) {
out = "\u2026";
dots = max_dots;
}
for (std::size_t i = 0; i < dots; ++i) {
out += "\u2022";
}
return out;
}

std::string SecretInput::take_line() {
// Siempre en el montón (más de lo que cabe dentro del propio std::string): al moverla de
// un sitio a otro se pasa el puntero y no quedan copias sueltas.
std::string line;
line.reserve(kMaxLength + 1);
line = text_;
line.push_back('\n');
clear();
return line;
}

} // namespace power
61 changes: 61 additions & 0 deletions src/model/sudo_password.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* SPDX-License-Identifier: MIT
*/

#pragma once

#include <cstddef>
#include <cstdint>
#include <string>

namespace power {

// Qué ha pasado con una orden lanzada con sudo, según su código de salida y lo que dice
// (sudo se lanza con LC_ALL=C: los mensajes llegan en inglés).
enum class SudoOutcome {
Ok, // la orden se ejecutó y acabó bien
NeedsPassword, // `sudo -n` sin contraseña guardada: hay que pedirla
WrongPassword, // la contraseña no vale
NotAllowed, // el usuario no puede usar sudo para esto
Failed, // la orden se ejecutó y falló, o sudo falló por otra cosa
};

SudoOutcome classify_sudo(int exit_code, const std::string& output);

// Borra el contenido de verdad (el compilador no puede quitarse la escritura de encima) y
// deja la cadena vacía.
void wipe(std::string& text);

// Lo que se teclea en la pantalla de la contraseña. Reserva la memoria de una vez, para
// que al crecer no queden copias de la contraseña por el montón, y la borra al limpiar.
class SecretInput {
public:
static constexpr std::size_t kMaxLength = 128;

SecretInput();
~SecretInput();
SecretInput(const SecretInput&) = delete;
SecretInput& operator=(const SecretInput&) = delete;

bool add(std::uint32_t ch); // sólo ASCII imprimible; false si no cabe o no vale
bool backspace();
void clear();

std::size_t size() const {
return text_.size();
}
bool empty() const {
return text_.empty();
}
// Un punto por carácter, para enseñarla sin enseñarla. Si son más de `max_dots`, sólo
// los últimos, detrás de «…».
std::string masked(std::size_t max_dots = kMaxLength) const;
// Lo tecleado seguido de un salto de línea (lo que espera `sudo -S`), y se borra de aquí.
// Quien lo recibe tiene que borrarlo con wipe() al acabar.
std::string take_line();

private:
std::string text_;
};

} // namespace power
137 changes: 133 additions & 4 deletions src/platform/linux_input.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ struct EvdevKeypad {
bool router_event_pending{false};
uint32_t router_key{0};
bool router_pressed{false};
bool cardputer{false}; // el teclado del Cardputer (tca8418), con su capa Sym
bool shift{false};
// Lo que dio cada tecla al pulsarla: al soltarla tiene que salir lo mismo aunque
// entretanto se haya soltado Shift, o se quedaría pulsada.
std::array<uint32_t, KEY_CNT> pressed_as{};
};
#endif

Expand Down Expand Up @@ -242,10 +247,118 @@ uint32_t map_evdev_char(uint16_t code) {
return 0;
}

uint32_t map_evdev_key(uint16_t code) {
// Teclado de PC (distribución de EE. UU.): lo que dan los números y signos con Shift, y los
// signos que map_evdev_char no trae (sólo hacen falta para escribir la contraseña).
uint32_t map_us_symbol(uint16_t code, bool shift) {
static constexpr struct {
uint16_t code;
char plain;
char shifted;
} kSymbols[] = {
{KEY_1, '1', '!'}, {KEY_2, '2', '@'}, {KEY_3, '3', '#'},
{KEY_4, '4', '$'}, {KEY_5, '5', '%'}, {KEY_6, '6', '^'},
{KEY_7, '7', '&'}, {KEY_8, '8', '*'}, {KEY_9, '9', '('},
{KEY_0, '0', ')'}, {KEY_MINUS, '-', '_'}, {KEY_EQUAL, '=', '+'},
{KEY_LEFTBRACE, '[', '{'}, {KEY_RIGHTBRACE, ']', '}'}, {KEY_SEMICOLON, ';', ':'},
{KEY_APOSTROPHE, '\'', '"'}, {KEY_GRAVE, '`', '~'}, {KEY_BACKSLASH, '\\', '|'},
{KEY_COMMA, ',', '<'}, {KEY_DOT, '.', '>'}, {KEY_SLASH, '/', '?'},
{KEY_KPASTERISK, '*', '*'}, {KEY_KPSLASH, '/', '/'}, {KEY_KPDOT, '.', '.'},
};
for (const auto& entry : kSymbols) {
if (entry.code == code) {
return static_cast<uint32_t>(shift ? entry.shifted : entry.plain);
}
}
return 0;
}

// La capa Sym del Cardputer: el teclado manda códigos propios para cada signo, que no son
// los de un teclado de PC (el 51, la coma de un PC, aquí es «&»). Se leen de su mapa de
// teclas, que trae el sistema, y si no está, los de la versión que hay ahora.
constexpr const char* kCardputerKeymap = "/usr/share/keymaps/tca8418_keypad_m5stack_keymap.map";

uint32_t keysym_char(const std::string& name) {
static constexpr struct {
const char* name;
char ch;
} kNames[] = {
{"exclam", '!'}, {"at", '@'}, {"numbersign", '#'}, {"dollar", '$'},
{"percent", '%'}, {"asciicircum", '^'}, {"ampersand", '&'}, {"asterisk", '*'},
{"parenleft", '('}, {"parenright", ')'}, {"asciitilde", '~'}, {"grave", '`'},
{"underscore", '_'}, {"minus", '-'}, {"plus", '+'}, {"equal", '='},
{"bracketleft", '['}, {"bracketright", ']'}, {"braceleft", '{'}, {"braceright", '}'},
{"semicolon", ';'}, {"colon", ':'}, {"apostrophe", '\''}, {"quotedbl", '"'},
{"less", '<'}, {"greater", '>'}, {"backslash", '\\'}, {"bar", '|'},
{"comma", ','}, {"period", '.'}, {"slash", '/'}, {"question", '?'},
};
for (const auto& entry : kNames) {
if (name == entry.name) {
return static_cast<uint32_t>(entry.ch);
}
}
return 0;
}

const std::array<uint32_t, KEY_CNT>& cardputer_symbols() {
static const std::array<uint32_t, KEY_CNT> table = [] {
std::array<uint32_t, KEY_CNT> t{};
bool loaded = false;
if (FILE* f = std::fopen(kCardputerKeymap, "r")) {
char line[160];
while (std::fgets(line, sizeof(line), f)) {
unsigned code = 0;
char name[48] = {};
if (std::sscanf(line, " keycode %u = %47s", &code, name) == 2 && code < KEY_CNT) {
if (const uint32_t ch = keysym_char(name)) {
t[code] = ch;
loaded = true;
}
}
}
std::fclose(f);
}
if (!loaded) {
static constexpr struct {
uint16_t code;
char ch;
} kDefault[] = {
{26, '!'}, {27, '@'}, {39, '#'}, {40, '$'}, {41, '%'}, {43, '^'}, {51, '&'},
{52, '*'}, {53, '('}, {94, ')'}, {55, '~'}, {69, '`'}, {70, '_'}, {71, '-'},
{72, '+'}, {73, '='}, {74, '['}, {75, ']'}, {76, '{'}, {77, '}'}, {79, ';'},
{80, ':'}, {81, '\''}, {82, '"'}, {83, '<'}, {85, '>'}, {86, '\\'}, {89, '|'},
{90, ','}, {91, '.'}, {92, '/'}, {93, '?'},
};
for (const auto& entry : kDefault) {
t[entry.code] = static_cast<uint32_t>(entry.ch);
}
}
return t;
}();
return table;
}

uint32_t map_evdev_key(uint16_t code, const EvdevKeypad& keypad) {
if (keypad.cardputer && code < KEY_CNT) {
if (const uint32_t ch = cardputer_symbols()[code]) {
return ch;
}
}
if (const uint32_t ch = map_evdev_char(code)) {
if (keypad.shift && ch >= 'a' && ch <= 'z') {
return ch - 'a' + 'A';
}
if (!keypad.cardputer && keypad.shift) {
if (const uint32_t sym = map_us_symbol(code, true)) {
return sym;
}
}
return ch;
}
if (!keypad.cardputer) {
if (const uint32_t sym = map_us_symbol(code, keypad.shift)) {
return sym;
}
}
switch (code) {
case KEY_ESC:
return LV_KEY_ESC;
Expand Down Expand Up @@ -309,12 +422,24 @@ void evdev_read_cb(lv_indev_t* indev, lv_indev_data_t* data) {

input_event input{};
while (read(keypad->fd, &input, sizeof(input)) == sizeof(input)) {
if (input.type != EV_KEY) {
if (input.type != EV_KEY || input.value == 2 || input.code >= KEY_CNT) {
continue;
}
if (input.code == KEY_LEFTSHIFT || input.code == KEY_RIGHTSHIFT) {
keypad->shift = input.value != 0;
continue;
}

const auto key = map_evdev_key(input.code);
if (!key || input.value == 2) {
uint32_t key = 0;
if (input.value) {
key = map_evdev_key(input.code, *keypad);
keypad->pressed_as[input.code] = key;
}
else {
key = keypad->pressed_as[input.code];
keypad->pressed_as[input.code] = 0;
}
if (!key) {
continue;
}

Expand Down Expand Up @@ -347,6 +472,10 @@ void evdev_delete_cb(lv_event_t* event) {
lv_indev_t* create_keypad_from_fd(int fd) {
auto* keypad = new EvdevKeypad;
keypad->fd = fd;
char name[64] = {};
if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0) {
keypad->cardputer = std::strncmp(name, "tca8418", 7) == 0;
}

auto* indev = lv_indev_create();
if (!indev) {
Expand Down
Loading