aboutsummaryrefslogtreecommitdiff
path: root/src/Chatbar.cpp
blob: 6a459cc2f91d9689ac978e64febb16573bb64e58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#include "../include/Chatbar.hpp"
#include "../include/ResourceCache.hpp"
#include "../include/Settings.hpp"
#include "../include/Channel.hpp"
#include "../include/ChannelSidePanel.hpp"
#include "../include/UsersSidePanel.hpp"
#include "../include/Command.hpp"
#include "../include/ColorScheme.hpp"
#include "../include/Cache.hpp"
#include <cmath>
#include <cstring>
#include <process.hpp>

using namespace std;

namespace dchat
{
    const float FONT_SIZE = 18.0f;
    const float BOX_PADDING_X = 15.0f;
    const float BOX_PADDING_Y = 5.0f;
    const int BLINK_TIME_VISIBLE_MS = 500;
    const int BLINK_TIME_INVISIBLE_MS = 500;
    const float PADDING_SIDE = 20.0f;
    const float PADDING_TOP = 30.0f;
    const float PADDING_BOTTOM = 30.0f;
    const float LINE_PADDING_SIDE = 20.0f;
    const float LINE_HEIGHT = 1.0f;
    
    unordered_map<string, string> binds;
    
    Chatbar::Chatbar() : 
        text("", ResourceCache::getFont("fonts/Nunito-Regular.ttf"), FONT_SIZE * Settings::getScaling(), 0),
        focused(true)
    {
        text.setEditable(true);
        text.setFillColor(sf::Color(240, 240, 240));
        background.setFillColor(ColorScheme::getBackgroundColor());
        inputBackground.setFillColor(ColorScheme::getBackgroundColor() + sf::Color(10, 10, 10));
    }
    
    bool Chatbar::isFocused() const
    {
        return focused;
    }
    
    class ArgParseException : public std::runtime_error
    {
    public:
        ArgParseException(const string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    string stringRemoveQuotes(const StringView &str)
    {
        string result;
        result.reserve(str.size);
        for(usize i = 0; i < str.size; ++i)
        {
            char c = str[i];
            if(c != '\'' && c != '"')
                result += c;
        }
        return result;
    }
    
    vector<string> splitCommandArgs(const StringView &str)
    {
        vector<string> result;
        ssize offset = 0;
        char quoteChar = '\0';
        
        for(ssize i = 0; i < str.size; ++i)
        {
            char c = str[i];
            if(c == '\'' || c == '"')
            {
                if(c == quoteChar)
                    quoteChar = '\0';
                else
                    quoteChar = c;
            }
            else if(quoteChar == '\0' && c == ' ')
            {
                ssize substrLength = i - offset;
                if(substrLength > 0)
                {
                    StringView substrView(str.data + offset, substrLength);
                    string substr = stringRemoveQuotes(substrView);
                    if(!substr.empty())
                        result.emplace_back(move(substr));
                }
                offset = i + 1;
            }
        }
        
        if(quoteChar != '\0')
        {
            string errMsg = "Reached end of command before end of quote (";
            errMsg += quoteChar;
            errMsg += ")";
            throw ArgParseException(errMsg);
        }
        
        ssize strLeft = str.size - offset;
        if(strLeft > 0)
        {
            StringView substrView(str.data + offset, strLeft);
            string substr = stringRemoveQuotes(substrView);
            if(!substr.empty())
                result.emplace_back(move(substr));
        }
        return result;
    }
    
    void Chatbar::processChatCommand(const StringView &cmd)
    {
        vector<string> args;
        try
        {
            args = splitCommandArgs(cmd);
        }
        catch(ArgParseException &e)
        {
            fprintf(stderr, "Failed to parse command arguments, reason: %s\n", e.what());
            return;
        }
        
        if(!args.empty())
        {
            string command = args.front();
            args.erase(args.begin());
            if(!Command::call(command, args))
                fprintf(stderr, "No such command: %s\n", command.c_str());
        }
    }
    
    static void findReplaceAll(string &str, const string &substrToReplace, const string &stringToReplaceWith)
    {
        size_t findOffset = 0;
        while(findOffset < (size_t)str.size())
        {
            findOffset = str.find(substrToReplace, findOffset);
            if(findOffset != string::npos)
            {
                string substr = str.replace(findOffset, substrToReplace.size(), stringToReplaceWith);
                findOffset += stringToReplaceWith.size();
            }
        }
    }
    
    static void replaceBinds(string &msg)
    {
        for(auto &it : binds)
        {
            findReplaceAll(msg, it.first, it.second);
        }
    }
    
    void Chatbar::processEvent(const sf::Event &event, Cache &cache, Channel *channel)
    {
        if(!focused) return;
        
        text.processEvent(event, cache);
        if(event.type == sf::Event::TextEntered)
        {
            if(event.text.unicode == 13) // enter
            {
                if(!text.getString().isEmpty())
                {
                    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::RShift))
                    {
                        //addChar('\n');
                    }
                    else
                    {
                        auto chatbarMsgUtf8 = text.getString().toUtf8();
                        string msg;
                        msg.resize(chatbarMsgUtf8.size());
                        memcpy(&msg[0], chatbarMsgUtf8.data(), chatbarMsgUtf8.size());
                        if(msg[0] == '/')
                            processChatCommand(StringView(msg.data() + 1, msg.size() - 1));
                        else
                        {
                            replaceBinds(msg);
                            channel->addMessage(msg);
                        }
                        text.setString("");
                    }
                }
            }
        }
    }
    
