Skip to content

Input: first prototype#27

Merged
kimkulling merged 5 commits intomainfrom
feature/implement_input_text
Apr 1, 2026
Merged

Input: first prototype#27
kimkulling merged 5 commits intomainfrom
feature/implement_input_text

Conversation

@kimkulling
Copy link
Copy Markdown
Owner

@kimkulling kimkulling commented Apr 1, 2026

Features:

  • Prototype for input field
  • Fix focus handling for the input field

What is missing

  • Enumeration shows numeric + password, but these features are currently not supported
  • Backspace not supported
  • No navigation in input is supported
  • Hard-coded SDL-enums are used

Summary by CodeRabbit

  • New Features

    • Input fields support selectable input modes (character/password/numeric) with customizable initial text and visible typing (including backspace).
    • Added a millisecond delay capability for more precise timing.
  • Bug Fixes

    • Improved error reporting and fallback behavior when requested fonts cannot be loaded.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2026

Warning

Rate limit exceeded

@kimkulling has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 24 minutes and 30 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 24 minutes and 30 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 201166fb-dd99-43c5-8c04-373657d1997d

📥 Commits

Reviewing files that changed from the base of the PR and between 7c4d08e and d051142.

📒 Files selected for processing (2)
  • src/widgets.cpp
  • src/widgets.h

Walkthrough

Adds KeyInputType and default-text support to input text widgets and updates input handling and rendering; introduces IODevice::delay(uint32_t) in the SDL2 backend; adds an error log when a requested font cannot be loaded in the SDL2 renderer.

Changes

Cohort / File(s) Summary
Input widget API & logic
src/widgets.h, src/widgets.cpp, samples/demo/main.cpp
Added KeyInputType enum and Widget::mKeyInputType; changed Widgets::inputText signature to include KeyInputType and const char *default; updated event dispatch to handle key-down only, added input handling (backspace/append), focus callback, and render of widget text; demo call updated.
SDL2 IODevice delay
src/backends/sdl2_iodevice.h, src/backends/sdl2_iodevice.cpp
Declared and implemented static IODevice::delay(uint32_t ms) which calls SDL_Delay(ms).
SDL2 renderer font handling
src/backends/sdl2_renderer.cpp
Added an error log when requested font cannot be loaded and clarified fallback to default font; minor formatting/control-flow adjustments.
Minor layout typing fix
src/widgets.cpp
Added explicit static_cast<int32_t> in treeItem layout math to avoid implicit type mixing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Reorga #4 — Modifies widget input/event APIs and implementations similar to the input handling and signature changes in this PR.
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.74% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Input: first prototype' clearly and concisely summarizes the main change: adding an initial prototype for an input field widget, which aligns with the primary objective and the substantial changes across multiple files to implement input functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/implement_input_text

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/widgets.cpp (1)

260-283: ⚠️ Potential issue | 🔴 Critical

default is a reserved keyword – rename the parameter to match the header fix.

Same issue as in the header: default is a C++ reserved keyword. Rename to defaultText or similar.

