zhouhaoGGs-key-pendant 桌面按键挂件源代码 for c++17 with SFML3.0.0

· · 个人记录

for c++17 with SFML-3.0.0\ (But release for c++20)\ main.cpp

#include<SFML/System.hpp>
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
#include<windows.h>
#include<iostream>
#include<cstdlib>
#include<string>
#include<cmath>

#define PIf 3.141592653589f

std::string GetSystemFontPath(const std::string& fontName){
    HKEY hKey;
    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts",
                    0,KEY_READ,&hKey)!=ERROR_SUCCESS)
        return "";
    char value[255];
    DWORD size=sizeof(value);
    if(RegQueryValueEx(hKey,(fontName+" (TrueType)").c_str(),nullptr,nullptr,(LPBYTE)value,&size)==ERROR_SUCCESS){
        RegCloseKey(hKey);
        return "C:\\Windows\\Fonts\\"+std::string(value);
    }
    RegCloseKey(hKey);
    return "";
}
class ShinyText:public sf::Text{
public:
    using sf::Text::Text;
    void shine(sf::Color color=sf::Color::Yellow){
        setOutlineColor(color);
        m_remaining=duration;
    }
    void update(sf::Time frameTime){
        setLineSpacing(static_cast<float>(getCharacterSize())/getFont().getLineSpacing(getCharacterSize()));
        sf::Color color=getOutlineColor();
        if(color==sf::Color::Black) return;
        const float ratio=m_remaining/duration;
        const float alpha=std::max(0.f,ratio*(2.f-ratio))*0.5f;
        color.a=static_cast<std::uint8_t>(255*alpha);
        setOutlineColor(color);
        if(m_remaining>sf::Time::Zero)
            m_remaining-=frameTime;
    }
private:
    static constexpr sf::Time duration=sf::milliseconds(150);
    sf::Time m_remaining;
};
ShinyText makeShinyText(const sf::Font& font,const sf::String& string,
                        float tn=2.5f,sf::Vector2f position={0.f,0.f}){
    ShinyText text(font,string);
    text.setOutlineThickness(3.f);
    text.setPosition(position);
    return text;
}
struct RoundedRectangleGenerator{
    sf::Vector2f m_size;
    float m_radius;size_t m_pointCount;
    sf::Vector2f const centers[4];
    RoundedRectangleGenerator(const sf::Vector2f& size,float radius,std::size_t pointCount=32)
        :m_size(size),m_radius(radius),m_pointCount(pointCount),
        centers{{size.x-radius,size.y-radius},{radius,size.y-radius},{radius,radius},{size.x-radius,radius}}{}
    sf::Vector2f getPoint(std::size_t index)const{
        float angle=index*2*PIf/m_pointCount-PIf*2;
        return centers[index*4/m_pointCount]+sf::Vector2f(m_radius*std::cos(angle),m_radius*std::sin(angle));
    }
};
void inline GenerateRoundedRectangle(sf::VertexArray& vertices,sf::Vector2f pos,
                        sf::Vector2f size,float radius,std::size_t pointCount=32){
    RoundedRectangleGenerator const generator(size,radius,pointCount);
    for(std::size_t i=0;i<pointCount;i++)
        vertices[i].position=pos+generator.getPoint(i);
}
class RoundedRectangleShape : public sf::Shape{
    sf::Vector2f m_size;
    float m_radius;size_t m_pointCount;
    sf::Vector2f centers[4];
    void setCenter(){
        centers[0]={m_size.x-m_radius,m_size.y-m_radius};
        centers[1]={m_radius,m_size.y-m_radius};
        centers[2]={m_radius,m_radius};
        centers[3]={m_size.x-m_radius,m_radius};
    }
public:
    explicit RoundedRectangleShape(const sf::Vector2f& size,float radius,std::size_t pointCount=32)
        :m_size(size),m_radius(radius),m_pointCount(pointCount){
        setCenter();
        update();
    }
    void setSize(const sf::Vector2f& size){
        m_size=size;
        setCenter();
        update();
    }
    void setRadius(float radius){
        m_radius=radius;
        setCenter();
        update();
    }
    const sf::Vector2f& getSize()const{return m_size;}
    float getRadius()const{return m_radius;}
    std::size_t getPointCount()const{return m_pointCount;}
    sf::Vector2f getPoint(std::size_t index) const override{
        float angle=index*2*(float)PIf/m_pointCount-(float)PIf*2;
        return centers[index*4/m_pointCount]+sf::Vector2f(m_radius*std::cos(angle),m_radius*std::sin(angle));
    }
    void generateOutline(sf::VertexArray& vertex_array,sf::Vector2f position,sf::Vector2f size,
            float r,float thickness,size_t quality){
        RoundedRectangleGenerator const generator_out(size,r,quality);
        sf::Vector2f const in_offset{thickness,thickness};
        sf::Vector2f const in_size=size-2.f*in_offset;
        RoundedRectangleGenerator const generator_in(in_size,r-thickness,quality);
        for(size_t i=0;i<quality;++i){
            vertex_array[2*i+0].position=position+in_offset+generator_in.getPoint(i);
            vertex_array[2*i+1].position=position+generator_out.getPoint(i);
        }
        vertex_array[2*quality+0].position=position+in_offset+generator_in.getPoint(0);
        vertex_array[2*quality+1].position=position+generator_out.getPoint(0);
    }
};
float hueToRgb(float p,float q,float t){
    if(t<0) t+=1;
    if(t>1) t-=1;
    if(t<1.f/6.f) return p+(q-p)*6*t;
    if(t<1.f/2.f) return q;
    if(t<2.f/3.f) return p+(q-p)*(2.0f/3.0f-t)*6;
    return p;
}
sf::Color HSLtoRGB(float h,float s,float l){
    h/=100.f;s/=100.f;l/=100.f;
    float r,g,b;
    if(s==0){
        r=g=b=l;
    }else{
        float q=l<0.5f?l*(1+s):l+s-l*s;
        float p=2*l-q;
        r=hueToRgb(p,q,h+1.0f/3.0f);
        g=hueToRgb(p,q,h);
        b=hueToRgb(p,q,h-1.0f/3.0f);
    }
    r*=255.f;g*=255.f;b*=255.f;
    return sf::Color(static_cast<uint8_t>(r),static_cast<uint8_t>(g),static_cast<uint8_t>(b));
}
std::ostream& operator<<(std::ostream& os,const sf::Color& color){
    os<<'('<<(int)color.r<<','<<(int)color.g<<','<<(int)color.b<<','<<(int)color.a<<')';
    return os;
}
struct keybubble{
    RoundedRectangleShape rrect;
    sf::Text text;float charsize;
    keybubble(const sf::Vector2f& pos,float scale,const sf::Text& _text,
                const RoundedRectangleShape& _rrect):rrect(_rrect),text(_text){
        text.setOrigin({text.getLocalBounds().position.x+\
            text.getLocalBounds().size.x/2.f,text.getCharacterSize()*0.55f});
        rrect.setOrigin(rrect.getSize()/2.f);
        rrect.setPosition(pos);
        rrect.setScale({scale,scale});
        text.setPosition(pos);
        charsize=text.getCharacterSize();
        text.setCharacterSize(charsize*scale);
    }
    void gopos(sf::Vector2f pos){
        rrect.setPosition(rrect.getPosition()+(pos-rrect.getPosition())/3.f);
        text.setPosition(rrect.getPosition());
    }
    void goscale(float scale){
        text.setCharacterSize(text.getCharacterSize()+(charsize*scale-text.getCharacterSize())/4.f);
        float s=rrect.getScale().x+(scale-rrect.getScale().x)/4.f;
        rrect.setScale({s,s});
        rrect.setOrigin(rrect.getSize()/2.f);
        text.setPosition(rrect.getPosition());
        text.setOrigin({text.getLocalBounds().position.x+\
            text.getLocalBounds().size.x/2.f,text.getCharacterSize()*0.55f});
    }
    void draw(sf::RenderWindow& window){
        window.draw(rrect);
        window.draw(text);
    }
};

