From 90dbba2cddcdddbf4b85998ca4632aeb268dfeed Mon Sep 17 00:00:00 2001 From: Liu Date: Sun, 22 Nov 2026 16:22:25 +0800 Subject: [PATCH] feat(widgets): migrate textinput editing to the stb_textedit kernel - vendor stb_textedit and add the textedit core with canonical text - map edit indices to pd_text layout for caret, selection and hit testing - support caret movement, selection, clipboard, undo/redo, password, read-only and multiline editing - render selections with the accent color and configurable text color - fix caret scaling, input-group repaint and zero-size reflow regressions - add integration tests, a preview page and internals notes --- docs/internals/widgets.md | 28 + ...2026-11-21-textinput-edit-kernel-design.md | 123 ++ include/LCUI/widgets/textinput.h | 23 +- lib/pandagl/include/pandagl/text.h | 17 + lib/pandagl/src/text/text.c | 51 +- lib/pandagl/src/text/text_edit.c | 57 +- lib/pandagl/tests/test_text_edit.c | 38 + src/styles/accent-rules.h | 4 + src/styles/accents/amber.css | 16 + src/styles/accents/amber.css.h | 10 +- src/styles/accents/blue.css | 16 + src/styles/accents/blue.css.h | 10 +- src/styles/accents/cyan.css | 16 + src/styles/accents/cyan.css.h | 10 +- src/styles/accents/emerald.css | 16 + src/styles/accents/emerald.css.h | 10 +- src/styles/accents/fuchsia.css | 16 + src/styles/accents/fuchsia.css.h | 10 +- src/styles/accents/green.css | 16 + src/styles/accents/green.css.h | 10 +- src/styles/accents/indigo.css | 16 + src/styles/accents/indigo.css.h | 10 +- src/styles/accents/lime.css | 16 + src/styles/accents/lime.css.h | 10 +- src/styles/accents/neutral.css | 16 + src/styles/accents/neutral.css.h | 10 +- src/styles/accents/orange.css | 16 + src/styles/accents/orange.css.h | 10 +- src/styles/accents/pink.css | 16 + src/styles/accents/pink.css.h | 10 +- src/styles/accents/purple.css | 16 + src/styles/accents/purple.css.h | 10 +- src/styles/accents/red.css | 16 + src/styles/accents/red.css.h | 10 +- src/styles/accents/rose.css | 16 + src/styles/accents/rose.css.h | 10 +- src/styles/accents/sky.css | 16 + src/styles/accents/sky.css.h | 10 +- src/styles/accents/teal.css | 16 + src/styles/accents/teal.css.h | 10 +- src/styles/accents/violet.css | 16 + src/styles/accents/violet.css.h | 10 +- src/styles/accents/yellow.css | 16 + src/styles/accents/yellow.css.h | 10 +- src/styles/style-nova.css | 14 + src/styles/style-nova.css.h | 16 +- src/widgets/input_group.c | 4 + src/widgets/textcaret.c | 1 - src/widgets/textedit.c | 789 ++++++++ src/widgets/textedit.h | 101 + src/widgets/textinput.c | 1208 +++++++----- src/widgets/third-party/README.md | 9 + src/widgets/third-party/stb_textedit.h | 1662 +++++++++++++++++ tests/integration/test_style_nova.c | 32 +- tests/integration/test_textinput.c | 1412 ++++++++++++++ tests/integration/test_textinput_edit.c | 346 ++++ tests/main.c | 2 + tests/previews/preview_textinput_edit.c | 60 + tests/previews/xmake.lua | 10 +- 59 files changed, 5970 insertions(+), 505 deletions(-) create mode 100644 docs/superpowers/specs/2026-11-21-textinput-edit-kernel-design.md create mode 100644 src/widgets/textedit.c create mode 100644 src/widgets/textedit.h create mode 100644 src/widgets/third-party/README.md create mode 100644 src/widgets/third-party/stb_textedit.h create mode 100644 tests/integration/test_textinput_edit.c create mode 100644 tests/previews/preview_textinput_edit.c diff --git a/docs/internals/widgets.md b/docs/internals/widgets.md index 273079f7..b783f798 100644 --- a/docs/internals/widgets.md +++ b/docs/internals/widgets.md @@ -528,3 +528,31 @@ ui_mutation_observer_observe(observer, w, options); /* 观察自身 */ `ui_widget_add_mutation_record`),所以观察自身同样收到整个子树的变更;而自身在 destroy 回调 里仍然有效,无悬挂指针。scrollarea / combobox 也是观察自身。 + +## textinput 编辑内核(stb_textedit) + +`textinput` 的编辑状态由 `src/widgets/textedit.c` 封装 `stb_textedit.h` v1.16: + +- canonical 文本是唯一事实来源(`wchar_t`,`\r\n`/`\r` 归一化为 `\n`); +- `pd_text` 只是投影:每次编辑后 `pd_text_clear + pd_text_append` 重建,再 + `pd_text_update`,保证 stb 的后续布局查询看到最新行结构; +- 索引映射:软换行不消耗字符,硬换行(`eol != PD_TEXT_EOL_NONE`)消耗 1 个字符; + 视觉行信息来自 `pd_text_get_line_eol` / `pd_text_get_line_char_start`; +- `ui_textinput_update_caret` 必须使用文本层缓存的 `layer_scale`,不能用事件期的 + `ui_get_actual_scale()`(事件分发发生在 `ui_server_update()` 之外,全局 dpi 可能 + 仍是默认值); +- 选区由 textinput 在 `on_paint` 中先于 `pd_text_render_to` 绘制; +- 选区颜色默认是实色 `primary`,文字用 `primary-foreground`(亮色主题白字、 + 暗色主题深字);可用 `selection-color` / `selection-text-color` 属性或 + `ui_textinput_set_selection_color()` / `ui_textinput_set_selection_text_color()`; + 也支持 CSS 规则 `textinput .selection { background-color: ...; color: ...; }`。 + textinput 内部维护一个 0×0、绝对定位的 `.selection` 隐藏子部件,只用于承载 + 这些样式,绘制时读取它的 computed `background-color` / `color`。属性/API 会写入 + 该元素的 inline 样式,优先级高于 CSS 规则;两者都没有时回退到默认值; +- 编辑场景不支持样式标签(canonical 索引会被 pd_text 消费);Windows 下通过 + `GETPREV/NEXTCHARINDEX` 跳过 UTF-16 代理对; +- 当前重建是 O(N),定位为表单级文本(KB 级);GB 级文档需要 rope/piece table + + 虚拟化排版,不能沿用该实现。 + +测试:`tests/integration/test_textinput.c`、`test_textinput_edit.c`; +可视诊断:`tests/previews/preview_textinput_edit.c`。 \ No newline at end of file diff --git a/docs/superpowers/specs/2026-11-21-textinput-edit-kernel-design.md b/docs/superpowers/specs/2026-11-21-textinput-edit-kernel-design.md new file mode 100644 index 00000000..9851cf9a --- /dev/null +++ b/docs/superpowers/specs/2026-11-21-textinput-edit-kernel-design.md @@ -0,0 +1,123 @@ +# textinput 编辑内核设计(stb_textedit) + +## 目标 + +为 `textinput` 引入 `stb_textedit.h` v1.16 作为编辑状态内核,补齐多行编辑能力: +光标、选区、撤销/重做、剪贴板快捷键、鼠标拖选。排版与绘制继续由 Pandagl 的 +`pd_text_t` 负责,避免两套字体/布局实现漂移。 + +## 范围 + +v1 包含: + +- 单行 / 多行(硬换行 `\n`) +- 软换行(依赖 `pd_text` 的 autowrap;索引映射需跳过软换行行尾) +- 光标移动:Left/Right/Up/Down/Home/End/PageUp/PageDown +- 选区:Shift + 方向键、Shift + Home/End、鼠标点击/拖拽 +- 撤销/重做:Ctrl+Z / Ctrl+Y +- 剪贴板:Ctrl+A / Ctrl+C / Ctrl+X / Ctrl+V(有选区时复制/剪切选区) +- 输入法提交文本(`textinput` 事件)作为一次编辑 +- 密码模式、只读模式、placeholder + +v1 不包含: + +- IME preedit(组合态)内联显示;只接收最终提交文本 +- 样式标签在编辑场景下的索引同步(编辑场景保持禁用) +- 语法高亮、多光标、行号、bidi、grapheme cluster 级移动(仅保证不拆 + Windows 代理对) + +## 分层 + +``` +PTK 输入事件 + ↓ +textinput widget(焦点、只读、密码、剪贴板、IME 事件) + ↓ +textedit(canonical 文本 + stb 状态 + 索引映射 + 撤销栈) + ↓ +pd_text(排版、换行、行高、字符 advance、光标像素) + ↓ +Canvas 绘制(文本 + 选区 overlay + textcaret) +``` + +## 数据结构 + +```c +typedef struct ui_text_edit { + wchar_t *text; /* canonical,统一使用 \n */ + int length; + int capacity; + STB_TexteditState state; /* cursor / selection / undo */ + pd_text_t *layer; /* 投影层,用于排版/渲染 */ + float layer_scale; /* 逻辑像素 -> 实际像素 */ + bool style_tag_enabled; /* v1 编辑时禁用 */ +} ui_text_edit_t; +``` + +- canonical 是唯一事实来源;`pd_text` 是它的投影。 +- `\r\n` / `\r` 在进入 canonical 前统一归一化为 `\n`。 +- 公共读取 API(`ui_textinput_get_text_w` / `get_text_length`)改读 canonical。 + +## stb 配置 + +```c +#define STB_TEXTEDIT_CHARTYPE wchar_t +#define STB_TEXTEDIT_NEWLINE L'\n' +#define STB_TEXTEDIT_STRING ui_text_edit_t +#define STB_TEXTEDIT_STRINGLEN(e) ((e)->length) +#define STB_TEXTEDIT_GETCHAR(e, i) ((e)->text[i]) +#define STB_TEXTEDIT_INSERTCHARS(e, i, c, n) ui_text_edit_insert_raw(e, i, c, n) +#define STB_TEXTEDIT_DELETECHARS(e, i, n) ui_text_edit_delete_raw(e, i, n) +#define STB_TEXTEDIT_LAYOUTROW(r, e, i) ui_text_edit_layout_row(r, e, i) +#define STB_TEXTEDIT_GETWIDTH(e, start, i) ui_text_edit_get_width(e, start, i) +#define STB_TEXTEDIT_GETPREVCHARINDEX(e, i) ui_text_edit_prev_index(e, i) +#define STB_TEXTEDIT_GETNEXTCHARINDEX(e, i) ui_text_edit_next_index(e, i) +#define STB_TEXTEDIT_IS_SPACE(ch) iswspace(ch) +``` + +- 不定义 `STB_TEXTEDIT_KEYTOTEXT`;字符输入统一走 `stb_textedit_text()`,避免 + stb 把按键与字符混在一起。 +- Undo 使用默认 99 条 / 999 字符;后续如需要可在 `textedit.c` 内调整宏。 + +## 索引映射 + +- canonical 索引 ↔ pd_text 视觉行列通过一次线性扫描完成: + - 每个视觉行消耗 `line->length` 个字符; + - 硬换行(`eol != PD_TEXT_EOL_NONE`)额外消耗 1 个 `\n`; + - 软换行(`eol == PD_TEXT_EOL_NONE`)不消耗字符。 +- `LAYOUTROW(r, e, index)`:从 `index` 开始找到视觉行,`num_chars = 行剩余 + 字符数 + (硬换行 ? 1 : 0)`,`baseline_y_delta = line->height`。 +- `GETWIDTH` 直接读 `line->string[col]->bitmap->metrics.hori_advance`,不调用 + `pd_text_get_char_pixel()`,避免 O(N²)。 + +## 排版同步 + +- 每次 `INSERTCHARS` / `DELETECHARS` 后: + 1. 更新 canonical; + 2. 用 `pd_text_clear` + `pd_text_append` 重建投影层(小文本可接受); + 3. 立即 `pd_text_update()`,保证 stb 后续查询看到新行结构。 +- caret 像素由 `pd_text_set_caret()` + `pd_text_get_caret_pixel()` 提供; + textinput 负责除以 `layer_scale` 转逻辑像素。 + +## 选区绘制 + +- 在 `ui_textinput_on_paint()` 中、`pd_text_render_to()` 之前绘制。 +- 按视觉行拆分 `[select_start, select_end)`,用 `pd_text_get_char_pixel()` 取 + 每行起止 x,`line->height` 取高度。 +- 选区颜色使用主题 `primary/20` 或 `foreground/15`(实现时二选一并加测试)。 +- 密码模式可选:v1 允许选中,但绘制仍显示屏蔽字符;不额外暴露明文。 + +## 失败模式(Review Focus) + +1. 软换行边界:光标落在软换行行尾/下一行行首时必须只对应一个 canonical 索引。 +2. 硬换行删除:Backspace 跨行合并、Delete 行尾合并必须与 canonical 一致。 +3. Windows 代理对(emoji):左右移动和退格不能拆代理对。 +4. 排版延迟:插入/删除后未立即 `pd_text_update()` 会导致光标/选区错位。 +5. CRLF:canonical 必须归一化,否则 `pd_text->length` 与 canonical 索引错位。 +6. 密码/只读:只读仍允许选择与复制;密码模式不能把明文写进剪贴板以外的地方。 +7. 样式标签:编辑场景若开启会破坏索引,v1 必须显式拒绝或忽略。 + +## 许可 + +`stb_textedit.h` 为 MIT 或公有领域双许可,与 LCUI 的 MIT 兼容。vendor 时保留 +文件头与许可证原文,并在 `src/widgets/third-party/README.md` 记录来源与版本。 diff --git a/include/LCUI/widgets/textinput.h b/include/LCUI/widgets/textinput.h index b26eff86..5a198126 100644 --- a/include/LCUI/widgets/textinput.h +++ b/include/LCUI/widgets/textinput.h @@ -31,28 +31,43 @@ LCUI_BEGIN_HEADER -/** Enable style tag parser */ +/** Enable the style tag parser (read-only display only; ignored while editable) + */ LCUI_API void ui_textinput_enable_style_tag(ui_widget_t *widget, bool enable); LCUI_API void ui_textinput_enable_multiline(ui_widget_t *widget, bool enable); +/** 设置只读状态:仍可移动光标和选择/复制,但不能修改文本 */ +LCUI_API void ui_textinput_set_read_only(ui_widget_t *widget, bool read_only); + +/** 设置选区背景色(支持 rgba;默认实色 primary) */ +LCUI_API void ui_textinput_set_selection_color(ui_widget_t *widget, + pd_color_t color); + +/** 设置选区文字颜色(默认 primary-foreground) */ +LCUI_API void ui_textinput_set_selection_text_color(ui_widget_t *widget, + pd_color_t color); + LCUI_API void ui_textinput_move_caret(ui_widget_t *widget, int row, int col); /** 清空文本内容 */ LCUI_API void ui_textinput_clear_text(ui_widget_t *widget); -/** 获取文本内容 */ +/** + * 获取文本内容。start 是包含换行符的扁平字符索引; + * 文本写入时 CRLF / CR 已归一化为 LF。 + */ LCUI_API size_t ui_textinput_get_text_w(ui_widget_t *w, size_t start, size_t max_len, wchar_t *buf); -/** 获取文本长度 */ +/** 获取文本长度(CRLF 已归一化) */ LCUI_API size_t ui_textinput_get_text_length(ui_widget_t *w); /** 设置文本编辑框内的光标,指定是否闪烁、闪烁时间间隔 */ LCUI_API void ui_textinput_set_caret_blink(ui_widget_t *w, bool visible, int time); -/** 为文本框设置文本(宽字符版) */ +/** 为文本框设置文本(宽字符版);CRLF / CR 会归一化为 LF */ LCUI_API int ui_textinput_set_text_w(ui_widget_t *widget, const wchar_t *wstr); LCUI_API int ui_textinput_set_text(ui_widget_t *widget, const char *utf8_str); diff --git a/lib/pandagl/include/pandagl/text.h b/lib/pandagl/include/pandagl/text.h index 32b35ae7..49ce621c 100644 --- a/lib/pandagl/include/pandagl/text.h +++ b/lib/pandagl/include/pandagl/text.h @@ -142,6 +142,15 @@ PD_PUBLIC int pd_text_get_line_height(pd_text_t *layer, int line_num); /** 获取指定文本行的文本长度 */ PD_PUBLIC int pd_text_get_line_length(pd_text_t *layer, int line_num); +/** 获取指定视觉行的行尾类型(越界返回 PD_TEXT_EOL_NONE) */ +PD_PUBLIC pd_text_eol_t pd_text_get_line_eol(pd_text_t *layer, int line_num); + +/** + * 获取指定视觉行首字符在扁平文本中的索引(包含前序硬换行的字符数)。 + * 软换行不消耗字符,越界返回 -1。 + */ +PD_PUBLIC int pd_text_get_line_char_start(pd_text_t *layer, int line_num); + /** 添加 更新文本排版 的任务 */ PD_PUBLIC void pd_text_request_typeset(pd_text_t *layer, int start_row); @@ -171,6 +180,14 @@ PD_PUBLIC int pd_text_get_char_pixel(pd_text_t *layer, int line_num, int col, /** 获取文本光标的像素坐标 */ PD_PUBLIC int pd_text_get_caret_pixel(pd_text_t *layer, pd_pos_t *pixel_pos); +/** + * 获取视觉行中 [start_col, end_col] 字符范围的矩形(实际像素坐标, + * 包含 offset 与对齐偏移)。返回 0 表示有效区域。 + */ +PD_PUBLIC int pd_text_get_line_rect(pd_text_t *layer, int line_num, + int start_col, int end_col, + pd_rect_t *rect); + /** 清空文本 */ PD_PUBLIC void pd_text_clear(pd_text_t *layer); diff --git a/lib/pandagl/src/text/text.c b/lib/pandagl/src/text/text.c index 57af616a..7af58c27 100644 --- a/lib/pandagl/src/text/text.c +++ b/lib/pandagl/src/text/text.c @@ -349,6 +349,43 @@ int pd_text_get_line_length(pd_text_t *text, int line_num) return text->lines[line_num]->length; } +static int pd_text_eol_length(pd_text_eol_t eol) +{ + switch (eol) { + case PD_TEXT_EOL_CR: + case PD_TEXT_EOL_LF: + return 1; + case PD_TEXT_EOL_CR_LF: + return 2; + case PD_TEXT_EOL_NONE: + default: + break; + } + return 0; +} + +pd_text_eol_t pd_text_get_line_eol(pd_text_t *text, int line_num) +{ + if (line_num < 0 || line_num >= text->lines_length) { + return PD_TEXT_EOL_NONE; + } + return text->lines[line_num]->eol; +} + +int pd_text_get_line_char_start(pd_text_t *text, int line_num) +{ + int i, start = 0; + + if (line_num < 0 || line_num >= text->lines_length) { + return -1; + } + for (i = 0; i < line_num; ++i) { + start += text->lines[i]->length + + pd_text_eol_length(text->lines[i]->eol); + } + return start; +} + void pd_text_request_typeset(pd_text_t *text, int start_line) { if (start_line < text->task.typeset_start_line) { @@ -364,7 +401,7 @@ int pd_text_get_line_rect(pd_text_t *text, int line_num, int start_col, int i; pd_text_line_t *line; - if (line_num >= text->lines_length) { + if (line_num < 0 || line_num >= text->lines_length) { return -1; } /* 先计算在有效区域内的起始行的y轴坐标 */ @@ -374,6 +411,14 @@ int pd_text_get_line_rect(pd_text_t *text, int line_num, int start_col, rect->y += text->lines[i]->height; } line = text->lines[line_num]; + if (start_col < 0) { + start_col = 0; + } else if (start_col > line->length) { + start_col = line->length; + } + if (end_col < start_col) { + end_col = start_col - 1; + } if (end_col < 0 || end_col >= line->length) { end_col = line->length - 1; } @@ -383,7 +428,7 @@ int pd_text_get_line_rect(pd_text_t *text, int line_num, int start_col, rect->width = line->width; } else { for (i = 0; i < start_col; ++i) { - if (!line->string[i]->bitmap) { + if (!line->string[i] || !line->string[i]->bitmap) { continue; } rect->x += @@ -391,7 +436,7 @@ int pd_text_get_line_rect(pd_text_t *text, int line_num, int start_col, } rect->width = 0; for (i = start_col; i <= end_col && i < line->length; ++i) { - if (!line->string[i]->bitmap) { + if (!line->string[i] || !line->string[i]->bitmap) { continue; } rect->width += diff --git a/lib/pandagl/src/text/text_edit.c b/lib/pandagl/src/text/text_edit.c index 0b488d58..44812eed 100644 --- a/lib/pandagl/src/text/text_edit.c +++ b/lib/pandagl/src/text/text_edit.c @@ -285,54 +285,61 @@ int pd_text_write(pd_text_t *text, const wchar_t *wstr, list_t *tag_stack) size_t pd_text_read(pd_text_t *text, size_t start_pos, size_t max_len, wchar_t *wstr_buff) { - size_t i, line_num, col; + size_t i, out = 0; + int col, line_num; pd_text_line_t *line; if (max_len == 0) { wstr_buff[0] = 0; return 0; } - /* 先根据一维坐标计算行列坐标 */ - for (i = 0, line_num = 0, col = 0; line_num < text->lines_length; - ++line_num) { - if (i >= start_pos) { - col = start_pos - i; - break; - } - i += text->lines[line_num]->length; - } - for (i = 0; line_num < text->lines_length && i < max_len; ++line_num) { + /* 一维坐标包含行尾换行符,与编辑器内核的字符索引保持一致 */ + for (i = 0, line_num = 0; line_num < text->lines_length; ++line_num) { line = text->lines[line_num]; - for (; col < line->length && i < max_len; ++col, ++i) { - wstr_buff[i] = line->string[col]->code; + for (col = 0; col < line->length && out < max_len; ++col) { + if (i >= start_pos) { + wstr_buff[out++] = line->string[col]->code; + } + ++i; } - /* 进入下一行前,按行尾符还原对应的换行字符 */ - if (i >= max_len) { + if (out >= max_len) { break; } switch (line->eol) { case PD_TEXT_EOL_CR: - wstr_buff[i++] = L'\r'; + if (i >= start_pos) { + wstr_buff[out++] = L'\r'; + } + ++i; break; case PD_TEXT_EOL_LF: - wstr_buff[i++] = L'\n'; + if (i >= start_pos) { + wstr_buff[out++] = L'\n'; + } + ++i; break; case PD_TEXT_EOL_CR_LF: - wstr_buff[i++] = L'\r'; - if (i >= max_len) { - break; + if (i >= start_pos) { + wstr_buff[out++] = L'\r'; + } + ++i; + if (out < max_len) { + if (i >= start_pos) { + wstr_buff[out++] = L'\n'; + } + ++i; } - wstr_buff[i++] = L'\n'; break; case PD_TEXT_EOL_NONE: default: break; } - /* 切换到下一行时必须重置列号 */ - col = 0; + if (out >= max_len) { + break; + } } - wstr_buff[i] = 0; - return i; + wstr_buff[out] = 0; + return out; } wchar_t *pd_text_to_wcs(pd_text_t *text) diff --git a/lib/pandagl/tests/test_text_edit.c b/lib/pandagl/tests/test_text_edit.c index 04f48ac6..b254d4a1 100644 --- a/lib/pandagl/tests/test_text_edit.c +++ b/lib/pandagl/tests/test_text_edit.c @@ -207,6 +207,41 @@ static void should_dump_respect_max_len(void) pd_text_destroy(text); } +static void should_dump_from_multiline_offset(void) +{ + pd_text_t *text = pd_text_create(); + wchar_t buf[16]; + + pd_text_set_multiline(text, true); + pd_text_write(text, L"abc\ndef", NULL); + /* 一维索引包含换行符:0..2=abc, 3=\n, 4..6=def */ + ctest_equal_uint("should read from the second line", + (unsigned)pd_text_read(text, 4, 16, buf), 3u); + ctest_equal_wcs("should return the second line text", buf, L"def"); + ctest_equal_uint("should read starting at the newline", + (unsigned)pd_text_read(text, 3, 16, buf), 4u); + ctest_equal_wcs("should include the newline", buf, L"\ndef"); + pd_text_destroy(text); +} + +static void should_report_line_char_start(void) +{ + pd_text_t *text = pd_text_create(); + + pd_text_set_multiline(text, true); + pd_text_write(text, L"abc\ndef", NULL); + ctest_equal_int("line 0 should start at 0", + pd_text_get_line_char_start(text, 0), 0); + ctest_equal_int("line 1 should follow the newline", + pd_text_get_line_char_start(text, 1), 4); + ctest_equal_bool("line 0 eol is LF", + pd_text_get_line_eol(text, 0) == PD_TEXT_EOL_LF, true); + ctest_equal_bool("line 1 eol is none", + pd_text_get_line_eol(text, 1) == PD_TEXT_EOL_NONE, + true); + pd_text_destroy(text); +} + static void should_to_wcs_return_full_text(void) { pd_text_t *text = pd_text_create(); @@ -346,6 +381,9 @@ void test_pandagl_text_edit(void) ctest_describe("text dump trailing newline", should_dump_multiline_with_trailing_newline); ctest_describe("text dump max len", should_dump_respect_max_len); + ctest_describe("text dump multiline offset", + should_dump_from_multiline_offset); + ctest_describe("text line char start", should_report_line_char_start); ctest_describe("text to_wcs full text", should_to_wcs_return_full_text); ctest_describe("text to_wcs empty", should_to_wcs_handle_empty_text); ctest_describe("text escape open bracket", should_escape_open_bracket); diff --git a/src/styles/accent-rules.h b/src/styles/accent-rules.h index db78b12c..fd553c70 100644 --- a/src/styles/accent-rules.h +++ b/src/styles/accent-rules.h @@ -87,6 +87,10 @@ static const ui_theme_rule_t ui_theme_rules[] = { { "checkbox:indeterminate", "background-color", UI_THEME_TOKEN_PRIMARY, 1, -1 }, { "checkbox:checked", "color", UI_THEME_TOKEN_PRIMARY_FOREGROUND, 1, -1 }, { "checkbox:indeterminate", "color", UI_THEME_TOKEN_PRIMARY_FOREGROUND, 1, -1 }, + { "textinput .selection", "background-color", UI_THEME_TOKEN_PRIMARY, 0, -1 }, + { "textinput .selection", "color", UI_THEME_TOKEN_PRIMARY_FOREGROUND, 0, -1 }, + { "textinput .selection", "background-color", UI_THEME_TOKEN_PRIMARY, 1, -1 }, + { "textinput .selection", "color", UI_THEME_TOKEN_PRIMARY_FOREGROUND, 1, -1 }, { ".sidebar-menu-button:hover", "background-color", UI_THEME_TOKEN_SIDEBAR_ACCENT, 0, -1 }, { ".sidebar-menu-button:hover", "color", UI_THEME_TOKEN_SIDEBAR_ACCENT_FOREGROUND, 0, -1 }, { ".sidebar-menu-button:hover", "background-color", UI_THEME_TOKEN_SIDEBAR_ACCENT, 1, -1 }, diff --git a/src/styles/accents/amber.css b/src/styles/accents/amber.css index 984d4fd9..1c62317f 100644 --- a/src/styles/accents/amber.css +++ b/src/styles/accents/amber.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-amber textinput .selection { + background-color: rgba(217, 119, 6, 1); +} + +.accent-amber textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-amber.dark textinput .selection { + background-color: rgba(251, 191, 36, 1); +} + +.accent-amber.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-amber .sidebar-menu-button:hover { background-color: rgba(217, 119, 6, 0.1); } diff --git a/src/styles/accents/amber.css.h b/src/styles/accents/amber.css.h index 6c82332c..9d109228 100644 --- a/src/styles/accents/amber.css.h +++ b/src/styles/accents/amber.css.h @@ -197,8 +197,16 @@ static const struct { { " background-color: rgba(251, 191, 36, 0.15);\n", 46 }, { " color: rgba(251, 191, 36, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-amber textinput .selection {\n", 37 }, + { " background-color: rgba(217, 119, 6, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-amber.dark textinput .selection {\n", 42 }, + { " background-color: rgba(251, 191, 36, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_amber_total_length = 5402; +static const size_t css_str_amber_total_length = 5633; static inline void ui_load_css_string_amber_chunks(void) { size_t i; diff --git a/src/styles/accents/blue.css b/src/styles/accents/blue.css index 3dad5b60..01a5d9d7 100644 --- a/src/styles/accents/blue.css +++ b/src/styles/accents/blue.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-blue textinput .selection { + background-color: rgba(37, 99, 235, 1); +} + +.accent-blue textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-blue.dark textinput .selection { + background-color: rgba(96, 165, 250, 1); +} + +.accent-blue.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-blue .sidebar-menu-button:hover { background-color: rgba(37, 99, 235, 0.1); } diff --git a/src/styles/accents/blue.css.h b/src/styles/accents/blue.css.h index a1a5e4f8..9b174f96 100644 --- a/src/styles/accents/blue.css.h +++ b/src/styles/accents/blue.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(96, 165, 250, 0.15);\n", 46 }, { " color: rgba(96, 165, 250, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-blue textinput .selection {\n", 36 }, + { " background-color: rgba(37, 99, 235, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-blue.dark textinput .selection {\n", 41 }, + { " background-color: rgba(96, 165, 250, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_blue_total_length = 5375; +static const size_t css_str_blue_total_length = 5607; static inline void ui_load_css_string_blue_chunks(void) { size_t i; diff --git a/src/styles/accents/cyan.css b/src/styles/accents/cyan.css index 07fc53cc..4637b436 100644 --- a/src/styles/accents/cyan.css +++ b/src/styles/accents/cyan.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-cyan textinput .selection { + background-color: rgba(8, 145, 178, 1); +} + +.accent-cyan textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-cyan.dark textinput .selection { + background-color: rgba(34, 211, 238, 1); +} + +.accent-cyan.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-cyan .sidebar-menu-button:hover { background-color: rgba(8, 145, 178, 0.1); } diff --git a/src/styles/accents/cyan.css.h b/src/styles/accents/cyan.css.h index 5a738184..155849db 100644 --- a/src/styles/accents/cyan.css.h +++ b/src/styles/accents/cyan.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(34, 211, 238, 0.15);\n", 46 }, { " color: rgba(34, 211, 238, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-cyan textinput .selection {\n", 36 }, + { " background-color: rgba(8, 145, 178, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-cyan.dark textinput .selection {\n", 41 }, + { " background-color: rgba(34, 211, 238, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_cyan_total_length = 5342; +static const size_t css_str_cyan_total_length = 5571; static inline void ui_load_css_string_cyan_chunks(void) { size_t i; diff --git a/src/styles/accents/emerald.css b/src/styles/accents/emerald.css index 16290b8b..3214ffbd 100644 --- a/src/styles/accents/emerald.css +++ b/src/styles/accents/emerald.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-emerald textinput .selection { + background-color: rgba(5, 150, 105, 1); +} + +.accent-emerald textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-emerald.dark textinput .selection { + background-color: rgba(52, 211, 153, 1); +} + +.accent-emerald.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-emerald .sidebar-menu-button:hover { background-color: rgba(5, 150, 105, 0.1); } diff --git a/src/styles/accents/emerald.css.h b/src/styles/accents/emerald.css.h index b6f2c0ae..43582f7f 100644 --- a/src/styles/accents/emerald.css.h +++ b/src/styles/accents/emerald.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(52, 211, 153, 0.15);\n", 46 }, { " color: rgba(52, 211, 153, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-emerald textinput .selection {\n", 39 }, + { " background-color: rgba(5, 150, 105, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-emerald.dark textinput .selection {\n", 44 }, + { " background-color: rgba(52, 211, 153, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_emerald_total_length = 5555; +static const size_t css_str_emerald_total_length = 5793; static inline void ui_load_css_string_emerald_chunks(void) { size_t i; diff --git a/src/styles/accents/fuchsia.css b/src/styles/accents/fuchsia.css index 9ba578ee..ff7676b4 100644 --- a/src/styles/accents/fuchsia.css +++ b/src/styles/accents/fuchsia.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-fuchsia textinput .selection { + background-color: rgba(192, 38, 211, 1); +} + +.accent-fuchsia textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-fuchsia.dark textinput .selection { + background-color: rgba(232, 121, 249, 1); +} + +.accent-fuchsia.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-fuchsia .sidebar-menu-button:hover { background-color: rgba(192, 38, 211, 0.1); } diff --git a/src/styles/accents/fuchsia.css.h b/src/styles/accents/fuchsia.css.h index e978b844..876b429f 100644 --- a/src/styles/accents/fuchsia.css.h +++ b/src/styles/accents/fuchsia.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(232, 121, 249, 0.15);\n", 47 }, { " color: rgba(232, 121, 249, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-fuchsia textinput .selection {\n", 39 }, + { " background-color: rgba(192, 38, 211, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-fuchsia.dark textinput .selection {\n", 44 }, + { " background-color: rgba(232, 121, 249, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_fuchsia_total_length = 5609; +static const size_t css_str_fuchsia_total_length = 5849; static inline void ui_load_css_string_fuchsia_chunks(void) { size_t i; diff --git a/src/styles/accents/green.css b/src/styles/accents/green.css index a36e0aeb..07253538 100644 --- a/src/styles/accents/green.css +++ b/src/styles/accents/green.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-green textinput .selection { + background-color: rgba(22, 163, 74, 1); +} + +.accent-green textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-green.dark textinput .selection { + background-color: rgba(74, 222, 128, 1); +} + +.accent-green.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-green .sidebar-menu-button:hover { background-color: rgba(22, 163, 74, 0.1); } diff --git a/src/styles/accents/green.css.h b/src/styles/accents/green.css.h index 38d82fc5..e64cd4bf 100644 --- a/src/styles/accents/green.css.h +++ b/src/styles/accents/green.css.h @@ -197,8 +197,16 @@ static const struct { { " background-color: rgba(74, 222, 128, 0.15);\n", 46 }, { " color: rgba(74, 222, 128, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-green textinput .selection {\n", 37 }, + { " background-color: rgba(22, 163, 74, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-green.dark textinput .selection {\n", 42 }, + { " background-color: rgba(74, 222, 128, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_green_total_length = 5402; +static const size_t css_str_green_total_length = 5633; static inline void ui_load_css_string_green_chunks(void) { size_t i; diff --git a/src/styles/accents/indigo.css b/src/styles/accents/indigo.css index 7137bba1..5ea2eafe 100644 --- a/src/styles/accents/indigo.css +++ b/src/styles/accents/indigo.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-indigo textinput .selection { + background-color: rgba(79, 70, 229, 1); +} + +.accent-indigo textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-indigo.dark textinput .selection { + background-color: rgba(129, 140, 248, 1); +} + +.accent-indigo.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-indigo .sidebar-menu-button:hover { background-color: rgba(79, 70, 229, 0.1); } diff --git a/src/styles/accents/indigo.css.h b/src/styles/accents/indigo.css.h index b3793ca5..659c9098 100644 --- a/src/styles/accents/indigo.css.h +++ b/src/styles/accents/indigo.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(129, 140, 248, 0.15);\n", 47 }, { " color: rgba(129, 140, 248, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-indigo textinput .selection {\n", 38 }, + { " background-color: rgba(79, 70, 229, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-indigo.dark textinput .selection {\n", 43 }, + { " background-color: rgba(129, 140, 248, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_indigo_total_length = 5522; +static const size_t css_str_indigo_total_length = 5759; static inline void ui_load_css_string_indigo_chunks(void) { size_t i; diff --git a/src/styles/accents/lime.css b/src/styles/accents/lime.css index 42b90be9..a99b4277 100644 --- a/src/styles/accents/lime.css +++ b/src/styles/accents/lime.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-lime textinput .selection { + background-color: rgba(101, 163, 13, 1); +} + +.accent-lime textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-lime.dark textinput .selection { + background-color: rgba(163, 230, 53, 1); +} + +.accent-lime.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-lime .sidebar-menu-button:hover { background-color: rgba(101, 163, 13, 0.1); } diff --git a/src/styles/accents/lime.css.h b/src/styles/accents/lime.css.h index 43a75ef1..bd08839d 100644 --- a/src/styles/accents/lime.css.h +++ b/src/styles/accents/lime.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(163, 230, 53, 0.15);\n", 46 }, { " color: rgba(163, 230, 53, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-lime textinput .selection {\n", 36 }, + { " background-color: rgba(101, 163, 13, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-lime.dark textinput .selection {\n", 41 }, + { " background-color: rgba(163, 230, 53, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_lime_total_length = 5369; +static const size_t css_str_lime_total_length = 5599; static inline void ui_load_css_string_lime_chunks(void) { size_t i; diff --git a/src/styles/accents/neutral.css b/src/styles/accents/neutral.css index 6fc99820..8c60bd06 100644 --- a/src/styles/accents/neutral.css +++ b/src/styles/accents/neutral.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-neutral textinput .selection { + background-color: rgba(23, 23, 23, 1); +} + +.accent-neutral textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-neutral.dark textinput .selection { + background-color: rgba(245, 245, 245, 1); +} + +.accent-neutral.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-neutral .sidebar-menu-button:hover { background-color: rgba(23, 23, 23, 0.1); } diff --git a/src/styles/accents/neutral.css.h b/src/styles/accents/neutral.css.h index c408ff1b..c84272a7 100644 --- a/src/styles/accents/neutral.css.h +++ b/src/styles/accents/neutral.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(245, 245, 245, 0.15);\n", 47 }, { " color: rgba(245, 245, 245, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-neutral textinput .selection {\n", 39 }, + { " background-color: rgba(23, 23, 23, 1);\n", 41 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-neutral.dark textinput .selection {\n", 44 }, + { " background-color: rgba(245, 245, 245, 1);\n", 44 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_neutral_total_length = 5522; +static const size_t css_str_neutral_total_length = 5757; static inline void ui_load_css_string_neutral_chunks(void) { size_t i; diff --git a/src/styles/accents/orange.css b/src/styles/accents/orange.css index 2b192c2f..331f0825 100644 --- a/src/styles/accents/orange.css +++ b/src/styles/accents/orange.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-orange textinput .selection { + background-color: rgba(234, 88, 12, 1); +} + +.accent-orange textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-orange.dark textinput .selection { + background-color: rgba(251, 146, 60, 1); +} + +.accent-orange.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-orange .sidebar-menu-button:hover { background-color: rgba(234, 88, 12, 0.1); } diff --git a/src/styles/accents/orange.css.h b/src/styles/accents/orange.css.h index 8922fa72..1b15bb29 100644 --- a/src/styles/accents/orange.css.h +++ b/src/styles/accents/orange.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(251, 146, 60, 0.15);\n", 46 }, { " color: rgba(251, 146, 60, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-orange textinput .selection {\n", 38 }, + { " background-color: rgba(234, 88, 12, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-orange.dark textinput .selection {\n", 43 }, + { " background-color: rgba(251, 146, 60, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_orange_total_length = 5495; +static const size_t css_str_orange_total_length = 5731; static inline void ui_load_css_string_orange_chunks(void) { size_t i; diff --git a/src/styles/accents/pink.css b/src/styles/accents/pink.css index 31601c36..fc1cd52b 100644 --- a/src/styles/accents/pink.css +++ b/src/styles/accents/pink.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-pink textinput .selection { + background-color: rgba(219, 39, 119, 1); +} + +.accent-pink textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-pink.dark textinput .selection { + background-color: rgba(244, 114, 182, 1); +} + +.accent-pink.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-pink .sidebar-menu-button:hover { background-color: rgba(219, 39, 119, 0.1); } diff --git a/src/styles/accents/pink.css.h b/src/styles/accents/pink.css.h index c43d33c5..8b067acd 100644 --- a/src/styles/accents/pink.css.h +++ b/src/styles/accents/pink.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(244, 114, 182, 0.15);\n", 47 }, { " color: rgba(244, 114, 182, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-pink textinput .selection {\n", 36 }, + { " background-color: rgba(219, 39, 119, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-pink.dark textinput .selection {\n", 41 }, + { " background-color: rgba(244, 114, 182, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_pink_total_length = 5429; +static const size_t css_str_pink_total_length = 5663; static inline void ui_load_css_string_pink_chunks(void) { size_t i; diff --git a/src/styles/accents/purple.css b/src/styles/accents/purple.css index 481c1473..84c1df6b 100644 --- a/src/styles/accents/purple.css +++ b/src/styles/accents/purple.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-purple textinput .selection { + background-color: rgba(147, 51, 234, 1); +} + +.accent-purple textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-purple.dark textinput .selection { + background-color: rgba(192, 132, 252, 1); +} + +.accent-purple.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-purple .sidebar-menu-button:hover { background-color: rgba(147, 51, 234, 0.1); } diff --git a/src/styles/accents/purple.css.h b/src/styles/accents/purple.css.h index 353402cd..c5831f42 100644 --- a/src/styles/accents/purple.css.h +++ b/src/styles/accents/purple.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(192, 132, 252, 0.15);\n", 47 }, { " color: rgba(192, 132, 252, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-purple textinput .selection {\n", 38 }, + { " background-color: rgba(147, 51, 234, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-purple.dark textinput .selection {\n", 43 }, + { " background-color: rgba(192, 132, 252, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_purple_total_length = 5549; +static const size_t css_str_purple_total_length = 5787; static inline void ui_load_css_string_purple_chunks(void) { size_t i; diff --git a/src/styles/accents/red.css b/src/styles/accents/red.css index 39717522..5940d300 100644 --- a/src/styles/accents/red.css +++ b/src/styles/accents/red.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-red textinput .selection { + background-color: rgba(220, 38, 38, 1); +} + +.accent-red textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-red.dark textinput .selection { + background-color: rgba(248, 113, 113, 1); +} + +.accent-red.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-red .sidebar-menu-button:hover { background-color: rgba(220, 38, 38, 0.1); } diff --git a/src/styles/accents/red.css.h b/src/styles/accents/red.css.h index 1d1613cb..f04e2a82 100644 --- a/src/styles/accents/red.css.h +++ b/src/styles/accents/red.css.h @@ -193,8 +193,16 @@ static const struct { { " background-color: rgba(248, 113, 113, 0.15);\n", 47 }, { " color: rgba(248, 113, 113, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-red textinput .selection {\n", 35 }, + { " background-color: rgba(220, 38, 38, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-red.dark textinput .selection {\n", 40 }, + { " background-color: rgba(248, 113, 113, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_red_total_length = 5342; +static const size_t css_str_red_total_length = 5573; static inline void ui_load_css_string_red_chunks(void) { size_t i; diff --git a/src/styles/accents/rose.css b/src/styles/accents/rose.css index 97ac9444..362e1c25 100644 --- a/src/styles/accents/rose.css +++ b/src/styles/accents/rose.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-rose textinput .selection { + background-color: rgba(225, 29, 72, 1); +} + +.accent-rose textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-rose.dark textinput .selection { + background-color: rgba(251, 113, 133, 1); +} + +.accent-rose.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-rose .sidebar-menu-button:hover { background-color: rgba(225, 29, 72, 0.1); } diff --git a/src/styles/accents/rose.css.h b/src/styles/accents/rose.css.h index 696f49df..d8b50b15 100644 --- a/src/styles/accents/rose.css.h +++ b/src/styles/accents/rose.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(251, 113, 133, 0.15);\n", 47 }, { " color: rgba(251, 113, 133, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-rose textinput .selection {\n", 36 }, + { " background-color: rgba(225, 29, 72, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-rose.dark textinput .selection {\n", 41 }, + { " background-color: rgba(251, 113, 133, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_rose_total_length = 5402; +static const size_t css_str_rose_total_length = 5635; static inline void ui_load_css_string_rose_chunks(void) { size_t i; diff --git a/src/styles/accents/sky.css b/src/styles/accents/sky.css index c96e6b6b..9704d317 100644 --- a/src/styles/accents/sky.css +++ b/src/styles/accents/sky.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-sky textinput .selection { + background-color: rgba(2, 132, 199, 1); +} + +.accent-sky textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-sky.dark textinput .selection { + background-color: rgba(56, 189, 248, 1); +} + +.accent-sky.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-sky .sidebar-menu-button:hover { background-color: rgba(2, 132, 199, 0.1); } diff --git a/src/styles/accents/sky.css.h b/src/styles/accents/sky.css.h index 932becad..3c0e4dfa 100644 --- a/src/styles/accents/sky.css.h +++ b/src/styles/accents/sky.css.h @@ -193,8 +193,16 @@ static const struct { { " background-color: rgba(56, 189, 248, 0.15);\n", 46 }, { " color: rgba(56, 189, 248, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-sky textinput .selection {\n", 35 }, + { " background-color: rgba(2, 132, 199, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-sky.dark textinput .selection {\n", 40 }, + { " background-color: rgba(56, 189, 248, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_sky_total_length = 5315; +static const size_t css_str_sky_total_length = 5545; static inline void ui_load_css_string_sky_chunks(void) { size_t i; diff --git a/src/styles/accents/teal.css b/src/styles/accents/teal.css index 3efc0b7f..523526ed 100644 --- a/src/styles/accents/teal.css +++ b/src/styles/accents/teal.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-teal textinput .selection { + background-color: rgba(13, 148, 136, 1); +} + +.accent-teal textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-teal.dark textinput .selection { + background-color: rgba(45, 212, 191, 1); +} + +.accent-teal.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-teal .sidebar-menu-button:hover { background-color: rgba(13, 148, 136, 0.1); } diff --git a/src/styles/accents/teal.css.h b/src/styles/accents/teal.css.h index 8ba3a122..36c09b0e 100644 --- a/src/styles/accents/teal.css.h +++ b/src/styles/accents/teal.css.h @@ -195,8 +195,16 @@ static const struct { { " background-color: rgba(45, 212, 191, 0.15);\n", 46 }, { " color: rgba(45, 212, 191, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-teal textinput .selection {\n", 36 }, + { " background-color: rgba(13, 148, 136, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-teal.dark textinput .selection {\n", 41 }, + { " background-color: rgba(45, 212, 191, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_teal_total_length = 5369; +static const size_t css_str_teal_total_length = 5599; static inline void ui_load_css_string_teal_chunks(void) { size_t i; diff --git a/src/styles/accents/violet.css b/src/styles/accents/violet.css index 5e2b4b70..76bb79da 100644 --- a/src/styles/accents/violet.css +++ b/src/styles/accents/violet.css @@ -238,6 +238,22 @@ color: rgba(250, 250, 250, 1); } +.accent-violet textinput .selection { + background-color: rgba(124, 58, 237, 1); +} + +.accent-violet textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-violet.dark textinput .selection { + background-color: rgba(167, 139, 250, 1); +} + +.accent-violet.dark textinput .selection { + color: rgba(250, 250, 250, 1); +} + .accent-violet .sidebar-menu-button:hover { background-color: rgba(124, 58, 237, 0.1); } diff --git a/src/styles/accents/violet.css.h b/src/styles/accents/violet.css.h index 4877b2fb..feb6e40a 100644 --- a/src/styles/accents/violet.css.h +++ b/src/styles/accents/violet.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(167, 139, 250, 0.15);\n", 47 }, { " color: rgba(167, 139, 250, 1);\n", 33 }, { "}\n", 2 }, + { ".accent-violet textinput .selection {\n", 38 }, + { " background-color: rgba(124, 58, 237, 1);\n", 43 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-violet.dark textinput .selection {\n", 43 }, + { " background-color: rgba(167, 139, 250, 1);\n", 44 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, }; -static const size_t css_str_violet_total_length = 5549; +static const size_t css_str_violet_total_length = 5787; static inline void ui_load_css_string_violet_chunks(void) { size_t i; diff --git a/src/styles/accents/yellow.css b/src/styles/accents/yellow.css index 5de3a838..8c8634f3 100644 --- a/src/styles/accents/yellow.css +++ b/src/styles/accents/yellow.css @@ -238,6 +238,22 @@ color: rgba(23, 23, 23, 1); } +.accent-yellow textinput .selection { + background-color: rgba(202, 138, 4, 1); +} + +.accent-yellow textinput .selection { + color: rgba(250, 250, 250, 1); +} + +.accent-yellow.dark textinput .selection { + background-color: rgba(250, 204, 21, 1); +} + +.accent-yellow.dark textinput .selection { + color: rgba(23, 23, 23, 1); +} + .accent-yellow .sidebar-menu-button:hover { background-color: rgba(202, 138, 4, 0.1); } diff --git a/src/styles/accents/yellow.css.h b/src/styles/accents/yellow.css.h index 9b25b1b5..b2cebc81 100644 --- a/src/styles/accents/yellow.css.h +++ b/src/styles/accents/yellow.css.h @@ -199,8 +199,16 @@ static const struct { { " background-color: rgba(250, 204, 21, 0.15);\n", 46 }, { " color: rgba(250, 204, 21, 1);\n", 32 }, { "}\n", 2 }, + { ".accent-yellow textinput .selection {\n", 38 }, + { " background-color: rgba(202, 138, 4, 1);\n", 42 }, + { " color: rgba(250, 250, 250, 1);\n", 33 }, + { "}\n", 2 }, + { ".accent-yellow.dark textinput .selection {\n", 43 }, + { " background-color: rgba(250, 204, 21, 1);\n", 43 }, + { " color: rgba(23, 23, 23, 1);\n", 30 }, + { "}\n", 2 }, }; -static const size_t css_str_yellow_total_length = 5462; +static const size_t css_str_yellow_total_length = 5695; static inline void ui_load_css_string_yellow_chunks(void) { size_t i; diff --git a/src/styles/style-nova.css b/src/styles/style-nova.css index 1d7934a2..95868d39 100644 --- a/src/styles/style-nova.css +++ b/src/styles/style-nova.css @@ -1657,6 +1657,20 @@ textinput { box-sizing: border-box; } +/* textcaret: structural rules live in src/widgets/textcaret.c; its color + * follows the theme foreground so it stays visible on every background. */ +textcaret { + @apply bg-foreground dark:bg-foreground-dark; +} + +/* textinput selection: solid accent background with its foreground color. + * The widget renders this hidden element's computed style over the selection + * range and draws the selected glyphs again in the foreground color. */ +textinput .selection { + @apply bg-primary text-primary-foreground; + @apply dark:bg-primary-dark dark:text-primary-foreground-dark; +} + textinput:focus { @apply border-foreground dark:border-foreground-dark; box-shadow: theme("boxShadow.focus"); diff --git a/src/styles/style-nova.css.h b/src/styles/style-nova.css.h index 064581d6..dac8514d 100644 --- a/src/styles/style-nova.css.h +++ b/src/styles/style-nova.css.h @@ -2311,6 +2311,12 @@ static const struct { { "textinput {\r\n", 13 }, { " box-sizing: border-box;\n", 26 }, { "}\n", 2 }, + { "textcaret {\r\n", 13 }, + { " background-color: #0a0a0a;\n", 29 }, + { "}\n", 2 }, + { ".dark textcaret {\r\n", 19 }, + { " background-color: #fafafa;\n", 29 }, + { "}\n", 2 }, { "textinput:focus {\r\n", 19 }, { " border-color: #0a0a0a;\n", 25 }, { "}\n", 2 }, @@ -2521,8 +2527,16 @@ static const struct { { ".dark scrollbar-thumb:active {\r\n", 32 }, { " background-color: rgb(250 250 250 / 0.6);\n", 44 }, { "}\n", 2 }, + { "textinput .selection {\r\n", 24 }, + { " background-color: #171717;\r\n", 30 }, + { " color: #fafafa;\n", 18 }, + { "}\n", 2 }, + { ".dark textinput .selection {\r\n", 30 }, + { " background-color: #fafafa;\r\n", 30 }, + { " color: #171717;\n", 18 }, + { "}\n", 2 }, }; -static const size_t css_str_style_nova_total_length = 50776; +static const size_t css_str_style_nova_total_length = 51024; static inline void ui_load_css_string_style_nova_chunks(void) { size_t i; diff --git a/src/widgets/input_group.c b/src/widgets/input_group.c index 018d46e4..a146a696 100644 --- a/src/widgets/input_group.c +++ b/src/widgets/input_group.c @@ -212,11 +212,15 @@ static bool ui_input_group_is_button(ui_widget_t *target, ui_widget_t *stop) static void ui_input_group_on_focus(ui_widget_t *w, ui_event_t *e, void *arg) { ui_widget_add_status(w, "focused"); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_GRAPH_BOX); + ui_widget_request_update(w); } static void ui_input_group_on_blur(ui_widget_t *w, ui_event_t *e, void *arg) { ui_widget_remove_status(w, "focused"); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_GRAPH_BOX); + ui_widget_request_update(w); } static void ui_input_group_on_disabled(ui_widget_t *w, ui_event_t *e, void *arg) diff --git a/src/widgets/textcaret.c b/src/widgets/textcaret.c index 27e9cb87..11c03ce8 100644 --- a/src/widgets/textcaret.c +++ b/src/widgets/textcaret.c @@ -38,7 +38,6 @@ textcaret {\ width: 1px;\ height: 14px;\ position: absolute;\ - background-color: #000;\ }"; void ui_textcaret_refresh(ui_widget_t *widget) diff --git a/src/widgets/textedit.c b/src/widgets/textedit.c new file mode 100644 index 00000000..b7f70cd7 --- /dev/null +++ b/src/widgets/textedit.c @@ -0,0 +1,789 @@ +/* + * src/widgets/textedit.c: -- text editing state used by textinput. + * + * Copyright (c) 2026, Liu Chao All rights reserved. + * + * SPDX-License-Identifier: MIT + * + * This file is part of LCUI, distributed under the MIT License found + * in the LICENSE.TXT file in the root directory of this source tree. + */ + +#include +#include +#include +#include +#include +#include "textedit.h" + +#define STB_TEXTEDIT_CHARTYPE wchar_t +#define STB_TEXTEDIT_NEWLINE L'\n' +#define STB_TEXTEDIT_GETWIDTH_NEWLINE (-1) + +#include "third-party/stb_textedit.h" + +typedef struct ui_text_edit { + wchar_t *text; + int length; + int capacity; + pd_text_t *layer; + STB_TexteditState state; +} ui_text_edit_t; + +static bool ui_text_edit_index_to_caret(ui_text_edit_t *edit, int index, + int *row, int *col); +static int ui_text_edit_eol_length(pd_text_eol_t eol); +static void ui_text_edit_on_changed(ui_text_edit_t *edit); + +static void ui_text_edit_rebuild_layer(ui_text_edit_t *edit) +{ + list_t rects; + + if (!edit->layer) { + return; + } + pd_text_clear(edit->layer); + if (edit->length > 0) { + pd_text_append(edit->layer, edit->text, NULL); + } + list_create(&rects); + pd_text_update(edit->layer, &rects); + pd_rects_clear(&rects); +} + +void ui_text_edit_sync_caret(ui_text_edit_t *edit) +{ + int row = 0, col = 0; + + if (!edit->layer) { + return; + } + ui_text_edit_index_to_caret(edit, edit->state.cursor, &row, &col); + pd_text_set_caret(edit->layer, row, col); +} + +void ui_text_edit_sync_layer(ui_text_edit_t *edit) +{ + if (!edit) { + return; + } + ui_text_edit_rebuild_layer(edit); + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_set_layer(ui_text_edit_t *edit, pd_text_t *layer) +{ + if (!edit) { + return; + } + edit->layer = layer; + ui_text_edit_sync_layer(edit); +} + +void ui_text_edit_set_page_rows(ui_text_edit_t *edit, int rows) +{ + if (!edit) { + return; + } + edit->state.row_count_per_page = rows > 0 ? rows : 1; +} + +int ui_text_edit_get_caret_row(ui_text_edit_t *edit) +{ + return (edit && edit->layer) ? edit->layer->caret.y : 0; +} + +int ui_text_edit_get_caret_col(ui_text_edit_t *edit) +{ + return (edit && edit->layer) ? edit->layer->caret.x : 0; +} + +static void ui_text_edit_on_changed(ui_text_edit_t *edit) +{ + if (!edit->layer) { + return; + } + ui_text_edit_rebuild_layer(edit); + ui_text_edit_sync_caret(edit); +} + +static bool ui_text_edit_index_to_caret(ui_text_edit_t *edit, int index, + int *row, int *col) +{ + int i, start, len, lines; + + *row = 0; + *col = 0; + if (!edit->layer) { + return false; + } + lines = pd_text_get_lines_length(edit->layer); + if (lines <= 0) { + return false; + } + for (i = 0, start = 0; i < lines; ++i) { + len = pd_text_get_line_length(edit->layer, i); + if (index < start) { + continue; + } + if (index < start + len) { + *row = i; + *col = index - start; + return true; + } + if (index == start + len) { + if (i + 1 < lines && + pd_text_get_line_eol(edit->layer, i) == + PD_TEXT_EOL_NONE) { + /* Soft wrap: the index belongs to the next + * visual line for display; stb layout uses + * layout_row_at for the same boundary. */ + start += len; + continue; + } + *row = i; + *col = len; + return true; + } + start += len + ui_text_edit_eol_length( + pd_text_get_line_eol(edit->layer, i)); + } + *row = lines - 1; + *col = pd_text_get_line_length(edit->layer, lines - 1); + return true; +} + +static int ui_text_edit_reserve(ui_text_edit_t *edit, int capacity) +{ + wchar_t *text; + + if (capacity < 0 || capacity > INT_MAX - 1) { + return -1; + } + if (capacity <= edit->capacity) { + return 0; + } + text = realloc(edit->text, sizeof(wchar_t) * (capacity + 1)); + if (!text) { + return -1; + } + edit->text = text; + edit->capacity = capacity; + return 0; +} + +static int ui_text_edit_raw_insert(ui_text_edit_t *edit, int at, + const wchar_t *text, int len) +{ + if (len <= 0 || at < 0 || at > edit->length) { + return 0; + } + if (ui_text_edit_reserve(edit, edit->length + len) != 0) { + return 0; + } + memmove(edit->text + at + len, edit->text + at, + sizeof(wchar_t) * (edit->length - at)); + memcpy(edit->text + at, text, sizeof(wchar_t) * len); + edit->length += len; + edit->text[edit->length] = 0; + ui_text_edit_on_changed(edit); + return 1; +} + +static int ui_text_edit_raw_delete(ui_text_edit_t *edit, int at, int len) +{ + if (len <= 0 || at < 0 || at + len > edit->length) { + return 0; + } + memmove(edit->text + at, edit->text + at + len, + sizeof(wchar_t) * (edit->length - at - len + 1)); + edit->length -= len; + ui_text_edit_on_changed(edit); + return 1; +} + +static int ui_text_edit_eol_length(pd_text_eol_t eol) +{ + switch (eol) { + case PD_TEXT_EOL_CR: + case PD_TEXT_EOL_LF: + return 1; + case PD_TEXT_EOL_CR_LF: + return 2; + case PD_TEXT_EOL_NONE: + default: + break; + } + return 0; +} + +static bool ui_text_edit_is_high_surrogate(wchar_t ch) +{ +#if defined(_WIN32) + return ch >= 0xD800 && ch <= 0xDBFF; +#else + return false; +#endif +} + +static bool ui_text_edit_is_low_surrogate(wchar_t ch) +{ +#if defined(_WIN32) + return ch >= 0xDC00 && ch <= 0xDFFF; +#else + return false; +#endif +} + +static int ui_text_edit_next_index(ui_text_edit_t *edit, int i) +{ + if (i < 0 || i >= edit->length) { + return edit->length; + } + if (i + 1 < edit->length && + ui_text_edit_is_high_surrogate(edit->text[i]) && + ui_text_edit_is_low_surrogate(edit->text[i + 1])) { + return i + 2; + } + return i + 1; +} + +static int ui_text_edit_prev_index(ui_text_edit_t *edit, int i) +{ + if (i <= 0) { + return 0; + } + if (i >= 2 && ui_text_edit_is_low_surrogate(edit->text[i - 1]) && + ui_text_edit_is_high_surrogate(edit->text[i - 2])) { + return i - 2; + } + return i - 1; +} + +static bool ui_text_edit_layout_row_at(ui_text_edit_t *edit, int at, int *row, + int *col) +{ + int i, start, len, lines; + + *row = 0; + *col = 0; + if (!edit->layer) { + return false; + } + lines = pd_text_get_lines_length(edit->layer); + if (lines <= 0) { + return false; + } + for (i = 0, start = 0; i < lines; ++i) { + len = pd_text_get_line_length(edit->layer, i); + if (at == start) { + *row = i; + *col = 0; + return true; + } + if (at > start && at < start + len) { + *row = i; + *col = at - start; + return true; + } + if (at == start + len) { + if (i + 1 < lines && + pd_text_get_line_eol(edit->layer, i) == + PD_TEXT_EOL_NONE) { + /* Soft wrap: the next visual line starts at + * this index, so LAYOUTROW must use it. */ + start += len; + continue; + } + *row = i; + *col = len; + return true; + } + start += len + ui_text_edit_eol_length( + pd_text_get_line_eol(edit->layer, i)); + } + *row = lines - 1; + *col = pd_text_get_line_length(edit->layer, lines - 1); + return true; +} + +static void ui_text_edit_layout_row(ui_text_edit_t *edit, int at, + StbTexteditRow *row) +{ + int line, col, len; + pd_pos_t pos; + pd_text_line_t *text_line; + + row->x0 = 0; + row->x1 = 0; + row->baseline_y_delta = 0; + row->ymin = 0; + row->ymax = 0; + row->num_chars = 0; + if (!edit->layer || + !ui_text_edit_layout_row_at(edit, at, &line, &col)) { + return; + } + text_line = edit->layer->lines[line]; + if (!text_line) { + return; + } + len = text_line->length; + if (col > len) { + col = len; + } + row->num_chars = + len - col + + ui_text_edit_eol_length(pd_text_get_line_eol(edit->layer, line)); + row->baseline_y_delta = + (float)pd_text_get_line_height(edit->layer, line); + row->ymin = 0; + row->ymax = row->baseline_y_delta; + if (pd_text_get_char_pixel(edit->layer, line, 0, &pos) == 0) { + row->x0 = (float)pos.x; + row->x1 = row->x0 + (float)text_line->width; + } +} + +static int ui_text_edit_get_width(ui_text_edit_t *edit, int row_start, int i) +{ + int line, col; + pd_text_line_t *text_line; + pd_char_t *ch; + + if (!edit->layer || + !ui_text_edit_layout_row_at(edit, row_start, &line, &col)) { + return 0; + } + text_line = edit->layer->lines[line]; + if (!text_line || col + i >= text_line->length) { + return STB_TEXTEDIT_GETWIDTH_NEWLINE; + } + ch = text_line->string[col + i]; + if (!ch || !ch->bitmap) { + return 0; + } + return ch->bitmap->metrics.hori_advance; +} + +#define STB_TEXTEDIT_STRING ui_text_edit_t +#define STB_TEXTEDIT_STRINGLEN(e) ((e)->length) +#define STB_TEXTEDIT_GETCHAR(e, i) ((e)->text[i]) +#define STB_TEXTEDIT_INSERTCHARS(e, i, c, n) \ + ui_text_edit_raw_insert(e, i, c, (int)(n)) +#define STB_TEXTEDIT_DELETECHARS(e, i, n) \ + ui_text_edit_raw_delete(e, i, (int)(n)) +#define STB_TEXTEDIT_LAYOUTROW(r, e, i) ui_text_edit_layout_row(e, i, r) +#define STB_TEXTEDIT_GETWIDTH(e, s, i) ui_text_edit_get_width(e, s, i) +#define STB_TEXTEDIT_IS_SPACE(ch) iswspace(ch) + +#define STB_TEXTEDIT_K_SHIFT UI_TEXT_EDIT_KEY_SHIFT +#define STB_TEXTEDIT_K_LEFT UI_TEXT_EDIT_KEY_LEFT +#define STB_TEXTEDIT_K_RIGHT UI_TEXT_EDIT_KEY_RIGHT +#define STB_TEXTEDIT_K_UP UI_TEXT_EDIT_KEY_UP +#define STB_TEXTEDIT_K_DOWN UI_TEXT_EDIT_KEY_DOWN +#define STB_TEXTEDIT_K_PGUP UI_TEXT_EDIT_KEY_PGUP +#define STB_TEXTEDIT_K_PGDOWN UI_TEXT_EDIT_KEY_PGDOWN +#define STB_TEXTEDIT_K_LINESTART UI_TEXT_EDIT_KEY_LINESTART +#define STB_TEXTEDIT_K_LINEEND UI_TEXT_EDIT_KEY_LINEEND +#define STB_TEXTEDIT_K_TEXTSTART UI_TEXT_EDIT_KEY_TEXTSTART +#define STB_TEXTEDIT_K_TEXTEND UI_TEXT_EDIT_KEY_TEXTEND +#define STB_TEXTEDIT_K_DELETE UI_TEXT_EDIT_KEY_DELETE +#define STB_TEXTEDIT_K_BACKSPACE UI_TEXT_EDIT_KEY_BACKSPACE +#define STB_TEXTEDIT_K_UNDO UI_TEXT_EDIT_KEY_UNDO +#define STB_TEXTEDIT_K_REDO UI_TEXT_EDIT_KEY_REDO +#define STB_TEXTEDIT_K_WORDLEFT UI_TEXT_EDIT_KEY_WORDLEFT +#define STB_TEXTEDIT_K_WORDRIGHT UI_TEXT_EDIT_KEY_WORDRIGHT +#define STB_TEXTEDIT_GETPREVCHARINDEX(e, i) ui_text_edit_prev_index(e, i) +#define STB_TEXTEDIT_GETNEXTCHARINDEX(e, i) ui_text_edit_next_index(e, i) + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4244) +#elif defined(__GNUC__) +/* stb_textedit is vendored as-is; it contains helpers (and a dead local) that + * our integration does not call. Silence those diagnostics only for the + * implementation translation unit so -Werror does not reject the header. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-function" +#endif +#define STB_TEXTEDIT_IMPLEMENTATION +#include "third-party/stb_textedit.h" +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +ui_text_edit_t *ui_text_edit_create(void) +{ + ui_text_edit_t *edit = calloc(1, sizeof(ui_text_edit_t)); + + if (!edit) { + return NULL; + } + ui_text_edit_reserve(edit, 32); + stb_textedit_initialize_state(&edit->state, 0); + return edit; +} + +void ui_text_edit_destroy(ui_text_edit_t *edit) +{ + if (!edit) { + return; + } + free(edit->text); + free(edit); +} + +void ui_text_edit_set_text(ui_text_edit_t *edit, const wchar_t *text, + size_t len) +{ + size_t i; + int j = 0; + + if (!edit) { + return; + } + if (!text) { + len = 0; + } + if (len > (size_t)INT_MAX) { + return; + } + if (ui_text_edit_reserve(edit, (int)len) != 0) { + return; + } + for (i = 0; i < len; ++i) { + if (text[i] == L'\r') { + if (i + 1 < len && text[i + 1] == L'\n') { + ++i; + } + edit->text[j++] = L'\n'; + } else { + edit->text[j++] = text[i]; + } + } + edit->length = j; + edit->text[edit->length] = 0; + stb_textedit_initialize_state(&edit->state, 0); + /* Match the previous textinput behavior: after set_text the caret is + * at the end, so subsequent typing appends. */ + edit->state.cursor = edit->length; + edit->state.select_start = edit->length; + edit->state.select_end = edit->length; + ui_text_edit_sync_layer(edit); +} + +size_t ui_text_edit_get_text(ui_text_edit_t *edit, size_t start, size_t max_len, + wchar_t *buf) +{ + size_t n = 0; + + if (!buf || max_len == 0) { + if (buf) { + buf[0] = 0; + } + return 0; + } + if (!edit || start >= (size_t)edit->length) { + buf[0] = 0; + return 0; + } + while (n < max_len && start + n < (size_t)edit->length) { + buf[n] = edit->text[start + n]; + ++n; + } + buf[n] = 0; + return n; +} + +size_t ui_text_edit_get_length(ui_text_edit_t *edit) +{ + return edit ? (size_t)edit->length : 0; +} + +void ui_text_edit_text_input(ui_text_edit_t *edit, const wchar_t *text, + size_t len) +{ + size_t i, j; + wchar_t *normalized; + bool has_cr = false; + + if (!edit || !text || len == 0) { + return; + } + if (len > (size_t)INT_MAX) { + return; + } + for (i = 0; i < len; ++i) { + if (text[i] == L'\r') { + has_cr = true; + break; + } + } + if (!has_cr) { + stb_textedit_text(edit, &edit->state, (wchar_t *)text, + (int)len); + ui_text_edit_sync_caret(edit); + return; + } + normalized = malloc(sizeof(wchar_t) * (len + 1)); + if (!normalized) { + return; + } + for (i = 0, j = 0; i < len; ++i) { + if (text[i] == L'\r') { + if (i + 1 < len && text[i + 1] == L'\n') { + ++i; + } + normalized[j++] = L'\n'; + } else { + normalized[j++] = text[i]; + } + } + stb_textedit_text(edit, &edit->state, normalized, (int)j); + free(normalized); + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_key(ui_text_edit_t *edit, int key) +{ + if (!edit) { + return; + } + stb_textedit_key(edit, &edit->state, key); + ui_text_edit_sync_caret(edit); +} + +static int ui_text_edit_clamp_index(ui_text_edit_t *edit, int index) +{ + if (index < 0) { + return 0; + } + if (index > edit->length) { + return edit->length; + } + if (index > 0 && index < edit->length && + ui_text_edit_is_low_surrogate(edit->text[index]) && + ui_text_edit_is_high_surrogate(edit->text[index - 1])) { + --index; + } + return index; +} + +void ui_text_edit_move_caret_extend(ui_text_edit_t *edit, int row, int col, + bool extend) +{ + int index = 0; + + if (!edit) { + return; + } + if (edit->layer) { + int lines = pd_text_get_lines_length(edit->layer); + if (row < 0) { + row = 0; + } else if (lines > 0 && row >= lines) { + row = lines - 1; + } + index = pd_text_get_line_char_start(edit->layer, row); + col = pd_text_get_line_length(edit->layer, row) < col + ? pd_text_get_line_length(edit->layer, row) + : col; + if (col < 0) { + col = 0; + } + index += col; + } + index = ui_text_edit_clamp_index(edit, index); + if (extend) { + if (edit->state.select_start == edit->state.select_end) { + edit->state.select_start = edit->state.cursor; + } + edit->state.cursor = index; + edit->state.select_end = index; + } else { + edit->state.cursor = index; + edit->state.select_start = index; + edit->state.select_end = index; + } + edit->state.has_preferred_x = 0; + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_move_caret(ui_text_edit_t *edit, int row, int col) +{ + ui_text_edit_move_caret_extend(edit, row, col, false); +} + +void ui_text_edit_move_vertical(ui_text_edit_t *edit, int delta, bool extend) +{ + int row, col, lines, target, i, start, len, best_col = 0; + int target_x, best_dx = INT_MAX; + pd_pos_t pos; + + if (!edit || !edit->layer || delta == 0) { + return; + } + ui_text_edit_index_to_caret(edit, edit->state.cursor, &row, &col); + if (!edit->state.has_preferred_x) { + if (pd_text_get_char_pixel(edit->layer, row, col, &pos) != 0) { + return; + } + edit->state.preferred_x = (float)pos.x; + edit->state.has_preferred_x = 1; + } + target_x = (int)edit->state.preferred_x; + lines = pd_text_get_lines_length(edit->layer); + target = row + delta; + if (target < 0) { + target = 0; + } else if (target >= lines) { + target = lines - 1; + } + start = pd_text_get_line_char_start(edit->layer, target); + len = pd_text_get_line_length(edit->layer, target); + for (i = 0; i <= len; ++i) { + int dx; + + if (pd_text_get_char_pixel(edit->layer, target, i, &pos) != 0) { + break; + } + dx = pos.x - target_x; + if (dx < 0) { + dx = -dx; + } + if (dx < best_dx) { + best_dx = dx; + best_col = i; + } + } + if (extend) { + if (edit->state.select_start == edit->state.select_end) { + edit->state.select_start = edit->state.cursor; + } + edit->state.cursor = + ui_text_edit_clamp_index(edit, start + best_col); + edit->state.select_end = edit->state.cursor; + } else { + edit->state.cursor = + ui_text_edit_clamp_index(edit, start + best_col); + edit->state.select_start = edit->state.cursor; + edit->state.select_end = edit->state.cursor; + } + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_append_text(ui_text_edit_t *edit, const wchar_t *text, + size_t len) +{ + if (!edit || !text || len == 0 || len > (size_t)INT_MAX) { + return; + } + edit->state.cursor = edit->length; + edit->state.select_start = edit->length; + edit->state.select_end = edit->length; + ui_text_edit_text_input(edit, text, len); +} + +void ui_text_edit_click(ui_text_edit_t *edit, float x, float y) +{ + if (!edit) { + return; + } + stb_textedit_click(edit, &edit->state, x, y); + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_drag(ui_text_edit_t *edit, float x, float y) +{ + if (!edit) { + return; + } + stb_textedit_drag(edit, &edit->state, x, y); + ui_text_edit_sync_caret(edit); +} + +bool ui_text_edit_has_selection(ui_text_edit_t *edit) +{ + return edit && edit->state.select_start != edit->state.select_end; +} + +void ui_text_edit_selection(ui_text_edit_t *edit, size_t *start, size_t *end) +{ + size_t a = 0, b = 0; + + if (edit) { + a = (size_t)edit->state.select_start; + b = (size_t)edit->state.select_end; + } + if (a > b) { + size_t tmp = a; + a = b; + b = tmp; + } + if (start) { + *start = a; + } + if (end) { + *end = b; + } +} + +void ui_text_edit_select_all(ui_text_edit_t *edit) +{ + if (!edit) { + return; + } + edit->state.select_start = 0; + edit->state.select_end = edit->length; + edit->state.cursor = edit->length; + edit->state.has_preferred_x = 0; + ui_text_edit_sync_caret(edit); +} + +void ui_text_edit_clear_selection(ui_text_edit_t *edit) +{ + if (!edit) { + return; + } + edit->state.select_start = edit->state.cursor; + edit->state.select_end = edit->state.cursor; + ui_text_edit_sync_caret(edit); +} + +size_t ui_text_edit_copy(ui_text_edit_t *edit, wchar_t *buf, size_t max_len) +{ + size_t start, end, n = 0; + + if (!buf || max_len == 0) { + if (buf) { + buf[0] = 0; + } + return 0; + } + ui_text_edit_selection(edit, &start, &end); + if (!edit) { + buf[0] = 0; + return 0; + } + while (n < max_len && start + n < end) { + buf[n] = edit->text[start + n]; + ++n; + } + buf[n] = 0; + return n; +} + +size_t ui_text_edit_cut(ui_text_edit_t *edit, wchar_t *buf, size_t max_len) +{ + size_t n = ui_text_edit_copy(edit, buf, max_len); + + if (edit) { + stb_textedit_cut(edit, &edit->state); + ui_text_edit_sync_caret(edit); + } + return n; +} diff --git a/src/widgets/textedit.h b/src/widgets/textedit.h new file mode 100644 index 00000000..404519ee --- /dev/null +++ b/src/widgets/textedit.h @@ -0,0 +1,101 @@ +/* + * src/widgets/textedit.h: -- text editing state used by textinput. + * + * Copyright (c) 2026, Liu Chao All rights reserved. + * + * SPDX-License-Identifier: MIT + * + * This file is part of LCUI, distributed under the MIT License found + * in the LICENSE.TXT file in the root directory of this source tree. + */ + +#ifndef LCUI_WIDGETS_TEXTEDIT_H +#define LCUI_WIDGETS_TEXTEDIT_H + +#include +#include +#include +#include + +/* Keyboard input is encoded as a single integer. The shift state must be a + * power of two. Character input is submitted through + * ui_text_edit_text_input() instead of these key values. */ +typedef enum ui_text_edit_key { + UI_TEXT_EDIT_KEY_LEFT = 0x00000001, + UI_TEXT_EDIT_KEY_RIGHT = 0x00000002, + UI_TEXT_EDIT_KEY_UP = 0x00000003, + UI_TEXT_EDIT_KEY_DOWN = 0x00000004, + UI_TEXT_EDIT_KEY_PGUP = 0x00000005, + UI_TEXT_EDIT_KEY_PGDOWN = 0x00000006, + UI_TEXT_EDIT_KEY_LINESTART = 0x00000007, + UI_TEXT_EDIT_KEY_LINEEND = 0x00000008, + UI_TEXT_EDIT_KEY_TEXTSTART = 0x00000009, + UI_TEXT_EDIT_KEY_TEXTEND = 0x0000000a, + UI_TEXT_EDIT_KEY_DELETE = 0x0000000b, + UI_TEXT_EDIT_KEY_BACKSPACE = 0x0000000c, + UI_TEXT_EDIT_KEY_UNDO = 0x0000000d, + UI_TEXT_EDIT_KEY_REDO = 0x0000000e, + UI_TEXT_EDIT_KEY_WORDLEFT = 0x0000000f, + UI_TEXT_EDIT_KEY_WORDRIGHT = 0x00000010, + UI_TEXT_EDIT_KEY_SHIFT = 0x20000000 +} ui_text_edit_key_t; + +typedef struct ui_text_edit ui_text_edit_t; + +ui_text_edit_t *ui_text_edit_create(void); +void ui_text_edit_destroy(ui_text_edit_t *edit); + +/** Replace the whole text. CRLF and CR are normalized to LF. */ +void ui_text_edit_set_text(ui_text_edit_t *edit, const wchar_t *text, + size_t len); + +/** Copy up to max_len characters starting at start. Returns copied count. */ +size_t ui_text_edit_get_text(ui_text_edit_t *edit, size_t start, size_t max_len, + wchar_t *buf); + +size_t ui_text_edit_get_length(ui_text_edit_t *edit); + +/** Insert committed text at the cursor (IME / paste / typing). */ +void ui_text_edit_text_input(ui_text_edit_t *edit, const wchar_t *text, + size_t len); + +/** Send a navigation or editing key, e.g. UI_TEXT_EDIT_KEY_BACKSPACE. */ +void ui_text_edit_key(ui_text_edit_t *edit, int key); + +/** Move the caret to a visual row/column. */ +void ui_text_edit_move_caret(ui_text_edit_t *edit, int row, int col); + +/** Move the caret to a visual row/column, optionally extending the selection. + */ +void ui_text_edit_move_caret_extend(ui_text_edit_t *edit, int row, int col, + bool extend); + +/** Move the caret up/down by visual rows, keeping the preferred x. */ +void ui_text_edit_move_vertical(ui_text_edit_t *edit, int delta, bool extend); + +/** Append text at the end regardless of the current caret. */ +void ui_text_edit_append_text(ui_text_edit_t *edit, const wchar_t *text, + size_t len); + +/** Mouse click/drag, in text-layer pixel coordinates (origin = text top-left). + */ +void ui_text_edit_click(ui_text_edit_t *edit, float x, float y); +void ui_text_edit_drag(ui_text_edit_t *edit, float x, float y); + +bool ui_text_edit_has_selection(ui_text_edit_t *edit); +void ui_text_edit_selection(ui_text_edit_t *edit, size_t *start, size_t *end); +void ui_text_edit_select_all(ui_text_edit_t *edit); +void ui_text_edit_clear_selection(ui_text_edit_t *edit); +size_t ui_text_edit_copy(ui_text_edit_t *edit, wchar_t *buf, size_t max_len); +size_t ui_text_edit_cut(ui_text_edit_t *edit, wchar_t *buf, size_t max_len); + +/* Layout projection: the pd_text layer is rebuilt from the canonical text + * after every edit, and the stb caret index is mapped to its visual row/col. */ +void ui_text_edit_set_layer(ui_text_edit_t *edit, pd_text_t *layer); +void ui_text_edit_set_page_rows(ui_text_edit_t *edit, int rows); +void ui_text_edit_sync_layer(ui_text_edit_t *edit); +void ui_text_edit_sync_caret(ui_text_edit_t *edit); +int ui_text_edit_get_caret_row(ui_text_edit_t *edit); +int ui_text_edit_get_caret_col(ui_text_edit_t *edit); + +#endif diff --git a/src/widgets/textinput.c b/src/widgets/textinput.c index 6cf302e4..f015ff02 100644 --- a/src/widgets/textinput.c +++ b/src/widgets/textinput.c @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -20,58 +21,35 @@ #include #include #include "textstyle.h" +#include "textedit.h" -#define TEXTBLOCK_SIZE 512 #define DEFAULT_WIDTH 176.0f #define PLACEHOLDER_COLOR pd_rgb(140, 140, 140) -enum task_type_t { TASK_SET_TEXT, TASK_UPDATE, TASK_TOTAL }; +enum task_type_t { TASK_UPDATE, TASK_TOTAL }; typedef struct ui_textinput { - ui_text_style_t style; /**< 字体样式 */ - pd_text_t *layer_source; /**< 实际文本层 */ - pd_text_t *layer_mask; /**< 屏蔽后的文本层 */ - pd_text_t *layer_placeholder; /**< 占位符的文本层 */ - pd_text_t *layer; /**< 当前使用的文本层 */ - ui_widget_t *scrollbars[2]; /**< 两个滚动条 */ - ui_widget_t *caret; /**< 文本插入符 */ - bool is_read_only; /**< 是否只读 */ - bool is_multiline_mode; /**< 是否为多行模式 */ - bool placeholder_visible; /**< 是否已经显示占位符 */ - wchar_t *allow_input_char; /**< 允许输入的字符 */ - wchar_t password_char; /**< 屏蔽符的副本 */ - size_t text_block_size; /**< 块大小 */ - list_t text_blocks; /**< 文本块缓冲区 */ - list_t text_tags; /**< 当前处理的标签列表 */ - bool tasks[TASK_TOTAL]; /**< 待处理的任务 */ - thread_mutex_t mutex; /**< 互斥锁 */ + ui_text_style_t style; /**< 字体样式 */ + pd_color_t selection_color; /**< 选区背景色 */ + pd_color_t selection_text_color; /**< 选区文字颜色 */ + ui_text_edit_t *editor; /**< 文本编辑状态(canonical text) */ + pd_text_t *layer_source; /**< 实际文本层 */ + pd_text_t *layer_mask; /**< 屏蔽后的文本层 */ + pd_text_t *layer_placeholder; /**< 占位符的文本层 */ + pd_text_t *layer; /**< 当前使用的文本层 */ + float layer_scale; /**< 文本层排版时使用的实际缩放比例 */ + ui_widget_t *caret; /**< 文本插入符 */ + ui_widget_t *selection_style; /**< 承载选区样式(0x0 隐藏元素) */ + bool is_read_only; /**< 是否只读 */ + bool is_multiline_mode; /**< 是否为多行模式 */ + bool placeholder_visible; /**< 是否已经显示占位符 */ + wchar_t *allow_input_char; /**< 允许输入的字符 */ + wchar_t password_char; /**< 屏蔽符的副本 */ + bool change_pending; /**< 是否有待发送的 change 事件 */ + bool tasks[TASK_TOTAL]; /**< 待处理的任务 */ + thread_mutex_t mutex; /**< 互斥锁 */ } ui_textinput_t; -typedef enum { - TEXTBLOCK_BEGIN, - TEXTBLOCK_BODY, - TEXTBLOCK_END -} textblock_type_t; - -typedef enum { - TEXTBLOCK_ACTION_INSERT, - TEXTBLOCK_ACTION_APPEND -} textblock_action_t; - -typedef enum { - TEXTBLOCK_OWNER_SOURCE, - TEXTBLOCK_OWNER_PLACEHOLDER -} textblock_owner_t; - -/** 文本块数据结构 */ -typedef struct textblock { - textblock_type_t type; /**< 文本块类型 */ - textblock_owner_t owner; /**< 所属的文本层 */ - textblock_action_t action; /**< 指定该文本块的添加方式 */ - wchar_t *text; /**< 文本块(段) */ - size_t length; /**< 文本块的长度 */ -} textblock_t; - static ui_widget_prototype_t *ui_textinput_proto; static const char *ui_textinput_css = "\ @@ -92,16 +70,6 @@ textinput:disabled {\ opacity: 0.45;\ }"; -static void fillchar(wchar_t *str, wchar_t ch) -{ - if (str) { - wchar_t *p; - for (p = str; *p; ++p) { - *p = ch; - } - } -} - static void ui_textinput_update_caret(ui_widget_t *widget) { ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); @@ -109,9 +77,16 @@ static void ui_textinput_update_caret(ui_widget_t *widget) int row = edit->layer->caret.y; int offset_x, offset_y; float height, width; - float scale = ui_get_actual_scale(); + float scale = edit->layer_scale; float x, y, caret_x = 0, caret_y = 0; + /* A transient zero-sized layout (e.g. a column collapsing during a + * focus/reflow pass) must not scroll the text layer; otherwise the + * caret update can move the whole text out of view. */ + if (widget->content_box.width <= 0 || widget->content_box.height <= 0) { + return; + } + if (!edit->placeholder_visible) { pd_pos_t pos; if (pd_text_get_caret_pixel(edit->layer, &pos) != 0) { @@ -160,244 +135,94 @@ static void ui_textinput_update_caret(ui_widget_t *widget) ui_widget_move(edit->caret, x, y); ui_textcaret_refresh(edit->caret); if (edit->password_char) { - pd_text_set_caret(edit->layer_source, edit->layer->caret.y, - edit->layer->caret.x); + pd_text_set_caret(edit->layer_mask, + ui_text_edit_get_caret_row(edit->editor), + ui_text_edit_get_caret_col(edit->editor)); } } +static void ui_textinput_update_caret_by_pointer(ui_widget_t *w, ui_event_t *e, + bool drag) +{ + float scale, offset_x, offset_y, x, y; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + /* 鼠标坐标是逻辑像素,文本层按 layer_scale 排版为实际像素 */ + scale = edit->layer_scale; + ui_widget_get_offset(w, NULL, &offset_x, &offset_y); + x = (e->mouse.x - offset_x - w->computed_style.padding_left) * scale; + y = (e->mouse.y - offset_y - w->computed_style.padding_top) * scale; + if (edit->password_char) { + /* 密码显示层是统一宽度的 mask,命中检测必须与显示同源 */ + pd_text_set_caret_pixel(edit->layer_mask, (int)x, (int)y); + ui_text_edit_move_caret_extend(edit->editor, + edit->layer_mask->caret.y, + edit->layer_mask->caret.x, drag); + } else if (drag) { + ui_text_edit_drag(edit->editor, + x - edit->layer_source->offset_x, + y - edit->layer_source->offset_y); + } else { + ui_text_edit_click(edit->editor, + x - edit->layer_source->offset_x, + y - edit->layer_source->offset_y); + } + if (edit->password_char) { + pd_text_set_caret(edit->layer_mask, + ui_text_edit_get_caret_row(edit->editor), + ui_text_edit_get_caret_col(edit->editor)); + } + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_CONTENT_BOX); + ui_textinput_update_caret(w); +} + void ui_textinput_move_caret(ui_widget_t *widget, int row, int col) { ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); + if (edit->placeholder_visible) { row = col = 0; } - pd_text_set_caret(edit->layer, row, col); - ui_textinput_update_caret(widget); -} - -static void textblock_destroy(textblock_t *blk) -{ - free(blk->text); - blk->text = NULL; - free(blk); -} - -static int ui_textinput_add_textblock(ui_widget_t *widget, const wchar_t *wtext, - textblock_action_t action, - textblock_owner_t owner) -{ - const wchar_t *p; - ui_textinput_t *edit; - textblock_t *block; - size_t i, j, len, tag_len, size; - - if (!wtext) { - return -1; - } - len = wcslen(wtext); - edit = ui_widget_get_data(widget, ui_textinput_proto); - for (i = 0; i < len; ++i) { - block = malloc(sizeof(textblock_t)); - if (!block) { - return -ENOMEM; - } - block->owner = owner; - block->action = action; - size = edit->text_block_size; - if (i == 0) { - block->type = TEXTBLOCK_BEGIN; - } else if (len - i > edit->text_block_size) { - block->type = TEXTBLOCK_BODY; - } else { - size = len - i; - block->type = TEXTBLOCK_END; - } - block->text = malloc(sizeof(wchar_t) * size); - if (!block->text) { - return -ENOMEM; - } - /* 如果未启用样式标签功能 */ - if (!edit->layer->style_tag_enabled) { - for (j = 0; i < len && j < size - 1; ++j, ++i) { - block->text[j] = wtext[i]; - } - --i; - block->text[j] = 0; - block->length = j; - list_append(&edit->text_blocks, block); - continue; - } - for (j = 0; i < len && j < size - 1; ++j, ++i) { - wchar_t *text; - block->text[j] = wtext[i]; - /* 检测是否有样式标签 */ - p = pd_scan_style_open_tag(wtext + i, NULL, 0, NULL); - if (!p) { - p = pd_scan_style_close_tag(wtext + i, NULL); - if (!p) { - continue; - } - } - /* 计算标签的长度 */ - tag_len = p - wtext - i; - /* 若当前块大小能够容纳这个标签 */ - if (j + tag_len <= size - 1) { - continue; - } - /* 重新计算该文本块的大小,并重新分配内存空间 */ - size = j + tag_len + 1; - text = realloc(block->text, sizeof(wchar_t) * size); - if (!text) { - return -ENOMEM; - } - block->text = text; - } - --i; - block->text[j] = 0; - block->length = j; - /* 添加文本块至缓冲区 */ - list_append(&edit->text_blocks, block); - } - edit->tasks[TASK_SET_TEXT] = true; - ui_widget_request_update(widget); - return 0; -} - -/** 更新文本框内的字体位图 */ -static void textinput_process_textblock(ui_widget_t *widget, - textblock_t *txtblk) -{ - list_t *tags; - ui_textinput_t *edit; - pd_text_t *layer; - - edit = ui_widget_get_data(widget, ui_textinput_proto); - switch (txtblk->owner) { - case TEXTBLOCK_OWNER_SOURCE: - layer = edit->layer_source; - tags = &edit->text_tags; - break; - case TEXTBLOCK_OWNER_PLACEHOLDER: - layer = edit->layer_placeholder; - tags = NULL; - break; - default: - return; - } - switch (txtblk->action) { - case TEXTBLOCK_ACTION_APPEND: - /* 将此文本块追加至文本末尾 */ - pd_text_append(layer, txtblk->text, tags); - break; - case TEXTBLOCK_ACTION_INSERT: - /* 将此文本块插入至文本插入符所在处 */ - pd_text_insert(layer, txtblk->text, tags); - default: - break; - } - if (edit->password_char && txtblk->owner == TEXTBLOCK_OWNER_SOURCE) { - wchar_t *text = malloc(sizeof(wchar_t) * (txtblk->length + 1)); - wcsncpy(text, txtblk->text, txtblk->length + 1); - fillchar(text, edit->password_char); - layer = edit->layer_mask; - if (txtblk->action == TEXTBLOCK_ACTION_INSERT) { - pd_text_insert(layer, text, NULL); - } else { - pd_text_append(layer, text, NULL); - } - free(text); - } -} - -/** 更新文本框的文本图层 */ -static void textinput_update_textlayer(ui_widget_t *w) -{ - float scale; - list_t rects; - ui_rect_t rect; - ui_textinput_t *edit; - pd_text_style_t style; - list_node_t *node; - - list_create(&rects); - scale = ui_get_actual_scale(); - edit = ui_widget_get_data(w, ui_textinput_proto); - pd_text_style_copy(&style, &edit->layer_source->default_style); + ui_text_edit_move_caret(edit->editor, row, col); if (edit->password_char) { - pd_text_set_style(edit->layer_mask, &style); + pd_text_set_caret(edit->layer_mask, + ui_text_edit_get_caret_row(edit->editor), + ui_text_edit_get_caret_col(edit->editor)); } - style.has_fore_color = true; - style.fore_color = PLACEHOLDER_COLOR; - pd_text_set_style(edit->layer_placeholder, &style); - pd_text_style_destroy(&style); - pd_text_update(edit->layer, &rects); - for (list_each(node, &rects)) { - ui_rect_from_pd_rect(&rect, node->data, scale); - ui_widget_mark_dirty_rect(w, &rect, UI_BOX_TYPE_CONTENT_BOX); - } - pd_rects_clear(&rects); -} - -static void ui_textinput_update(ui_widget_t *w) -{ - ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - bool placeholder_visible = edit->layer_source->length == 0; - - if (placeholder_visible) { - edit->layer = edit->layer_placeholder; - } else if (edit->password_char) { - edit->layer = edit->layer_mask; - } else { - edit->layer = edit->layer_source; - } - textinput_update_textlayer(w); - if (edit->placeholder_visible != placeholder_visible) { - ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_PADDING_BOX); - } - edit->placeholder_visible = placeholder_visible; - ui_textinput_update_caret(w); -} - -static void ui_textinput_update_text(ui_widget_t *widget) -{ - list_t blocks; - list_node_t *node; - ui_event_t ev; - ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); - - list_create(&blocks); - thread_mutex_lock(&edit->mutex); - list_concat(&blocks, &edit->text_blocks); - thread_mutex_unlock(&edit->mutex); - for (list_each(node, &blocks)) { - textinput_process_textblock(widget, node->data); - } - list_destroy(&blocks, (list_item_destructor_t)textblock_destroy); - ui_event_init(&ev, "change"); - ui_widget_emit_event(widget, ev, NULL); + ui_textinput_update_caret(widget); + ui_widget_mark_dirty_rect(widget, NULL, UI_BOX_TYPE_CONTENT_BOX); } static void ui_textinput_on_resize(ui_widget_t *w, float width, float height) { + int i; float scale = ui_get_actual_scale(); - list_t rects; list_node_t *node; - ui_rect_t rect; + pd_text_t *layers[3]; ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - list_create(&rects); - pd_text_set_fixed_size(edit->layer, (int)(width * scale), - (int)(width * scale)); - pd_text_set_max_size(edit->layer, (int)(height * scale), - (int)(height * scale)); - pd_text_update(edit->layer, &rects); - for (list_each(node, &rects)) { - ui_rect_from_pd_rect(&rect, node->data, scale); - ui_widget_mark_dirty_rect(w, &rect, UI_BOX_TYPE_CONTENT_BOX); + layers[0] = edit->layer_source; + layers[1] = edit->layer_mask; + layers[2] = edit->layer_placeholder; + edit->layer_scale = scale; + for (i = 0; i < 3; ++i) { + list_create(&rects); + pd_text_set_fixed_size(layers[i], (int)(width * scale), + (int)(height * scale)); + pd_text_set_max_size(layers[i], (int)(width * scale), + (int)(height * scale)); + pd_text_update(layers[i], &rects); + for (list_each(node, &rects)) { + ui_rect_from_pd_rect(&rect, node->data, scale); + ui_widget_mark_dirty_rect(w, &rect, + UI_BOX_TYPE_CONTENT_BOX); + } + pd_rects_clear(&rects); } - pd_rects_clear(&rects); } static void ui_textinput_on_autosize(ui_widget_t *w, ui_sizehint_t *hint) @@ -410,10 +235,11 @@ static void ui_textinput_on_autosize(ui_widget_t *w, ui_sizehint_t *hint) max_width = ui_compute(DEFAULT_WIDTH); if (edit->is_multiline_mode) { for (max_height = 0, i = 0; i < 6; ++i) { - max_height += pd_text_get_line_height(edit->layer, i); + max_height += + pd_text_get_line_height(edit->layer_source, i); } } else { - max_height = pd_text_get_height(edit->layer); + max_height = pd_text_get_height(edit->layer_source); } hint->max_height = max_height / scale; hint->max_width = max_width / scale; @@ -424,7 +250,13 @@ static void ui_textinput_on_autosize(ui_widget_t *w, ui_sizehint_t *hint) void ui_textinput_enable_style_tag(ui_widget_t *widget, bool enable) { ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); - pd_text_set_style_tag(edit->layer, enable); + + /* 编辑模式使用 canonical 字符索引;样式标签会被 pd_text 消费, + * 造成索引错位,因此仅允许在只读展示时启用。 */ + if (enable && !edit->is_read_only) { + return; + } + pd_text_set_style_tag(edit->layer_source, enable); } /* FIXME: improve multiline editing mode of the textinput widget @@ -434,10 +266,16 @@ void ui_textinput_enable_style_tag(ui_widget_t *widget, bool enable) void ui_textinput_enable_multiline(ui_widget_t *w, bool enable) { + int i; + pd_text_t *layers[3]; ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - if (edit) { - edit->is_multiline_mode = enable; + edit->is_multiline_mode = enable; + layers[0] = edit->layer_source; + layers[1] = edit->layer_mask; + layers[2] = edit->layer_placeholder; + for (i = 0; i < 3; ++i) { + pd_text_set_multiline(layers[i], enable); } if (enable) { ui_widget_set_style_keyword_value(w, css_prop_white_space, @@ -448,28 +286,81 @@ void ui_textinput_enable_multiline(ui_widget_t *w, bool enable) } } +static void ui_textinput_request_change(ui_widget_t *w) +{ + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + edit->change_pending = true; + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); +} + +void ui_textinput_set_read_only(ui_widget_t *w, bool read_only) +{ + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + edit->is_read_only = read_only; + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); +} + +void ui_textinput_set_selection_color(ui_widget_t *w, pd_color_t color) +{ + char value[64]; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + edit->selection_color = color; + snprintf(value, sizeof(value), "rgba(%u,%u,%u,%.3f)", color.r, color.g, + color.b, color.a / 255.0f); + ui_widget_set_style_string(edit->selection_style, "background-color", + value); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_CONTENT_BOX); +} + +void ui_textinput_set_selection_text_color(ui_widget_t *w, pd_color_t color) +{ + char value[64]; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + edit->selection_text_color = color; + snprintf(value, sizeof(value), "rgba(%u,%u,%u,%.3f)", color.r, color.g, + color.b, color.a / 255.0f); + ui_widget_set_style_string(edit->selection_style, "color", value); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_CONTENT_BOX); +} + +static wchar_t *ui_textinput_filter_newlines(const wchar_t *text, size_t *len) +{ + size_t i, j, n = wcslen(text); + wchar_t *out = malloc(sizeof(wchar_t) * (n + 1)); + + if (!out) { + *len = 0; + return NULL; + } + for (i = 0, j = 0; i < n; ++i) { + if (text[i] != L'\r' && text[i] != L'\n') { + out[j++] = text[i]; + } + } + out[j] = 0; + *len = j; + return out; +} + void ui_textinput_clear_text(ui_widget_t *widget) { ui_textinput_t *edit; - textblock_t *block; - list_node_t *node, *prev; edit = ui_widget_get_data(widget, ui_textinput_proto); thread_mutex_lock(&edit->mutex); - for (list_each(node, &edit->text_blocks)) { - block = node->data; - prev = node->prev; - if (block->owner == TEXTBLOCK_OWNER_SOURCE) { - textblock_destroy(block); - list_delete_node(&edit->text_blocks, node); - node = prev; - } - } - pd_text_clear(edit->layer_source); - pd_style_tags_clear(&edit->text_tags); - edit->tasks[TASK_UPDATE] = true; - ui_widget_request_update(widget); + ui_text_edit_set_text(edit->editor, L"", 0); thread_mutex_unlock(&edit->mutex); + ui_textinput_request_change(widget); ui_widget_mark_dirty_rect(widget, NULL, UI_BOX_TYPE_PADDING_BOX); } @@ -477,20 +368,40 @@ size_t ui_textinput_get_text_w(ui_widget_t *w, size_t start, size_t max_len, wchar_t *buf) { ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - return pd_text_read(edit->layer_source, start, max_len, buf); + return ui_text_edit_get_text(edit->editor, start, max_len, buf); } size_t ui_textinput_get_text_length(ui_widget_t *w) { ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - return edit->layer_source->length; + return ui_text_edit_get_length(edit->editor); } int ui_textinput_set_text_w(ui_widget_t *w, const wchar_t *wstr) { - ui_textinput_clear_text(w); - return ui_textinput_add_textblock(w, wstr, TEXTBLOCK_ACTION_APPEND, - TEXTBLOCK_OWNER_SOURCE); + size_t len; + wchar_t *filtered = NULL; + const wchar_t *value = wstr; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!wstr) { + return -1; + } + len = wcslen(wstr); + if (!edit->is_multiline_mode) { + filtered = ui_textinput_filter_newlines(wstr, &len); + if (!filtered) { + return -ENOMEM; + } + value = filtered; + } + thread_mutex_lock(&edit->mutex); + ui_text_edit_set_text(edit->editor, value, len); + thread_mutex_unlock(&edit->mutex); + free(filtered); + ui_textinput_request_change(w); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_PADDING_BOX); + return 0; } int ui_textinput_set_text(ui_widget_t *widget, const char *utf8_str) @@ -510,50 +421,82 @@ int ui_textinput_set_text(ui_widget_t *widget, const char *utf8_str) void ui_textinput_set_password_char(ui_widget_t *w, wchar_t ch) { - size_t i, len; - wchar_t text[256]; ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); edit->password_char = ch; edit->tasks[TASK_UPDATE] = true; ui_widget_request_update(w); - pd_text_clear(edit->layer_mask); - if (!edit->password_char) { - edit->layer = edit->layer_source; - return; - } - edit->layer = edit->layer_mask; - len = ui_textinput_get_text_length(w); - for (i = 0; i < len; i += 255) { - ui_textinput_get_text_w(w, i, 255, text); - fillchar(text, edit->password_char); - pd_text_append(edit->layer, text, NULL); - } } int ui_textinput_append_text_w(ui_widget_t *w, const wchar_t *wstr) { - return ui_textinput_add_textblock(w, wstr, TEXTBLOCK_ACTION_APPEND, - TEXTBLOCK_OWNER_SOURCE); + size_t len; + wchar_t *filtered = NULL; + const wchar_t *value = wstr; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!wstr) { + return -1; + } + len = wcslen(wstr); + if (!edit->is_multiline_mode) { + filtered = ui_textinput_filter_newlines(wstr, &len); + if (!filtered) { + return -ENOMEM; + } + value = filtered; + } + thread_mutex_lock(&edit->mutex); + ui_text_edit_append_text(edit->editor, value, len); + thread_mutex_unlock(&edit->mutex); + free(filtered); + ui_textinput_request_change(w); + return 0; } int ui_textinput_insert_text_w(ui_widget_t *w, const wchar_t *wstr) { - return ui_textinput_add_textblock(w, wstr, TEXTBLOCK_ACTION_INSERT, - TEXTBLOCK_OWNER_SOURCE); + size_t len; + wchar_t *filtered = NULL; + const wchar_t *value = wstr; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!wstr) { + return -1; + } + len = wcslen(wstr); + if (!edit->is_multiline_mode) { + filtered = ui_textinput_filter_newlines(wstr, &len); + if (!filtered) { + return -ENOMEM; + } + value = filtered; + } + thread_mutex_lock(&edit->mutex); + ui_text_edit_text_input(edit->editor, value, len); + thread_mutex_unlock(&edit->mutex); + free(filtered); + ui_textinput_request_change(w); + return 0; } int ui_textinput_set_placeholder_w(ui_widget_t *w, const wchar_t *wstr) { ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!wstr) { + return -1; + } thread_mutex_lock(&edit->mutex); pd_text_clear(edit->layer_placeholder); + pd_text_append(edit->layer_placeholder, wstr, NULL); thread_mutex_unlock(&edit->mutex); if (edit->placeholder_visible) { ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_PADDING_BOX); } - return ui_textinput_add_textblock(w, wstr, TEXTBLOCK_ACTION_INSERT, - TEXTBLOCK_OWNER_PLACEHOLDER); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(w); + return 0; } int ui_textinput_set_placeholder(ui_widget_t *w, const char *str) @@ -580,7 +523,11 @@ void ui_textinput_set_caret_blink(ui_widget_t *w, bool visible, int time) static void ui_textinput_on_parse_text(ui_widget_t *w, const char *text) { + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + ui_textinput_set_text(w, text); + /* Initial parsed content is not a user edit. */ + edit->change_pending = false; } static void ui_textinput_on_focus(ui_widget_t *widget, ui_event_t *e, void *arg) @@ -590,6 +537,7 @@ static void ui_textinput_on_focus(ui_widget_t *widget, ui_event_t *e, void *arg) edit = ui_widget_get_data(widget, ui_textinput_proto); ui_textcaret_set_visible(edit->caret, true); ui_textinput_update_caret(widget); + ui_widget_mark_dirty_rect(widget, NULL, UI_BOX_TYPE_GRAPH_BOX); } static void ui_textinput_on_blur(ui_widget_t *widget, ui_event_t *e, void *arg) @@ -598,6 +546,10 @@ static void ui_textinput_on_blur(ui_widget_t *widget, ui_event_t *e, void *arg) edit = ui_widget_get_data(widget, ui_textinput_proto); ui_textcaret_set_visible(edit->caret, false); + ui_text_edit_clear_selection(edit->editor); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, UI_BOX_TYPE_GRAPH_BOX); /* In single-line editing mode, we should reset the caret position to * the head, otherwise it will mistakenly think that only the last part * is entered after inputting long text. */ @@ -606,50 +558,34 @@ static void ui_textinput_on_blur(ui_widget_t *widget, ui_event_t *e, void *arg) } } -static void ui_textinput_on_press_backspace_key(ui_widget_t *widget, int n_ch) -{ - ui_textinput_t *edit; - ui_event_t ev; - - edit = ui_widget_get_data(widget, ui_textinput_proto); - thread_mutex_lock(&edit->mutex); - pd_text_backspace(edit->layer_source, n_ch); - if (edit->password_char) { - pd_text_backspace(edit->layer_mask, n_ch); - } - ui_textcaret_refresh(edit->caret); - edit->tasks[TASK_UPDATE] = true; - ui_widget_request_update(widget); - thread_mutex_unlock(&edit->mutex); - ui_event_init(&ev, "change"); - ui_widget_emit_event(widget, ev, NULL); -} - -static void ui_textinput_on_press_delete_key(ui_widget_t *widget, int n_ch) -{ - ui_textinput_t *edit; - ui_event_t ev; - - edit = ui_widget_get_data(widget, ui_textinput_proto); - thread_mutex_lock(&edit->mutex); - pd_text_delete(edit->layer_source, n_ch); - if (edit->password_char) { - pd_text_delete(edit->layer_mask, n_ch); - } - ui_textcaret_refresh(edit->caret); - edit->tasks[TASK_UPDATE] = true; - ui_widget_request_update(widget); - thread_mutex_unlock(&edit->mutex); - ui_event_init(&ev, "change"); - ui_widget_emit_event(widget, ev, NULL); -} - static void ui_textinput_on_paste(ui_widget_t *w, ui_event_t *e, void *arg) { + size_t i, j; + wchar_t *text; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); ptk_clipboard_t *clipboard = arg; - if (clipboard) { - ui_textinput_insert_text_w(w, clipboard->text); + + if (!clipboard || !clipboard->text || edit->is_read_only) { + return; } + if (edit->is_multiline_mode) { + ui_textinput_insert_text_w(w, clipboard->text); + return; + } + /* 单行模式需要丢弃粘贴文本中的换行符 */ + text = malloc(sizeof(wchar_t) * (wcslen(clipboard->text) + 1)); + if (!text) { + return; + } + for (i = 0, j = 0; clipboard->text[i]; ++i) { + if (clipboard->text[i] != L'\r' && + clipboard->text[i] != L'\n') { + text[j++] = clipboard->text[i]; + } + } + text[j] = 0; + ui_textinput_insert_text_w(w, text); + free(text); } static void ui_textinput_on_clipboard_ready(void *arg, ui_widget_t *widget) @@ -661,83 +597,198 @@ static void ui_textinput_on_clipboard_ready(void *arg, ui_widget_t *widget) ui_widget_emit_event(widget, e, clipboard); } +static int ui_textinput_map_edit_key(ui_event_t *e) +{ + int key; + + switch (e->key.code) { + case KEY_LEFT: + key = e->key.ctrl_key ? UI_TEXT_EDIT_KEY_WORDLEFT + : UI_TEXT_EDIT_KEY_LEFT; + break; + case KEY_RIGHT: + key = e->key.ctrl_key ? UI_TEXT_EDIT_KEY_WORDRIGHT + : UI_TEXT_EDIT_KEY_RIGHT; + break; + case KEY_UP: + key = UI_TEXT_EDIT_KEY_UP; + break; + case KEY_DOWN: + key = UI_TEXT_EDIT_KEY_DOWN; + break; + case KEY_HOME: + key = e->key.ctrl_key ? UI_TEXT_EDIT_KEY_TEXTSTART + : UI_TEXT_EDIT_KEY_LINESTART; + break; + case KEY_END: + key = e->key.ctrl_key ? UI_TEXT_EDIT_KEY_TEXTEND + : UI_TEXT_EDIT_KEY_LINEEND; + break; + case KEY_PAGEUP: + key = UI_TEXT_EDIT_KEY_PGUP; + break; + case KEY_PAGEDOWN: + key = UI_TEXT_EDIT_KEY_PGDOWN; + break; + case KEY_BACKSPACE: + key = UI_TEXT_EDIT_KEY_BACKSPACE; + break; + case KEY_DELETE: + key = UI_TEXT_EDIT_KEY_DELETE; + break; + default: + return 0; + } + if (e->key.shift_key) { + key |= UI_TEXT_EDIT_KEY_SHIFT; + } + return key; +} + /** 处理按键事件 */ static void ui_textinput_on_keydown(ui_widget_t *widget, ui_event_t *e, void *arg) { - int cols, rows; - int cur_col, cur_row; + int key; ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); - cur_row = edit->layer->caret.y; - cur_col = edit->layer->caret.x; - rows = pd_text_get_lines_length(edit->layer); - cols = pd_text_get_line_length(edit->layer, cur_row); e->cancel_bubble = true; - switch (e->key.code) { - case KEY_HOME: - cur_col = 0; - break; - case KEY_END: - cur_col = cols; - break; - case KEY_LEFT: - if (cur_col > 0) { - --cur_col; - } else if (cur_row > 0) { - --cur_row; - cur_col = pd_text_get_line_length(edit->layer, cur_row); - } - break; - case KEY_RIGHT: - if (cur_col < cols) { - ++cur_col; - } else if (cur_row < rows - 1) { - ++cur_row; - cur_col = 0; - } - break; - case KEY_UP: - if (cur_row > 0) { - --cur_row; - } - break; - case KEY_DOWN: - if (cur_row < rows - 1) { - ++cur_row; - } - break; - case KEY_BACKSPACE: - ui_textinput_on_press_backspace_key(widget, 1); - return; - case KEY_DELETE: - ui_textinput_on_press_delete_key(widget, 1); - return; - default: - break; - } - ui_textinput_move_caret(widget, cur_row, cur_col); + key = ui_textinput_map_edit_key(e); + if (key) { + int base = key & ~UI_TEXT_EDIT_KEY_SHIFT; + size_t length_before, length_after; - char key = e->key.code; + if (base == UI_TEXT_EDIT_KEY_UP || + base == UI_TEXT_EDIT_KEY_DOWN) { + thread_mutex_lock(&edit->mutex); + ui_text_edit_move_vertical( + edit->editor, base == UI_TEXT_EDIT_KEY_UP ? -1 : 1, + (key & UI_TEXT_EDIT_KEY_SHIFT) != 0); + thread_mutex_unlock(&edit->mutex); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, + UI_BOX_TYPE_CONTENT_BOX); + return; + } + if (edit->is_read_only && (base == UI_TEXT_EDIT_KEY_BACKSPACE || + base == UI_TEXT_EDIT_KEY_DELETE || + base == UI_TEXT_EDIT_KEY_UNDO || + base == UI_TEXT_EDIT_KEY_REDO)) { + return; + } + thread_mutex_lock(&edit->mutex); + length_before = ui_text_edit_get_length(edit->editor); + ui_text_edit_key(edit->editor, key); + length_after = ui_text_edit_get_length(edit->editor); + thread_mutex_unlock(&edit->mutex); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, + UI_BOX_TYPE_CONTENT_BOX); + if (((base == UI_TEXT_EDIT_KEY_BACKSPACE) || + (base == UI_TEXT_EDIT_KEY_DELETE)) && + length_after != length_before) { + ui_textinput_request_change(widget); + } + return; + } + if (e->key.code == KEY_ENTER) { + if (edit->is_multiline_mode && !edit->is_read_only) { + ui_textinput_insert_text_w(widget, L"\n"); + } + return; + } + + int key_code = e->key.code; + if (edit->is_read_only && e->key.ctrl_key && + (key_code == KEY_V || key_code == KEY_X || key_code == KEY_Z || + key_code == KEY_Y)) { + return; + } // CTRL+V - if (key == KEY_V && e->key.ctrl_key) { + if (key_code == KEY_V && e->key.ctrl_key) { ptk_clipboard_request_text( (ptk_clipboard_callback_t)ui_textinput_on_clipboard_ready, widget); + return; } - // CTRL+C - if (key == KEY_C && e->key.ctrl_key) { - // @WhoAteDaCake - // Currently copies internal widget text - // once selection is implemented, it would copy that instead - size_t len = ui_textinput_get_text_length(widget); - wchar_t *wcs = malloc((len + 1) * sizeof(wchar_t)); - ui_textinput_get_text_w(widget, 0, len, wcs); - ptk_clipboard_set_text(wcs, len); + // CTRL+A + if (key_code == KEY_A && e->key.ctrl_key) { + thread_mutex_lock(&edit->mutex); + ui_text_edit_select_all(edit->editor); + thread_mutex_unlock(&edit->mutex); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, + UI_BOX_TYPE_CONTENT_BOX); + return; + } + // CTRL+Z / CTRL+Y (CTRL+SHIFT+Z redoes) + if (key_code == KEY_Z && e->key.ctrl_key) { + thread_mutex_lock(&edit->mutex); + ui_text_edit_key(edit->editor, e->key.shift_key + ? UI_TEXT_EDIT_KEY_REDO + : UI_TEXT_EDIT_KEY_UNDO); + thread_mutex_unlock(&edit->mutex); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, + UI_BOX_TYPE_CONTENT_BOX); + ui_textinput_request_change(widget); + return; + } + if (key_code == KEY_Y && e->key.ctrl_key) { + thread_mutex_lock(&edit->mutex); + ui_text_edit_key(edit->editor, UI_TEXT_EDIT_KEY_REDO); + thread_mutex_unlock(&edit->mutex); + edit->tasks[TASK_UPDATE] = true; + ui_widget_request_update(widget); + ui_widget_mark_dirty_rect(widget, NULL, + UI_BOX_TYPE_CONTENT_BOX); + ui_textinput_request_change(widget); + return; + } + // CTRL+C / CTRL+X + if ((key_code == KEY_C || key_code == KEY_X) && e->key.ctrl_key) { + size_t n, len; + bool changed = false; + wchar_t *wcs; + + if (edit->password_char) { + return; + } + thread_mutex_lock(&edit->mutex); + len = ui_text_edit_get_length(edit->editor); + wcs = malloc((len + 1) * sizeof(wchar_t)); + if (!wcs) { + thread_mutex_unlock(&edit->mutex); + return; + } + if (key_code == KEY_X) { + if (!ui_text_edit_has_selection(edit->editor)) { + free(wcs); + thread_mutex_unlock(&edit->mutex); + return; + } + n = ui_text_edit_cut(edit->editor, wcs, len); + changed = true; + } else if (ui_text_edit_has_selection(edit->editor)) { + n = ui_text_edit_copy(edit->editor, wcs, len); + } else { + n = ui_text_edit_get_text(edit->editor, 0, len, wcs); + } + thread_mutex_unlock(&edit->mutex); + if (n > 0) { + ptk_clipboard_set_text(wcs, n); + } free(wcs); + if (changed) { + ui_textinput_request_change(widget); + } + return; } } - /** 处理输入法对文本框输入的内容 */ static void ui_textinput_on_textinput(ui_widget_t *widget, ui_event_t *e, void *arg) @@ -773,17 +824,14 @@ static void ui_textinput_on_textinput(ui_widget_t *widget, ui_event_t *e, continue; } /* 判断当前字符是否为限制范围内的字符 */ - for (j = 0; edit->allow_input_char[j]; ++j) { - if (edit->allow_input_char[j] == ch) { + for (k = 0; edit->allow_input_char[k]; ++k) { + if (edit->allow_input_char[k] == ch) { break; } } - /* 如果已提前结束循环,则表明当前字符是允许的 */ - if (edit->allow_input_char[j]) { - text[j++] = e->text.text[i]; - continue; + if (edit->allow_input_char[k]) { + text[j++] = ch; } - text[j] = 0; } text[j] = 0; ui_textinput_insert_text_w(widget, text); @@ -792,19 +840,13 @@ static void ui_textinput_on_textinput(ui_widget_t *widget, ui_event_t *e, static void ui_textinput_on_mousemove(ui_widget_t *w, ui_event_t *e, void *arg) { - float offset_x, offset_y; ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); if (edit->placeholder_visible) { ui_textinput_update_caret(w); return; } - ui_widget_get_offset(w, NULL, &offset_x, &offset_y); - pd_text_set_caret_pixel( - edit->layer, - ui_compute(e->mouse.x - offset_x - w->computed_style.padding_left), - ui_compute(e->mouse.y - offset_y - w->computed_style.padding_top)); - ui_textinput_update_caret(w); + ui_textinput_update_caret_by_pointer(w, e, true); } static void ui_textinput_on_mouseup(ui_widget_t *w, ui_event_t *e, void *arg) @@ -815,15 +857,7 @@ static void ui_textinput_on_mouseup(ui_widget_t *w, ui_event_t *e, void *arg) static void ui_textinput_on_mousedown(ui_widget_t *w, ui_event_t *e, void *arg) { - float offset_x, offset_y; - ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); - - ui_widget_get_offset(w, NULL, &offset_x, &offset_y); - pd_text_set_caret_pixel( - edit->layer, - ui_compute(e->mouse.x - offset_x - w->computed_style.padding_left), - ui_compute(e->mouse.y - offset_y - w->computed_style.padding_top)); - ui_textinput_update_caret(w); + ui_textinput_update_caret_by_pointer(w, e, false); ui_widget_set_mouse_capture(w); ui_widget_on(w, "mousemove", ui_textinput_on_mousemove, w); } @@ -854,6 +888,28 @@ static void ui_textinput_on_set_attr(ui_widget_t *w, const char *name, } else if (strcmp(name, "multiline") == 0) { ui_textinput_enable_multiline(w, ui_textinput_attr_to_bool(val)); + } else if (strcmp(name, "readonly") == 0) { + ui_textinput_set_read_only(w, ui_textinput_attr_to_bool(val)); + } else if (strcmp(name, "selection-color") == 0 && val) { + css_style_value_t parsed; + + if (css_parse_color_value(&parsed, val) && + parsed.type == CSS_COLOR_VALUE) { + css_color_value_t cv = parsed.color_value; + ui_textinput_set_selection_color( + w, pd_argb((uint8_t)(cv >> 24), (uint8_t)(cv >> 16), + (uint8_t)(cv >> 8), (uint8_t)cv)); + } + } else if (strcmp(name, "selection-text-color") == 0 && val) { + css_style_value_t parsed; + + if (css_parse_color_value(&parsed, val) && + parsed.type == CSS_COLOR_VALUE) { + css_color_value_t cv = parsed.color_value; + ui_textinput_set_selection_text_color( + w, pd_argb((uint8_t)(cv >> 24), (uint8_t)(cv >> 16), + (uint8_t)(cv >> 8), (uint8_t)cv)); + } } } @@ -868,16 +924,29 @@ static void ui_textinput_on_init(ui_widget_t *w) edit->allow_input_char = NULL; edit->placeholder_visible = false; edit->is_multiline_mode = false; + edit->change_pending = false; + edit->selection_color = pd_rgb(23, 23, 23); + edit->selection_text_color = pd_rgb(255, 255, 255); edit->layer_mask = pd_text_create(); edit->layer_source = pd_text_create(); edit->layer_placeholder = pd_text_create(); edit->layer = edit->layer_source; - edit->text_block_size = TEXTBLOCK_SIZE; + edit->layer_scale = ui_get_actual_scale(); + edit->editor = ui_text_edit_create(); + ui_text_edit_set_layer(edit->editor, edit->layer_source); edit->caret = ui_create_widget("textcaret"); + edit->selection_style = ui_create_widget(NULL); + ui_widget_add_class(edit->selection_style, "selection"); + ui_widget_set_style_string(edit->selection_style, "position", + "absolute"); + ui_widget_set_style_string(edit->selection_style, "left", "0px"); + ui_widget_set_style_string(edit->selection_style, "top", "0px"); + ui_widget_set_style_string(edit->selection_style, "width", "0px"); + ui_widget_set_style_string(edit->selection_style, "height", "0px"); + ui_widget_set_style_string(edit->selection_style, "pointer-events", + "none"); w->tab_index = 0; memset(edit->tasks, 0, sizeof(edit->tasks)); - list_create(&edit->text_blocks); - list_create(&edit->text_tags); ui_textinput_enable_multiline(w, false); pd_text_set_autowrap(edit->layer, true); pd_text_set_autowrap(edit->layer_mask, true); @@ -891,6 +960,7 @@ static void ui_textinput_on_init(ui_widget_t *w) ui_widget_on(w, "ready", ui_textinput_on_ready, NULL); ui_widget_on(w, "paste", ui_textinput_on_paste, NULL); ui_widget_append(w, edit->caret); + ui_widget_append(w, edit->selection_style); ui_widget_hide(edit->caret); thread_mutex_init(&edit->mutex); ui_text_style_init(&edit->style); @@ -901,13 +971,147 @@ static void ui_textinput_on_destroy(ui_widget_t *widget) ui_textinput_t *edit = ui_widget_get_data(widget, ui_textinput_proto); edit->layer = NULL; + ui_text_edit_destroy(edit->editor); pd_text_destroy(edit->layer_source); pd_text_destroy(edit->layer_placeholder); pd_text_destroy(edit->layer_mask); ui_text_style_destroy(&edit->style); thread_mutex_destroy(&edit->mutex); - list_destroy(&edit->text_blocks, - (list_item_destructor_t)textblock_destroy); +} + +static pd_color_t ui_textinput_get_selection_color(ui_textinput_t *edit) +{ + css_color_value_t c = + edit->selection_style->computed_style.background_color; + + if ((c >> 24) & 0xff) { + return pd_argb((uint8_t)(c >> 24), (uint8_t)(c >> 16), + (uint8_t)(c >> 8), (uint8_t)c); + } + return edit->selection_color; +} + +static void ui_textinput_paint_selection(ui_widget_t *w, pd_canvas_t *canvas, + pd_pos_t layer_pos, pd_rect_t area) +{ + int i, line_start, line_len, col_start, col_end; + size_t sel_start, sel_end; + pd_rect_t r, clipped; + pd_color_t color; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!ui_text_edit_has_selection(edit->editor)) { + return; + } + color = ui_textinput_get_selection_color(edit); + ui_text_edit_selection(edit->editor, &sel_start, &sel_end); + if (sel_start == sel_end) { + return; + } + for (i = 0; i < pd_text_get_lines_length(edit->layer); ++i) { + line_start = pd_text_get_line_char_start(edit->layer, i); + line_len = pd_text_get_line_length(edit->layer, i); + if ((int)sel_end <= line_start) { + break; + } + if ((int)sel_start > line_start + line_len) { + continue; + } + col_start = (int)sel_start > line_start + ? (int)sel_start - line_start + : 0; + col_end = (int)sel_end < line_start + line_len + ? (int)sel_end - line_start + : line_len; + if (col_start >= col_end) { + continue; + } + if (pd_text_get_line_rect(edit->layer, i, col_start, + col_end - 1, &r) != 0) { + continue; + } + /* 与 pd_text_render_to 使用相同的 canvas / layer_pos / area, + * 避免选区随 widget 的 paint 偏移而错位 */ + if (!pd_rect_overlap(&r, &area, &clipped)) { + continue; + } + clipped.x += layer_pos.x; + clipped.y += layer_pos.y; + pd_canvas_fill_rect(canvas, color, clipped); + } +} + +static pd_color_t ui_textinput_get_selection_text_color(ui_widget_t *w, + ui_textinput_t *edit) +{ + css_color_value_t c = edit->selection_style->computed_style.color; + + if (c == w->computed_style.color) { + return edit->selection_text_color; + } + return pd_argb((uint8_t)(c >> 24), (uint8_t)(c >> 16), + (uint8_t)(c >> 8), (uint8_t)c); +} + +static void ui_textinput_paint_selected_text(ui_widget_t *w, + pd_canvas_t *canvas, + pd_pos_t layer_pos, pd_rect_t area) +{ + int i, line_start, line_len, col_start, col_end; + size_t sel_start, sel_end; + pd_rect_t r, clipped, clip_area; + pd_pos_t sel_pos; + pd_canvas_t sel_canvas; + pd_color_t old_color, text_color; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + if (!ui_text_edit_has_selection(edit->editor)) { + return; + } + ui_text_edit_selection(edit->editor, &sel_start, &sel_end); + text_color = ui_textinput_get_selection_text_color(w, edit); + if (sel_start == sel_end || text_color.a == 0) { + return; + } + for (i = 0; i < pd_text_get_lines_length(edit->layer); ++i) { + line_start = pd_text_get_line_char_start(edit->layer, i); + line_len = pd_text_get_line_length(edit->layer, i); + if ((int)sel_end <= line_start) { + break; + } + if ((int)sel_start > line_start + line_len) { + continue; + } + col_start = (int)sel_start > line_start + ? (int)sel_start - line_start + : 0; + col_end = (int)sel_end < line_start + line_len + ? (int)sel_end - line_start + : line_len; + if (col_start >= col_end) { + continue; + } + if (pd_text_get_line_rect(edit->layer, i, col_start, + col_end - 1, &r) != 0) { + continue; + } + if (!pd_rect_overlap(&r, &area, &clipped)) { + continue; + } + clip_area = clipped; + clip_area.x += layer_pos.x; + clip_area.y += layer_pos.y; + pd_canvas_init(&sel_canvas); + if (pd_canvas_quote(&sel_canvas, canvas, &clip_area) != 0) { + continue; + } + sel_pos.x = layer_pos.x - clip_area.x; + sel_pos.y = layer_pos.y - clip_area.y; + old_color = edit->layer->default_style.fore_color; + edit->layer->default_style.fore_color = text_color; + pd_text_render_to(edit->layer, r, sel_pos, &sel_canvas); + edit->layer->default_style.fore_color = old_color; + } } static void ui_textinput_on_paint(ui_widget_t *w, pd_context_t *paint, @@ -934,6 +1138,113 @@ static void ui_textinput_on_paint(ui_widget_t *w, pd_context_t *paint, rect.x -= content_rect.x; rect.y -= content_rect.y; pd_text_render_to(edit->layer, rect, pos, &canvas); + ui_textinput_paint_selection(w, &canvas, pos, rect); + ui_textinput_paint_selected_text(w, &canvas, pos, rect); +} + +static void ui_textinput_update_mask(ui_widget_t *w) +{ + size_t i, len; + wchar_t *text; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + + pd_text_clear(edit->layer_mask); + if (!edit->password_char) { + return; + } + len = ui_text_edit_get_length(edit->editor); + text = malloc(sizeof(wchar_t) * (len + 1)); + if (!text) { + return; + } + ui_text_edit_get_text(edit->editor, 0, len, text); + for (i = 0; i < len; ++i) { + if (text[i] != L'\n') { + text[i] = edit->password_char; + } + } + pd_text_append(edit->layer_mask, text, NULL); + free(text); + pd_text_set_caret(edit->layer_mask, edit->layer_source->caret.y, + edit->layer_source->caret.x); + pd_text_set_offset(edit->layer_mask, edit->layer_source->offset_x, + edit->layer_source->offset_y); +} + +/** 更新文本框的文本图层 */ +static void textinput_update_textlayer(ui_widget_t *w) +{ + float scale; + list_t rects; + ui_rect_t rect; + ui_textinput_t *edit; + pd_text_style_t style; + list_node_t *node; + + list_create(&rects); + scale = ui_get_actual_scale(); + edit = ui_widget_get_data(w, ui_textinput_proto); + edit->layer_scale = scale; + pd_text_style_copy(&style, &edit->layer_source->default_style); + if (edit->password_char) { + pd_text_set_style(edit->layer_mask, &style); + ui_textinput_update_mask(w); + } + style.has_fore_color = true; + style.fore_color = PLACEHOLDER_COLOR; + pd_text_set_style(edit->layer_placeholder, &style); + pd_text_style_destroy(&style); + pd_text_update(edit->layer, &rects); + for (list_each(node, &rects)) { + ui_rect_from_pd_rect(&rect, node->data, scale); + ui_widget_mark_dirty_rect(w, &rect, UI_BOX_TYPE_CONTENT_BOX); + } + pd_rects_clear(&rects); +} + +static void ui_textinput_update(ui_widget_t *w) +{ + ui_event_t ev; + ui_textinput_t *edit = ui_widget_get_data(w, ui_textinput_proto); + bool placeholder_visible = ui_text_edit_get_length(edit->editor) == 0; + + if (placeholder_visible) { + edit->layer = edit->layer_placeholder; + } else if (edit->password_char) { + edit->layer = edit->layer_mask; + } else { + edit->layer = edit->layer_source; + } + textinput_update_textlayer(w); + { + int line_h = pd_text_get_line_height(edit->layer, 0); + int rows = 1; + + if (line_h > 0) { + rows = + (int)((w->content_box.height * edit->layer_scale) / + line_h); + } + ui_text_edit_set_page_rows(edit->editor, rows); + } + if (edit->placeholder_visible != placeholder_visible) { + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_PADDING_BOX); + } + edit->placeholder_visible = placeholder_visible; + ui_textinput_update_caret(w); + ui_widget_mark_dirty_rect(w, NULL, UI_BOX_TYPE_CONTENT_BOX); + /* A change handler may edit the widget again (validation/formatting). + * Emit the follow-up change in the same update, with a small guard to + * avoid an infinite handler loop. */ + { + int guard = 0; + + while (edit->change_pending && guard++ < 8) { + edit->change_pending = false; + ui_event_init(&ev, "change"); + ui_widget_emit_event(w, ev, NULL); + } + } } static void ui_textinput_on_update_style(ui_widget_t *w) @@ -975,14 +1286,9 @@ static void ui_textinput_on_update(ui_widget_t *w, ui_task_type_t task) ui_textinput_on_update_style(w); break; case UI_TASK_AFTER_UPDATE: - if (edit->tasks[TASK_SET_TEXT]) { - ui_textinput_update_text(w); - edit->tasks[TASK_SET_TEXT] = false; - edit->tasks[TASK_UPDATE] = true; - } if (edit->tasks[TASK_UPDATE]) { - ui_textinput_update(w); edit->tasks[TASK_UPDATE] = false; + ui_textinput_update(w); } default: break; diff --git a/src/widgets/third-party/README.md b/src/widgets/third-party/README.md new file mode 100644 index 00000000..1c2802d5 --- /dev/null +++ b/src/widgets/third-party/README.md @@ -0,0 +1,9 @@ +# stb_textedit + +- Upstream: +- Vendored file: `stb_textedit.h` +- Version: v1.16 (2026-11-12) +- License: MIT OR public domain (see the end of `stb_textedit.h`) + +The file is vendored unchanged. To update it, replace the file, record the new +version here, and re-run the textinput edit tests. diff --git a/src/widgets/third-party/stb_textedit.h b/src/widgets/third-party/stb_textedit.h new file mode 100644 index 00000000..9a4f7494 --- /dev/null +++ b/src/widgets/third-party/stb_textedit.h @@ -0,0 +1,1662 @@ +// stb_textedit.h - v1.16 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// See end of file for license information. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// 1.16 (2026-11-12) add stb_textedit_text(), STB_TEXTEDIT_GETPREVCHARINDEX(), +// STB_TEXTEDIT_GETNEXTCHARINDEX() to facilitate UTF-8 support while +// preserving byte indices. 1.15 (2026-11-08) various fixes 1.14 (2021-07-11) +// page up/down, various fixes 1.13 (2019-02-07) fix bug in undo size +// management 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo +// to avoid crash 1.11 (2017-03-03) fix HOME on last line, dragging off +// single-line textfield 1.10 (2016-10-25) suppress warnings about casting +// away const with -Wcast-qual 1.9 (2016-08-27) customizable move-by-word 1.8 +// (2016-04-02) better keyboard handling when mouse button is down 1.7 +// (2015-09-13) change y range handling in case baseline is non-0 1.6 +// (2015-04-15) allow STB_TEXTEDIT_memmove 1.5 (2014-09-10) add support for +// secondary keys for OS X 1.4 (2014-08-17) fix signed/unsigned warnings 1.3 +// (2014-06-19) fix mouse clicking to round to nearest char boundary 1.2 +// (2014-05-27) fix some RAD types that had crept into the new code 1.1 +// (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) 1.0 +// (2012-07-26) improve documentation, initial public release 0.3 (2012-02-24) +// bugfixes, single-line mode; insert mode 0.2 (2011-11-28) fixes to +// undo/redo 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +// Louis Schnellbach: page up/down in 1.14 +// Omar Cornut, alektron@github: move-by-codepoint in UTF8, stb_textedit_text +// in 1.16 +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Dan Thompson +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor +// position STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to +// allow STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to +// store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * +// STB_TEXTEDIT_UNDOSTATECOUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * +// STB_TEXTEDIT_UNDOCHARCOUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor +// position STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to +// allow STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store +// in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string +// being edited, +// typically this is a wrapper object with +// other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line +// of characters +// starting from character #n (see +// discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of +// the i'th character +// to the xpos of the i+1'th char for a +// line of characters starting at +// character #n (i.e. accounts for +// kerning with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable +// character +// (return type is int, -1 means not +// valid to insert) (not supported if you +// want to use UTF-8, see below) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, +// 0-based STB_TEXTEDIT_NEWLINE the character returned by +// _GETCHAR() we recognize +// as manually wordwrapping for +// end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed +// to by STB_TEXTEDIT_CHARTYPE*) +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard +// input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line +// // e.g. HOME STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to +// end of line // e.g. END STB_TEXTEDIT_K_TEXTSTART keyboard input to +// move cursor to start of text // e.g. ctrl-HOME STB_TEXTEDIT_K_TEXTEND +// keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character +// under cursor STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection +// or character left of cursor STB_TEXTEDIT_K_UNDO keyboard input to +// perform undo STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. +// 'isspace'), +// required for default +// WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns +// index to move cursor to STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler +// for WORDRIGHT, returns index to move cursor to STB_TEXTEDIT_K_WORDLEFT +// keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one +// word // e.g. ctrl-RIGHT STB_TEXTEDIT_K_LINESTART2 secondary +// keyboard input to move cursor to start of line STB_TEXTEDIT_K_LINEEND2 +// secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor +// to start of text STB_TEXTEDIT_K_TEXTEND2 secondary keyboard +// input to move cursor to end of text +// +// To support UTF-8 while using indices to _bytes_ (instead of indices to +// _codepoints_): +// +// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character +// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// Call stb_textedit_text() directly to submit text contents. +// Do NOT define STB_TEXTEDIT_KEYTOTEXT. +// +// Keyboard input must be encoded as a single integer value; e.g. a character +// code and some bitflags that represent shift states. to simplify the +// interface, SHIFT must be a bitflag, so we can test the shifted state of +// cursor movements to allow selection, i.e. +// (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional +// KEYDOWN bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN +// bit, and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in +// the API below. The control keys will only match WM_KEYDOWN events because of +// the keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute +// word-wrapping here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int +// is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState +// *state, float x, float y) void stb_textedit_drag(STB_TEXTEDIT_STRING *str, +// STB_TexteditState *state, float x, float y) int +// stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) int +// stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, +// STB_TEXTEDIT_CHARTYPE *text, int len) void +// stb_textedit_char(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, +// STB_TEXTEDIT_CHARTYPE ch) void stb_textedit_text(STB_TEXTEDIT_STRING *str, +// STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) void +// stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, +// STB_TEXEDIT_KEYTYPE key) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the +// cursor and reset the selection start/end to the cursor point. the +// x,y must be relative to the text widget, with (0,0) being the top +// left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste +// buffer. (To copy, just copy the current selection out of the string +// yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the +// current selection if there is one. +// +// char: +// (optional) call this for character input sent to the textfield. if +// the framework you are using supplies you with a character or text +// event, it makes sense to use this function. make sure to set +// STB_TEXTEDIT_KEYTOTEXT to 0 for any key that generates a +// corresponding character or text event. +// +// text: +// (optional) call this to directly send text input the textfield, +// which is helpful for UTF-8 support, because stb_textedit_key() + +// STB_TEXTEDIT_KEYTOTEXT() cannot infer text length. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from +// control inputs, set a high bit to distinguish the two; then you can +// define the various definitions like STB_TEXTEDIT_K_LEFT have the +// is-key-event bit set, and make STB_TEXTEDIT_KEYTOCHAR check that the +// is-key-event bit is clear. STB_TEXTEDIT_KEYTYPE defaults to int, but +// you can #define it to any other type you want before including. if +// the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are +// transformed into text and stb_textedit_text() is automatically +// called. +// +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_STB_TEXTEDIT_H +#define INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef STB_TEXTEDIT_UNDOSTATECOUNT +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef STB_TEXTEDIT_UNDOCHARCOUNT +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_CHARTYPE int +#endif +#ifndef STB_TEXTEDIT_POSITIONTYPE +#define STB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct { + // private data + STB_TEXTEDIT_POSITIONTYPE where; + STB_TEXTEDIT_POSITIONTYPE insert_length; + STB_TEXTEDIT_POSITIONTYPE delete_length; + int char_storage; +} StbUndoRecord; + +typedef struct { + // private data + StbUndoRecord undo_rec[STB_TEXTEDIT_UNDOSTATECOUNT]; + STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + int undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct { + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + int row_count_per_page; + // page size in number of row. + // this value MUST be set to >0 for pageup or pagedown in multilines + // documents. + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries + // to seek to along x + StbUndoState undostate; +} STB_TexteditState; + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct { + float x0, x1; // starting x location, end x location (allows for + // align=right, etc) + float baseline_y_delta; // position of baseline relative to previous + // row's baseline + float ymin, ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif // INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef STB_TEXTEDIT_IMPLEMENTATION + +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif + +// Functions must be implemented for UTF-8 support with indices to bytes. +#ifndef STB_TEXTEDIT_GETPREVCHARINDEX +#define STB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +#endif +#ifndef STB_TEXTEDIT_GETNEXTCHARINDEX +#define STB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) +#endif + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i = 0, k; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (i == 0 && y < base_y + r.ymin) + return 0; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + return n; + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + prev_x = r.x0; + for (k = 0; k < r.num_chars; + k = STB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); + if (x < prev_x + w) { + if (x < prev_x + w / 2) + return k + i; + else + return STB_TEXTEDIT_GETNEXTCHARINDEX( + str, i + k); + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line + // case + } + + // if the last character is a newline, return that. otherwise return + // 'after' the last character + if (STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) == + STB_TEXTEDIT_NEWLINE) + return i + r.num_chars - 1; + else + return i + r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset +// the selection +static void stb_textedit_click(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, float x, float y) +{ + // In single-line mode, just always make y = 0. This lets the drag keep + // working if the mouse goes off the top or bottom of the text + if (state->single_line) { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + state->cursor = stb_text_locate_coord(str, x, y); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the +// clicked location +static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, float x, float y) +{ + int p = 0; + + // In single-line mode, just always make y = 0. This lets the drag keep + // working if the mouse goes off the top or bottom of the text + if (state->single_line) { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + if (state->select_start == state->select_end) + state->select_start = state->cursor; + + p = stb_text_locate_coord(str, x, y); + state->cursor = state->select_end = p; +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, int where, + int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, + int length); +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, int where, + int old_length, int new_length); + +typedef struct { + float x, y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous +// row in case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, + STB_TEXTEDIT_STRING *str, int n, + int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i = 0, first; + + // search rows to find the one that straddles character n + find->y = 0; + + for (;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + + // generally, the row that contains n is found if n is less than + // the next row start. however, if n is at the end of the text + // there is no row past n, so another termination criterion is + // needed: + // 1. either the row is empty (this catches z == 0 too) + // 2. or the row does not have a trailing newline + // neither of these conditions can be true for any row other + // than the last one. to avoid checking all three conditions + // every iterations, the main conditions is loosened such that + // it includes n == z the additional single_line check is only + // needed if someone accidentally pasted a newline character at + // the end in single line mode + if (n <= i + r.num_chars) { + if (n < i + r.num_chars || r.num_chars == 0 || + STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != + STB_TEXTEDIT_NEWLINE || + single_line) { + break; + } + } + + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + for (i = 0; first + i < n; + i = STB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i) - first) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) + state->select_start = n; + if (state->select_end > n) + state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) + state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete( + str, state, state->select_start, + state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete( + str, state, state->select_end, + state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary(STB_TEXTEDIT_STRING *str, int idx) +{ + return idx > 0 + ? (STB_TEXTEDIT_IS_SPACE( + STB_TEXTEDIT_GETCHAR(str, idx - 1)) && + !STB_TEXTEDIT_IS_SPACE(STB_TEXTEDIT_GETCHAR(str, idx))) + : 1; +} + +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous(STB_TEXTEDIT_STRING *str, int c) +{ + c = STB_TEXTEDIT_GETPREVCHARINDEX( + str, c); // always move at least one character + while (c >= 0 && !is_word_boundary(str, c)) + c = STB_TEXTEDIT_GETPREVCHARINDEX(str, c); + + if (c < 0) + c = 0; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif + +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next(STB_TEXTEDIT_STRING *str, int c) +{ + const int len = STB_TEXTEDIT_STRINGLEN(str); + c = STB_TEXTEDIT_GETNEXTCHARINDEX( + str, c); // always move at least one character + while (c < len && !is_word_boundary(str, c)) + c = STB_TEXTEDIT_GETNEXTCHARINDEX(str, c); + + if (c > len) + c = len; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str, + state); // implicitly clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, + STB_TEXTEDIT_CHARTYPE *text, int len) +{ + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str, state); + // try to insert the characters + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // note: paste failure will leave deleted selection, may be restored + // with an undo (see https://github.com/nothings/stb/issues/734 for + // details) + return 0; +} + +// API key: process text input +static void stb_textedit_text(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, + const STB_TEXTEDIT_CHARTYPE *text, int text_len) +{ + // can't add newline in single-line mode + if (text[0] == STB_TEXTEDIT_NEWLINE && state->single_line) + return; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && + state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, + (STB_TEXTEDIT_CHARTYPE *)text, + text_len)) { + state->cursor += text_len; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str, + state); // implicitly clamps + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, + (STB_TEXTEDIT_CHARTYPE *)text, + text_len)) { + stb_text_makeundo_insert(state, state->cursor, + text_len); + state->cursor += text_len; + state->has_preferred_x = 0; + } + } +} + +// API char: process a character input +static void stb_textedit_char(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, + STB_TEXTEDIT_CHARTYPE ch) +{ + stb_textedit_text(str, state, &ch, 1); +} + +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + +// API key: process a keyboard input +static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, + STB_TEXTEDIT_KEYTYPE key) +{ +retry: + switch (key) { + default: { +#ifdef STB_TEXTEDIT_KEYTOTEXT + // This is not suitable for UTF-8 support with indices to bytes. + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE)c; + stb_textedit_char(str, state, ch); + } +#endif + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of + // selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else if (state->cursor > 0) + state->cursor = + STB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of + // selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + state->cursor = + STB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + state->select_end = STB_TEXTEDIT_GETPREVCHARINDEX( + str, state->select_end); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_MOVEWORDLEFT + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = + STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + stb_textedit_clamp(str, state); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if (!STB_TEXT_HAS_SELECTION(state)) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp(str, state); + break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = + STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp(str, state); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if (!STB_TEXT_HAS_SELECTION(state)) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp(str, state); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + state->select_end = + STB_TEXTEDIT_GETNEXTCHARINDEX(str, state->select_end); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGDOWN: + case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = + (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down in single-line behave like + // left&right + key = + STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, + state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x + ? state->preferred_x + : find.x; + int start = find.first_char + find.length; + + if (find.length == 0) + break; + + // now find character position down a row + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i = 0; i < row.num_chars;) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + int next = STB_TEXTEDIT_GETNEXTCHARINDEX( + str, state->cursor); +#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; +#endif + x += dx; + if (x > goal_x) + break; + i += next - state->cursor; + state->cursor = next; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to next line + find.first_char = find.first_char + find.length; + find.length = row.num_chars; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGUP: + case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = + (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down become left&right + key = + STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, + state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x + ? state->preferred_x + : find.x; + + // if there's no previous row set cursor to start of the + // line + if (find.prev_first == find.first_char) { + state->cursor = find.first_char; + stb_textedit_clamp(str, state); + + if (sel) + state->select_end = state->cursor; + break; + } + + // now find character position up a row + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i = 0; i < row.num_chars;) { + float dx = STB_TEXTEDIT_GETWIDTH( + str, find.prev_first, i); + int next = STB_TEXTEDIT_GETNEXTCHARINDEX( + str, state->cursor); +#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; +#endif + x += dx; + if (x > goal_x) + break; + i += next - state->cursor; + state->cursor = next; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to previous line + // (we need to scan previous line the hard way. maybe we + // could expose this as a new API function?) + prev_scan = + find.prev_first > 0 ? find.prev_first - 1 : 0; + while (prev_scan > 0) { + int prev = STB_TEXTEDIT_GETPREVCHARINDEX( + str, prev_scan); + if (STB_TEXTEDIT_GETCHAR(str, prev) == + STB_TEXTEDIT_NEWLINE) + break; + prev_scan = prev; + } + find.first_char = find.prev_first; + find.prev_first = prev_scan; + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete( + str, state, state->cursor, + STB_TEXTEDIT_GETNEXTCHARINDEX( + str, state->cursor) - + state->cursor); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + int prev = STB_TEXTEDIT_GETPREVCHARINDEX( + str, state->cursor); + stb_textedit_delete(str, state, prev, + state->cursor - prev); + state->cursor = prev; + } + } + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = 0; + else + while (state->cursor > 0 && + STB_TEXTEDIT_GETCHAR(str, state->cursor - 1) != + STB_TEXTEDIT_NEWLINE) + state->cursor = STB_TEXTEDIT_GETPREVCHARINDEX( + str, state->cursor); + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif + case STB_TEXTEDIT_K_LINEEND: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_move_to_last(str, state); + if (state->single_line) + state->cursor = n; + else + while (state->cursor < n && + STB_TEXTEDIT_GETCHAR(str, state->cursor) != + STB_TEXTEDIT_NEWLINE) + state->cursor = STB_TEXTEDIT_GETNEXTCHARINDEX( + str, state->cursor); + state->has_preferred_x = 0; + break; + } + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = 0; + else + while (state->cursor > 0 && + STB_TEXTEDIT_GETCHAR(str, state->cursor - 1) != + STB_TEXTEDIT_NEWLINE) + state->cursor = STB_TEXTEDIT_GETPREVCHARINDEX( + str, state->cursor); + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = n; + else + while (state->cursor < n && + STB_TEXTEDIT_GETCHAR(str, state->cursor) != + STB_TEXTEDIT_NEWLINE) + state->cursor = STB_TEXTEDIT_GETNEXTCHARINDEX( + str, state->cursor); + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + } + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point -= n; + STB_TEXTEDIT_memmove( + state->undo_char, state->undo_char + n, + (size_t)(state->undo_char_point * + sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i = 0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage -= + n; // @OPTIMIZE: get rid of + // char_storage and infer it + } + --state->undo_point; + STB_TEXTEDIT_memmove( + state->undo_rec, state->undo_rec + 1, + (size_t)(state->undo_point * sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = STB_TEXTEDIT_UNDOSTATECOUNT - 1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // move the remaining redo character data to the end of + // the buffer + state->redo_char_point += n; + STB_TEXTEDIT_memmove( + state->undo_char + state->redo_char_point, + state->undo_char + state->redo_char_point - n, + (size_t)((STB_TEXTEDIT_UNDOCHARCOUNT - + state->redo_char_point) * + sizeof(STB_TEXTEDIT_CHARTYPE))); + // adjust the position of all the other records to + // account for above memmove + for (i = state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage += n; + } + // now move all the redo records towards the end of the buffer; + // the first one is at 'redo_point' + STB_TEXTEDIT_memmove( + state->undo_rec + state->redo_point + 1, + state->undo_rec + state->redo_point, + (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point) * + sizeof(state->undo_rec[0]))); + // now move redo_point to point to the new one + ++state->redo_point; + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, + int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't + // undo + if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to + // make room + while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, + int insert_len, + int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (STB_TEXTEDIT_POSITIONTYPE)insert_len; + r->delete_length = (STB_TEXTEDIT_POSITIONTYPE)delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point += insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo + // record + u = s->undo_rec[s->undo_point - 1]; + r = &s->undo_rec[s->redo_point - 1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo + // record will need to re-insert the characters that get + // deleted, so we need to store them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= + STB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; + // there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters + // eventually + while (s->undo_char_point + u.delete_length > + s->redo_char_point) { + // should never happen: + if (s->redo_point == + STB_TEXTEDIT_UNDOSTATECOUNT) + return; + // there's currently not enough room, so discard + // a redo record + stb_textedit_discard_redo(s); + } + r = &s->undo_rec[s->redo_point - 1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = + s->redo_char_point - u.delete_length; + + // now save the characters + for (i = 0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = + STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, u.where, + &s->undo_char[u.char_storage], + u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + state->select_start = state->select_end = state->cursor; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo + // record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo + // record was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo + // record needs to store the characters + + if (s->undo_char_point + u->insert_length > + s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = + s->undo_char_point + u->insert_length; + + // now save the characters + for (i = 0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = + STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, r.where, + &s->undo_char[r.char_storage], + r.insert_length); + s->redo_char_point += r.insert_length; + } + + state->cursor = r.where + r.insert_length; + state->select_start = state->select_end = state->cursor; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, + int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, int where, + int length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = + stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i = 0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where + i); + } +} + +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, int where, + int old_length, int new_length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, + old_length, new_length); + if (p) { + for (i = 0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where + i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, + int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char)is_single_line; + state->insert_mode = 0; + state->row_count_per_page = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, + int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, + STB_TexteditState *state, + STB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + return stb_textedit_paste_internal(str, state, + (STB_TEXTEDIT_CHARTYPE *)ctext, len); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TEXTEDIT_IMPLEMENTATION + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +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. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +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 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/tests/integration/test_style_nova.c b/tests/integration/test_style_nova.c index 148398ff..c92fce74 100644 --- a/tests/integration/test_style_nova.c +++ b/tests/integration/test_style_nova.c @@ -606,6 +606,35 @@ static void check_link_button_has_no_background_in_dark(void) ui_clear_trash(); } +static void check_textcaret_follows_theme_foreground(void) +{ + ui_widget_t *input = ui_create_widget("textinput"); + ui_widget_t *caret; + + ui_widget_append(ui_root(), input); + ui_update(); + caret = ui_widget_get_child(input, 0); + ctest_equal_bool("light caret should match the text foreground", + caret->computed_style.background_color == + input->computed_style.color, + true); + ctest_equal_bool( + "light caret should not use the old black color", + caret->computed_style.background_color != css_color(255, 0, 0, 0), + true); + + ui_widget_add_class(ui_root(), "dark"); + ui_update(); + ctest_equal_bool("dark caret should match the text foreground", + caret->computed_style.background_color == + input->computed_style.color, + true); + + ui_widget_remove_class(ui_root(), "dark"); + ui_widget_destroy(input); + ui_clear_trash(); +} + void test_style_nova(void) { lcui_init(); @@ -636,6 +665,7 @@ void test_style_nova(void) ctest_describe("style-nova: toast", check_toast_theme); ctest_describe("style-nova: card", check_card_theme); ctest_describe("style-nova: attachment", check_attachment_theme); - + ctest_describe("style-nova: textcaret", + check_textcaret_follows_theme_foreground); lcui_destroy(); } diff --git a/tests/integration/test_textinput.c b/tests/integration/test_textinput.c index 165050f7..6a1be30f 100644 --- a/tests/integration/test_textinput.c +++ b/tests/integration/test_textinput.c @@ -11,6 +11,150 @@ #include #include +#include + +#define SEL_TEST_W 240 +#define SEL_TEST_H 80 + +static bool pixel_equal(pd_color_t a, pd_color_t b) +{ + return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a; +} + +static bool pixel_is_dark(pd_color_t c) +{ + return c.a > 0 && c.r < 128 && c.g < 128 && c.b < 128; +} + +static void render_root_canvas(pd_canvas_t *canvas) +{ + pd_context_t paint; + pd_rect_t rect = { 0, 0, SEL_TEST_W, SEL_TEST_H }; + + pd_canvas_init(canvas); + pd_canvas_create(canvas, SEL_TEST_W, SEL_TEST_H); + pd_canvas_fill(canvas, pd_rgb(255, 255, 255)); + memset(&paint, 0, sizeof(paint)); + paint.rect = rect; + pd_canvas_init(&paint.canvas); + pd_canvas_quote(&paint.canvas, canvas, &rect); + ui_widget_render(ui_root(), &paint); +} + +static void scan_dark_bbox(const pd_canvas_t *canvas, pd_rect_t *bbox) +{ + int x, y; + + bbox->x = bbox->y = bbox->width = bbox->height = 0; + for (y = 0; y < (int)canvas->height; ++y) { + for (x = 0; x < (int)canvas->width; ++x) { + if (!pixel_is_dark(pd_canvas_get_pixel( + canvas, (unsigned)x, (unsigned)y))) { + continue; + } + if (bbox->width == 0) { + bbox->x = x; + bbox->y = y; + bbox->width = bbox->height = 1; + } else { + if (x < bbox->x) { + bbox->width += bbox->x - x; + bbox->x = x; + } + if (y < bbox->y) { + bbox->height += bbox->y - y; + bbox->y = y; + } + if (x >= bbox->x + bbox->width) { + bbox->width = x - bbox->x + 1; + } + if (y >= bbox->y + bbox->height) { + bbox->height = y - bbox->y + 1; + } + } + } + } +} + +static void scan_diff_bbox(const pd_canvas_t *a, const pd_canvas_t *b, + pd_rect_t *bbox) +{ + int x, y; + + bbox->x = bbox->y = bbox->width = bbox->height = 0; + for (y = 0; y < (int)a->height; ++y) { + for (x = 0; x < (int)a->width; ++x) { + if (pixel_equal(pd_canvas_get_pixel(a, (unsigned)x, + (unsigned)y), + pd_canvas_get_pixel(b, (unsigned)x, + (unsigned)y))) { + continue; + } + if (bbox->width == 0) { + bbox->x = x; + bbox->y = y; + bbox->width = bbox->height = 1; + } else { + if (x < bbox->x) { + bbox->width += bbox->x - x; + bbox->x = x; + } + if (y < bbox->y) { + bbox->height += bbox->y - y; + bbox->y = y; + } + if (x >= bbox->x + bbox->width) { + bbox->width = x - bbox->x + 1; + } + if (y >= bbox->y + bbox->height) { + bbox->height = y - bbox->y + 1; + } + } + } + } +} + +static void check_selection_background_alignment(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t glyphs, sel; + ui_event_t e = { 0 }; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(w, "position", "absolute"); + ui_widget_set_style_string(w, "left", "20px"); + ui_widget_set_style_string(w, "top", "10px"); + ui_widget_set_style_string(w, "width", "180px"); + ui_textinput_set_text_w(w, L"abc"); + ui_root_append(w); + ui_update(); + + render_root_canvas(&before); + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + ui_update(); + render_root_canvas(&after); + + scan_dark_bbox(&before, &glyphs); + scan_diff_bbox(&before, &after, &sel); + ctest_equal_bool("selection should start near the text start", + sel.x <= glyphs.x + 2, true); + ctest_equal_bool("selection should end near the text end", + sel.x + sel.width >= glyphs.x + glyphs.width - 2, + true); + ctest_equal_bool("selection should share the text row", + sel.y <= glyphs.y + 2 && + sel.y + sel.height >= glyphs.y + glyphs.height - 2, + true); + + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + ui_widget_destroy(w); + ui_clear_trash(); +} static void check_password_input(void) { @@ -68,6 +212,1229 @@ static void check_multiline_attr(void) ui_clear_trash(); } +#define CARET_TEST_DPI 192.f + +static ui_widget_t *create_scaled_textinput(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_text_w(w, L"hello world"); + ui_root_append(w); + ui_update(); + return w; +} + +static void destroy_scaled_textinput(ui_widget_t *w) +{ + ui_widget_destroy(w); + ui_clear_trash(); + ui_metrics.dpi = 96.f; + ui_update(); +} + +static void check_multiline_enter_inserts_newline(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + + ui_widget_set_attr(w, "multiline", "true"); + ui_root_append(w); + ui_update(); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_ENTER; + ui_widget_emit_event(w, e, NULL); + ui_update(); + ctest_equal_bool("enter should insert a line break in multiline mode", + ui_textinput_get_text_length(w) == 1, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_paste_newline_filter(void) +{ + ui_widget_t *single = ui_create_widget("textinput"); + ui_widget_t *multi = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + ptk_clipboard_t clipboard = { 0 }; + wchar_t text[] = L"a\nb"; + + ui_widget_set_attr(multi, "multiline", "true"); + ui_root_append(single); + ui_root_append(multi); + clipboard.text = text; + clipboard.len = wcslen(text); + ui_event_init(&e, "paste"); + ui_widget_emit_event(single, e, &clipboard); + ui_widget_emit_event(multi, e, &clipboard); + ui_update(); + + ctest_equal_bool("single-line paste should drop line breaks", + ui_textinput_get_text_length(single) == 2, true); + ctest_equal_bool("multiline paste should keep line breaks", + ui_textinput_get_text_length(multi) == 3, true); + + ui_widget_destroy(single); + ui_widget_destroy(multi); + ui_clear_trash(); +} + +static void check_multiline_autowrap(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *caret; + float expect_top; + + ui_widget_set_attr(w, "multiline", "true"); + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_widget_set_style_unit_value(w, css_prop_height, 120, CSS_UNIT_PX); + ui_textinput_set_text_w( + w, L"Lorem ipsum dolor sit amet, consectetur adipiscing elit."); + ui_root_append(w); + ui_update(); + + caret = ui_widget_get_child(w, 0); + ui_textinput_move_caret(w, 0, 0); + ui_update(); + expect_top = caret->border_box.y; + ui_textinput_move_caret(w, 1, 1); + ui_update(); + ctest_equal_bool("long text should wrap into a second visual line", + caret->border_box.y > expect_top, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_edit_roundtrip_multiline(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + wchar_t buf[64]; + + ui_widget_set_attr(w, "multiline", "true"); + ui_textinput_set_text_w(w, L"abc\ndef"); + ui_widget_update(w); + + ctest_equal_bool("multiline length should include the newline", + ui_textinput_get_text_length(w) == 7, true); + ctest_equal_bool("multiline text should round-trip", + ui_textinput_get_text_w(w, 0, 64, buf) == 7 && + wcscmp(buf, L"abc\ndef") == 0, + true); + + ui_textinput_move_caret(w, 1, 0); + ui_textinput_insert_text_w(w, L"X"); + ui_widget_update(w); + ctest_equal_bool("insert at line start should stay on line 1", + ui_textinput_get_text_w(w, 0, 64, buf) == 8 && + wcscmp(buf, L"abc\nXdef") == 0, + true); + + ui_textinput_append_text_w(w, L"!"); + ui_widget_update(w); + ctest_equal_bool("append should add text at the end", + ui_textinput_get_text_w(w, 0, 64, buf) == 9 && + wcscmp(buf, L"abc\nXdef!") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_password_edit_roundtrip(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + wchar_t buf[64]; + + ui_textinput_set_password_char(w, L'*'); + ui_textinput_set_text_w(w, L"secret"); + ui_widget_update(w); + ui_textinput_move_caret(w, 0, 3); + ui_textinput_insert_text_w(w, L"X"); + ui_widget_update(w); + ctest_equal_bool("password input should keep the plaintext editable", + ui_textinput_get_text_w(w, 0, 64, buf) == 7 && + wcscmp(buf, L"secXret") == 0, + true); + ctest_equal_bool("password input length should match plaintext", + ui_textinput_get_text_length(w) == 7, true); + + ui_textinput_set_password_char(w, 0); + ui_widget_update(w); + ctest_equal_bool( + "disabling password masking should keep the edited text", + ui_textinput_get_text_w(w, 0, 64, buf) == 7 && + wcscmp(buf, L"secXret") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_undo_redo(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + wchar_t buf[32]; + + ui_textinput_set_text_w(w, L"abc"); + ui_widget_update(w); + + ui_event_init(&e, "textinput"); + e.text.text = L"d"; + e.text.length = 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("typed text should extend the value", + ui_textinput_get_text_w(w, 0, 32, buf) == 4 && + wcscmp(buf, L"abcd") == 0, + true); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_Z; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("ctrl+z should undo the last input", + ui_textinput_get_text_w(w, 0, 32, buf) == 3 && + wcscmp(buf, L"abc") == 0, + true); + + e.key.code = KEY_Y; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("ctrl+y should redo the input", + ui_textinput_get_text_w(w, 0, 32, buf) == 4 && + wcscmp(buf, L"abcd") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_read_only(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + + ui_textinput_set_text_w(w, L"abc"); + ui_widget_update(w); + ui_textinput_set_read_only(w, true); + + ui_event_init(&e, "textinput"); + e.text.text = L"d"; + e.text.length = 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("read-only textinput should ignore text input", + ui_textinput_get_text_length(w) == 3, true); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_BACKSPACE; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("read-only textinput should ignore backspace", + ui_textinput_get_text_length(w) == 3, true); + + e.key.code = KEY_ENTER; + e.key.shift_key = false; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("read-only textinput should ignore enter", + ui_textinput_get_text_length(w) == 3, true); + + ui_textinput_set_read_only(w, false); + e.type = UI_EVENT_TEXTINPUT; + e.text.text = L"d"; + e.text.length = 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_bool("editable textinput should accept text again", + ui_textinput_get_text_length(w) == 4, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static int textinput_change_count; + +static void on_textinput_change(ui_widget_t *w, ui_event_t *e, void *arg) +{ + ++textinput_change_count; +} + +static void check_password_copy_blocked(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + + ui_textinput_set_password_char(w, L'*'); + ui_textinput_set_text_w(w, L"secret"); + ui_root_append(w); + ui_update(); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + e.key.code = KEY_X; + ui_widget_emit_event(w, e, NULL); + ui_update(); + ctest_equal_bool("password cut should not remove or copy plaintext", + ui_textinput_get_text_length(w) == 6, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static int reentrant_change_count; + +static void on_reentrant_change(ui_widget_t *w, ui_event_t *e, void *arg) +{ + ++reentrant_change_count; + if (reentrant_change_count == 1) { + ui_textinput_append_text_w(w, L"!"); + } +} + +static void check_change_reentrancy(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + wchar_t buf[16]; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_text_w(w, L"ab"); + ui_root_append(w); + ui_update(); + ui_widget_on(w, "change", on_reentrant_change, NULL); + reentrant_change_count = 0; + + ui_textinput_append_text_w(w, L"c"); + ui_update(); + ui_update(); + ctest_equal_int("change handler edits should emit another change", + reentrant_change_count, 2); + ctest_equal_bool("change handler edits should be applied", + ui_textinput_get_text_w(w, 0, 16, buf) == 4 && + wcscmp(buf, L"abc!") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_single_line_api_filter(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + wchar_t buf[16]; + + ui_textinput_set_text_w(w, L"a\nb"); + ui_widget_update(w); + ctest_equal_bool("single-line set_text_w should drop newlines", + ui_textinput_get_text_w(w, 0, 16, buf) == 2 && + wcscmp(buf, L"ab") == 0, + true); + + ui_textinput_insert_text_w(w, L"c\rd"); + ui_widget_update(w); + ctest_equal_bool("single-line insert_text_w should drop newlines", + ui_textinput_get_text_w(w, 0, 16, buf) == 4 && + wcscmp(buf, L"abcd") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_noop_change(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + + ui_textinput_set_text_w(w, L"ab"); + ui_root_append(w); + ui_update(); + ui_widget_on(w, "change", on_textinput_change, NULL); + textinput_change_count = 0; + + ui_textinput_move_caret(w, 0, 0); + ui_update(); + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_BACKSPACE; + ui_widget_emit_event(w, e, NULL); + ui_update(); + ctest_equal_int("backspace at text start should not emit change", + textinput_change_count, 0); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_page_down(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + wchar_t buf[64]; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_widget_set_style_unit_value(w, css_prop_height, 120, CSS_UNIT_PX); + ui_textinput_enable_multiline(w, true); + ui_textinput_set_text_w(w, L"0\n1\n2\n3\n4\n5\n6\n7"); + ui_root_append(w); + ui_update(); + ui_textinput_move_caret(w, 0, 0); + ui_update(); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_PAGEDOWN; + ui_widget_emit_event(w, e, NULL); + ui_update(); + ui_textinput_insert_text_w(w, L"X"); + ui_update(); + ctest_equal_bool( + "page down should move the caret off the first line", + ui_textinput_get_text_w(w, 0, 64, buf) == 16 && buf[0] != L'X', + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_parse_change_suppressed(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + + ui_widget_on(w, "change", on_textinput_change, NULL); + textinput_change_count = 0; + ui_widget_set_text(w, "abc"); + ui_widget_update(w); + ctest_equal_bool( + "parsed initial text should not emit change", + textinput_change_count == 0 && ui_textinput_get_text_length(w) == 3, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_change_event(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_text_w(w, L"ab"); + ui_root_append(w); + ui_update(); + ui_widget_on(w, "change", on_textinput_change, NULL); + textinput_change_count = 0; + + ui_event_init(&e, "textinput"); + e.text.text = L"c"; + e.text.length = 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_update(w); + ctest_equal_int("text input should emit one change event", + textinput_change_count, 1); + + ui_textinput_insert_text_w(w, L"d"); + ui_widget_update(w); + ctest_equal_int("insert_text_w should emit one change event", + textinput_change_count, 2); + + ui_textinput_set_text_w(w, L"x"); + ui_widget_update(w); + ctest_equal_int("set_text_w should emit one change event", + textinput_change_count, 3); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_edit_marks_content_dirty(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + list_t rects; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_text_w(w, L"ab"); + ui_root_append(w); + ui_update(); + list_create(&rects); + ui_widget_get_dirty_rects(ui_root(), &rects); + list_destroy(&rects, free); + + ui_textinput_insert_text_w(w, L"c"); + ui_widget_update(w); + ctest_equal_bool( + "editing should mark the text area dirty", + w->rendering.dirty_rect_type != UI_DIRTY_RECT_TYPE_NONE, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_password_multiline_caret(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *caret; + float first_y, second_y; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_widget_set_style_unit_value(w, css_prop_height, 120, CSS_UNIT_PX); + ui_textinput_enable_multiline(w, true); + ui_textinput_set_password_char(w, L'*'); + ui_textinput_set_text_w(w, L"a\nb"); + ui_root_append(w); + ui_update(); + caret = ui_widget_get_child(w, 0); + + ui_textinput_move_caret(w, 0, 0); + ui_update(); + first_y = caret->border_box.y; + ui_textinput_move_caret(w, 1, 0); + ui_update(); + second_y = caret->border_box.y; + ctest_equal_bool( + "password mask should keep line breaks for caret placement", + second_y > first_y, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_password_pointer_mask_width(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *caret; + ui_event_t e = { 0 }; + wchar_t buf[16]; + float expect_x; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_password_char(w, L'*'); + ui_textinput_set_text_w(w, L"iiii"); + ui_root_append(w); + ui_update(); + caret = ui_widget_get_child(w, 0); + ui_textinput_move_caret(w, 0, 1); + ui_update(); + expect_x = caret->border_box.x; + ui_textinput_move_caret(w, 0, 0); + ui_update(); + + e.type = UI_EVENT_MOUSEDOWN; + e.mouse.x = w->border_box.x + expect_x + 1; + e.mouse.y = w->border_box.y + w->computed_style.padding_top + 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_release_mouse_capture(w); + ui_update(); + ui_textinput_insert_text_w(w, L"X"); + ui_update(); + ctest_equal_bool("password click should hit the rendered mask column", + ui_textinput_get_text_w(w, 0, 16, buf) == 5 && + wcscmp(buf, L"iXiii") == 0, + true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_password_pointer_mapping(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *caret; + ui_event_t e = { 0 }; + float expect_x; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_password_char(w, L'*'); + ui_textinput_set_text_w(w, L"secret"); + ui_root_append(w); + ui_update(); + caret = ui_widget_get_child(w, 0); + ui_textinput_move_caret(w, 0, 3); + ui_update(); + expect_x = caret->border_box.x; + ui_textinput_move_caret(w, 0, 0); + ui_update(); + + e.type = UI_EVENT_MOUSEDOWN; + e.mouse.x = w->border_box.x + expect_x + 1; + e.mouse.y = w->border_box.y + w->computed_style.padding_top + 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_release_mouse_capture(w); + ui_update(); + ctest_equal_bool("password click should keep the caret position", + fabsf(caret->border_box.x - expect_x) <= 1.f, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_drag_marks_content_dirty(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_event_t e = { 0 }; + list_t rects; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_textinput_set_text_w(w, L"hello world"); + ui_root_append(w); + ui_update(); + list_create(&rects); + ui_widget_get_dirty_rects(ui_root(), &rects); + list_destroy(&rects, free); + + e.type = UI_EVENT_MOUSEDOWN; + e.mouse.x = w->border_box.x + w->computed_style.padding_left + 2; + e.mouse.y = w->border_box.y + w->computed_style.padding_top + 2; + ui_widget_emit_event(w, e, NULL); + ui_widget_release_mouse_capture(w); + ui_update(); + list_create(&rects); + ui_widget_get_dirty_rects(ui_root(), &rects); + list_destroy(&rects, free); + + e.type = UI_EVENT_MOUSEMOVE; + e.mouse.x += 60; + w->rendering.dirty_rect_type = UI_DIRTY_RECT_TYPE_NONE; + ui_widget_emit_event(w, e, NULL); + ctest_equal_bool( + "dragging should mark the text area dirty", + w->rendering.dirty_rect_type != UI_DIRTY_RECT_TYPE_NONE, true); + ui_update(); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static int count_diff_pixels_in_rect(const pd_canvas_t *a, const pd_canvas_t *b, + pd_rect_t r) +{ + int x, y, count = 0; + + for (y = r.y; y < r.y + r.height; ++y) { + for (x = r.x; x < r.x + r.width; ++x) { + if (y < 0 || x < 0 || y >= (int)a->height || + x >= (int)a->width) { + continue; + } + if (!pixel_equal(pd_canvas_get_pixel(a, (unsigned)x, + (unsigned)y), + pd_canvas_get_pixel(b, (unsigned)x, + (unsigned)y))) { + ++count; + } + } + } + return count; +} + +static int count_dark_pixels_in_rect(const pd_canvas_t *canvas, pd_rect_t r) +{ + int x, y, count = 0; + + for (y = r.y; y < r.y + r.height; ++y) { + for (x = r.x; x < r.x + r.width; ++x) { + if (y < 0 || x < 0 || y >= (int)canvas->height || + x >= (int)canvas->width) { + continue; + } + if (pixel_is_dark(pd_canvas_get_pixel( + canvas, (unsigned)x, (unsigned)y))) { + ++count; + } + } + } + return count; +} + +static void check_blur_keeps_text(void) +{ + ui_widget_t *a = ui_create_widget("textinput"); + ui_widget_t *b = ui_create_widget("textinput"); + pd_canvas_t canvas; + pd_rect_t area; + int dark_before, dark_after; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(a, "position", "absolute"); + ui_widget_set_style_string(a, "left", "20px"); + ui_widget_set_style_string(a, "top", "5px"); + ui_widget_set_style_string(a, "width", "180px"); + ui_widget_set_style_string(b, "position", "absolute"); + ui_widget_set_style_string(b, "left", "20px"); + ui_widget_set_style_string(b, "top", "45px"); + ui_widget_set_style_string(b, "width", "180px"); + ui_textinput_set_text_w(a, L"abc"); + ui_textinput_set_text_w(b, L"def"); + ui_root_append(a); + ui_root_append(b); + ui_update(); + ui_set_focus(a); + ui_update(); + render_root_canvas(&canvas); + area.x = (int)a->content_box.x; + area.y = (int)a->content_box.y; + area.width = (int)a->content_box.width; + area.height = (int)a->content_box.height; + dark_before = count_dark_pixels_in_rect(&canvas, area); + pd_canvas_destroy(&canvas); + + ui_set_focus(b); + ui_update(); + render_root_canvas(&canvas); + dark_after = count_dark_pixels_in_rect(&canvas, area); + ctest_equal_bool("blur should keep the text visible", + dark_before > 0 && dark_after > 0, true); + pd_canvas_destroy(&canvas); + + ui_widget_destroy(a); + ui_widget_destroy(b); + ui_clear_trash(); +} + +static void check_blur_keeps_long_text(void) +{ + ui_widget_t *a = ui_create_widget("textinput"); + ui_widget_t *b = ui_create_widget("textinput"); + pd_canvas_t canvas; + pd_rect_t area; + int dark_after; + int i; + + ui_metrics.dpi = 192.f; + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(a, "position", "absolute"); + ui_widget_set_style_string(a, "left", "20px"); + ui_widget_set_style_string(a, "top", "5px"); + ui_widget_set_style_string(a, "width", "180px"); + ui_widget_set_style_string(b, "position", "absolute"); + ui_widget_set_style_string(b, "left", "20px"); + ui_widget_set_style_string(b, "top", "45px"); + ui_widget_set_style_string(b, "width", "180px"); + for (i = 0; i < 40; ++i) { + ui_textinput_append_text_w(a, L"W"); + } + ui_root_append(a); + ui_root_append(b); + ui_update(); + ui_set_focus(a); + ui_update(); + + ui_set_focus(b); + ui_update(); + render_root_canvas(&canvas); + area.x = (int)a->content_box.x; + area.y = (int)a->content_box.y; + area.width = (int)a->content_box.width; + area.height = (int)a->content_box.height; + dark_after = count_dark_pixels_in_rect(&canvas, area); + ctest_equal_bool("blur should keep long text visible", dark_after > 0, + true); + pd_canvas_destroy(&canvas); + + ui_widget_destroy(a); + ui_widget_destroy(b); + ui_clear_trash(); + ui_metrics.dpi = 96.f; + ui_update(); +} + +static void check_blur_keeps_text_with_placeholder(void) +{ + ui_widget_t *a = ui_create_widget("textinput"); + ui_widget_t *b = ui_create_widget("textinput"); + pd_canvas_t canvas; + pd_rect_t area; + int dark_after; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(a, "position", "absolute"); + ui_widget_set_style_string(a, "left", "20px"); + ui_widget_set_style_string(a, "top", "5px"); + ui_widget_set_style_string(a, "width", "180px"); + ui_widget_set_style_string(b, "position", "absolute"); + ui_widget_set_style_string(b, "left", "20px"); + ui_widget_set_style_string(b, "top", "45px"); + ui_widget_set_style_string(b, "width", "180px"); + ui_textinput_set_placeholder(a, "Please input..."); + ui_textinput_set_text_w(a, L"abc"); + ui_root_append(a); + ui_root_append(b); + ui_update(); + ui_set_focus(a); + ui_update(); + + ui_set_focus(b); + ui_update(); + render_root_canvas(&canvas); + area.x = (int)a->content_box.x; + area.y = (int)a->content_box.y; + area.width = (int)a->content_box.width; + area.height = (int)a->content_box.height; + dark_after = count_dark_pixels_in_rect(&canvas, area); + ctest_equal_bool("placeholder should not replace a blurred value", + dark_after > 0, true); + pd_canvas_destroy(&canvas); + + ui_widget_destroy(a); + ui_widget_destroy(b); + ui_clear_trash(); +} + +static void check_blur_keeps_typed_text(void) +{ + ui_widget_t *a = ui_create_widget("textinput"); + ui_widget_t *b = ui_create_widget("textinput"); + pd_canvas_t canvas; + pd_rect_t area; + ui_event_t e = { 0 }; + int dark_after; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(a, "position", "absolute"); + ui_widget_set_style_string(a, "left", "20px"); + ui_widget_set_style_string(a, "top", "5px"); + ui_widget_set_style_string(a, "width", "180px"); + ui_widget_set_style_string(b, "position", "absolute"); + ui_widget_set_style_string(b, "left", "20px"); + ui_widget_set_style_string(b, "top", "45px"); + ui_widget_set_style_string(b, "width", "180px"); + ui_root_append(a); + ui_root_append(b); + ui_update(); + ui_set_focus(a); + ui_update(); + + ui_event_init(&e, "textinput"); + e.text.text = L"typed"; + e.text.length = 5; + ui_widget_emit_event(a, e, NULL); + ui_update(); + + ui_set_focus(b); + ui_update(); + render_root_canvas(&canvas); + area.x = (int)a->content_box.x; + area.y = (int)a->content_box.y; + area.width = (int)a->content_box.width; + area.height = (int)a->content_box.height; + dark_after = count_dark_pixels_in_rect(&canvas, area); + ctest_equal_bool("blur should keep typed text visible", dark_after > 0, + true); + pd_canvas_destroy(&canvas); + + ui_widget_destroy(a); + ui_widget_destroy(b); + ui_clear_trash(); +} + +static void check_blur_keeps_input_group_text(void) +{ + ui_widget_t *group = ui_create_input_group(); + ui_widget_t *input = ui_create_input_group_input(); + ui_widget_t *notes = ui_create_input_group_textarea(); + pd_canvas_t canvas; + pd_rect_t area; + int dark_after; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(group, "position", "absolute"); + ui_widget_set_style_string(group, "left", "20px"); + ui_widget_set_style_string(group, "top", "5px"); + ui_widget_set_style_string(group, "width", "180px"); + ui_widget_set_style_string(notes, "position", "absolute"); + ui_widget_set_style_string(notes, "left", "20px"); + ui_widget_set_style_string(notes, "top", "45px"); + ui_widget_set_style_string(notes, "width", "180px"); + ui_textinput_set_text_w(input, L"typed"); + ui_widget_append(group, input); + ui_root_append(group); + ui_root_append(notes); + ui_update(); + ui_set_focus(input); + ui_update(); + + ui_set_focus(notes); + ui_update(); + render_root_canvas(&canvas); + area.x = (int)group->border_box.x; + area.y = (int)group->border_box.y; + area.width = (int)group->border_box.width; + area.height = (int)group->border_box.height; + dark_after = count_dark_pixels_in_rect(&canvas, area); + ctest_equal_bool("input-group blur should keep text visible", + dark_after > 0, true); + pd_canvas_destroy(&canvas); + + ui_widget_destroy(group); + ui_widget_destroy(notes); + ui_clear_trash(); +} + +static void check_selection_cleared_on_blur(void) +{ + ui_widget_t *a = ui_create_widget("textinput"); + ui_widget_t *b = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t area; + ui_event_t e = { 0 }; + int changed; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(a, "position", "absolute"); + ui_widget_set_style_string(a, "left", "20px"); + ui_widget_set_style_string(a, "top", "5px"); + ui_widget_set_style_string(a, "width", "180px"); + ui_widget_set_style_string(b, "position", "absolute"); + ui_widget_set_style_string(b, "left", "20px"); + ui_widget_set_style_string(b, "top", "45px"); + ui_widget_set_style_string(b, "width", "180px"); + ui_textinput_enable_multiline(a, true); + ui_textinput_set_text_w(a, L"abc"); + ui_textinput_set_text_w(b, L"def"); + ui_root_append(a); + ui_root_append(b); + ui_update(); + + ui_set_focus(a); + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(a, e, NULL); + ui_update(); + render_root_canvas(&before); + + ui_set_focus(b); + ui_update(); + render_root_canvas(&after); + area.x = (int)a->content_box.x; + area.y = (int)a->content_box.y; + area.width = (int)a->content_box.width; + area.height = (int)a->content_box.height; + changed = count_diff_pixels_in_rect(&before, &after, area); + ctest_equal_bool("blur should clear the text selection", changed > 100, + true); + ctest_equal_bool("blur should keep the selected text visible", + count_dark_pixels_in_rect(&after, area) > 0, true); + + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + ui_widget_destroy(a); + ui_widget_destroy(b); + ui_clear_trash(); +} + +static void check_selection_css_class(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t diff; + pd_color_t pixel; + ui_event_t e = { 0 }; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(w, "position", "absolute"); + ui_widget_set_style_string(w, "left", "20px"); + ui_widget_set_style_string(w, "top", "10px"); + ui_widget_set_style_string(w, "width", "180px"); + ui_textinput_set_text_w(w, L"abc"); + ui_root_append(w); + ui_update(); + + ui_load_css_string("textinput .selection { background-color: #00ff00; " + "color: #ff0000; }", + "test-selection-css"); + ui_refresh_style(); + ui_update(); + render_root_canvas(&before); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + ui_update(); + render_root_canvas(&after); + scan_diff_bbox(&before, &after, &diff); + pixel = pd_canvas_get_pixel(&after, (unsigned)(diff.x + 1), + (unsigned)(diff.y + 2)); + ctest_equal_bool("selection class should tint the selection", + pixel.g > 200 && pixel.r < 100 && pixel.b < 100, true); + { + int x, y, red = 0; + + for (y = diff.y; y < diff.y + diff.height; ++y) { + for (x = diff.x; x < diff.x + diff.width; ++x) { + pd_color_t p = pd_canvas_get_pixel( + &after, (unsigned)x, (unsigned)y); + if (p.r > 200 && p.g < 80 && p.b < 80) { + ++red; + } + } + } + ctest_equal_bool( + "selection class should let CSS set the text color", + red > 0, true); + } + + ui_unload_css_string("test-selection-css"); + ui_refresh_style(); + ui_update(); + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_selection_accent_color(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t diff; + pd_color_t pixel; + ui_event_t e = { 0 }; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(w, "position", "absolute"); + ui_widget_set_style_string(w, "left", "20px"); + ui_widget_set_style_string(w, "top", "10px"); + ui_widget_set_style_string(w, "width", "180px"); + ui_textinput_set_text_w(w, L"abc"); + ui_root_append(w); + + ui_theme_set_accent("blue"); + ui_refresh_style(); + ui_update(); + render_root_canvas(&before); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + ui_update(); + render_root_canvas(&after); + scan_diff_bbox(&before, &after, &diff); + pixel = pd_canvas_get_pixel(&after, (unsigned)(diff.x + 1), + (unsigned)(diff.y + 2)); + ctest_equal_bool("accent should tint the selection background", + pixel.b > pixel.r + 20, true); + + ui_theme_set_accent(NULL); + ui_refresh_style(); + ui_update(); + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_selection_default_colors(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *selection; + + ui_root_append(w); + ui_update(); + selection = ui_widget_get_child(w, 1); + ctest_equal_bool("default selection background should be solid primary", + selection->computed_style.background_color == + css_color(255, 0x17, 0x17, 0x17), + true); + ctest_equal_bool( + "default selection text should use primary foreground", + selection->computed_style.color == css_color(255, 0xfa, 0xfa, 0xfa), + true); + + ui_widget_add_class(ui_root(), "dark"); + ui_update(); + ctest_equal_bool("dark selection background should be light", + selection->computed_style.background_color == + css_color(255, 0xfa, 0xfa, 0xfa), + true); + ctest_equal_bool( + "dark selection text should be dark", + selection->computed_style.color == css_color(255, 0x17, 0x17, 0x17), + true); + ui_widget_remove_class(ui_root(), "dark"); + ui_update(); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_selection_color_attr(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t diff; + pd_color_t pixel; + ui_event_t e = { 0 }; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(w, "position", "absolute"); + ui_widget_set_style_string(w, "left", "20px"); + ui_widget_set_style_string(w, "top", "10px"); + ui_widget_set_style_string(w, "width", "180px"); + ui_widget_set_attr(w, "selection-color", "#00ff00"); + ui_textinput_set_text_w(w, L"abc"); + ui_root_append(w); + ui_update(); + render_root_canvas(&before); + + e.type = UI_EVENT_KEYDOWN; + e.key.code = KEY_A; + e.key.ctrl_key = true; + ui_widget_emit_event(w, e, NULL); + ui_update(); + render_root_canvas(&after); + scan_diff_bbox(&before, &after, &diff); + pixel = pd_canvas_get_pixel(&after, (unsigned)(diff.x + 1), + (unsigned)(diff.y + 2)); + ctest_equal_bool("selection-color attribute should tint the selection", + pixel.g > 200 && pixel.r < 100 && pixel.b < 100, true); + + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_first_char_caret(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + ui_widget_t *caret; + ui_event_t e = { 0 }; + float empty_x, typed_x; + + ui_widget_set_style_unit_value(w, css_prop_width, 200, CSS_UNIT_PX); + ui_root_append(w); + ui_update(); + ui_set_focus(w); + ui_update(); + caret = ui_widget_get_child(w, 0); + empty_x = caret->border_box.x; + + ui_event_init(&e, "textinput"); + e.text.text = L"a"; + e.text.length = 1; + ui_widget_emit_event(w, e, NULL); + ui_update(); + typed_x = caret->border_box.x; + ctest_equal_bool("caret should move after the first typed character", + typed_x > empty_x + 1.f, true); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_collapsed_layout_keeps_text(void) +{ + ui_widget_t *w = ui_create_widget("textinput"); + pd_canvas_t before, after; + pd_rect_t bbox_before, bbox_after; + + ui_widget_resize(ui_root(), SEL_TEST_W, SEL_TEST_H); + ui_widget_set_style_string(w, "position", "absolute"); + ui_widget_set_style_string(w, "left", "20px"); + ui_widget_set_style_string(w, "top", "10px"); + ui_widget_set_style_string(w, "width", "180px"); + ui_textinput_set_text_w(w, L"hello"); + ui_root_append(w); + ui_update(); + + render_root_canvas(&before); + scan_dark_bbox(&before, &bbox_before); + ctest_equal_bool("text should be visible before the collapse", + bbox_before.width > 0, true); + + /* A reflow can deliver a caret update while the widget reports a + * zero-sized content box. That must not queue a scroll offset which + * the next update pass applies before the layout grows back. */ + { + float width = w->content_box.width; + float height = w->content_box.height; + + w->content_box.width = 0; + w->content_box.height = 0; + ui_textinput_move_caret(w, 0, 5); + ui_widget_update(w); + w->content_box.width = width; + w->content_box.height = height; + } + + render_root_canvas(&after); + scan_dark_bbox(&after, &bbox_after); + ctest_equal_bool("collapsed layout should not hide the text", + bbox_after.width > 0, true); + + pd_canvas_destroy(&before); + pd_canvas_destroy(&after); + + ui_widget_destroy(w); + ui_clear_trash(); +} + +static void check_caret_geometry_with_stale_metrics(void) +{ + ui_widget_t *w, *caret; + float expect_x, expect_height; + + ui_metrics.dpi = CARET_TEST_DPI; + w = create_scaled_textinput(); + caret = ui_widget_get_child(w, 0); + ui_textinput_move_caret(w, 0, 5); + ui_update(); + expect_x = caret->border_box.x; + expect_height = caret->border_box.height; + ctest_equal_bool("scaled caret should have a visible height", + expect_height > 0, true); + + /* 事件分发发生在 ui_server_update() 之外,此时全局 dpi 还是默认值 96, + * caret 计算必须使用文本层的实际排版比例,不能跟随这个临时值 */ + ui_metrics.dpi = 96.f; + ui_textinput_move_caret(w, 0, 5); + ui_metrics.dpi = CARET_TEST_DPI; + ui_update(); + ctest_equal_float("caret x should not apply the scale twice", + caret->border_box.x, expect_x); + ctest_equal_float("caret height should not apply the scale twice", + caret->border_box.height, expect_height); + destroy_scaled_textinput(w); +} + +static void check_caret_pointer_mapping_at_scale(void) +{ + ui_widget_t *w, *caret; + ui_event_t e = { 0 }; + float expect_x; + + ui_metrics.dpi = CARET_TEST_DPI; + w = create_scaled_textinput(); + caret = ui_widget_get_child(w, 0); + ui_textinput_move_caret(w, 0, 5); + ui_update(); + expect_x = caret->border_box.x; + ui_textinput_move_caret(w, 0, 0); + ui_update(); + + /* 模拟一次在高 DPI 窗口内、以逻辑坐标发出的点击 */ + ui_metrics.dpi = 96.f; + e.type = UI_EVENT_MOUSEDOWN; + e.mouse.x = w->border_box.x + expect_x + 1; + e.mouse.y = w->border_box.y + w->computed_style.padding_top + 1; + ui_widget_emit_event(w, e, NULL); + ui_widget_release_mouse_capture(w); + ui_metrics.dpi = CARET_TEST_DPI; + ui_update(); + ctest_equal_float("pointer should select the same caret column", + caret->border_box.x, expect_x); + destroy_scaled_textinput(w); +} + void test_textinput(void) { ui_widget_t *w; @@ -130,5 +1497,50 @@ void test_textinput(void) ui_widget_destroy(w); check_password_input(); check_multiline_attr(); + ctest_describe("multiline editing", + check_multiline_enter_inserts_newline); + ctest_describe("multiline autowrap", check_multiline_autowrap); + ctest_describe("paste newline filter", check_paste_newline_filter); + ctest_describe("edit roundtrip", check_edit_roundtrip_multiline); + ctest_describe("password edit roundtrip", + check_password_edit_roundtrip); + ctest_describe("undo redo", check_undo_redo); + ctest_describe("read only", check_read_only); + ctest_describe("password pointer", check_password_pointer_mapping); + ctest_describe("password pointer mask width", + check_password_pointer_mask_width); + ctest_describe("drag dirty", check_drag_marks_content_dirty); + ctest_describe("selection alignment", + check_selection_background_alignment); + ctest_describe("selection blur", check_selection_cleared_on_blur); + ctest_describe("blur keeps text", check_blur_keeps_text); + ctest_describe("blur keeps typed text", check_blur_keeps_typed_text); + ctest_describe("blur keeps input-group text", + check_blur_keeps_input_group_text); + ctest_describe("blur keeps long text", check_blur_keeps_long_text); + ctest_describe("blur keeps placeholder text", + check_blur_keeps_text_with_placeholder); + ctest_describe("selection color", check_selection_color_attr); + ctest_describe("selection default colors", + check_selection_default_colors); + ctest_describe("selection css", check_selection_css_class); + ctest_describe("selection accent", check_selection_accent_color); + ctest_describe("first char caret", check_first_char_caret); + ctest_describe("edit dirty", check_edit_marks_content_dirty); + ctest_describe("change event", check_change_event); + ctest_describe("parse change suppression", + check_parse_change_suppressed); + ctest_describe("single-line api filter", check_single_line_api_filter); + ctest_describe("noop change", check_noop_change); + ctest_describe("page down", check_page_down); + ctest_describe("change reentrancy", check_change_reentrancy); + ctest_describe("password copy", check_password_copy_blocked); + ctest_describe("password multiline caret", + check_password_multiline_caret); + ctest_describe("collapsed layout keeps text", + check_collapsed_layout_keeps_text); + ctest_describe("caret scale", check_caret_geometry_with_stale_metrics); + ctest_describe("caret pointer scale", + check_caret_pointer_mapping_at_scale); lcui_destroy(); } diff --git a/tests/integration/test_textinput_edit.c b/tests/integration/test_textinput_edit.c new file mode 100644 index 00000000..7ff1ac51 --- /dev/null +++ b/tests/integration/test_textinput_edit.c @@ -0,0 +1,346 @@ +/* + * tests/integration/test_textinput_edit.c + * + * Copyright (c) 2026, Liu Chao All rights reserved. + * + * SPDX-License-Identifier: MIT + * + * This file is part of LCUI, distributed under the MIT License found + * in the LICENSE.TXT file in the root directory of this source tree. + */ + +#include +#include +#include "../../src/widgets/textedit.h" + +static void check_text_edit_core(void) +{ + ui_text_edit_t *edit = ui_text_edit_create(); + wchar_t buf[16]; + + ui_text_edit_set_text(edit, L"hello", 5); + ctest_equal_int("should store text length", + (int)ui_text_edit_get_length(edit), 5); + ctest_equal_int("should read text back", + (int)ui_text_edit_get_text(edit, 0, 16, buf), 5); + ctest_equal_wcs("should return the identical text", buf, L"hello"); + + ui_text_edit_text_input(edit, L"!", 1); + ctest_equal_int("text input should insert at the cursor", + (int)ui_text_edit_get_length(edit), 6); + ctest_equal_int("should read the inserted text", + (int)ui_text_edit_get_text(edit, 0, 16, buf), 6); + ctest_equal_wcs("should append the input text", buf, L"hello!"); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_BACKSPACE); + ctest_equal_int("backspace should delete one character", + (int)ui_text_edit_get_length(edit), 5); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_UNDO); + ctest_equal_int("undo should restore the deleted character", + (int)ui_text_edit_get_length(edit), 6); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_REDO); + ctest_equal_int("redo should delete it again", + (int)ui_text_edit_get_length(edit), 5); + + ui_text_edit_destroy(edit); +} + +static void check_layer_mapping(void) +{ + pd_text_t *layer = pd_text_create(); + ui_text_edit_t *edit = ui_text_edit_create(); + wchar_t buf[16]; + + pd_text_set_multiline(layer, true); + pd_text_set_fixed_size(layer, 200, 100); + pd_text_set_max_size(layer, 200, 100); + ui_text_edit_set_layer(edit, layer); + ui_text_edit_set_text(edit, L"abc\ndef", 7); + ui_text_edit_sync_layer(edit); + ui_text_edit_sync_caret(edit); + /* set_text leaves the caret at the end of the text */ + ctest_equal_int("caret should start at the last line", + ui_text_edit_get_caret_row(edit), 1); + ctest_equal_int("caret should start at the line end", + ui_text_edit_get_caret_col(edit), 3); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ui_text_edit_sync_caret(edit); + ctest_equal_int("left should stay on the same line", + ui_text_edit_get_caret_row(edit), 1); + ctest_equal_int("left should reach the line start", + ui_text_edit_get_caret_col(edit), 0); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ui_text_edit_sync_caret(edit); + ctest_equal_int("crossing the newline should land on the previous line", + ui_text_edit_get_caret_row(edit), 0); + ctest_equal_int("crossing the newline should land at the line end", + ui_text_edit_get_caret_col(edit), 3); + + ui_text_edit_move_caret(edit, 1, 0); + ui_text_edit_text_input(edit, L"X", 1); + ui_text_edit_get_text(edit, 0, 16, buf); + ctest_equal_wcs("move_caret should place typing at the visual line", + buf, L"abc\nXdef"); + ui_text_edit_append_text(edit, L"!", 1); + ui_text_edit_get_text(edit, 0, 16, buf); + ctest_equal_wcs("append_text should always append at the end", buf, + L"abc\nXdef!"); + + ui_text_edit_destroy(edit); + pd_text_destroy(layer); +} + +static void check_layout_queries(void) +{ + pd_text_t *layer = pd_text_create(); + ui_text_edit_t *edit = ui_text_edit_create(); + pd_text_style_t style; + int line_h; + size_t start, end; + + pd_text_style_init(&style); + pd_text_style_set_default_font(&style); + pd_text_style_set_size(&style, 14); + pd_text_set_style(layer, &style); + pd_text_style_destroy(&style); + pd_text_set_multiline(layer, true); + pd_text_set_fixed_size(layer, 200, 100); + pd_text_set_max_size(layer, 200, 100); + ui_text_edit_set_layer(edit, layer); + ui_text_edit_set_text(edit, L"abc\ndef", 7); + + ui_text_edit_click(edit, 0, 0); + ctest_equal_int("click should land on the first row", + ui_text_edit_get_caret_row(edit), 0); + ctest_equal_int("click should land at the row start", + ui_text_edit_get_caret_col(edit), 0); + + line_h = pd_text_get_line_height(layer, 0); + ui_text_edit_click(edit, 0, (float)line_h + 1); + ctest_equal_int("click should land on the second row", + ui_text_edit_get_caret_row(edit), 1); + ctest_equal_int("click should land at the second row start", + ui_text_edit_get_caret_col(edit), 0); + + ui_text_edit_move_caret(edit, 0, 0); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_RIGHT | UI_TEXT_EDIT_KEY_SHIFT); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_RIGHT | UI_TEXT_EDIT_KEY_SHIFT); + ctest_equal_bool("shift-right should create a selection", + ui_text_edit_has_selection(edit), true); + ui_text_edit_selection(edit, &start, &end); + ctest_equal_int("selection should start at the caret origin", + (int)start, 0); + ctest_equal_int("selection should cover two characters", (int)end, 2); + + ui_text_edit_destroy(edit); + pd_text_destroy(layer); +} + +static void check_selection_operations(void) +{ + ui_text_edit_t *edit = ui_text_edit_create(); + wchar_t buf[16]; + size_t start, end; + + ui_text_edit_set_text(edit, L"hello", 5); + ui_text_edit_select_all(edit); + ctest_equal_bool("select-all should select the whole text", + ui_text_edit_has_selection(edit), true); + ui_text_edit_selection(edit, &start, &end); + ctest_equal_int("select-all start", (int)start, 0); + ctest_equal_int("select-all end", (int)end, 5); + ctest_equal_int("copy should return the selected length", + (int)ui_text_edit_copy(edit, buf, 16), 5); + ctest_equal_wcs("copy should return the selected text", buf, L"hello"); + + ctest_equal_int("cut should return the selected length", + (int)ui_text_edit_cut(edit, buf, 16), 5); + ctest_equal_int("cut should remove the selection", + (int)ui_text_edit_get_length(edit), 0); + ctest_equal_bool("cut should clear the selection", + ui_text_edit_has_selection(edit), false); + + ui_text_edit_destroy(edit); +} + +static void check_crlf_and_surrogates(void) +{ + pd_text_t *layer = pd_text_create(); + ui_text_edit_t *edit = ui_text_edit_create(); + pd_text_style_t style; + wchar_t buf[32]; + + pd_text_style_init(&style); + pd_text_style_set_default_font(&style); + pd_text_style_set_size(&style, 14); + pd_text_set_style(layer, &style); + pd_text_style_destroy(&style); + pd_text_set_multiline(layer, true); + pd_text_set_fixed_size(layer, 200, 100); + pd_text_set_max_size(layer, 200, 100); + ui_text_edit_set_layer(edit, layer); + + ui_text_edit_set_text(edit, L"a\r\nb", 4); + ctest_equal_int("set_text should normalize CRLF", + (int)ui_text_edit_get_length(edit), 3); + ui_text_edit_get_text(edit, 0, 32, buf); + ctest_equal_wcs("set_text should keep LF only", buf, L"a\nb"); + + ui_text_edit_set_text(edit, L"", 0); + ui_text_edit_text_input(edit, L"a\r\nb", 4); + ctest_equal_int("text input should normalize CRLF", + (int)ui_text_edit_get_length(edit), 3); + ui_text_edit_get_text(edit, 0, 32, buf); + ctest_equal_wcs("text input should keep LF only", buf, L"a\nb"); + +#if defined(_WIN32) + { + wchar_t emoji[4] = { 0xD83D, 0xDE00, L'a', 0 }; + + ui_text_edit_set_text(edit, emoji, 3); + ctest_equal_int("emoji text should keep three code units", + (int)ui_text_edit_get_length(edit), 3); + ui_text_edit_move_caret(edit, 0, 3); + ctest_equal_int("move_caret should reach the text end", + ui_text_edit_get_caret_col(edit), 3); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ctest_equal_int("left should stop before the trailing letter", + ui_text_edit_get_caret_col(edit), 2); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_LEFT); + ctest_equal_int("left should skip the surrogate pair", + ui_text_edit_get_caret_col(edit), 0); + } +#endif + + ui_text_edit_destroy(edit); + pd_text_destroy(layer); +} + +static void check_soft_wrap_queries(void) +{ + pd_text_t *layer = pd_text_create(); + ui_text_edit_t *edit = ui_text_edit_create(); + pd_text_style_t style; + int line_len; + + pd_text_style_init(&style); + pd_text_style_set_default_font(&style); + pd_text_style_set_size(&style, 14); + pd_text_set_style(layer, &style); + pd_text_style_destroy(&style); + pd_text_set_multiline(layer, true); + pd_text_set_autowrap(layer, true); + pd_text_set_word_break(layer, PD_WORD_BREAK_BREAK_ALL); + pd_text_set_fixed_size(layer, 40, 100); + pd_text_set_max_size(layer, 40, 100); + ui_text_edit_set_layer(edit, layer); + ui_text_edit_set_text(edit, L"aaaaaaaaaaaaaaaa", 16); + + ctest_equal_bool("narrow layer should wrap into several lines", + pd_text_get_lines_length(layer) >= 2, true); + line_len = pd_text_get_line_length(layer, 0); + ctest_equal_int("soft wrap should not consume characters", + pd_text_get_line_char_start(layer, 1), line_len); + + ui_text_edit_move_caret(edit, 0, line_len); + ctest_equal_int("soft boundary should map to the next visual row", + ui_text_edit_get_caret_row(edit), 1); + ctest_equal_int("soft boundary should map to the next row start", + ui_text_edit_get_caret_col(edit), 0); + + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_DOWN); + ctest_equal_int("down from a soft boundary should move one row", + ui_text_edit_get_caret_row(edit), 2); + + ui_text_edit_move_caret(edit, 1, line_len); + ctest_equal_int("second boundary should map to row 2", + ui_text_edit_get_caret_row(edit), 2); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_UP); + ctest_equal_int("up from a boundary should move one row up", + ui_text_edit_get_caret_row(edit), 1); + + ui_text_edit_move_caret(edit, 0, 0); + ui_text_edit_key(edit, UI_TEXT_EDIT_KEY_DOWN); + ctest_equal_int("down should cross a soft wrap", + ui_text_edit_get_caret_row(edit), 1); + + ui_text_edit_destroy(edit); + pd_text_destroy(layer); +} + +static void check_vertical_movement(void) +{ + pd_text_t *layer = pd_text_create(); + ui_text_edit_t *edit = ui_text_edit_create(); + pd_text_style_t style; + size_t start, end; + + pd_text_style_init(&style); + pd_text_style_set_default_font(&style); + pd_text_style_set_size(&style, 14); + pd_text_set_style(layer, &style); + pd_text_style_destroy(&style); + pd_text_set_multiline(layer, true); + pd_text_set_fixed_size(layer, 200, 100); + pd_text_set_max_size(layer, 200, 100); + ui_text_edit_set_layer(edit, layer); + ui_text_edit_set_text(edit, L"abcdef\nxy\nabcdef", 15); + + ui_text_edit_move_caret(edit, 0, 4); + ui_text_edit_move_vertical(edit, 1, false); + ctest_equal_int("vertical should land on the short line", + ui_text_edit_get_caret_row(edit), 1); + ctest_equal_int("vertical should clamp to the short line end", + ui_text_edit_get_caret_col(edit), 2); + + ui_text_edit_move_vertical(edit, 1, false); + ctest_equal_int("vertical should reach the third line", + ui_text_edit_get_caret_row(edit), 2); + ctest_equal_int("vertical should restore the preferred column", + ui_text_edit_get_caret_col(edit), 4); + + ui_text_edit_move_vertical(edit, -1, true); + ctest_equal_bool("shift+vertical should create a selection", + ui_text_edit_has_selection(edit), true); + ui_text_edit_selection(edit, &start, &end); + ctest_equal_bool("selection should span the vertical range", + start != end, true); + +#if defined(_WIN32) + { + wchar_t emoji[4] = { 0xD83D, 0xDE00, L'a', 0 }; + + ui_text_edit_set_text(edit, emoji, 3); + ui_text_edit_move_caret(edit, 0, 1); + ctest_equal_int("move_caret should not split a surrogate pair", + ui_text_edit_get_caret_col(edit), 0); + ui_text_edit_move_caret(edit, 0, 2); + ctest_equal_int("move_caret should keep the pair boundary", + ui_text_edit_get_caret_col(edit), 2); + } +#endif + + ui_text_edit_destroy(edit); + pd_text_destroy(layer); +} + +void test_textinput_edit(void) +{ + lcui_init(); + ctest_describe("text edit core", check_text_edit_core); + ctest_describe("text edit layer mapping", check_layer_mapping); + ctest_describe("text edit layout queries", check_layout_queries); + ctest_describe("text edit selection operations", + check_selection_operations); + ctest_describe("text edit crlf and surrogates", + check_crlf_and_surrogates); + ctest_describe("text edit soft wrap", check_soft_wrap_queries); + ctest_describe("text edit vertical movement", check_vertical_movement); + lcui_destroy(); +} diff --git a/tests/main.c b/tests/main.c index 3638d1c7..94297a5f 100644 --- a/tests/main.c +++ b/tests/main.c @@ -24,6 +24,7 @@ extern void test_css_unload(void); extern void test_text_resize(void); extern void test_text_decoration(void); extern void test_textinput(void); +extern void test_textinput_edit(void); extern void test_font_face(void); extern void test_widget_opacity(void); extern void test_widget_status(void); @@ -93,6 +94,7 @@ static const ctest_suite_t suites[] = { { "text resize", test_text_resize }, { "text decoration", test_text_decoration }, { "textinput", test_textinput }, + { "textinput edit", test_textinput_edit }, { "font face", test_font_face }, { "widget opacity", test_widget_opacity }, { "widget status", test_widget_status }, diff --git a/tests/previews/preview_textinput_edit.c b/tests/previews/preview_textinput_edit.c new file mode 100644 index 00000000..c05a555e --- /dev/null +++ b/tests/previews/preview_textinput_edit.c @@ -0,0 +1,60 @@ +/* + * tests/previews/preview_textinput_edit.c + * + * Copyright (c) 2026, Liu Chao All rights reserved. + * + * SPDX-License-Identifier: MIT + * + * This file is part of LCUI, distributed under the MIT License found in the + * LICENSE.TXT file in the root directory of this source tree. + */ + +#include +#include "preview_window.h" + +static ui_widget_t *add_input(const char *left, const char *top, + const char *width, const char *height) +{ + ui_widget_t *input = ui_create_widget("textinput"); + + ui_widget_set_style_string(input, "position", "absolute"); + ui_widget_set_style_string(input, "left", left); + ui_widget_set_style_string(input, "top", top); + ui_widget_set_style_string(input, "width", width); + ui_widget_set_style_string(input, "height", height); + ui_root_append(input); + return input; +} + +int main(int argc, char **argv) +{ + ui_widget_t *input; + + lcui_init(); + ui_widget_set_title(ui_root(), L"textinput edit preview"); + + input = add_input("20px", "20px", "330px", "32px"); + ui_textinput_set_placeholder(input, "Single line, try Shift+Arrows"); + ui_textinput_set_text(input, "Hello world"); + + input = add_input("20px", "70px", "330px", "32px"); + ui_textinput_set_password_char(input, L'*'); + ui_textinput_set_text(input, "secret"); + + input = add_input("20px", "120px", "330px", "32px"); + ui_textinput_set_read_only(input, true); + ui_textinput_set_text(input, "Read-only, still selectable"); + + input = add_input("20px", "170px", "330px", "110px"); + ui_textinput_enable_multiline(input, true); + ui_textinput_set_text_w( + input, + L"Line one\n" + L"Line two with a longer sentence that should wrap inside the " + L"box when it exceeds the available width.\n" + L"Line three"); + + ui_widget_resize(ui_root(), 380, 310); + preview_show_default_window(); + return lcui_main(); +} diff --git a/tests/previews/xmake.lua b/tests/previews/xmake.lua index a2b7afcb..08d67ad3 100644 --- a/tests/previews/xmake.lua +++ b/tests/previews/xmake.lua @@ -22,8 +22,16 @@ for _, topic in ipairs(previews) do add_deps("lcui") end -target("preview-flex-layout-percentage-wrap") +target("preview-textinput-edit") set_default(false) + set_kind("binary") + set_group("previews") + set_rundir("../fixtures") + add_includedirs("../helpers") + add_files("preview_textinput_edit.c") + add_deps("lcui") + +target("preview-flex-layout-percentage-wrap") set_default(false) set_kind("binary") set_group("previews") set_rundir("../fixtures")