    void Chatbar::draw(sf::RenderWindow &window, Cache &cache)
    {
        auto windowSize = window.getSize();
        
        text.setCharacterSize(FONT_SIZE * Settings::getScaling());
        const float fontHeight = text.getFont()->getLineSpacing(text.getCharacterSize());
        
        sf::RectangleShape lineShape(sf::Vector2f(floor(windowSize.x - ChannelSidePanel::getWidth() - LINE_PADDING_SIDE * Settings::getScaling() * 2.0f), LINE_HEIGHT));
        lineShape.setFillColor(ColorScheme::getBackgroundColor() + sf::Color(10, 10, 10));
        lineShape.setPosition(ChannelSidePanel::getWidth() + LINE_PADDING_SIDE * Settings::getScaling(), floor(windowSize.y - getHeight()));
        window.draw(lineShape);
        
        sf::Vector2f inputBackgroundSize(floor(windowSize.x - ChannelSidePanel::getWidth() - PADDING_SIDE * Settings::getScaling() * 2.0f), floor(fontHeight * 1.7f + BOX_PADDING_Y * Settings::getScaling() * 2.0f));
        sf::Vector2f backgroundSize(floor(windowSize.x - ChannelSidePanel::getWidth()), floor(getHeight() - LINE_HEIGHT));
        background.setSize(backgroundSize);
        background.setPosition(ChannelSidePanel::getWidth(), floor(windowSize.y - backgroundSize.y));
        window.draw(background);
        
        sf::Vector2f inputBackgroundPos(floor(ChannelSidePanel::getWidth() + PADDING_SIDE * Settings::getScaling()), floor(windowSize.y - inputBackgroundSize.y - PADDING_BOTTOM  * Settings::getScaling()));
        inputBackground.setSize(inputBackgroundSize);
        inputBackground.setPosition(inputBackgroundPos);
        text.setPosition(floor(inputBackgroundPos.x + BOX_PADDING_X), floor(inputBackgroundPos.y + inputBackgroundSize.y * 0.5f - fontHeight * 0.5f));
        text.setMaxWidth(inputBackgroundSize.x - BOX_PADDING_X * 2.0f);
        
        window.draw(inputBackground);
        text.draw(window, cache);
    }

    sf::Vector2f Chatbar::getInputPosition(sf::RenderWindow &window)
    {
        auto windowSize = window.getSize();
        return { floor(ChannelSidePanel::getWidth() + PADDING_SIDE * Settings::getScaling()), floor(windowSize.y - getInputSize(window).y - PADDING_BOTTOM  * Settings::getScaling()) };
    }

    sf::Vector2f Chatbar::getInputSize(sf::RenderWindow &window)
    {
        auto windowSize = window.getSize();
        const float fontSize = FONT_SIZE * Settings::getScaling();
        const float fontHeight = ResourceCache::getFont("fonts/Nunito-Regular.ttf")->getLineSpacing(fontSize);
        return { floor(windowSize.x - ChannelSidePanel::getWidth() - PADDING_SIDE * Settings::getScaling() * 2.0f), floor(fontHeight * 1.7f + BOX_PADDING_Y * Settings::getScaling() * 2.0f) };
    }
    
    float Chatbar::getHeight()
    {
        const float fontSize = FONT_SIZE * Settings::getScaling();
        const float fontHeight = ResourceCache::getFont("fonts/Nunito-Regular.ttf")->getLineSpacing(fontSize);
        return PADDING_TOP * Settings::getScaling() + floor(fontHeight * 1.7f + BOX_PADDING_Y * Settings::getScaling() * 2.0f) + PADDING_BOTTOM * Settings::getScaling();
    }
    
    bool Chatbar::addBind(const std::string &key, const std::string &value, bool updateFile)
    {
        if(binds.find(key) != binds.end())
            return false;
        
        binds[key] = value;
        if(updateFile)
            Cache::replaceBindsInFile(binds);
        return true;
    }
    
    bool Chatbar::removeBind(const std::string &key, bool updateFile)
    {
        auto it = binds.find(key);
        if(it == binds.end())
            return false;
        
        binds.erase(it);
        if(updateFile)
            Cache::replaceBindsInFile(binds);
        return true;
    }
    
    const unordered_map<string, string>& Chatbar::getBinds()
    {
        return binds;
    }
}