sf::Font font;
HWND windowHWND;
bool dkey[101],rkey[101];
std::string keyname[101]={
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"0","1","2","3","4","5","6","7","8","9",
"Esc",
"Ctrl","Shift","Alt","Win", // Left
"Ctrl","Shift","Alt","Win", // Right
"Menu",
"[","]",";",",",".","'","/","\\","`","=","-",
"Space","Enter","Backspace","Tab","PageUp","PageDown",
"End","Home","Insert","Delete","+","-","*","/",
"Left","Right","Up","Down",
"Np 0","Np 1","Np 2","Np 3","Np 4","Np 5","Np 6","Np 7","Np 8","Np 9",
"F1","F2","F3","F4","F5","F6","F7","F8","F9",
"F10","F11","F12","F13","F14","F15","Pause"
};
std::string fnkey0_9[10]={  //0-9 FN key
    ")","!","@","#","$","%","^","&","*","("
};
std::string fnkey_spl[11]={ //Special FN key
    "{","}",":","<",">","\"","?","|","~","+","_"
};
std::string tofnkey(int i){
    if((int)sf::Keyboard::Key::Num0<=i&&i<=(int)sf::Keyboard::Key::Num9)
        return fnkey0_9[i-(int)sf::Keyboard::Key::Num0];
    if((int)sf::Keyboard::Key::LBracket<=i&&i<=(int)sf::Keyboard::Key::Equal)
        return fnkey_spl[i-(int)sf::Keyboard::Key::LBracket];
    return keyname[i];
}
std::string downkey;
bool downkey_p=false;
uint32_t accpress=0,keyspeed=0,max_keyspeed=0;
sf::Vector2i premouse=sf::Mouse::getPosition();
sf::Vector2f mousemove;
void handle(){
    static bool keylist[30];
    static int keylist_i=0;
    mousemove=sf::Vector2f(sf::Mouse::getPosition()-premouse);
    premouse=sf::Mouse::getPosition();
    for(int i=0;i<101;i++){
        bool down=sf::Keyboard::isKeyPressed(sf::Keyboard::Key(i));
        rkey[i]=(!dkey[i])&&down;
        dkey[i]=down;
    }
    downkey_p=false;
    for(int i=0;i<101;i++)
        if(dkey[i]){
            downkey_p=true;
            break;
        }
    keyspeed-=keylist[keylist_i];
    keylist[keylist_i]=false;
    for(int i=0;i<101;i++)
        if(rkey[i]){
            if(dkey[(int)sf::Keyboard::Key::LShift]||
                    dkey[(int)sf::Keyboard::Key::RShift])
                downkey=tofnkey(i);
            else downkey=keyname[i];
            accpress++;
            keylist[keylist_i]=true;
            keylist_i=(keylist_i+1)%30;
            keyspeed++;
            max_keyspeed=std::max(max_keyspeed,keyspeed);
            return;
        }
    keylist_i=(keylist_i+1)%30;
    downkey="";
}
void draw(sf::RenderWindow& window,float scale=1.f){

    static ShinyText keytext=makeShinyText(font,"zhouhaoGG",2.5f,{186,75});
    static float keylight=200,buttonw=10,keysize=1.f;
    static std::vector<keybubble> keybubblelist;
    if(!downkey.empty()){
        keytext.shine(sf::Color(rand()%256,rand()%256,rand()%256));
        keytext.setString(downkey);
        sf::Text text(font,downkey,5);
        text.setFillColor(sf::Color::White);
        RoundedRectangleShape rrect({5,5},2);
        rrect.setFillColor(sf::Color(0x30,0x32,0x32));
        keybubblelist.emplace_back(sf::Vector2f{310*scale,130*scale},4.f,text,rrect);
    }
    keylight+=((downkey_p?100.f:200.f)-keylight)/3;
    keysize+=((downkey_p?1.2f:1.f)-keysize)/2;
    keytext.setCharacterSize(37*scale*keysize);
    keytext.update(sf::milliseconds(33));
    if(keytext.getOutlineColor().a<1) keytext.setOutlineColor(sf::Color::Black);
    keytext.setOrigin({keytext.getLocalBounds().size.x/2,keytext.getCharacterSize()/2.f});
    keytext.setPosition({186*scale,75*scale});
    window.draw(keytext);

    buttonw+=(keytext.getLocalBounds().size.x*0.5f+10*scale-buttonw)/4;

    sf::ConvexShape button(4);
    button.setFillColor(sf::Color(keylight,keylight,keylight));
    button.setOutlineThickness(2*scale);
    button.setOutlineColor(sf::Color::Black);

    sf::Vector2f codot[4];  // 重复点
    codot[0]={186*scale+buttonw*keysize-8,(75+33*keysize+downkey_p*6)*scale};
    codot[1]={186*scale-buttonw*keysize-8,codot[0].y};
    codot[2]={codot[0].x,(75+46*keysize)*scale};
    codot[3]={codot[0].x+16,(75-32*keysize+downkey_p*6)*scale};

    button.setPoint(0,codot[0]);
    button.setPoint(1,codot[1]);
    button.setPoint(3,codot[3]);
    button.setPoint(2,{codot[1].x+16,codot[3].y});
    window.draw(button);

    button.setPoint(0,codot[1]);
    button.setPoint(1,codot[0]);
    button.setPoint(2,codot[2]);
    button.setPoint(3,{codot[1].x,codot[2].y});
    window.draw(button);

    button.setPoint(0,codot[2]);
    button.setPoint(1,codot[0]);
    button.setPoint(2,codot[3]);
    button.setPoint(3,{codot[3].x,codot[2].y+codot[3].y-codot[0].y});
    window.draw(button);

    sf::RectangleShape rect({16*scale,32*scale});
    rect.setFillColor(sf::Color(1,2,1));
    rect.setPosition({codot[2].x-8*scale,codot[2].y+2.1f*scale});
    window.draw(rect);

    rect.setOrigin({0,32*scale});
    rect.setPosition({codot[3].x-8*scale,codot[3].y-2.1f*scale});
    window.draw(rect);

    window.draw(keytext);

    sf::Text text(font,(L"累计按下:"+std::to_wstring(accpress)+L" key").c_str(),16*scale);
    text.setPosition({55*scale,5*scale});
    text.setFillColor(sf::Color::White);
    text.setOutlineThickness(scale);
    text.setOutlineColor(sf::Color::Black);
    window.draw(text);

    text.setString((L"最快:"+std::to_wstring(max_keyspeed)+L" key/s").c_str());
    text.setPosition({215*scale,5*scale});
    window.draw(text);

    static sf::Angle angle;
    if(mousemove.x!=0||mousemove.y!=0){
        sf::Angle ang=sf::radians(std::atan2(mousemove.normalized().y,mousemove.normalized().x));
        angle-=ang;
        angle=angle.wrapSigned();
        angle+=ang-angle/5;
        angle=angle.wrapSigned();
    }

    sf::CircleShape circle(22.5f*scale);
    circle.setOrigin({22.5f*scale,22.5f*scale});
    circle.setFillColor(sf::Color(0,0,0,0));
    circle.setOutlineThickness(1*scale);
    circle.setOutlineColor(sf::Color::White);
    circle.setPosition({27.5f*scale,132.5f*scale});
    window.draw(circle);

    rect.setSize({23*scale,3*scale});
    rect.setOrigin({0,1.5f*scale});
    rect.setPosition(circle.getPosition());
    rect.setFillColor(sf::Color::Red);
    rect.setRotation(angle);
    window.draw(rect);

    RoundedRectangleShape rrect({33*scale,96*scale},7.f*scale);
    rrect.setPosition({11*scale,7*scale});
    rrect.setFillColor(sf::Color(0x34,0x36,0x36));
    rrect.setOutlineThickness(2.f);
    rrect.setOutlineColor(sf::Color(0xd1,0x64,0x6e));
    window.draw(rrect);

    static float speedhigh=0;
    speedhigh+=(keyspeed-speedhigh)/4;
    rrect.setOutlineThickness(0.f);
    rrect.setRadius(4*scale);
    rrect.setFillColor(HSLtoRGB(30*std::min(1.f,speedhigh/7),100.f,50.f));
    rrect.setPosition({13*scale,101*scale});
    rrect.setSize({29*scale,92*scale*std::min(0.85f,speedhigh/10+8.f/92)});
    rrect.setScale({1.f,-1.f});
    window.draw(rrect);

    text.setString(std::to_wstring(keyspeed).c_str());
    text.setCharacterSize(12*scale);
    text.setOrigin({text.getLocalBounds().size.x/2,text.getCharacterSize()/2.f});
    text.setPosition({27.5f*scale,rrect.getPosition().y-rrect.getSize().y-7*scale});
    window.draw(text);

    if(IsIconic(windowHWND)){
        keybubblelist.clear();
        return;
    }
    float wsum=0;
    for(auto &kb:keybubblelist){
        kb.charsize=(kb.text.getString().getSize()<2?18:10)*scale;
        kb.rrect.setSize({kb.text.getLocalBounds().size.x+5*scale,20*scale});
        kb.rrect.setRadius(3*scale);
        wsum+=kb.rrect.getSize().x;
    }
    if(wsum>190*scale)
        keybubblelist.erase(keybubblelist.begin());
    sf::Vector2f pos={53*scale,145*scale};
    for(auto &kb:keybubblelist){
        pos.x+=kb.rrect.getGlobalBounds().size.x/2;
        kb.goscale(1.f);
        kb.gopos(pos);
        kb.draw(window);
        pos.x+=kb.rrect.getGlobalBounds().size.x/2+scale*2;
    }

}
int main(){
    windowHWND=FindWindow(nullptr,"zhouhaoGG's key pendant");
    if(windowHWND) return 0;
    srand(time(nullptr));
    sf::RenderWindow window(sf::VideoMode({330,160}),"zhouhaoGG's key pendant",sf::Style::Default,
            sf::State::Windowed,sf::ContextSettings{.antiAliasingLevel=8});
    window.setFramerateLimit(30);
    windowHWND=FindWindow(nullptr,"zhouhaoGG's key pendant");
    if(!font.openFromFile(GetSystemFontPath("Microsoft YaHei & Microsoft YaHei UI").c_str()))
        if(!font.openFromFile(GetSystemFontPath("Segoe UI").c_str())){
            MessageBox(windowHWND,"Can't find font!\n找不到字体!","Error 错误",MB_OK|MB_ICONERROR);
            return 1;
        }
    SetWindowLong(windowHWND,GWL_EXSTYLE,GetWindowLong(windowHWND,GWL_EXSTYLE)|WS_EX_LAYERED);
    SetLayeredWindowAttributes(windowHWND,0x010201,0,LWA_COLORKEY);
    uint32_t tick=0;
    while(window.isOpen()){
        while(const std::optional event=window.pollEvent())
            if(event->is<sf::Event::Closed>()){
                window.close();
            }else if(const auto* resized=event->getIf<sf::Event::Resized>()){
                window.setSize({resized->size.x,resized->size.x*160/330});
                window.setView(sf::View(sf::FloatRect({0,0},{(float)resized->size.x,(float)resized->size.y})));
            }
        if(tick%30==0)
            SetWindowPos(windowHWND,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
        window.clear(sf::Color(1,2,1));
        handle();
        draw(window,window.getSize().x/330.f);
        window.display();
        tick++;
    }
    return 0;
}