ReplView
头文件: examples/UI/REPL/ReplView.h
命名空间: 全局
ReplView 是一个基于 M5GFX LGFX_Sprite(画布)构建的终端风格 REPL(Read-Eval-Print Loop)UI 框架。它提供了键盘驱动的界面,包含提示符、输入缓冲区、闪烁光标和命令回调。适用于在 M5Cardputer 上构建交互式 Shell、调试控制台或基于文本的 UI。
回调
onRenderTips
在 init() 期间清屏后调用。用于在屏幕顶部渲染标题文字、使用提示或 ASCII 艺术。
repl.onRenderTips = []() {
M5Cardputer.Display.println("=== 我的应用 v1.0 ===");
M5Cardputer.Display.println("输入 'help' 查看命令");
};
onCommand
当用户按下 Enter 且输入缓冲区非空时调用。接收原始命令字符串。
repl.onCommand = [](const std::string& cmd) {
if (cmd == "help") {
M5Cardputer.Display.println("可用命令: help, clear, exit");
} else if (cmd == "clear") {
// ...
}
};
字段
autoClearPrompt
为 true(默认)时,onCommand 调用后自动清空输入缓冲区。设为 false 可在命令执行后保留输入内容。
方法
init(canvas)
在指定画布上初始化 REPL。调用 render_interface() 执行以下操作:
1. 清屏为黑色
2. 设置默认字体 (efontCN_16) 和文字滚动模式
3. 调用 onRenderTips(若已设置)
4. 渲染初始提示符
| 参数 | 类型 | 说明 |
|---|---|---|
canvas |
LGFX_Sprite* |
指向 LGFX_Sprite 的指针(通常为 &M5Cardputer.Display) |
update()
每次 loop() 迭代中调用。处理:
- 通过 M5Cardputer.Keyboard 获取键盘输入(调用 isChange() + keysState())
- 每 500ms 闪烁光标
- Enter 键 → 调用 onCommand 回调
- 退格键 → 从输入缓冲区删除最后一个字符
- 可打印字符 → 追加到输入缓冲区
clearScreen()
清空整个屏幕(填充黑色,光标重置到左上角,推送精灵)。
showMessage(message, color)
向画布打印一行文字并推送到显示屏。用于在命令执行后输出结果。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
message |
const std::string& |
— | 要显示的文本 |
color |
uint16_t |
TFT_WHITE |
文字颜色 |
showPrompt(prompt_text)
更改输入光标前显示的提示符文本,并重新渲染当前行。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
prompt_text |
const std::string& |
">>> " |
新的提示符字符串 |
setPromptText(prompt)
更改提示符文本但不重新渲染。若需要立即视觉更新请使用 showPrompt();若希望在下一个渲染周期中生效请使用 setPromptText()。
setInputBuffer(text)
设置当前输入缓冲区内容并重新渲染提示行。用于程序化输入注入。
getInputBuffer()
返回当前输入缓冲区内容。
clearInputBuffer()
清空输入缓冲区并重新渲染提示符。
完整示例
#include <M5Cardputer.h>
#include "examples/UI/REPL/ReplView.h"
ReplView repl;
void setup() {
auto cfg = M5.config();
M5Cardputer.begin(cfg, true);
repl.onRenderTips = []() {
M5Cardputer.Display.println("=== REPL 演示 ===");
M5Cardputer.Display.println("命令: help, hello, clear");
};
repl.onCommand = [](const std::string& cmd) {
if (cmd == "help") {
repl.showMessage("help - 显示此消息", TFT_CYAN);
repl.showMessage("hello - 打招呼", TFT_CYAN);
repl.showMessage("clear - 清屏", TFT_CYAN);
} else if (cmd == "hello") {
repl.showMessage("你好,M5Cardputer!", TFT_GREEN);
} else if (cmd == "clear") {
repl.clearScreen();
repl.onRenderTips();
repl.showPrompt();
} else {
repl.showMessage("未知命令: " + cmd, TFT_RED);
}
};
repl.init(&M5Cardputer.Display);
}
void loop() {
M5Cardputer.update();
repl.update();
}
Note
ReplView 以示例类的形式发布,不属于 src/ 库。使用时需将 ReplView.h 和 ReplView.cpp 复制到你的项目中,或将 examples 目录添加到 include 路径中。