🐛 Proposed fix
-ret_code Widgets::inputText(Id id, Id parentId, const Rect &rect, Alignment alignment, KeyInputType type, const char *default) {
+ret_code Widgets::inputText(Id id, Id parentId, const Rect &rect, Alignment alignment, KeyInputType type, const char *defaultText) {
     auto &ctx = TinyUi::getContext();
     if (ctx.mBackendCtx == nullptr) {
         return InvalidRenderHandle;
     }
 
     if (ctx.mRoot == nullptr) {
         return InvalidRenderHandle;
     }
 
     Widget *widget = createWidget(ctx, id, parentId, rect, WidgetType::InputField);
     if (widget == nullptr) {
         return ErrorCode;
     }
 
     widget->mAlignment = alignment;
     widget->mKeyInputType = type;
-    if (default != nullptr) {
-        widget->mText.assign(default);
+    if (defaultText != nullptr) {
+        widget->mText.assign(defaultText);
     }
 
     widget->mCallback = new CallbackI(inputHandler, (void *)&ctx, Events::MouseButtonDownEvent);
 
     return ResultOk;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/widgets.cpp` around lines 260 - 283, The function Widgets::inputText uses
a parameter named "default", which is a reserved C++ keyword; rename that
parameter to match the header change (e.g., "defaultText") in the
Widgets::inputText signature and all uses inside the implementation (including
the null check and widget->mText.assign call) so the definition matches the
header and compiles cleanly.
src/backends/sdl2_renderer.cpp (1)

204-218: ⚠️ Potential issue | 🟠 Major

The font parameter is always overwritten, making the conditional block dead code.

Line 215 unconditionally assigns font = ctx.mDefaultFont;, which means:

  1. The font parameter passed to drawText is always ignored
  2. The error message at lines 208-209 fires when the passed font is null, but then immediately gets overwritten anyway
  3. The conditional assignment at line 210 (font = ctx.mDefaultFont;) is redundant

This appears to be unintended. If the intent is to always use the default font, remove the parameter. Otherwise, preserve the passed font when it's valid.

🔧 Proposed fix to respect the font parameter
     if (ctx.mDefaultFont == nullptr) {
         if (ctx.mStyle.mFont.mName != nullptr) {
             loadFont(ctx);
-            if (font == nullptr) {
-                const std::string msg = "Cannot load font: " + std::string(ctx.mStyle.mFont.mName) + ", using the default font.";
-                ctx.mLogger(LogSeverity::Error, msg.c_str());
-                font = ctx.mDefaultFont;
-            }
         }
     }
-    
-    font = ctx.mDefaultFont;
+
+    if (font == nullptr) {
+        font = ctx.mDefaultFont;
+    }
     if (font == nullptr) {
         return InvalidHandle;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/backends/sdl2_renderer.cpp` around lines 204 - 218, The code currently
overwrites the incoming font parameter by unconditionally setting font =
ctx.mDefaultFont;—remove that unconditional assignment and instead only fall
back to ctx.mDefaultFont when the passed-in font is null: i.e., if (font ==
nullptr) { if (ctx.mDefaultFont == nullptr && ctx.mStyle.mFont.mName != nullptr)
{ loadFont(ctx); if (ctx.mDefaultFont == nullptr) {
ctx.mLogger(LogSeverity::Error, ("Cannot load font: " +
std::string(ctx.mStyle.mFont.mName) + ", using the default font.").c_str());
return InvalidHandle; } } font = ctx.mDefaultFont; } This preserves a valid
passed font, attempts to load the default only when needed (using loadFont(ctx)
and ctx.mDefaultFont), and returns InvalidHandle if no font is available.
🧹 Nitpick comments (2)
src/widgets.h (1)

56-62: Consider specifying int32_t as the underlying type for the enum.

As per coding guidelines, enums should use int32_t as the underlying type: enum class KeyInputType : int32_t.

♻️ Suggested change
-enum class KeyInputType {
+enum class KeyInputType : int32_t {
     Invalid = -1,       ///< Not initialized
     Character,          ///< A character input
     Password,           ///< A special key input
     Numeric,            ///< A numeric input
     Count               ///< The number of key input types
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/widgets.h` around lines 56 - 62, The enum class KeyInputType currently
has no explicit underlying type; update its declaration to use int32_t as the
underlying type to follow coding guidelines (declare as enum class KeyInputType
: int32_t). Modify the KeyInputType declaration so all enumerators (Invalid,
Character, Password, Numeric, Count) remain the same but the enum is explicitly
typed as int32_t; include the necessary <cstdint> include if not already
present.
src/widgets.cpp (1)

249-258: Consider using auto for the type deduction.

Static analysis suggests replacing Context *ctx with auto *ctx at line 254 since the type is already clear from the static_cast.

♻️ Minor cleanup
 static int inputHandler(Id id, void *instance) {
     if (instance == nullptr) {
         return ErrorCode;
     }
 
-    Context *ctx = static_cast<Context *>(instance);
+    auto *ctx = static_cast<Context *>(instance);
     ctx->mFocus = Widgets::findWidget(id, ctx->mRoot);
 
     return ResultOk;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/widgets.cpp` around lines 249 - 258, Replace the explicit pointer type
with automatic type deduction in inputHandler to match the static_cast; change
the declaration "Context *ctx = static_cast<Context *>(instance);" to use "auto
*ctx = static_cast<Context *>(instance);" so the pointer type is inferred while
preserving the cast and subsequent use of ctx and Widgets::findWidget(id,
ctx->mRoot) in the function.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/backends/sdl2_iodevice.h`:
- Around line 46-48: The delay(uint32_t ms) declaration conflicts with project
conventions; change its signature to return ret_code (int32_t) and accept an
explicit-width signed int (int32_t) so it becomes ret_code delay(int32_t ms),
update the corresponding implementation (method named delay) to validate the
input at the start (e.g., check ms >= 0), return an appropriate ret_code on
invalid input, and ensure callers and any header/implementation pairs are
updated to match the new signature.

In `@src/widgets.cpp`:
- Line 281: The assignment to widget->mCallback uses new CallbackI(inputHandler,
(void *)&ctx, Events::MouseButtonDownEvent) but omits the corresponding
reference increment; update the widget creation logic so that after assigning
widget->mCallback (the CallbackI instance created with inputHandler and ctx for
Events::MouseButtonDownEvent) you call the callback's incRef() method (mirroring
the pattern used in button and treeView creation) to ensure proper reference
counting and avoid premature deletion or double-free.
- Around line 153-164: The KeyDown handling can crash because
ctx.mFocus->mText.erase(ctx.mFocus->mText.size() - 1) is called without checking
for empty; modify the Events::KeyDownEvent branch inside the handler to first
early-return or continue if eventPayload is null or ctx.mFocus is null or
ctx.mFocus->mType != WidgetType::InputField, then when handling SDLK_BACKSPACE
check if ctx.mFocus->mText.empty() before calling mText.erase (or use
pop_back()), otherwise append the character from eventPayload->payload[0]; this
both prevents underflow/UB and reduces nesting.

In `@src/widgets.h`:
- Around line 204-207: The parameter name `default` in the function declaration
inputText(Id id, Id parentId, const Rect &rect, Alignment alignment,
KeyInputType type, const char *default) is a C++ keyword and causes compile
errors; rename that parameter to a non-reserved identifier like defaultText or
initialText in the declaration and in every implementation/usage (e.g., the
inputText definition, any calls, and related header/CPP references) so the
function signature becomes inputText(..., const char *defaultText) and all
references are updated accordingly.

---

Outside diff comments:
In `@src/backends/sdl2_renderer.cpp`:
- Around line 204-218: The code currently overwrites the incoming font parameter
by unconditionally setting font = ctx.mDefaultFont;—remove that unconditional
assignment and instead only fall back to ctx.mDefaultFont when the passed-in
font is null: i.e., if (font == nullptr) { if (ctx.mDefaultFont == nullptr &&
ctx.mStyle.mFont.mName != nullptr) { loadFont(ctx); if (ctx.mDefaultFont ==
nullptr) { ctx.mLogger(LogSeverity::Error, ("Cannot load font: " +
std::string(ctx.mStyle.mFont.mName) + ", using the default font.").c_str());
return InvalidHandle; } } font = ctx.mDefaultFont; } This preserves a valid
passed font, attempts to load the default only when needed (using loadFont(ctx)
and ctx.mDefaultFont), and returns InvalidHandle if no font is available.

In `@src/widgets.cpp`:
- Around line 260-283: The function Widgets::inputText uses a parameter named
"default", which is a reserved C++ keyword; rename that parameter to match the
header change (e.g., "defaultText") in the Widgets::inputText signature and all
uses inside the implementation (including the null check and
widget->mText.assign call) so the definition matches the header and compiles
cleanly.

---

Nitpick comments:
In `@src/widgets.cpp`:
- Around line 249-258: Replace the explicit pointer type with automatic type
deduction in inputHandler to match the static_cast; change the declaration
"Context *ctx = static_cast<Context *>(instance);" to use "auto *ctx =
static_cast<Context *>(instance);" so the pointer type is inferred while
preserving the cast and subsequent use of ctx and Widgets::findWidget(id,
ctx->mRoot) in the function.

In `@src/widgets.h`:
- Around line 56-62: The enum class KeyInputType currently has no explicit
underlying type; update its declaration to use int32_t as the underlying type to
follow coding guidelines (declare as enum class KeyInputType : int32_t). Modify
the KeyInputType declaration so all enumerators (Invalid, Character, Password,
Numeric, Count) remain the same but the enum is explicitly typed as int32_t;
include the necessary <cstdint> include if not already present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b552a7df-7487-4f01-99a0-9ba73f58e3e5

📥 Commits

Reviewing files that changed from the base of the PR and between 53b5ba6 and 6e69b06.

📒 Files selected for processing (6)
  • samples/demo/main.cpp
  • src/backends/sdl2_iodevice.cpp
  • src/backends/sdl2_iodevice.h
  • src/backends/sdl2_renderer.cpp
  • src/widgets.cpp
  • src/widgets.h

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 1, 2026

@kimkulling kimkulling merged commit b1ab18a into main Apr 1, 2026
4 checks passed
@kimkulling kimkulling deleted the feature/implement_input_text branch April 1, 2026 19:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant