+19









Ben Meadors
Jonathan Bennett
Jason P
Eric Sesterhenn
Vortetty
Mattatat25
Copilot
Max
Colby Dillion
Austin
Tom
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Chloe Bethel
Thomas Göttgens
Quency-D
HarukiToreda
oscgonfer
nikl
Hannes Fuchs
Nashui-Yan
Tom Fifield
Mike Robbins
WillyJL
renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Wessel
Christian Walther
Jorropo
Eric Barch
Clive Blackledge
4c91beeda9
* Don't ever define PIN_LED or BLE_LED_INVERTED (#9494) * Don't ever define PIN_LED * Deprecate BLE_LED_INVERTED * Add StatusMessage module and config overrides (#9351) * Add StatusMessage module and config overrides * Trunk * Don't reboot node simply for a StatusMessage config update * Missed in reviews - fixing send bubble (#9505) * Prefer EXT_PWR_DETECT pin over chargingVolt to detect power unplugged (#9511) * Make sure we always return a value in NodeDB::restorePreferences() (#9516) In case FScom is not defined there is no return statement. This moves the return outside of the ifdef to make sure a defined value is returned. * Inkhud battery icon improvements. (#9513) * Inkhud battery icon improvements. Fixes the battery icon draining from the flat side towards the bump, which is backwards from general design language seen on most devices By request of kr0n05_ on discord, adds the ability to mirror the battery icon which fixes that issue in another way, and is also a common design seen on other devices. * Remove option for icon mirroring * Add border + dither to battery to prevent font overlap * Fix trunk format * Code cleanup, courtesy of Xaositek. * Add reply bot module with DM-only responses and rate limiting (#9456) * Implement Meshtastic reply bot module with ping and status features Adds a reply bot module that listens for /ping, /hello, and /test commands received via direct messages or broadcasts on the primary channel. The module always replies via direct message to the sender only, reporting hop count, RSSI, and SNR. Per-sender cooldowns are enforced to reduce network spam, and the module can be excluded at build time via a compile flag. Updates include the new module source files and required build configuration changes. * Update ReplyBotModule.cpp Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/modules/ReplyBotModule.h Match the existing MESHTASTIC_EXCLUDE_* guard pattern so the module is excluded by default. Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/modules/ReplyBotModule.cpp Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Tidying up --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * HotFix for ReplyBot - Modules.cpp included and moved configuration.h (#9532) * Undefine LED_BUILTIN (#9531) Keep variant in sync with https://github.com/meshtastic/firmware/commit/df40085 Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Add agc reset attempt (#8163) * Add agc reset attempt * Add radioLibInterface include * Trunk * AGC reset don't crash, don't naively call * Update src/main.cpp Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Use Throttle function --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove unused hmx variable (#9529) The variable is not used at all in the function, remove it to silence the compiler warning. Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Rename LED_PIN to LED_POWER, move handling out of main to dedicated module (#9512) * Rename LED_PIN to LED_POWER, move handling out of main to dedicated module * Misc * Remove errant endif * Fix hop_limit upgrade detection (#9550) Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * meshtasticd: Fix install on Fedora 43 (#9556) * RPM: Include meshtasticd-start.sh (#9561) * Add Slash Key to VirtualKeyboard (#9563) Addition of ? and / to the virtual Keyboard via short and long press * Add support for CW2015 LiPo battery fuel gauge (#9564) * Add support for CW2015 LiPo battery fuel gauge * Address Copilot's concerns, minor fixups * Make LED_POWER blip even in critical battery (#9545) * Enable FORTIFY and SP for native builds (#9537) * Enable FORITFY and NX for native builds meshtasticd does have an executable stack and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and a non-executable stack. This gives the following improvements on Debian Trixie: $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH 13516 Symbols No 0 17 ./.pio/build/native/meshtasticd $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 13519 Symbols Yes 12 20 ./.pio/build/native/meshtasticd Tested with --sim mode I do not get any crashes or similar. * Enable FORTIFY and NX for native builds meshtasticd does have an executable stack and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and a non-executable stack. This gives the following improvements on Debian Trixie: $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH 13516 Symbols No 0 17 ./.pio/build/native/meshtasticd $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 13519 Symbols Yes 12 20 ./.pio/build/native/meshtasticd Tested with --sim mode I do not get any crashes or similar. * Enable FORTIFY and SP for native builds meshtasticd does have a stack canaries and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and stack canaries. This gives the following improvements on Debian Trixie: $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH 13516 Symbols No 0 17 ./.pio/build/native/meshtasticd $ checksec --file=./.pio/build/native/meshtasticd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 13519 Symbols Yes 12 20 ./.pio/build/native/meshtasticd Tested with --sim mode I do not get any crashes or similar. --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Update built-in documentation for current method of implementation (#9592) * Refactor logging in ProtobufModule to ensure message details are logged after successful decoding (#9536) * Automated version bumps (#9604) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Add missing openocd_target to custom nrf52 boards (#9603) This stops platformio complaining about `Missing target configuration for me25ls01-4y10td` etc when trying to flash with nrfutil. * Add sdl libs for native builds (#9595) * Add sdl libs for native builds * Alpine try again * fix some random compiler warnings (#9596) * Modify the dependency library of v4-tft (#9507) * BaseUI: Favorite Screen Signal Quality improvement (#9566) * Favorite Signal Quality improvement * Show Voltage if node shares it. * Trunk Fix * Change Favorite tittle to encase name with Asterisks * Add Pluggin In condition for Battery Line * Adjust getUptimeStr Prefixes * Create isAPIConnected for SharedCommon usage * Correct leftSideSpacing to account for isAPIConnected --------- Co-authored-by: Jason P <applewiz@mac.com> * ExternalNotification and StatusLED now call AmbientLighting to update… (#9554) * ExternalNotification and StatusLED now call AmbientLighting to update RGB LEDs. Add optional heartbeat * Don't overwrite RGB state if heartbeat is disabled. * Use the right define * Remove another .h and make rgb static * move rgb objects into AmbientLighting class * Straighten out AmbientLighting Thread object * Use %f for floats * Fixes on SCD4X admin comands (#9607) * Fixes on SCD4X admin comands * Minor fix in logs for SEN5X --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * feat/add sfa30 (#9372) * Move PMSA003I to separate class and update AQ telemetry * AirQualityTelemetry module not depend on PM sensor presence * Remove commented line * Fixes on PMS class * Add missing warmup period to wakeUp function * Fixes on compilation for different variants * Add functions to check for I2C bus speed and set it * Initial implementation for SFA30Sensor * Move PMSA003I to separate class and update AQ telemetry * AirQualityTelemetry module not depend on PM sensor presence * Remove commented line * Fixes on PMS class * Add missing warmup period to wakeUp function * Fixes on compilation for different variants * Add functions to check for I2C bus speed and set it * Add ScreenFonts.h Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de> * PMSA003I 1st round test * Fix I2C scan speed * Fix minor issues and bring back I2C SPEED def * Remove PMSA003I library as its no longer needed * Add functional SCD4X * Fix screen frame for CO2 * Add admin commands to SCD4X class * Add further admin commands and fixes. * Remove unused I2C speed functions and cleanup * Cleanup of SEN5X specific code added from switching branches * Remove SCAN_I2C_CLOCK_SPEED block as its not needed * Remove associated functions for setting I2C speed * Unify build epoch to add flag in platformio-custom.py (#7917) * Unify build_epoch replacement logic in platformio-custom * Missed one * Fix build error in rak_wismesh_tap_v2 (#7905) In the logs was: "No screen resolution defined in build_flags. Please define DISPLAY_SIZE." set according to similar devices. * Put guards in place around debug heap operations (#7955) * Put guards in place around debug heap operations * Add macros to clean up code * Add pointer as well * Cleanup * Fix memory leak in NextHopRouter: always free packet copy when removing from pending * Formatting * Only queue 2 client notification * Merge pull request #7965 from compumike/compumike/fix-nrf52-bluetooth-memory-leak Fix memory leak in `NRF52Bluetooth`: allocate `BluetoothStatus` on stack, not heap * Merge pull request #7964 from compumike/compumike/fix-nimble-bluetooth-memory-leak Fix memory leak in `NimbleBluetooth`: allocate `BluetoothStatus` on stack, not heap * Update protobufs (#7973) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * T-Lora Pager: Support LR1121 and SX1280 models (#7956) * T-Lora Pager: Support LR1121 and SX1280 models * Remove ifdefs * Trunk * Trunk * Static memory pool allocation (#7966) * Static memory pool * Initializer * T-Lora Pager: Support LR1121 and SX1280 models (#7956) * T-Lora Pager: Support LR1121 and SX1280 models * Remove ifdefs --------- Co-authored-by: WillyJL <me@willyjl.dev> * Portduino dynamic alloc * Missed * Drop the limit * Update meshtastic-esp8266-oled-ssd1306 digest to 0cbc26b (#7977) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Fix json report crashes on esp32 (#7978) * Tweak maximums * Fix DRAM overflow on old esp32 targets * Guard bad time warning logs using GPS_DEBUG (#7897) In 2.7.7 / 2.7.8 we introduced some new checks for time accuracy. In combination, these result in a spamming of the logs when a bad time is found When the GPS is active, we're calling the GPS thread every 0.2secs. So this log could be printed 4,500 times in a no-lock scenario :) Reserve this experience for developers using GPS_DEBUG. Fixes https://github.com/meshtastic/firmware/issues/7896 * Scale probe buffer size based on current baud rate (#7975) * Scale probe buffer size based on current baud rate * Throttle bad time validation logging and fix time comparison logic * Remove comment * Missed the other instances * Copy pasta * Fix GPS gm_mktime memory leak (#7981) * Fix overflow of time value (#7984) * Fix overflow of time value * Revert "Fix overflow of time value" This reverts commit 084796920179e80a7500d36c25fd4d82b3ef4214. * That got boogered up * Remove PMSA003 include from modules * Add flag to exclude air quality module * Rework PMSA003I to align with new I2C scanner * Reworks AQ telemetry to match new dynamic allocation method * Adds VBLE_I2C_CLOCK_SPEED build flag for sensors with different I2C speed requirements * Reworks PMSA003I * Move add sensor template to separate file * Split telemetry on screen options * Add variable I2C clock compile flag * Added to Seeed Xiao S3 as demo * Fix drawFrame in AQ module * Module settings override to i2cScan module function * Move to CAN_RECLOCK_I2C per architecture * Add reclock function in TelemetrySensor.cpp * Add flag in ESP32 common * Minor fix * Move I2C reclock function to src/detect * Fix uninitMemberVar errors and compile issue * Make sleep, wakeUp functions generic * Fix STM32 builds * Add exclude AQ sensor to builds that have environmental sensor excludes * Add includes to AddI2CSensorTemplate.h * SEN5X first pass * WIP Sen5X functions * Further (non-working) progress in SEN5X * WIP Sen5X functions * Changes on SEN5X library - removing pm_env as well * Small cleanup of SEN5X sensors * Minor change for SEN5X detection * Remove dup code * Enable PM sensor before sending telemetry. This enables the PM sensor for a predefined period to allow for warmup. Once telemetry is sent, the sensor shuts down again. * Small cleanups in SEN5X sensor * Add dynamic measurement interval for SEN5X * Only disable SEN5X if enough time after reading. * Idle for SEN5X on communication error * Cleanup of logs and remove unnecessary delays * Small TODO * Settle on uint16_t for SEN5X PM data * Make AQTelemetry sensors non-exclusive * Implementation of cleaning in FS prefs and cleanup * Remove unnecessary LOGS * Add cleaning date storage in FS * Report non-cumulative PN * Bring back detection code for SEN5X after branch rebase * Add placeholder for admin message * Add VOC measurements and persistence (WIP) * Adds VOC measurements and state * Still not working on VOC Index persistence * Should it stay in continuous mode? * Add one-shot mode config flag to SEN5X * Add nan checks on sensor data from SEN5X * Working implementation on VOCState * Adds initial timer for SEN55 to not sleep if VOCstate is not stable (1h) * Adds conditions for stability and sensor state * Fixes on VOC state and mode swtiching * Adds a new RHT/Gas only mode, with 3600s stabilization time * Fixes the VOCState buffer mismatch * Fixes SEN50/54/55 model mistake * Adapt SEN5X to new sensor list structure. Improve reclock. * Improve reClockI2C conditions for different variants * Add sleep, wakeUp, pendingForReady, hasSleep functions to PM sensors to save battery * Add SEN5X * Fix merge errors * Small reordering in PMS class for consistency * If one sensor fails, AQ telemetry still reports data * Small formatting fix * Add SEN5X to AQI in ScanI2C * SCD4X now part of AQ module with template list * Fixes difference between idle and sleep * In LowPower, sleep is disabled * Requires testing for I2C clock comms for commands * Remove unnecessary import * Add co2 to serialized AQ metrics * Add SFA30 with new sensor template in AQ module * Update library dependencies in platformio.ini * Fix unitialized variables in SEN5X constructor * Fix missing import * Fix uninitMemberVars * Fix import error for SCD4X * Fix I2CClock logic * Fix not reclocking back to 700000Hz * Fix multiple sensors being read simultaneously * The logic in AQ module is different to the one in EnvironmentTelemetryModule. In Env module, if any sensor fails to getMetrics, no valid flag for the module. This prevents other sensors to report data. * Fix pending clock change in PMSA003 * Cleanup of SEN5X class * Exclude AQ sensor from wio-e5 due to flash limitations * Fix I2C clock change logic * Make sure clock is always set to needed value * Fix returns * Fix trunk * Fix on condition in reclock * Fix trunk * Final SFA30 class implementation * Add HCHO to screen and improve logs * Add metrics to mesh packet serializer * Minor fixes in logs * OCD tidy up of logs * Fix sleep function * Remove old I2C_CLOCK_SPEED code --------- Co-authored-by: nikl <nikl174@mailbox.org> Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de> Co-authored-by: Nashui-Yan <yannashui10@gmail.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Tom Fifield <tom@tomfifield.net> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> Co-authored-by: WillyJL <me@willyjl.dev> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Log rxBad PacketHeaders with more info (id, relay_node) like printPacket, so we can try to match RX errors to other packets in the logs. (#9614) * Exclude status message module * fix: zero entire public key array instead of only first byte (#9619) * Update protobufs (#9621) * Xiao NRF - define suitable i2c pins for the sub-variants (#8866) Co-authored-by: Christian Walther <cwalther@gmx.ch> * Update src/detect/ScanI2C.cpp Co-authored-by: Wessel <wessel@weebl.me> * Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp Co-authored-by: Wessel <wessel@weebl.me> * Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp Co-authored-by: Wessel <wessel@weebl.me> * Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp Co-authored-by: Wessel <wessel@weebl.me> * Update src/mesh/NodeDB.cpp Co-authored-by: Wessel <wessel@weebl.me> * convert GPS global and some new in gps.cpp to unique_ptr (#9628) Trying this to see if anything bad happen if I were to replace most raw pointers with unique_ptr. I didn't used std::make_unique since it is only supported in C++14 and onwards but until we update esp32 to arduino 3.x the ESP32 xtensa chips use a C++11 std. * replace delete in RedirectablePrint.cpp with std::unique_ptr (#9642) Is part of the unique_ptr modernization effort. * replace delete in EInkDynamicDisplay.{cpp,h} with std::unique_ptr (#9643) Is part of the unique_ptr modernization effort. * Undefine LED_BUILTIN for Heltec v2 variant (#9647) * Undefine LED_BUILTIN for Heltec v2 variant * Undefine LED_BUILTIN for Heltec v2.1 variant --------- Co-authored-by: Jorropo <jorropo.pgm@gmail.com> * replace delete in RadioInterface.cpp with std::unique_ptr (#9645) Is part of the unique_ptr modernization effort. * fix typo in PIN_GPS_SWITCH (#9648) Wasn't caught by CI. * replace delete in CryptoEngine.{cpp,h} with std::unique_ptr (#9649) Is part of the unique_ptr modernization effort. * workaround NCP5623 and LP5562 I2C builds (#9652) Theses two appear to be buggy on r1-neo and nomadstar meteor pro, they rely on Wire.h being included previously to their import. Idk why other platforms using the same smart LEDs are working while theses ones don't. This should make CI green on the dev branch. * replace delete in AudioThread.h with std::unique_ptr (#9651) Is part of the unique_ptr modernization effort. * Add USB_MODE=1 for Station G2 (#9660) * InkHUD: Favorite Map Applet (#9654) * fix a lot of low level cppcheck warnings (#9623) * simplify the observer pattern, since all the called functions are const getters. * use arduino macro over std: for numerical values and refactor local variables in drawScrollbar() * oh, so Cppcheck actually complained about const pointers not being const. * slowly getting out of ifdef hell * fix inkHUD warnings as well * last 2 check warnings * git checks should fail on low defects from now on * Feat/add scd30 (#9609) * Merge develop into SCD30 * Add SCD30 class * Fix logging and admin commands * Minor cleanup and logging improvements * Minor formatting issue Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Improvements on setTemperature * Fix casting float-uint16_t * Pass 100 for resetting temperature offset * Fix issues pointed out by copilot * Add quick reboot to set interval quicker on scd30 * Change saveState to only happen after boot and minor log changes * Fix missing semicolon in one shot mode log --------- Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * fix: respect DontMqttMeBro flag regardless of channel PSK (#9626) The previous PSK check was broken from its introduction in #4643 — memcmp was used in boolean context without comparing to 0, inverting the condition. Since no one noticed for over a year, the PSK-based filtering provided no practical value. Simplifying to always respect the sender's preference is both more correct and easier to reason about. * our firmware action is too clever Update pio_target and add pio_opts for checks. * fix detection of SCD30 by checking if the size of the return from a 2 byte register read is correct (#9664) * fix detection of SCD30 by checking if thee size of the return from a 2 byte register read is correct fix signedness warning in PMSA003 sensor code. * Add alternate path for LPS22HB Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * check EndTransmission for errors and compare returned length to expected value Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * #9623 resolved a local shadow of next_key by converting it to int. (#9665) * zip a few gitrefs down (#9672) * InkHUD: Allow non-system applets to subscribe to input events (#9514) * Allow inkhud user applets to consume inputs with opt-in system Adds a way for applets to subscribe to input events while keeping it off by default to preserve compatibility and expected behaviours. Adds example for use as well. * Add check for nullptr on getActiveApplet uses * Remove redundant includes * Move subscribedInputs to protected * More consistent naming scheme * Fake IAQ values on Non-BSEC2 platforms like Platformio and the original ESP32 (#9663) * BSEC2 Replacement - add approximation for IAQ to non-BSEC2 platforms. - Re-add this sensor to ESP32 targets, and refactor env_extra includes. - Fix C++ 11 compatibility * Check for gas resistance 0 * ULED_BUILTIN for 9m2ibr_aprs_lora_tracker (#9685) --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Jason P <applewiz@mac.com> Co-authored-by: Eric Sesterhenn <eric.sesterhenn@x41-dsec.de> Co-authored-by: Vortetty <33466216+Vortetty@users.noreply.github.com> Co-authored-by: Mattatat25 <108779801+mattatat25@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Max <rekin.m@gmail.com> Co-authored-by: Colby Dillion <colby.dillion@pacshealth.com> Co-authored-by: Austin <vidplace7@gmail.com> Co-authored-by: Tom <116762865+NomDeTom@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Chloe Bethel <chloe@9net.org> Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com> Co-authored-by: Quency-D <55523105+Quency-D@users.noreply.github.com> Co-authored-by: HarukiToreda <116696711+HarukiToreda@users.noreply.github.com> Co-authored-by: oscgonfer <oscgonfer@users.noreply.github.com> Co-authored-by: nikl <nikl174@mailbox.org> Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de> Co-authored-by: Nashui-Yan <yannashui10@gmail.com> Co-authored-by: Tom Fifield <tom@tomfifield.net> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> Co-authored-by: WillyJL <me@willyjl.dev> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Wessel <wessel@weebl.me> Co-authored-by: Christian Walther <cwalther@gmx.ch> Co-authored-by: Jorropo <jorropo.pgm@gmail.com> Co-authored-by: Eric Barch <ericb@ericbarch.com> Co-authored-by: Clive Blackledge <clive@ansible.org>
749 lines
26 KiB
C++
749 lines
26 KiB
C++
#include "configuration.h"
|
|
#if HAS_SCREEN
|
|
#include "VirtualKeyboard.h"
|
|
#include "graphics/Screen.h"
|
|
#include "graphics/ScreenFonts.h"
|
|
#include "graphics/SharedUIDisplay.h"
|
|
#include "main.h"
|
|
#include <Arduino.h>
|
|
#include <vector>
|
|
|
|
namespace graphics
|
|
{
|
|
|
|
VirtualKeyboard::VirtualKeyboard() : cursorRow(0), cursorCol(0), lastActivityTime(millis())
|
|
{
|
|
initializeKeyboard();
|
|
// Set cursor to H(2, 5)
|
|
cursorRow = 2;
|
|
cursorCol = 5;
|
|
}
|
|
|
|
VirtualKeyboard::~VirtualKeyboard() {}
|
|
|
|
void VirtualKeyboard::initializeKeyboard()
|
|
{
|
|
// New 4 row, 11 column keyboard layout:
|
|
static const char LAYOUT[KEYBOARD_ROWS][KEYBOARD_COLS] = {{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\b'},
|
|
{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '\n'},
|
|
{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', ' '},
|
|
{'z', 'x', 'c', 'v', 'b', 'n', 'm', '.', ',', '?', '\x1b'}};
|
|
|
|
// Derive layout dimensions and assert they match the configured keyboard grid
|
|
constexpr int LAYOUT_ROWS = (int)(sizeof(LAYOUT) / sizeof(LAYOUT[0]));
|
|
constexpr int LAYOUT_COLS = (int)(sizeof(LAYOUT[0]) / sizeof(LAYOUT[0][0]));
|
|
static_assert(LAYOUT_ROWS == KEYBOARD_ROWS, "LAYOUT rows must equal KEYBOARD_ROWS");
|
|
static_assert(LAYOUT_COLS == KEYBOARD_COLS, "LAYOUT cols must equal KEYBOARD_COLS");
|
|
|
|
// Initialize all keys to empty first
|
|
for (int row = 0; row < LAYOUT_ROWS; row++) {
|
|
for (int col = 0; col < LAYOUT_COLS; col++) {
|
|
keyboard[row][col] = {0, VK_CHAR, 0, 0, 0, 0};
|
|
}
|
|
}
|
|
|
|
// Fill keyboard from the 2D layout
|
|
for (int row = 0; row < LAYOUT_ROWS; row++) {
|
|
for (int col = 0; col < LAYOUT_COLS; col++) {
|
|
char ch = LAYOUT[row][col];
|
|
// No empty slots in the simplified layout
|
|
|
|
VirtualKeyType type = VK_CHAR;
|
|
if (ch == '\b') {
|
|
type = VK_BACKSPACE;
|
|
} else if (ch == '\n') {
|
|
type = VK_ENTER;
|
|
} else if (ch == '\x1b') { // ESC
|
|
type = VK_ESC;
|
|
} else if (ch == ' ') {
|
|
type = VK_SPACE;
|
|
}
|
|
|
|
// Make action keys wider to fit text while keeping the last column aligned
|
|
uint8_t width = (type == VK_BACKSPACE || type == VK_ENTER || type == VK_SPACE) ? (KEY_WIDTH * 3) : KEY_WIDTH;
|
|
keyboard[row][col] = {ch, type, (uint8_t)(col * KEY_WIDTH), (uint8_t)(row * KEY_HEIGHT), width, KEY_HEIGHT};
|
|
}
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::draw(OLEDDisplay *display, int16_t offsetX, int16_t offsetY)
|
|
{
|
|
// Repeat ticking is driven by NotificationRenderer once per frame
|
|
// Base styles
|
|
display->setColor(WHITE);
|
|
display->setFont(FONT_SMALL);
|
|
|
|
// Screen geometry
|
|
const int screenW = display->getWidth();
|
|
const int screenH = display->getHeight();
|
|
|
|
// Decide wide-screen mode: if there is comfortable width, allow taller keys and reserve fixed width for last column labels
|
|
// Heuristic: if screen width >= 200px (e.g., 240x135), treat as wide
|
|
const bool isWide = screenW >= 200;
|
|
|
|
// Determine last-column label max width
|
|
display->setFont(FONT_SMALL);
|
|
const int wENTER = display->getStringWidth("ENTER");
|
|
int lastColLabelW = wENTER; // ENTER is usually the widest
|
|
// Smaller padding on very small screens to avoid excessive whitespace
|
|
const int lastColPad = (screenW <= 128 ? 2 : 6);
|
|
const int reservedLastColW = lastColLabelW + lastColPad; // reserved width for last column keys
|
|
|
|
// Always reserve width for the rightmost text column to avoid overlap on small screens
|
|
int cellW = 0;
|
|
int leftoverW = 0;
|
|
{
|
|
const int leftCols = KEYBOARD_COLS - 1; // 10 input characters
|
|
int usableW = screenW - reservedLastColW;
|
|
if (usableW < leftCols) {
|
|
// Guard: ensure at least 1px per left cell if labels are extremely wide (unlikely)
|
|
usableW = leftCols;
|
|
}
|
|
cellW = usableW / leftCols;
|
|
leftoverW = usableW - cellW * leftCols; // distribute extra pixels over left columns (left to right)
|
|
}
|
|
|
|
// Dynamic key geometry
|
|
int cellH = KEY_HEIGHT;
|
|
int keyboardStartY = 0;
|
|
if (screenH <= 64) {
|
|
const int headerHeight = headerText.empty() ? 0 : (FONT_HEIGHT_SMALL - 2);
|
|
const int gapBelowHeader = 0;
|
|
const int singleLineBoxHeight = FONT_HEIGHT_SMALL;
|
|
const int gapAboveKeyboard = 0;
|
|
keyboardStartY = offsetY + headerHeight + gapBelowHeader + singleLineBoxHeight + gapAboveKeyboard;
|
|
if (keyboardStartY < 0)
|
|
keyboardStartY = 0;
|
|
if (keyboardStartY > screenH)
|
|
keyboardStartY = screenH;
|
|
int keyboardHeight = screenH - keyboardStartY;
|
|
cellH = std::max(1, keyboardHeight / KEYBOARD_ROWS);
|
|
} else if (isWide) {
|
|
// For wide screens (e.g., T114 240x135), prefer square keys: height equals left-column key width.
|
|
cellH = std::max((int)KEY_HEIGHT, cellW);
|
|
|
|
// Guarantee at least 2 lines of input are visible by reducing cell height minimally if needed.
|
|
// Replicate the spacing used in drawInputArea(): headerGap=1, box-to-header gap=1, gap above keyboard=1
|
|
display->setFont(FONT_SMALL);
|
|
const int headerHeight = headerText.empty() ? 0 : (FONT_HEIGHT_SMALL + 1);
|
|
const int headerToBoxGap = 1;
|
|
const int gapAboveKb = 1;
|
|
const int minBoxHeightForTwoLines = 2 * FONT_HEIGHT_SMALL + 2; // inner 1px top/bottom
|
|
int maxKeyboardHeight = screenH - (offsetY + headerHeight + headerToBoxGap + minBoxHeightForTwoLines + gapAboveKb);
|
|
int maxCellHAllowed = maxKeyboardHeight / KEYBOARD_ROWS;
|
|
if (maxCellHAllowed < (int)KEY_HEIGHT)
|
|
maxCellHAllowed = KEY_HEIGHT;
|
|
if (maxCellHAllowed > 0 && cellH > maxCellHAllowed) {
|
|
cellH = maxCellHAllowed;
|
|
}
|
|
// Keyboard placement from bottom for wide screens
|
|
int keyboardHeight = KEYBOARD_ROWS * cellH;
|
|
keyboardStartY = screenH - keyboardHeight;
|
|
if (keyboardStartY < 0)
|
|
keyboardStartY = 0;
|
|
} else {
|
|
// Default (non-wide, non-64px) behavior: use key height heuristic and place at bottom
|
|
cellH = KEY_HEIGHT;
|
|
int keyboardHeight = KEYBOARD_ROWS * cellH;
|
|
keyboardStartY = screenH - keyboardHeight;
|
|
if (keyboardStartY < 0)
|
|
keyboardStartY = 0;
|
|
}
|
|
|
|
// Draw input area above keyboard
|
|
drawInputArea(display, offsetX, offsetY, keyboardStartY);
|
|
|
|
// Precompute per-column x and width with leftover distributed over left columns for even spacing
|
|
int colX[KEYBOARD_COLS];
|
|
int colW[KEYBOARD_COLS];
|
|
int runningX = offsetX;
|
|
for (int col = 0; col < KEYBOARD_COLS - 1; ++col) {
|
|
int wcol = cellW + (col < leftoverW ? 1 : 0);
|
|
colX[col] = runningX;
|
|
colW[col] = wcol;
|
|
runningX += wcol;
|
|
}
|
|
// Last column
|
|
colX[KEYBOARD_COLS - 1] = runningX;
|
|
colW[KEYBOARD_COLS - 1] = reservedLastColW;
|
|
|
|
// Draw keyboard grid
|
|
for (int row = 0; row < KEYBOARD_ROWS; row++) {
|
|
for (int col = 0; col < KEYBOARD_COLS; col++) {
|
|
const VirtualKey &k = keyboard[row][col];
|
|
if (k.character != 0 || k.type != VK_CHAR) {
|
|
const bool isLastCol = (col == KEYBOARD_COLS - 1);
|
|
int x = colX[col];
|
|
int w = colW[col];
|
|
int y = offsetY + keyboardStartY + row * cellH;
|
|
int h = cellH;
|
|
bool selected = (row == cursorRow && col == cursorCol);
|
|
drawKey(display, k, selected, x, y, (uint8_t)w, (uint8_t)h, isLastCol);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::drawInputArea(OLEDDisplay *display, int16_t offsetX, int16_t offsetY, int16_t keyboardStartY)
|
|
{
|
|
display->setColor(WHITE);
|
|
|
|
const int screenWidth = display->getWidth();
|
|
const int screenHeight = display->getHeight();
|
|
// Use the standard small font metrics for input box sizing (restore original size)
|
|
const int inputLineH = FONT_HEIGHT_SMALL;
|
|
|
|
// Header uses the standard small (which may be larger on big screens)
|
|
display->setFont(FONT_SMALL);
|
|
int headerHeight = 0;
|
|
if (!headerText.empty()) {
|
|
// Draw header and reserve exact font height (plus a tighter gap) to maximize input area
|
|
display->drawString(offsetX + 2, offsetY, headerText.c_str());
|
|
if (screenHeight <= 64) {
|
|
headerHeight = FONT_HEIGHT_SMALL - 2; // 11px
|
|
} else {
|
|
headerHeight = FONT_HEIGHT_SMALL; // no extra padding baked in
|
|
}
|
|
}
|
|
|
|
const int boxX = offsetX;
|
|
const int boxWidth = screenWidth;
|
|
int boxY;
|
|
int boxHeight;
|
|
if (screenHeight <= 64) {
|
|
const int gapBelowHeader = 0;
|
|
const int fixedBoxHeight = inputLineH;
|
|
const int gapAboveKeyboard = 0;
|
|
boxY = offsetY + headerHeight + gapBelowHeader;
|
|
boxHeight = fixedBoxHeight;
|
|
if (boxY + boxHeight + gapAboveKeyboard > keyboardStartY) {
|
|
int over = boxY + boxHeight + gapAboveKeyboard - keyboardStartY;
|
|
boxHeight = std::max(1, fixedBoxHeight - over);
|
|
}
|
|
} else {
|
|
const int gapBelowHeader = 1;
|
|
int gapAboveKeyboard = 1;
|
|
int tmpBoxY = offsetY + headerHeight + gapBelowHeader;
|
|
const int minBoxHeight = inputLineH + 2;
|
|
int availableH = keyboardStartY - tmpBoxY - gapAboveKeyboard;
|
|
if (availableH < minBoxHeight)
|
|
availableH = minBoxHeight;
|
|
boxY = tmpBoxY;
|
|
boxHeight = availableH;
|
|
}
|
|
|
|
// Draw box border
|
|
display->drawRect(boxX, boxY, boxWidth, boxHeight);
|
|
|
|
display->setFont(FONT_SMALL);
|
|
|
|
// Text rendering: multi-line if space allows (>= 2 lines), else single-line with leading ellipsis
|
|
const int textX = boxX + 2;
|
|
const int maxTextWidth = boxWidth - 4;
|
|
const int maxLines = (boxHeight - 2) / inputLineH;
|
|
if (maxLines >= 2) {
|
|
// Inner bounds for caret clamping
|
|
const int innerLeft = boxX + 1;
|
|
const int innerRight = boxX + boxWidth - 2;
|
|
const int innerTop = boxY + 1;
|
|
const int innerBottom = boxY + boxHeight - 2;
|
|
|
|
// Wrap text greedily into lines that fit maxTextWidth
|
|
std::vector<std::string> lines;
|
|
{
|
|
std::string remaining = inputText;
|
|
while (!remaining.empty()) {
|
|
int bestLen = 0;
|
|
for (int len = 1; len <= (int)remaining.size(); ++len) {
|
|
int w = display->getStringWidth(remaining.substr(0, len).c_str());
|
|
if (w <= maxTextWidth)
|
|
bestLen = len;
|
|
else
|
|
break;
|
|
}
|
|
if (bestLen == 0) {
|
|
// At least show one character to make progress
|
|
bestLen = 1;
|
|
}
|
|
lines.emplace_back(remaining.substr(0, bestLen));
|
|
remaining.erase(0, bestLen);
|
|
}
|
|
}
|
|
|
|
const bool scrolledUp = ((int)lines.size() > maxLines);
|
|
int caretX = textX;
|
|
int caretY = innerTop;
|
|
|
|
// Leave a small top gap to render '...' without replacing the first line
|
|
const int topInset = 2;
|
|
const int lineStep = std::max(1, inputLineH - 1); // slightly tighter than font height
|
|
int lineY = innerTop + topInset;
|
|
|
|
if (scrolledUp) {
|
|
// Draw three small dots centered horizontally, vertically at the midpoint of the gap
|
|
// between the inner top and the first line's top baseline. This avoids using a tall glyph.
|
|
const int firstLineTop = lineY; // baseline top for the first visible line
|
|
const int gapMidY = innerTop + (firstLineTop - innerTop) / 2 + 1; // shift down 1px as requested
|
|
const int centerX = boxX + boxWidth / 2;
|
|
const int dotSpacing = 3; // px between dots
|
|
const int dotSize = 1; // small square dot
|
|
display->fillRect(centerX - dotSpacing, gapMidY, dotSize, dotSize);
|
|
display->fillRect(centerX, gapMidY, dotSize, dotSize);
|
|
display->fillRect(centerX + dotSpacing, gapMidY, dotSize, dotSize);
|
|
}
|
|
|
|
// How many lines fit with our top inset and tighter step
|
|
const int linesCapacity = std::max(1, (innerBottom - lineY + 1) / lineStep);
|
|
const int linesToShow = std::min((int)lines.size(), linesCapacity);
|
|
const int startIndex = scrolledUp ? ((int)lines.size() - linesToShow) : 0;
|
|
|
|
for (int i = 0; i < linesToShow; ++i) {
|
|
const std::string &chunk = lines[startIndex + i];
|
|
display->drawString(textX, lineY, chunk.c_str());
|
|
caretX = textX + display->getStringWidth(chunk.c_str());
|
|
caretY = lineY;
|
|
lineY += lineStep;
|
|
}
|
|
|
|
// Draw caret at end of the last visible line
|
|
int caretPadY = 2;
|
|
if (boxHeight >= inputLineH + 4)
|
|
caretPadY = 3;
|
|
int cursorTop = caretY + caretPadY;
|
|
// Use lineStep so caret height matches the row spacing
|
|
int cursorH = lineStep - caretPadY * 2;
|
|
if (cursorH < 1)
|
|
cursorH = 1;
|
|
// Clamp vertical bounds to stay inside the inner rect
|
|
if (cursorTop < innerTop)
|
|
cursorTop = innerTop;
|
|
if (cursorTop + cursorH - 1 > innerBottom)
|
|
cursorH = innerBottom - cursorTop + 1;
|
|
if (cursorH < 1)
|
|
cursorH = 1;
|
|
// Only draw if cursor is inside inner bounds
|
|
if (caretX >= innerLeft && caretX <= innerRight) {
|
|
display->drawVerticalLine(caretX, cursorTop, cursorH);
|
|
}
|
|
} else {
|
|
std::string displayText = inputText;
|
|
int textW = display->getStringWidth(displayText.c_str());
|
|
std::string scrolled = displayText;
|
|
if (textW > maxTextWidth) {
|
|
// Trim from the left until it fits
|
|
while (textW > maxTextWidth && !scrolled.empty()) {
|
|
scrolled.erase(0, 1);
|
|
textW = display->getStringWidth(scrolled.c_str());
|
|
}
|
|
// Add leading ellipsis and ensure it still fits
|
|
if (scrolled != displayText) {
|
|
scrolled = "..." + scrolled;
|
|
textW = display->getStringWidth(scrolled.c_str());
|
|
// If adding ellipsis causes overflow, trim more after the ellipsis
|
|
while (textW > maxTextWidth && scrolled.size() > 3) {
|
|
scrolled.erase(3, 1); // remove chars after the ellipsis
|
|
textW = display->getStringWidth(scrolled.c_str());
|
|
}
|
|
}
|
|
} else {
|
|
// Keep textW in sync with what we draw
|
|
textW = display->getStringWidth(scrolled.c_str());
|
|
}
|
|
|
|
int textY;
|
|
if (screenHeight <= 64) {
|
|
textY = boxY + (boxHeight - inputLineH) / 2;
|
|
} else {
|
|
const int innerTop = boxY + 1;
|
|
const int innerBottom = boxY + boxHeight - 2;
|
|
|
|
// Center text vertically within inner box for single-line, then clamp so it never overlaps borders
|
|
int innerH = innerBottom - innerTop + 1;
|
|
textY = innerTop + std::max(0, (innerH - inputLineH) / 2);
|
|
// Clamp fully inside the inner rect
|
|
if (textY < innerTop)
|
|
textY = innerTop;
|
|
int maxTop = innerBottom - inputLineH + 1;
|
|
if (textY > maxTop)
|
|
textY = maxTop;
|
|
}
|
|
|
|
if (!scrolled.empty()) {
|
|
display->drawString(textX, textY, scrolled.c_str());
|
|
}
|
|
|
|
int cursorX = textX + textW;
|
|
if (screenHeight > 64) {
|
|
const int innerRight = boxX + boxWidth - 2;
|
|
if (cursorX > innerRight)
|
|
cursorX = innerRight;
|
|
}
|
|
|
|
int cursorTop, cursorH;
|
|
if (screenHeight <= 64) {
|
|
cursorH = 10;
|
|
cursorTop = boxY + (boxHeight - cursorH) / 2;
|
|
} else {
|
|
const int innerLeft = boxX + 1;
|
|
const int innerRight = boxX + boxWidth - 2;
|
|
const int innerTop = boxY + 1;
|
|
const int innerBottom = boxY + boxHeight - 2;
|
|
|
|
cursorTop = boxY + 2;
|
|
cursorH = boxHeight - 4;
|
|
if (cursorH < 1)
|
|
cursorH = 1;
|
|
if (cursorTop < innerTop)
|
|
cursorTop = innerTop;
|
|
if (cursorTop + cursorH - 1 > innerBottom)
|
|
cursorH = innerBottom - cursorTop + 1;
|
|
if (cursorH < 1)
|
|
cursorH = 1;
|
|
|
|
if (cursorX < innerLeft || cursorX > innerRight)
|
|
return;
|
|
}
|
|
|
|
display->drawVerticalLine(cursorX, cursorTop, cursorH);
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::drawKey(OLEDDisplay *display, const VirtualKey &key, bool selected, int16_t x, int16_t y, uint8_t width,
|
|
uint8_t height, bool isLastCol)
|
|
{
|
|
// Draw key content
|
|
display->setFont(FONT_SMALL);
|
|
const int fontH = FONT_HEIGHT_SMALL;
|
|
// Build label and metrics first
|
|
std::string keyText;
|
|
if (key.type == VK_BACKSPACE || key.type == VK_ENTER || key.type == VK_SPACE || key.type == VK_ESC) {
|
|
// Keep literal text labels for the action keys on the rightmost column
|
|
keyText = (key.type == VK_BACKSPACE) ? "BACK"
|
|
: (key.type == VK_ENTER) ? "ENTER"
|
|
: (key.type == VK_SPACE) ? "SPACE"
|
|
: (key.type == VK_ESC) ? "ESC"
|
|
: "";
|
|
} else {
|
|
char c = getCharForKey(key, false);
|
|
if (c >= 'a' && c <= 'z') {
|
|
c = c - 'a' + 'A';
|
|
}
|
|
keyText = (key.character == ' ' || key.character == '_') ? "_" : std::string(1, c);
|
|
// Show the common "/" pairing next to "?" like on a real keyboard
|
|
if (key.type == VK_CHAR && key.character == '?') {
|
|
keyText = "?/";
|
|
}
|
|
}
|
|
|
|
int textWidth = display->getStringWidth(keyText.c_str());
|
|
// Label alignment
|
|
// - Rightmost action column: right-align text with a small right padding (~2px) so it hugs screen edge neatly.
|
|
// - Other keys: center horizontally; use ceil-style rounding to avoid appearing left-biased on odd widths.
|
|
int textX;
|
|
if (isLastCol) {
|
|
const int rightPad = 1;
|
|
textX = x + width - textWidth - rightPad;
|
|
if (textX < x)
|
|
textX = x; // guard
|
|
} else {
|
|
if (display->getHeight() <= 64 && (key.character >= '0' && key.character <= '9')) {
|
|
textX = x + (width - textWidth + 1) / 2;
|
|
} else {
|
|
textX = x + (width - textWidth) / 2;
|
|
}
|
|
}
|
|
int contentTop = y;
|
|
int contentH = height;
|
|
if (selected) {
|
|
display->setColor(WHITE);
|
|
bool isAction = (key.type == VK_BACKSPACE || key.type == VK_ENTER || key.type == VK_SPACE || key.type == VK_ESC);
|
|
|
|
if (display->getHeight() <= 64 && !isAction) {
|
|
display->fillRect(x, y, width, height);
|
|
} else if (isAction) {
|
|
const int padX = 1;
|
|
const int padY = 2;
|
|
int hlW = textWidth + padX * 2;
|
|
int hlX = textX - padX;
|
|
|
|
if (hlX < x) {
|
|
hlW -= (x - hlX);
|
|
hlX = x;
|
|
}
|
|
int maxW = (x + width) - hlX;
|
|
if (hlW > maxW)
|
|
hlW = maxW;
|
|
if (hlW < 1)
|
|
hlW = 1;
|
|
|
|
int hlH = std::min(fontH + padY * 2, (int)height);
|
|
int hlY = y + (height - hlH) / 2;
|
|
display->fillRect(hlX, hlY, hlW, hlH);
|
|
contentTop = hlY;
|
|
contentH = hlH;
|
|
} else {
|
|
display->fillRect(x, y, width, height);
|
|
}
|
|
display->setColor(BLACK);
|
|
} else {
|
|
display->setColor(WHITE);
|
|
}
|
|
|
|
int centeredTextY;
|
|
if (display->getHeight() <= 64) {
|
|
centeredTextY = y + (height - fontH) / 2;
|
|
} else {
|
|
centeredTextY = contentTop + (contentH - fontH) / 2;
|
|
}
|
|
if (display->getHeight() > 64) {
|
|
if (centeredTextY < contentTop)
|
|
centeredTextY = contentTop;
|
|
if (centeredTextY + fontH > contentTop + contentH)
|
|
centeredTextY = std::max(contentTop, contentTop + contentH - fontH);
|
|
}
|
|
|
|
if (display->getHeight() <= 64 && keyText.size() == 1) {
|
|
char ch = keyText[0];
|
|
if (ch == '.' || ch == ',' || ch == ';') {
|
|
centeredTextY -= 1;
|
|
}
|
|
}
|
|
#ifdef MUZI_BASE // Correct issue with character vertical position on MUZI_BASE
|
|
centeredTextY -= 2;
|
|
#endif
|
|
display->drawString(textX, centeredTextY, keyText.c_str());
|
|
}
|
|
|
|
char VirtualKeyboard::getCharForKey(const VirtualKey &key, bool isLongPress)
|
|
{
|
|
if (key.type != VK_CHAR) {
|
|
return key.character;
|
|
}
|
|
|
|
char c = key.character;
|
|
|
|
// Long-press: letters become uppercase; for "?" provide "/" like a typical keyboard
|
|
if (isLongPress) {
|
|
if (c >= 'a' && c <= 'z') {
|
|
c = (char)(c - 'a' + 'A');
|
|
} else if (c == '?') {
|
|
c = '/';
|
|
}
|
|
}
|
|
|
|
return c;
|
|
}
|
|
|
|
void VirtualKeyboard::moveCursorDelta(int dRow, int dCol)
|
|
{
|
|
resetTimeout();
|
|
// wrap around rows and cols in the 4x11 grid
|
|
int r = (int)cursorRow + dRow;
|
|
int c = (int)cursorCol + dCol;
|
|
if (r < 0)
|
|
r = KEYBOARD_ROWS - 1;
|
|
else if (r >= KEYBOARD_ROWS)
|
|
r = 0;
|
|
if (c < 0)
|
|
c = KEYBOARD_COLS - 1;
|
|
else if (c >= KEYBOARD_COLS)
|
|
c = 0;
|
|
cursorRow = (uint8_t)r;
|
|
cursorCol = (uint8_t)c;
|
|
}
|
|
|
|
void VirtualKeyboard::moveCursorUp()
|
|
{
|
|
moveCursorDelta(-1, 0);
|
|
}
|
|
void VirtualKeyboard::moveCursorDown()
|
|
{
|
|
moveCursorDelta(1, 0);
|
|
}
|
|
void VirtualKeyboard::moveCursorLeft()
|
|
{
|
|
resetTimeout();
|
|
|
|
if (cursorCol > 0) {
|
|
cursorCol--;
|
|
} else {
|
|
if (cursorRow > 0) {
|
|
cursorRow--;
|
|
cursorCol = KEYBOARD_COLS - 1;
|
|
} else {
|
|
cursorRow = KEYBOARD_ROWS - 1;
|
|
cursorCol = KEYBOARD_COLS - 1;
|
|
}
|
|
}
|
|
}
|
|
void VirtualKeyboard::moveCursorRight()
|
|
{
|
|
resetTimeout();
|
|
|
|
if (cursorCol < KEYBOARD_COLS - 1) {
|
|
cursorCol++;
|
|
} else {
|
|
if (cursorRow < KEYBOARD_ROWS - 1) {
|
|
cursorRow++;
|
|
cursorCol = 0;
|
|
} else {
|
|
cursorRow = 0;
|
|
cursorCol = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::handlePress()
|
|
{
|
|
resetTimeout(); // Reset timeout on any input activity
|
|
|
|
const VirtualKey &key = keyboard[cursorRow][cursorCol];
|
|
|
|
// Don't handle press if the key is empty (but allow special keys)
|
|
if (key.character == 0 && key.type == VK_CHAR) {
|
|
return;
|
|
}
|
|
|
|
// For character keys, insert lowercase character
|
|
if (key.type == VK_CHAR) {
|
|
insertCharacter(getCharForKey(key, false)); // false = lowercase/normal char
|
|
return;
|
|
}
|
|
|
|
// Handle non-character keys immediately
|
|
switch (key.type) {
|
|
case VK_BACKSPACE:
|
|
deleteCharacter();
|
|
break;
|
|
case VK_ENTER:
|
|
submitText();
|
|
break;
|
|
case VK_SPACE:
|
|
insertCharacter(' ');
|
|
break;
|
|
case VK_ESC:
|
|
if (onTextEntered) {
|
|
std::function<void(const std::string &)> callback = onTextEntered;
|
|
onTextEntered = nullptr;
|
|
inputText = "";
|
|
callback("");
|
|
}
|
|
return;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::handleLongPress()
|
|
{
|
|
resetTimeout(); // Reset timeout on any input activity
|
|
|
|
const VirtualKey &key = keyboard[cursorRow][cursorCol];
|
|
|
|
// Don't handle press if the key is empty (but allow special keys)
|
|
if (key.character == 0 && key.type == VK_CHAR) {
|
|
return;
|
|
}
|
|
|
|
// For character keys, insert uppercase/alternate character
|
|
if (key.type == VK_CHAR) {
|
|
insertCharacter(getCharForKey(key, true)); // true = uppercase/alternate char
|
|
return;
|
|
}
|
|
|
|
switch (key.type) {
|
|
case VK_BACKSPACE:
|
|
// One-shot: delete up to 5 characters on long press
|
|
for (int i = 0; i < 5; ++i) {
|
|
if (inputText.empty())
|
|
break;
|
|
deleteCharacter();
|
|
}
|
|
break;
|
|
case VK_ENTER:
|
|
submitText();
|
|
break;
|
|
case VK_SPACE:
|
|
insertCharacter(' ');
|
|
break;
|
|
case VK_ESC:
|
|
if (onTextEntered) {
|
|
onTextEntered("");
|
|
}
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::insertCharacter(char c)
|
|
{
|
|
if (inputText.length() < 160) { // Reasonable text length limit
|
|
inputText += c;
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::deleteCharacter()
|
|
{
|
|
if (!inputText.empty()) {
|
|
inputText.pop_back();
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::submitText()
|
|
{
|
|
LOG_INFO("Virtual keyboard: submitting text '%s'", inputText.c_str());
|
|
|
|
// Only submit if text is not empty
|
|
if (!inputText.empty() && onTextEntered) {
|
|
// Store callback and text to submit before clearing callback
|
|
std::function<void(const std::string &)> callback = onTextEntered;
|
|
std::string textToSubmit = inputText;
|
|
onTextEntered = nullptr;
|
|
// Don't clear inputText here - let the calling module handle cleanup
|
|
// inputText = ""; // Removed: keep text visible until module cleans up
|
|
callback(textToSubmit);
|
|
} else if (inputText.empty()) {
|
|
// For empty text, just ignore the submission - don't clear callback
|
|
// This keeps the virtual keyboard responsive for further input
|
|
LOG_INFO("Virtual keyboard: empty text submitted, ignoring - keyboard remains active");
|
|
} else {
|
|
// No callback available
|
|
if (screen) {
|
|
screen->setFrames(graphics::Screen::FOCUS_PRESERVE);
|
|
}
|
|
}
|
|
}
|
|
|
|
void VirtualKeyboard::setInputText(const std::string &text)
|
|
{
|
|
inputText = text;
|
|
}
|
|
|
|
std::string VirtualKeyboard::getInputText() const
|
|
{
|
|
return inputText;
|
|
}
|
|
|
|
void VirtualKeyboard::setHeader(const std::string &header)
|
|
{
|
|
headerText = header;
|
|
}
|
|
|
|
void VirtualKeyboard::setCallback(std::function<void(const std::string &)> callback)
|
|
{
|
|
onTextEntered = callback;
|
|
}
|
|
|
|
void VirtualKeyboard::resetTimeout()
|
|
{
|
|
lastActivityTime = millis();
|
|
}
|
|
|
|
bool VirtualKeyboard::isTimedOut() const
|
|
{
|
|
return (millis() - lastActivityTime) > TIMEOUT_MS;
|
|
}
|
|
|
|
} // namespace graphics
|
|
#endif |