Fix: Data races on cursor state in OpenGL backends
[openttd-github.git] / src / network / network_chat_gui.cpp
blob80a0b78695f578579ee30afa63abb6bbd63b8916
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file network_chat_gui.cpp GUI for handling chat messages. */
10 #include <stdarg.h> /* va_list */
12 #include "../stdafx.h"
13 #include "../strings_func.h"
14 #include "../blitter/factory.hpp"
15 #include "../console_func.h"
16 #include "../video/video_driver.hpp"
17 #include "../querystring_gui.h"
18 #include "../town.h"
19 #include "../window_func.h"
20 #include "../toolbar_gui.h"
21 #include "../core/geometry_func.hpp"
22 #include "network.h"
23 #include "network_client.h"
24 #include "network_base.h"
26 #include "../widgets/network_chat_widget.h"
28 #include "table/strings.h"
30 #include "../safeguards.h"
32 /** The draw buffer must be able to contain the chat message, client name and the "[All]" message,
33 * some spaces and possible translations of [All] to other languages. */
34 static_assert((int)DRAW_STRING_BUFFER >= (int)NETWORK_CHAT_LENGTH + NETWORK_NAME_LENGTH + 40);
36 /** Spacing between chat lines. */
37 static const uint NETWORK_CHAT_LINE_SPACING = 3;
39 /** Container for a message. */
40 struct ChatMessage {
41 char message[DRAW_STRING_BUFFER]; ///< The action message.
42 TextColour colour; ///< The colour of the message.
43 std::chrono::steady_clock::time_point remove_time; ///< The time to remove the message.
46 /* used for chat window */
47 static ChatMessage *_chatmsg_list = nullptr; ///< The actual chat message list.
48 static bool _chatmessage_dirty = false; ///< Does the chat message need repainting?
49 static bool _chatmessage_visible = false; ///< Is a chat message visible.
50 static bool _chat_tab_completion_active; ///< Whether tab completion is active.
51 static uint MAX_CHAT_MESSAGES = 0; ///< The limit of chat messages to show.
53 /**
54 * The chatbox grows from the bottom so the coordinates are pixels from
55 * the left and pixels from the bottom. The height is the maximum height.
57 static PointDimension _chatmsg_box;
58 static uint8 *_chatmessage_backup = nullptr; ///< Backup in case text is moved.
60 /**
61 * Count the chat messages.
62 * @return The number of chat messages.
64 static inline uint GetChatMessageCount()
66 uint i = 0;
67 for (; i < MAX_CHAT_MESSAGES; i++) {
68 if (_chatmsg_list[i].message[0] == '\0') break;
71 return i;
74 /**
75 * Add a text message to the 'chat window' to be shown
76 * @param colour The colour this message is to be shown in
77 * @param duration The duration of the chat message in seconds
78 * @param message message itself in printf() style
80 void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message, ...)
82 char buf[DRAW_STRING_BUFFER];
83 va_list va;
85 va_start(va, message);
86 vseprintf(buf, lastof(buf), message, va);
87 va_end(va);
89 Utf8TrimString(buf, DRAW_STRING_BUFFER);
91 uint msg_count = GetChatMessageCount();
92 if (MAX_CHAT_MESSAGES == msg_count) {
93 memmove(&_chatmsg_list[0], &_chatmsg_list[1], sizeof(_chatmsg_list[0]) * (msg_count - 1));
94 msg_count = MAX_CHAT_MESSAGES - 1;
97 ChatMessage *cmsg = &_chatmsg_list[msg_count++];
98 strecpy(cmsg->message, buf, lastof(cmsg->message));
99 cmsg->colour = (colour & TC_IS_PALETTE_COLOUR) ? colour : TC_WHITE;
100 cmsg->remove_time = std::chrono::steady_clock::now() + std::chrono::seconds(duration);
102 _chatmessage_dirty = true;
105 /** Initialize all font-dependent chat box sizes. */
106 void NetworkReInitChatBoxSize()
108 _chatmsg_box.y = 3 * FONT_HEIGHT_NORMAL;
109 _chatmsg_box.height = MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING) + 4;
110 _chatmessage_backup = ReallocT(_chatmessage_backup, _chatmsg_box.width * _chatmsg_box.height * BlitterFactory::GetCurrentBlitter()->GetBytesPerPixel());
113 /** Initialize all buffers of the chat visualisation. */
114 void NetworkInitChatMessage()
116 MAX_CHAT_MESSAGES = _settings_client.gui.network_chat_box_height;
118 _chatmsg_list = ReallocT(_chatmsg_list, _settings_client.gui.network_chat_box_height);
119 _chatmsg_box.x = 10;
120 _chatmsg_box.width = _settings_client.gui.network_chat_box_width_pct * _screen.width / 100;
121 NetworkReInitChatBoxSize();
122 _chatmessage_visible = false;
124 for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
125 _chatmsg_list[i].message[0] = '\0';
129 /** Hide the chatbox */
130 void NetworkUndrawChatMessage()
132 /* Sometimes we also need to hide the cursor
133 * This is because both textmessage and the cursor take a shot of the
134 * screen before drawing.
135 * Now the textmessage takes his shot and paints his data before the cursor
136 * does, so in the shot of the cursor is the screen-data of the textmessage
137 * included when the cursor hangs somewhere over the textmessage. To
138 * avoid wrong repaints, we undraw the cursor in that case, and everything
139 * looks nicely ;)
140 * (and now hope this story above makes sense to you ;))
142 if (_cursor.visible &&
143 _cursor.draw_pos.x + _cursor.draw_size.x >= _chatmsg_box.x &&
144 _cursor.draw_pos.x <= _chatmsg_box.x + _chatmsg_box.width &&
145 _cursor.draw_pos.y + _cursor.draw_size.y >= _screen.height - _chatmsg_box.y - _chatmsg_box.height &&
146 _cursor.draw_pos.y <= _screen.height - _chatmsg_box.y) {
147 UndrawMouseCursor();
150 if (_chatmessage_visible) {
151 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
152 int x = _chatmsg_box.x;
153 int y = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
154 int width = _chatmsg_box.width;
155 int height = _chatmsg_box.height;
156 if (y < 0) {
157 height = std::max(height + y, std::min(_chatmsg_box.height, _screen.height));
158 y = 0;
160 if (x + width >= _screen.width) {
161 width = _screen.width - x;
163 if (width <= 0 || height <= 0) return;
165 _chatmessage_visible = false;
166 /* Put our 'shot' back to the screen */
167 blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
168 /* And make sure it is updated next time */
169 VideoDriver::GetInstance()->MakeDirty(x, y, width, height);
171 _chatmessage_dirty = true;
175 /** Check if a message is expired. */
176 void NetworkChatMessageLoop()
178 for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
179 ChatMessage *cmsg = &_chatmsg_list[i];
180 if (cmsg->message[0] == '\0') continue;
182 /* Message has expired, remove from the list */
183 if (std::chrono::steady_clock::now() > cmsg->remove_time) {
184 /* Move the remaining messages over the current message */
185 if (i != MAX_CHAT_MESSAGES - 1) memmove(cmsg, cmsg + 1, sizeof(*cmsg) * (MAX_CHAT_MESSAGES - i - 1));
187 /* Mark the last item as empty */
188 _chatmsg_list[MAX_CHAT_MESSAGES - 1].message[0] = '\0';
189 _chatmessage_dirty = true;
191 /* Go one item back, because we moved the array 1 to the left */
192 i--;
197 /** Draw the chat message-box */
198 void NetworkDrawChatMessage()
200 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
201 if (!_chatmessage_dirty) return;
203 /* First undraw if needed */
204 NetworkUndrawChatMessage();
206 if (_iconsole_mode == ICONSOLE_FULL) return;
208 /* Check if we have anything to draw at all */
209 uint count = GetChatMessageCount();
210 if (count == 0) return;
212 int x = _chatmsg_box.x;
213 int y = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
214 int width = _chatmsg_box.width;
215 int height = _chatmsg_box.height;
216 if (y < 0) {
217 height = std::max(height + y, std::min(_chatmsg_box.height, _screen.height));
218 y = 0;
220 if (x + width >= _screen.width) {
221 width = _screen.width - x;
223 if (width <= 0 || height <= 0) return;
225 assert(blitter->BufferSize(width, height) <= (int)(_chatmsg_box.width * _chatmsg_box.height * blitter->GetBytesPerPixel()));
227 /* Make a copy of the screen as it is before painting (for undraw) */
228 blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
230 _cur_dpi = &_screen; // switch to _screen painting
232 int string_height = 0;
233 for (uint i = 0; i < count; i++) {
234 SetDParamStr(0, _chatmsg_list[i].message);
235 string_height += GetStringLineCount(STR_JUST_RAW_STRING, width - 1) * FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING;
238 string_height = std::min<uint>(string_height, MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING));
240 int top = _screen.height - _chatmsg_box.y - string_height - 2;
241 int bottom = _screen.height - _chatmsg_box.y - 2;
242 /* Paint a half-transparent box behind the chat messages */
243 GfxFillRect(_chatmsg_box.x, top - 2, _chatmsg_box.x + _chatmsg_box.width - 1, bottom,
244 PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
247 /* Paint the chat messages starting with the lowest at the bottom */
248 int ypos = bottom - 2;
250 for (int i = count - 1; i >= 0; i--) {
251 ypos = DrawStringMultiLine(_chatmsg_box.x + 3, _chatmsg_box.x + _chatmsg_box.width - 1, top, ypos, _chatmsg_list[i].message, _chatmsg_list[i].colour, SA_LEFT | SA_BOTTOM | SA_FORCE) - NETWORK_CHAT_LINE_SPACING;
252 if (ypos < top) break;
255 /* Make sure the data is updated next flush */
256 VideoDriver::GetInstance()->MakeDirty(x, y, width, height);
258 _chatmessage_visible = true;
259 _chatmessage_dirty = false;
263 * Send an actual chat message.
264 * @param buf The message to send.
265 * @param type The type of destination.
266 * @param dest The actual destination index.
268 static void SendChat(const char *buf, DestType type, int dest)
270 if (StrEmpty(buf)) return;
271 if (!_network_server) {
272 MyClient::SendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0);
273 } else {
274 NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER);
278 /** Window to enter the chat message in. */
279 struct NetworkChatWindow : public Window {
280 DestType dtype; ///< The type of destination.
281 StringID dest_string; ///< String representation of the destination.
282 int dest; ///< The identifier of the destination.
283 QueryString message_editbox; ///< Message editbox.
286 * Create a chat input window.
287 * @param desc Description of the looks of the window.
288 * @param type The type of destination.
289 * @param dest The actual destination index.
291 NetworkChatWindow(WindowDesc *desc, DestType type, int dest) : Window(desc), message_editbox(NETWORK_CHAT_LENGTH)
293 this->dtype = type;
294 this->dest = dest;
295 this->querystrings[WID_NC_TEXTBOX] = &this->message_editbox;
296 this->message_editbox.cancel_button = WID_NC_CLOSE;
297 this->message_editbox.ok_button = WID_NC_SENDBUTTON;
299 static const StringID chat_captions[] = {
300 STR_NETWORK_CHAT_ALL_CAPTION,
301 STR_NETWORK_CHAT_COMPANY_CAPTION,
302 STR_NETWORK_CHAT_CLIENT_CAPTION
304 assert((uint)this->dtype < lengthof(chat_captions));
305 this->dest_string = chat_captions[this->dtype];
307 this->InitNested(type);
309 this->SetFocusedWidget(WID_NC_TEXTBOX);
310 InvalidateWindowData(WC_NEWS_WINDOW, 0, this->height);
311 _chat_tab_completion_active = false;
313 PositionNetworkChatWindow(this);
316 ~NetworkChatWindow()
318 InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
321 void FindWindowPlacementAndResize(int def_width, int def_height) override
323 Window::FindWindowPlacementAndResize(_toolbar_width, def_height);
327 * Find the next item of the list of things that can be auto-completed.
328 * @param item The current indexed item to return. This function can, and most
329 * likely will, alter item, to skip empty items in the arrays.
330 * @return Returns the char that matched to the index.
332 const char *ChatTabCompletionNextItem(uint *item)
334 static char chat_tab_temp_buffer[64];
336 /* First, try clients */
337 if (*item < MAX_CLIENT_SLOTS) {
338 /* Skip inactive clients */
339 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate(*item)) {
340 *item = ci->index;
341 return ci->client_name;
343 *item = MAX_CLIENT_SLOTS;
346 /* Then, try townnames
347 * Not that the following assumes all town indices are adjacent, ie no
348 * towns have been deleted. */
349 if (*item < (uint)MAX_CLIENT_SLOTS + Town::GetPoolSize()) {
350 for (const Town *t : Town::Iterate(*item - MAX_CLIENT_SLOTS)) {
351 /* Get the town-name via the string-system */
352 SetDParam(0, t->index);
353 GetString(chat_tab_temp_buffer, STR_TOWN_NAME, lastof(chat_tab_temp_buffer));
354 return &chat_tab_temp_buffer[0];
358 return nullptr;
362 * Find what text to complete. It scans for a space from the left and marks
363 * the word right from that as to complete. It also writes a \0 at the
364 * position of the space (if any). If nothing found, buf is returned.
366 static char *ChatTabCompletionFindText(char *buf)
368 char *p = strrchr(buf, ' ');
369 if (p == nullptr) return buf;
371 *p = '\0';
372 return p + 1;
376 * See if we can auto-complete the current text of the user.
378 void ChatTabCompletion()
380 static char _chat_tab_completion_buf[NETWORK_CHAT_LENGTH];
381 assert(this->message_editbox.text.max_bytes == lengthof(_chat_tab_completion_buf));
383 Textbuf *tb = &this->message_editbox.text;
384 size_t len, tb_len;
385 uint item;
386 char *tb_buf, *pre_buf;
387 const char *cur_name;
388 bool second_scan = false;
390 item = 0;
392 /* Copy the buffer so we can modify it without damaging the real data */
393 pre_buf = (_chat_tab_completion_active) ? stredup(_chat_tab_completion_buf) : stredup(tb->buf);
395 tb_buf = ChatTabCompletionFindText(pre_buf);
396 tb_len = strlen(tb_buf);
398 while ((cur_name = ChatTabCompletionNextItem(&item)) != nullptr) {
399 item++;
401 if (_chat_tab_completion_active) {
402 /* We are pressing TAB again on the same name, is there another name
403 * that starts with this? */
404 if (!second_scan) {
405 size_t offset;
406 size_t length;
408 /* If we are completing at the begin of the line, skip the ': ' we added */
409 if (tb_buf == pre_buf) {
410 offset = 0;
411 length = (tb->bytes - 1) - 2;
412 } else {
413 /* Else, find the place we are completing at */
414 offset = strlen(pre_buf) + 1;
415 length = (tb->bytes - 1) - offset;
418 /* Compare if we have a match */
419 if (strlen(cur_name) == length && strncmp(cur_name, tb->buf + offset, length) == 0) second_scan = true;
421 continue;
424 /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
427 len = strlen(cur_name);
428 if (tb_len < len && strncasecmp(cur_name, tb_buf, tb_len) == 0) {
429 /* Save the data it was before completion */
430 if (!second_scan) seprintf(_chat_tab_completion_buf, lastof(_chat_tab_completion_buf), "%s", tb->buf);
431 _chat_tab_completion_active = true;
433 /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
434 if (pre_buf == tb_buf) {
435 this->message_editbox.text.Print("%s: ", cur_name);
436 } else {
437 this->message_editbox.text.Print("%s %s", pre_buf, cur_name);
440 this->SetDirty();
441 free(pre_buf);
442 return;
446 if (second_scan) {
447 /* We walked all possibilities, and the user presses tab again.. revert to original text */
448 this->message_editbox.text.Assign(_chat_tab_completion_buf);
449 _chat_tab_completion_active = false;
451 this->SetDirty();
453 free(pre_buf);
456 Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
458 Point pt = { 0, _screen.height - sm_height - FindWindowById(WC_STATUS_BAR, 0)->height };
459 return pt;
462 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
464 if (widget != WID_NC_DESTINATION) return;
466 if (this->dtype == DESTTYPE_CLIENT) {
467 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
469 Dimension d = GetStringBoundingBox(this->dest_string);
470 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
471 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
472 *size = maxdim(*size, d);
475 void DrawWidget(const Rect &r, int widget) const override
477 if (widget != WID_NC_DESTINATION) return;
479 if (this->dtype == DESTTYPE_CLIENT) {
480 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
482 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, this->dest_string, TC_BLACK, SA_RIGHT);
485 void OnClick(Point pt, int widget, int click_count) override
487 switch (widget) {
488 case WID_NC_SENDBUTTON: /* Send */
489 SendChat(this->message_editbox.text.buf, this->dtype, this->dest);
490 FALLTHROUGH;
492 case WID_NC_CLOSE: /* Cancel */
493 delete this;
494 break;
498 EventState OnKeyPress(WChar key, uint16 keycode) override
500 EventState state = ES_NOT_HANDLED;
501 if (keycode == WKC_TAB) {
502 ChatTabCompletion();
503 state = ES_HANDLED;
505 return state;
508 void OnEditboxChanged(int wid) override
510 _chat_tab_completion_active = false;
514 * Some data on this window has become invalid.
515 * @param data Information about the changed data.
516 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
518 void OnInvalidateData(int data = 0, bool gui_scope = true) override
520 if (data == this->dest) delete this;
524 /** The widgets of the chat window. */
525 static const NWidgetPart _nested_chat_window_widgets[] = {
526 NWidget(NWID_HORIZONTAL),
527 NWidget(WWT_CLOSEBOX, COLOUR_GREY, WID_NC_CLOSE),
528 NWidget(WWT_PANEL, COLOUR_GREY, WID_NC_BACKGROUND),
529 NWidget(NWID_HORIZONTAL),
530 NWidget(WWT_TEXT, COLOUR_GREY, WID_NC_DESTINATION), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NULL, STR_NULL),
531 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_NC_TEXTBOX), SetMinimalSize(100, 12), SetPadding(1, 0, 1, 0), SetResize(1, 0),
532 SetDataTip(STR_NETWORK_CHAT_OSKTITLE, STR_NULL),
533 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NC_SENDBUTTON), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NETWORK_CHAT_SEND, STR_NULL),
534 EndContainer(),
535 EndContainer(),
536 EndContainer(),
539 /** The description of the chat window. */
540 static WindowDesc _chat_window_desc(
541 WDP_MANUAL, nullptr, 0, 0,
542 WC_SEND_NETWORK_MSG, WC_NONE,
544 _nested_chat_window_widgets, lengthof(_nested_chat_window_widgets)
549 * Show the chat window.
550 * @param type The type of destination.
551 * @param dest The actual destination index.
553 void ShowNetworkChatQueryWindow(DestType type, int dest)
555 DeleteWindowByClass(WC_SEND_NETWORK_MSG);
556 new NetworkChatWindow(&_chat_window_desc, type, dest);