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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
|
#include "../include/MessageBoard.hpp"
#include "../include/Settings.hpp"
#include "../include/ResourceCache.hpp"
#include "../include/Gif.hpp"
#include "../include/ChannelSidePanel.hpp"
#include "../include/UsersSidePanel.hpp"
#include "../include/ChannelTopPanel.hpp"
#include "../include/Chatbar.hpp"
#include "../include/ColorScheme.hpp"
#include "../include/Theme.hpp"
#include "../include/GlobalContextMenu.hpp"
#include "../include/Channel.hpp"
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Window/Mouse.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Text.hpp>
#include <cmath>
using namespace std;
namespace dchat
{
struct LineColor
{
sf::Color sideColor, centerColor;
};
const float USERNAME_PADDING_BOTTOM = 5.0f;
const float PADDING_SIDE = 40.0f;
const float PADDING_TOP = 0.0f;
const float LINE_SIDE_PADDING = 20.0f;
const float LINE_HEIGHT = 1.0f;
const float USERNAME_TIMESTAMP_SIDE_PADDING = 15.0f;
const float AVATAR_DIAMETER = 70.0f;
const float AVATAR_PADDING_SIDE = 30.0f;
const double SCROLL_MAX_SPEED = 20.0;
// Merge messages from same user that are sent within one minute
const int MERGE_TEXT_TIMESTAMP_DIFF_SEC = 60;
MessageBoard::MessageBoard(Channel *_channel) :
channel(_channel),
scroll(0.0),
scrollSpeed(0.0),
totalHeight(0.0),
scrollToBottom(false)
{
}
MessageBoard::~MessageBoard()
{
for(Message *message : messages)
{
delete message;
}
}
// TODO: Optimize this with binary search
usize MessageBoard::findPositionToInsertMessageByTimestamp(Message *message)
{
for(usize i = 0; i < messages.size(); ++i)
{
if(message->timestampSeconds < messages[i]->timestampSeconds)
return i;
}
return messages.size();
}
void MessageBoard::updateStaticContentTexture(const sf::Vector2u &newSize)
{
//if(!staticContentTexture.create(newSize.x, newSize.y))
// throw std::runtime_error("Failed to create render target for message board!");
dirty = true;
}
void MessageBoard::addMessage(Message *message, const odhtdb::Hash &id)
{
lock_guard<mutex> lock(messageProcessMutex);
messages.insert(messages.begin() + findPositionToInsertMessageByTimestamp(message), message);
if(!id.isEmpty())
messageIdMap[id] = message;
dirty = true;
scrollToBottom = true;
}
void MessageBoard::deleteMessage(const odhtdb::Hash &id, const odhtdb::Signature::PublicKey &requestedByUser)
{
lock_guard<mutex> lock(messageProcessMutex);
auto it = messageIdMap.find(id);
if(it == messageIdMap.end()) return;
if(it->second->user->isOnlineUser())
{
auto onlineUser = static_cast<const OnlineUser*>(it->second->user);
if(onlineUser->getPublicKey() != requestedByUser)
{
fprintf(stderr, "Warning: user %s requested to delete a message owned by user %s, ignoring request\n", requestedByUser.toString().c_str(), onlineUser->getPublicKey().toString().c_str());
return;
}
}
for(usize i = 0; i < messages.size(); ++i)
{
Message *message = messages[i];
if(message == it->second)
{
delete message;
messages.erase(messages.begin() + i);
messageIdMap.erase(it);
break;
}
}
}
void MessageBoard::drawDefault(sf::RenderWindow &window, Cache &cache)
{
const float LINE_SPACING = 5.0f * Settings::getScaling();
const float MESSAGE_PADDING_TOP = 25.0f;
const float MESSAGE_PADDING_BOTTOM = 30.0f;
const sf::Font *usernameFont = ResourceCache::getFont("fonts/Roboto-Regular.ttf");
const int usernameTextCharacterSize = 20 * Settings::getScaling();
const float usernameTextHeight = usernameFont->getLineSpacing(usernameTextCharacterSize);
const sf::Font *timestampFont = ResourceCache::getFont("fonts/Roboto-Regular.ttf");
const int timestampTextCharacterSize = (float)usernameTextCharacterSize * 0.75f;
const float timestampTextHeight = timestampFont->getLineSpacing(timestampTextCharacterSize);
sf::RectangleShape lineRect(sf::Vector2f(backgroundSizeWithoutPadding.x - LINE_SIDE_PADDING * Settings::getScaling() * 2.0f, LINE_HEIGHT));
lineRect.setFillColor(ColorScheme::getBackgroundColor() + sf::Color(10, 10, 10));
sf::Shader *circleShader = ResourceCache::getShader("shaders/circleMask.glsl", sf::Shader::Fragment);
sf::Vector2<double> position(ChannelSidePanel::getWidth() + PADDING_SIDE * Settings::getScaling(), ChannelTopPanel::getHeight() + PADDING_TOP);
double startHeight = position.y;
position.y += scroll;
usize numMessages = messages.size();
for(usize i = 0; i < numMessages; ++i)
{
Message *message = messages[i];
bool mergeTextWithPrev = false;
if(i > 0)
{
Message *prevMessage = messages[i - 1];
mergeTextWithPrev = prevMessage->user == message->user && (message->timestampSeconds == 0 || message->timestampSeconds - prevMessage->timestampSeconds <= MERGE_TEXT_TIMESTAMP_DIFF_SEC);
}
bool mergeTextWithNext = false;
if(i < numMessages - 1)
{
Message *nextMessage = messages[i + 1];
mergeTextWithNext = nextMessage->user == message->user && (nextMessage->timestampSeconds == 0 || nextMessage->timestampSeconds - message->timestampSeconds <= MERGE_TEXT_TIMESTAMP_DIFF_SEC);
}
if(!mergeTextWithPrev)
{
position.y += (MESSAGE_PADDING_TOP * Settings::getScaling());
if(position.y + usernameTextHeight > 0.0f && position.y < backgroundPos.y + backgroundSize.y)
{
sf::Text usernameText(sf::String::fromUtf8(message->user->getName().begin(), message->user->getName().end()), *usernameFont, usernameTextCharacterSize);
usernameText.setFillColor(sf::Color(15, 192, 252));
usernameText.setPosition(sf::Vector2f(floor(position.x + (AVATAR_DIAMETER + AVATAR_PADDING_SIDE) * Settings::getScaling()), floor(position.y)));
window.draw(usernameText);
if(message->timestampSeconds)
{
time_t time = (time_t)message->timestampSeconds;
struct tm *localTimePtr = localtime(&time);
char date[30];
strftime(date, sizeof(date), "%Y-%m-%d at %T", localTimePtr);
sf::Text timestamp(date, *timestampFont, timestampTextCharacterSize);
timestamp.setFillColor(ColorScheme::getTextRegularColor() * sf::Color(255, 255, 255, 50));
timestamp.setPosition(sf::Vector2f(floor(position.x + (AVATAR_DIAMETER + AVATAR_PADDING_SIDE) * Settings::getScaling() + usernameText.getLocalBounds().width + USERNAME_TIMESTAMP_SIDE_PADDING * Settings::getScaling()), floor(position.y + 2.0f * Settings::getScaling() + usernameTextHeight * 0.5f - timestampTextHeight * 0.5f)));
window.draw(timestamp);
}
// Max avatar size = 1mb
const ContentByUrlResult avatarResult = cache.getContentByUrl(message->user->avatarUrl, 1024 * 1024);
if(avatarResult.type == ContentByUrlResult::Type::CACHED)
{
circleShader->setUniform("texture", sf::Shader::CurrentTexture);
if(avatarResult.cachedType == ContentByUrlResult::CachedType::TEXTURE)
{
// TODO: Store this sprite somewhere, might not be efficient to create a new sprite object every frame
sf::Sprite sprite(*avatarResult.texture);
auto textureSize = avatarResult.texture->getSize();
sprite.setPosition(sf::Vector2f(floor(position.x), floor(position.y)));
sprite.setScale(sf::Vector2f(AVATAR_DIAMETER * Settings::getScaling() / (float)textureSize.x, AVATAR_DIAMETER * Settings::getScaling() / (float)textureSize.y));
window.draw(sprite, circleShader);
}
else if(avatarResult.cachedType == ContentByUrlResult::CachedType::GIF)
{
auto gifSize = avatarResult.gif->getSize();
avatarResult.gif->setPosition(sf::Vector2f(floor(position.x), floor(position.y)));
avatarResult.gif->setScale(sf::Vector2f(AVATAR_DIAMETER * Settings::getScaling() / (float)gifSize.x, AVATAR_DIAMETER * Settings::getScaling() / (float)gifSize.y));
avatarResult.gif->draw(window, circleShader);
}
}
else
{
sf::CircleShape avatarCircle(AVATAR_DIAMETER * 0.5f * Settings::getScaling(), 60 * Settings::getScaling());
avatarCircle.setPosition(sf::Vector2f(floor(position.x), floor(position.y)));
avatarCircle.setFillColor(ColorScheme::getBackgroundColor() + sf::Color(30, 30, 30));
window.draw(avatarCircle);
}
}
position.y += usernameTextHeight + USERNAME_PADDING_BOTTOM * Settings::getScaling();
}
// No need to perform culling here, that is done in @Text draw function
message->text.setCharacterSize(18.0f * Settings::getScaling());
message->text.setMaxWidth(backgroundSize.x - (AVATAR_DIAMETER + AVATAR_PADDING_SIDE) * Settings::getScaling());
message->text.setPosition(sf::Vector2f(floor(position.x + (AVATAR_DIAMETER + AVATAR_PADDING_SIDE) * Settings::getScaling()), floor(position.y)));
message->text.setLineSpacing(LINE_SPACING);
message->text.draw(window, cache);
position.y += message->text.getHeight();
if(!mergeTextWithNext)
{
position.y += (MESSAGE_PADDING_BOTTOM * Settings::getScaling());
if(position.y + LINE_HEIGHT > 0.0f && position.y < backgroundPos.y + backgroundSize.y && i + 1 != numMessages)
{
lineRect.setPosition(sf::Vector2f(position.x + LINE_SIDE_PADDING * Settings::getScaling() - PADDING_SIDE * Settings::getScaling(), floor(position.y)));
window.draw(lineRect);
//drawGradientLine(sf::Vector2f(position.x + LINE_SIDE_PADDING, floor(position.y)), sf::Vector2f(backgroundSizeWithoutPadding.x - LINE_SIDE_PADDING * 2.0f, LINE_HEIGHT), LINE_COLOR, window);
}
}
position.y += LINE_HEIGHT;
}
totalHeight = (position.y - scroll) - startHeight;
}
void MessageBoard::drawSimple(sf::RenderWindow &window, Cache &cache)
{
const float LINE_SPACING = 20.0f * Settings::getScaling();
const float MESSAGE_PADDING_TOP = 0.0f;
const float MESSAGE_PADDING_BOTTOM = 0.0f;
const sf::Font *usernameFont = ResourceCache::getFont("fonts/Roboto-Regular.ttf");
const int usernameTextCharacterSize = 20 * Settings::getScaling();
const float usernameTextHeight = usernameFont->getLineSpacing(usernameTextCharacterSize);
const float usernameMaxWidth = usernameTextHeight * 5.0f;
const sf::Font *timestampFont = ResourceCache::getFont("fonts/Roboto-Regular.ttf");
const int timestampTextCharacterSize = 15 * Settings::getScaling();
const float timestampTextHeight = timestampFont->getLineSpacing(timestampTextCharacterSize);
sf::Vector2<double> position(ChannelSidePanel::getWidth() + PADDING_SIDE * Settings::getScaling() + usernameMaxWidth, ChannelTopPanel::getHeight() + PADDING_TOP);
double startHeight = position.y;
position.y += scroll;
usize numMessages = messages.size();
for(usize i = 0; i < numMessages; ++i)
{
Message *message = messages[i];
position.y += (MESSAGE_PADDING_TOP * Settings::getScaling());
if(position.y + usernameTextHeight > 0.0f && position.y < backgroundPos.y + backgroundSize.y)
{
sf::String usernameTextStr = sf::String::fromUtf8(message->user->getName().begin(), message->user->getName().end());
usernameTextStr += " - ";
sf::Text usernameText(usernameTextStr, *usernameFont, usernameTextCharacterSize);
usernameText.setFillColor(sf::Color(15, 192, 252));
usernameText.setPosition(sf::Vector2f(floor(position.x - usernameText.getLocalBounds().width), floor(position.y)));
window.draw(usernameText);
if(message->timestampSeconds)
{
time_t time = (time_t)message->timestampSeconds;
struct tm *localTimePtr = localtime(&time);
char date[30];
strftime(date, sizeof(date), "%Y-%m-%d at %T", localTimePtr);
//sf::Text timestamp(date, *timestampFont, timestampTextCharacterSize);
//timestamp.setFillColor(ColorScheme::getTextRegularColor() * sf::Color(255, 255, 255, 30));
//timestamp.setPosition(sf::Vector2f(floor(position.x - usernameText.getLocalBounds().width + usernameText.getLocalBounds().width + USERNAME_TIMESTAMP_SIDE_PADDING * Settings::getScaling()), floor(position.y + 2.0f * Settings::getScaling() + usernameTextHeight * 0.5f - timestampTextHeight * 0.5f)));
//window.draw(timestamp);
}
}
// No need to perform culling here, that is done in @Text draw function
message->text.setCharacterSize(18 * Settings::getScaling());
message->text.setMaxWidth(backgroundSize.x - usernameMaxWidth * 2.0f);
message->text.setPosition(sf::Vector2f(floor(position.x), floor(position.y)));
message->text.setLineSpacing(LINE_SPACING);
message->text.draw(window, cache);
position.y += (message->text.getHeight() + MESSAGE_PADDING_BOTTOM * Settings::getScaling());
}
totalHeight = (position.y - scroll) - startHeight;
}
void MessageBoard::processEvent(const sf::Event &event)
{
lock_guard<mutex> lock(messageProcessMutex);
for(Message *message : messages)
{
message->text.processEvent(event);
}
OnlineLocalUser *onlineLocalUser = nullptr;
if(channel->getLocalUser()->type == User::Type::ONLINE_LOCAL_USER)
onlineLocalUser = static_cast<OnlineLocalUser*>(channel->getLocalUser());
if(onlineLocalUser && event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Button::Right)
{
for(auto it : messageIdMap)
{
it.second->text.processEvent(event);
auto textPos = it.second->text.getPosition();
if(it.second->user == channel->getLocalUser() && event.mouseButton.x >= textPos.x && event.mouseButton.x <= textPos.x + it.second->text.getMaxWidth() && event.mouseButton.y >= textPos.y && event.mouseButton.y <= textPos.y + it.second->text.getHeight())
{
auto contextMenu = GlobalContextMenu::getEditMessageContextMenu();
contextMenu->setPosition(sf::Vector2f(event.mouseButton.x, event.mouseButton.y));
contextMenu->setVisible(true);
GlobalContextMenu::setClickDeleteMessageCallbackFunc([this, it, onlineLocalUser](ContextMenuItem *menuItem)
{
channel->deleteMessage(it.first, onlineLocalUser->getPublicKey());
GlobalContextMenu::setClickDeleteMessageCallbackFunc(nullptr);
});
return;
}
}
GlobalContextMenu::setClickDeleteMessageCallbackFunc(nullptr);
}
else if(event.type == sf::Event::MouseWheelScrolled && event.mouseWheelScroll.wheel == sf::Mouse::Wheel::VerticalWheel)
{
scrollSpeed += (event.mouseWheelScroll.delta * 5.0);
if(scrollSpeed > SCROLL_MAX_SPEED)
scrollSpeed = SCROLL_MAX_SPEED;
else if(scrollSpeed < -SCROLL_MAX_SPEED)
scrollSpeed = -SCROLL_MAX_SPEED;
}
}
void MessageBoard::draw(sf::RenderWindow &window, Cache &cache)
{
auto windowSize = window.getSize();
backgroundSizeWithoutPadding = sf::Vector2f(floor(windowSize.x - ChannelSidePanel::getWidth() - UsersSidePanel::getWidth()), floor(windowSize.y - ChannelTopPanel::getHeight() - Chatbar::getHeight()));
backgroundSize = sf::Vector2f(floor(windowSize.x - ChannelSidePanel::getWidth() - UsersSidePanel::getWidth() - PADDING_SIDE * Settings::getScaling() * 2.0f), floor(windowSize.y - ChannelTopPanel::getHeight() - Chatbar::getHeight() - PADDING_TOP));
backgroundPos = sf::Vector2f(ChannelSidePanel::getWidth(), ChannelTopPanel::getHeight());
//if(backgroundSize != staticContentTexture.getSize())
// updateStaticContentTexture(backgroundSize);
// TODO: Remove this when dchat::Text can render to static and dynamic render target
dirty = true;
//if(dirty)
// staticContentTexture.clear(BACKGROUND_COLOR);
sf::RectangleShape backgroundRect(backgroundSizeWithoutPadding);
backgroundRect.setFillColor(ColorScheme::getBackgroundColor());
backgroundRect.setPosition(ChannelSidePanel::getWidth(), ChannelTopPanel::getHeight());
window.draw(backgroundRect);
double deltaTimeMicro = (double)frameTimer.getElapsedTime().asMicroseconds();
frameTimer.restart();
if(dirty)
{
lock_guard<mutex> lock(messageProcessMutex);
switch(Theme::getType())
{
case Theme::Type::DEFAULT:
drawDefault(window, cache);
break;
case Theme::Type::SIMPLE:
drawSimple(window, cache);
break;
}
}
scroll += scrollSpeed;
double deltaTimeScrollMultiplier = deltaTimeMicro * 0.0001;
if(scrollSpeed > 0.0)
{
scrollSpeed -= deltaTimeScrollMultiplier;
}
else
{
scrollSpeed += deltaTimeScrollMultiplier;
}
if(abs(scrollSpeed - deltaTimeScrollMultiplier) <= deltaTimeScrollMultiplier)
scrollSpeed = 0.0;
double textOverflow = (double)backgroundSize.y - totalHeight;
if(scroll > 0.0 || textOverflow > 0.0)
{
scroll = 0.0;
scrollSpeed = 0.0;
}
else if(textOverflow < 0.0 && scroll < textOverflow)
{
scroll = textOverflow;
scrollSpeed = 0.0;
}
if(scrollToBottom)
{
scrollToBottom = false;
if(textOverflow < 0.0)
scroll = textOverflow;
else
scroll = 0.0;
}
//staticContentTexture.display();
dirty = false;
// TODO: Save this, expensive to create on fly?
//sf::Sprite textureSprite(staticContentTexture.getTexture());
//textureSprite.setPosition(backgroundPos);
//window.draw(textureSprite);
}
}
|