This commit is contained in:
张壹 2025-02-27 09:53:00 +08:00
parent cf1b1ab4e4
commit 8e46c178be
2 changed files with 27 additions and 2 deletions

View File

@ -63,17 +63,33 @@ void gctl::cli_viewer::display()
{ {
int maxLines = LINES - 1; // 终端的行数(减去提示行) int maxLines = LINES - 1; // 终端的行数(减去提示行)
int startLine = 0; // 当前显示的起始行 int startLine = 0; // 当前显示的起始行
int startX = 0; // 当前水平滚动的起始位置
int maxLineLength = 0; // 最长行的长度
// 计算最长行的长度
for (const auto& line : lines)
{
maxLineLength = std::max(maxLineLength, static_cast<int>(line.length()));
}
// 主循环 // 主循环
while (true) while (true)
{ {
// 清屏并显示文件内容
werase(stdscr); // 清屏但不闪烁 werase(stdscr); // 清屏但不闪烁
// 显示文件内容
for (int i = startLine; i < startLine + maxLines && i < lines.size(); ++i) for (int i = startLine; i < startLine + maxLines && i < lines.size(); ++i)
{ {
mvprintw(i - startLine, 0, "%s", lines[i].c_str()); const std::string& line = lines[i];
if (startX < line.length())
{
mvprintw(i - startLine, 0, "%s", line.substr(startX).c_str());
} }
}
// 在最后一行显示提示信息 // 在最后一行显示提示信息
mvprintw(LINES - 1, 0, "Use arrow keys or mouse wheel to scroll. Press Q or ESC to exit."); mvprintw(LINES - 1, 0, "Use arrow keys or mouse wheel to scroll. Press Q or ESC to exit.");
int ch = getch(); // 获取按键 int ch = getch(); // 获取按键
if (ch == KEY_UP) if (ch == KEY_UP)
{ {
@ -83,6 +99,14 @@ void gctl::cli_viewer::display()
{ {
startLine = std::min(startLine + 1, static_cast<int>(lines.size()) - maxLines); // 向下滚动 startLine = std::min(startLine + 1, static_cast<int>(lines.size()) - maxLines); // 向下滚动
} }
else if (ch == KEY_LEFT)
{
startX = std::max(0, startX - 1); // 向左滚动
}
else if (ch == KEY_RIGHT)
{
startX = std::min(startX + 1, maxLineLength - COLS); // 向右滚动
}
else if (ch == 'q' || ch == 'Q' || ch == 27) else if (ch == 'q' || ch == 'Q' || ch == 27)
{ // 按Q或ESC退出 { // 按Q或ESC退出
break; break;

View File

@ -35,6 +35,7 @@
namespace gctl namespace gctl
{ {
// 命令行查看器,用于在终端内查看文本文件内容,支持上下左右鼠标滚动或按键导航和退出查看
class cli_viewer class cli_viewer
{ {
public: public: