自学内容网 自学内容网

C++拾趣——绘制Console中DropdownMenu

这次我们要绘制下拉菜单,如下图。

在这里插入图片描述

居中显示窗口

按照界面库的设计,Dropdown Menu不能独立存在,而是要位于一个窗口中。我们就用线段画出一个窗口。

这个窗口要位于终端中间,即居中。这样我们就需要先获取终端窗口的尺寸。

    // 获取终端窗口大小
    struct winsize w;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &w);
    int terminalWidth = w.ws_col;
    int terminalHeight = w.ws_row;

然后通过当前窗口的大小,计算出起始绘制的坐标。下面options里保存的是可供选择的单选项,窗口的高度会随着选项个数而变化。

    // 窗口的宽度和高度
    int windowWidth = 40;
    int windowHeight = options.size() + 8;

    // 计算窗口的起始位置
    int startX = (terminalWidth - windowWidth) / 2;
    int startY = (terminalHeight - windowHeight) / 2;

清屏并重设光标

在开始绘制之前,我们需要使用《C++拾趣——绘制Console中圆形进度》中介绍的\033[2J\033[H来清屏并将光标移动到左上角。这是我们需要反复从最开始的位置重新绘制所有内容。

    cout << "\033[2J\033[H"; // 清屏并将光标移动到左上角

绘制窗口

绘制窗口顶部

在这里插入图片描述
因为要居中,所以在Y轴方向,我们先要输出一些\n来换行。

    // 打印顶部边框
    cout << string(startY, '\n');
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

绘制下拉行

在这里插入图片描述
下拉行是未展开时的下拉框。我们可以通过Tab键切换焦点,让其被选中。
在这里插入图片描述

    // 打印下拉框行
    cout << string(startX, ' ') << "| ";
    if (isDropdownSelected) {
        cout << greenBackground << whiteText << "[Select Option]" << reset;
    } else {
        cout << "[Select Option]";
    }
    cout << string(windowWidth - 4 - 15, ' ') << " |" << endl;

绘制下拉框选项

在这里插入图片描述
下拉框选项是展开状态。我们可以对下拉行进行Enter操作,来让下拉框展开或者缩回。

    // 打印下拉框选项
    if (isDropdownOpen) {
        for (int i = 0; i < options.size(); ++i) {
            cout << string(startX, ' ') << "| ";
            if (i == selectedIndex) {
                cout << redBackground << whiteText << options[i] << reset;
            } else {
                cout << options[i];
            }
            cout << string(windowWidth - 4 - options[i].size(), ' ') << " |" << endl;
        }
    } else {
        cout << string(startX, ' ') << "| " << string(windowWidth - 4, ' ') << " |" << endl;
    }

绘制按钮行

在这里插入图片描述
我们需要绘制两个按钮:OK和Cancel。

因为按钮也要居中显示,所以我们先需要算出要空出多少列出来——padding值。

当按钮被选中时,它会变成绿色背景,另外一个按钮就会变成默认背景。

    // 打印按钮行
    string okButton = "[ OK ]";
    string cancelButton = "[Cancel]";
    int totalButtonLength = okButton.length() + cancelButton.length() + 2; // 2 spaces between buttons
    int padding = (windowWidth - totalButtonLength) / 2;

    cout << string(startX, ' ') << "| " << string(padding, ' ');
    if (isButtonSelected && buttonIndex == 0) {
        cout << greenBackground << whiteText << blinkText << okButton << reset;
    } else {
        cout << okButton;
    }
    cout << "  ";
    if (isButtonSelected && buttonIndex == 1) {
        cout << greenBackground << whiteText << blinkText << cancelButton << reset;
    } else {
        cout << cancelButton;
    }
    cout << string(windowWidth - totalButtonLength - padding - 2 - 2, ' ') << " |" << endl;

绘制窗口底部

在这里插入图片描述

    // 打印底部边框
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

修改终端默认行为

由于不能鼠标操作,所以我们只能通过键盘操作界面,比如进行Button的选择和按下操作。

我们只接受Tab、向左、向右、向上、向下、ESC和Enter等7个键。

Tab键可以在Dropdown Menu和Push Button之间切换;

向左、向右只能在Push Button间切换;

向上、向下只能在Dropdown Menu间切换;

ESC是退出程序;

Enter表示PushButton被按下,或者Dropdown Menu被选中。

默认情况下,我们在键盘上输出的可见字符都会显示在终端上。但是在当前场景下,我们并不希望有这样的效果。这就需要我们修改终端的默认行为。

下面的代码在将终端修改为静默模式(关闭规范模式(ICANON)和回显(ECHO),使得输入字符不需要按下回车键就能立即读取,并且输入的字符不会显示在终端上)后,等待并读取键盘的输入,然后再还原原始的设置。这步还原操作非常重要,否则程序退出后,终端会一直处于静默模式,后续的输入都不会显示在终端上。这也预示着,如果本程序使用ctrl+c强行终止,会出现终端行为异常的情况。

int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);   // 修改终端设置:关闭回显和规范模式
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);    // 设置终端为静默模式
    ch = getchar();
    ……
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

对方向键的特殊处理

在终端环境中,特殊键(如箭头键、功能键等)通常不会直接生成单个字符的输入,而是生成一系列字符的序列。对于箭头键,通常的序列是以 ESC 键(ASCII 码 27)开头,后面跟着一个或多个字符来表示具体的键。

  • 向上箭头:ESC + [ + A
  • 向下箭头:ESC + [ + B
  • 向右箭头:ESC + [ + C
  • 向左箭头:ESC + [ + D
    ch = getchar();
    if (ch == 27) { // 如果是ESC键
        ch = getchar();
        if (ch == 91) { // 如果是'['键
            ch = getchar();
            if (ch == 65) ch = 1000; // 上箭头键
            if (ch == 66) ch = 1001; // 下箭头键
            if (ch == 67) ch = 1002; // 右箭头键
            if (ch == 68) ch = 1003; // 左箭头键
        }
    }

过程控制

下面代码会在getch()中等待终端的输入。

int main() {
    bool isDropdownSelected = false;
    bool isDropdownOpen = false;
    vector<string> options = {"Option 1", "Option 2", "Option 3", "Option 4"};
    int selectedIndex = 0;
    bool isButtonSelected = false;
    int buttonIndex = 0;

    while (true) {
        display(isDropdownSelected, isDropdownOpen, options, selectedIndex, isButtonSelected, buttonIndex);

        int ch = getch();
        if (ch == 9) { // Tab 键
            if (!isDropdownSelected && !isButtonSelected) {
                isDropdownSelected = true;
            } else if (isDropdownSelected) {
                isDropdownSelected = false;
                isButtonSelected = true;
                buttonIndex = 0; // 默认选择 OK 按钮
            } else if (isButtonSelected) {
                if (buttonIndex == 1) {
                    isButtonSelected = false;
                    isDropdownSelected = true;
                } else {
                    buttonIndex = (buttonIndex + 1) % 2;
                }
            }
        } else if (ch == 10 || ch == 13) { // Enter 键
            if (isDropdownSelected) {
                isDropdownOpen = !isDropdownOpen;
            } else if (isButtonSelected) {
                cout << "\033[2J\033[H"; // 清空画面
                if (buttonIndex == 0) { // OK 按钮
                    cout << "You selected: " << options[selectedIndex] << endl;
                } else if (buttonIndex == 1) { // Cancel 按钮
                    cout << "Operation cancelled." << endl;
                }
                break;
            }
        } else if (ch == 1000) { // 上箭头键
            if (isDropdownOpen && selectedIndex > 0) {
                selectedIndex--;
            }
        } else if (ch == 1001) { // 下箭头键
            if (isDropdownOpen && selectedIndex < options.size() - 1) {
                selectedIndex++;
            }
        } else if (ch == 1002) { // 右箭头键
            if (isButtonSelected) {
                buttonIndex = (buttonIndex + 1) % 2;
            }
        } else if (ch == 1003) { // 左箭头键
            if (isButtonSelected) {
                buttonIndex = (buttonIndex + 1) % 2;
            }
        } else if (ch == 27) { // Esc 键退出
            cout << "\033[2J\033[H"; // 清空画面
            break;
        }
    }

    return 0;
}

Tab键的处理

该界面分为三个个区域:Dropdown Menu行区域、Dropdown Menu选项区域和Push Button区域。isButtonSelected变量表示当前焦点是否在Push Button区域;isDropdownSelected表示当前焦点是否在Dropdown Menu行区域;isDropdownOpen表示当前焦点是否在Dropdown Menu选项区域。

如果是Push Button区域(isButtonSelected == true),且当前聚焦的是Cancel(buttonIndex == 1),则在收到Tab键时,会跳到Dropdown Menu行区域(isDropdownSelected= true);如果聚焦的不是Cancel,则通过buttonIndex = (buttonIndex + 1) % 2计算出要聚焦到的Push Button的下标。

如果是Dropdown Menu行区域或者Dropdown Menu选项区域(isDropdownSelected== true),则在收到Tab键时,跳到Push Button区域(isButtonSelected == true)的OK按钮处。这就预示着光标在下拉框选项中时,Tab键并不会切换下拉选项。

在这里插入图片描述

Enter键的处理

如果当前聚焦的是Push Button区域(isButtonSelected == true),则判断聚焦的是OK还是Cancel。如果是OK,则输出用户的选项并退出;如果是Cancel则直接退出。

如果当前聚焦的是Dropdown Menu行区域(isButtonSelected == false),则会根据当前是否为展开状态决定后续是要展开还是收缩选项

在这里插入图片描述

上下左右方向键的处理

我们让上下键只能在Dropdown Menu区域切换焦点,左右键只能在Push Button区域切换焦点。这是因为Dropdown Menu区域中的项目是上下布局的,而Push Button区域是左右布局的。

在这里插入图片描述

完整代码

#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <vector>

using namespace std;

void display(bool isDropdownSelected, bool isDropdownOpen, const vector<string>& options, int selectedIndex, bool isButtonSelected, int buttonIndex) {
    const string greenBackground = "\033[42m"; // 绿色背景
    const string redBackground = "\033[41m";   // 红色背景
    const string whiteText = "\033[37m";       // 白色字体
    const string blinkText = "\033[5m";        // 闪烁文本
    const string reset = "\033[0m";            // 重置颜色

    // 获取终端窗口大小
    struct winsize w;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &w);
    int terminalWidth = w.ws_col;
    int terminalHeight = w.ws_row;

    // 窗口的宽度和高度
    int windowWidth = 40;
    int windowHeight = 10;

    // 计算窗口的起始位置
    int startX = (terminalWidth - windowWidth) / 2;
    int startY = (terminalHeight - windowHeight) / 2;

    cout << "\033[2J\033[H"; // 清屏并将光标移动到左上角

    // 打印顶部边框
    cout << string(startY, '\n');
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

    // 打印下拉框行
    cout << string(startX, ' ') << "| ";
    if (isDropdownSelected) {
        cout << greenBackground << whiteText << "[Select Option]" << reset;
    } else {
        cout << "[Select Option]";
    }
    cout << string(windowWidth - 4 - 15, ' ') << " |" << endl;

    // 打印下拉框选项
    if (isDropdownOpen) {
        for (int i = 0; i < options.size(); ++i) {
            cout << string(startX, ' ') << "| ";
            if (i == selectedIndex) {
                cout << redBackground << whiteText << options[i] << reset;
            } else {
                cout << options[i];
            }
            cout << string(windowWidth - 4 - options[i].size(), ' ') << " |" << endl;
        }
    } else {
        cout << string(startX, ' ') << "| " << string(windowWidth - 4, ' ') << " |" << endl;
    }

    // 打印按钮行
    string okButton = "[ OK ]";
    string cancelButton = "[Cancel]";
    int totalButtonLength = okButton.length() + cancelButton.length() + 2; // 2 spaces between buttons
    int padding = (windowWidth - totalButtonLength) / 2;

    cout << string(startX, ' ') << "| " << string(padding, ' ');
    if (isButtonSelected && buttonIndex == 0) {
        cout << greenBackground << whiteText << blinkText << okButton << reset;
    } else {
        cout << okButton;
    }
    cout << "  ";
    if (isButtonSelected && buttonIndex == 1) {
        cout << greenBackground << whiteText << blinkText << cancelButton << reset;
    } else {
        cout << cancelButton;
    }
    cout << string(windowWidth - totalButtonLength - padding - 2 - 2, ' ') << " |" << endl;

    // 打印底部边框
    cout << string(startX, ' ') << "+" << string(windowWidth - 2, '-') << "+" << endl;

    cout << reset; // 重置颜色
}

int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    if (ch == 27) { // 如果是ESC键
        ch = getchar();
        if (ch == 91) { // 如果是'['键
            ch = getchar();
            if (ch == 65) ch = 1000; // 上箭头键
            if (ch == 66) ch = 1001; // 下箭头键
            if (ch == 67) ch = 1002; // 右箭头键
            if (ch == 68) ch = 1003; // 左箭头键
        }
    }
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

int main() {
    bool isDropdownSelected = false;
    bool isDropdownOpen = false;
    vector<string> options = {"Option 1", "Option 2", "Option 3", "Option 4"};
    int selectedIndex = 0;
    bool isButtonSelected = false;
    int buttonIndex = 0;

    while (true) {
        display(isDropdownSelected, isDropdownOpen, options, selectedIndex, isButtonSelected, buttonIndex);

        int ch = getch();
        if (ch == 9) { // Tab 键
            if (!isDropdownSelected && !isButtonSelected) {
                isDropdownSelected = true;
            } else if (isDropdownSelected) {
                isDropdownSelected = false;
                isButtonSelected = true;
                buttonIndex = 0; // 默认选择 OK 按钮
            } else if (isButtonSelected) {
                if (buttonIndex == 1) {
                    isButtonSelected = false;
                    isDropdownSelected = true;
                } else {
                    buttonIndex = (buttonIndex + 1) % 2;
                }
            }
        } else if (ch == 10 || ch == 13) { // Enter 键
            if (isDropdownSelected) {
                isDropdownOpen = !isDropdownOpen;
            } else if (isButtonSelected) {
                cout << "\033[2J\033[H"; // 清空画面
                if (buttonIndex == 0) { // OK 按钮
                    cout << "You selected: " << options[selectedIndex] << endl;
                } else if (buttonIndex == 1) { // Cancel 按钮
                    cout << "Operation cancelled." << endl;
                }
                break;
            }
        } else if (ch == 1000) { // 上箭头键
            if (isDropdownOpen && selectedIndex > 0) {
                selectedIndex--;
            }
        } else if (ch == 1001) { // 下箭头键
            if (isDropdownOpen && selectedIndex < options.size() - 1) {
                selectedIndex++;
            }
        } else if (ch == 1002) { // 右箭头键
            if (isButtonSelected) {
                buttonIndex = (buttonIndex + 1) % 2;
            }
        } else if (ch == 1003) { // 左箭头键
            if (isButtonSelected) {
                buttonIndex = (buttonIndex + 1) % 2;
            }
        } else if (ch == 27) { // Esc 键退出
            cout << "\033[2J\033[H"; // 清空画面
            break;
        }
    }

    return 0;
}

代码地址

https://github.com/f304646673/cpulsplus/tree/master/console_ui/dropdownmenu


原文地址:https://blog.csdn.net/breaksoftware/article/details/142622843

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!