OpenTTD: src/network/network_chat_gui.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

network_chat_gui.cpp
Go to the documentation of this file.
1 /* $Id: network_chat_gui.cpp 26538 2014-04-28 21:06:51Z rubidium $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
9
12 #include <stdarg.h> /* va_list */
13
14 #ifdef ENABLE_NETWORK
15
16 #include "../stdafx.h"
17 #include "../strings_func.h"
18 #include "../blitter/factory.hpp"
19 #include "../console_func.h"
20 #include "../video/video_driver.hpp"
21 #include "../querystring_gui.h"
22 #include "../town.h"
23 #include "../window_func.h"
24 #include "../core/geometry_func.hpp"
25 #include "network.h"
26 #include "network_client.h"
27 #include "network_base.h"
28
29 #include "../widgets/network_chat_widget.h"
30
31 #include "table/strings.h"
32
33 #include "../safeguards.h"
34
37 assert_compile((int)DRAW_STRING_BUFFER >= (int)NETWORK_CHAT_LENGTH + NETWORK_NAME_LENGTH + 40);
38
40 static const uint NETWORK_CHAT_LINE_SPACING = 3;
41
43 struct ChatMessage {
44 char message[DRAW_STRING_BUFFER];
45 TextColour colour;
46 uint32 remove_time;
47 };
48
49 /* used for chat window */
50 static ChatMessage *_chatmsg_list = NULL;
51 static bool _chatmessage_dirty = false;
52 static bool _chatmessage_visible = false;
53 static bool _chat_tab_completion_active;
54 static uint MAX_CHAT_MESSAGES = 0;
55
60 static PointDimension _chatmsg_box;
61 static uint8 *_chatmessage_backup = NULL;
62
67 static inline uint GetChatMessageCount()
68 {
69 uint i = 0;
70 for (; i < MAX_CHAT_MESSAGES; i++) {
71 if (_chatmsg_list[i].message[0] == '\0') break;
72 }
73
74 return i;
75 }
76
83 void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message, ...)
84 {
85 char buf[DRAW_STRING_BUFFER];
86 va_list va;
87
88 va_start(va, message);
89 vseprintf(buf, lastof(buf), message, va);
90 va_end(va);
91
92 Utf8TrimString(buf, DRAW_STRING_BUFFER);
93
94 uint msg_count = GetChatMessageCount();
95 if (MAX_CHAT_MESSAGES == msg_count) {
96 memmove(&_chatmsg_list[0], &_chatmsg_list[1], sizeof(_chatmsg_list[0]) * (msg_count - 1));
97 msg_count = MAX_CHAT_MESSAGES - 1;
98 }
99
100 ChatMessage *cmsg = &_chatmsg_list[msg_count++];
101 strecpy(cmsg->message, buf, lastof(cmsg->message));
102 cmsg->colour = (colour & TC_IS_PALETTE_COLOUR) ? colour : TC_WHITE;
103 cmsg->remove_time = _realtime_tick + duration * 1000;
104
105 _chatmessage_dirty = true;
106 }
107
109 void NetworkReInitChatBoxSize()
110 {
111 _chatmsg_box.y = 3 * FONT_HEIGHT_NORMAL;
112 _chatmsg_box.height = MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING) + 2;
113 _chatmessage_backup = ReallocT(_chatmessage_backup, _chatmsg_box.width * _chatmsg_box.height * BlitterFactory::GetCurrentBlitter()->GetBytesPerPixel());
114 }
115
117 void NetworkInitChatMessage()
118 {
119 MAX_CHAT_MESSAGES = _settings_client.gui.network_chat_box_height;
120
121 _chatmsg_list = ReallocT(_chatmsg_list, _settings_client.gui.network_chat_box_height);
122 _chatmsg_box.x = 10;
123 _chatmsg_box.width = _settings_client.gui.network_chat_box_width;
124 NetworkReInitChatBoxSize();
125 _chatmessage_visible = false;
126
127 for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
128 _chatmsg_list[i].message[0] = '\0';
129 }
130 }
131
133 void NetworkUndrawChatMessage()
134 {
135 /* Sometimes we also need to hide the cursor
136 * This is because both textmessage and the cursor take a shot of the
137 * screen before drawing.
138 * Now the textmessage takes his shot and paints his data before the cursor
139 * does, so in the shot of the cursor is the screen-data of the textmessage
140 * included when the cursor hangs somewhere over the textmessage. To
141 * avoid wrong repaints, we undraw the cursor in that case, and everything
142 * looks nicely ;)
143 * (and now hope this story above makes sense to you ;))
144 */
145 if (_cursor.visible &&
146 _cursor.draw_pos.x + _cursor.draw_size.x >= _chatmsg_box.x &&
147 _cursor.draw_pos.x <= _chatmsg_box.x + _chatmsg_box.width &&
148 _cursor.draw_pos.y + _cursor.draw_size.y >= _screen.height - _chatmsg_box.y - _chatmsg_box.height &&
149 _cursor.draw_pos.y <= _screen.height - _chatmsg_box.y) {
150 UndrawMouseCursor();
151 }
152
153 if (_chatmessage_visible) {
154 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
155 int x = _chatmsg_box.x;
156 int y = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
157 int width = _chatmsg_box.width;
158 int height = _chatmsg_box.height;
159 if (y < 0) {
160 height = max(height + y, min(_chatmsg_box.height, _screen.height));
161 y = 0;
162 }
163 if (x + width >= _screen.width) {
164 width = _screen.width - x;
165 }
166 if (width <= 0 || height <= 0) return;
167
168 _chatmessage_visible = false;
169 /* Put our 'shot' back to the screen */
170 blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
171 /* And make sure it is updated next time */
172 VideoDriver::GetInstance()->MakeDirty(x, y, width, height);
173
174 _chatmessage_dirty = true;
175 }
176 }
177
179 void NetworkChatMessageLoop()
180 {
181 for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
182 ChatMessage *cmsg = &_chatmsg_list[i];
183 if (cmsg->message[0] == '\0') continue;
184
185 /* Message has expired, remove from the list */
186 if (cmsg->remove_time < _realtime_tick) {
187 /* Move the remaining messages over the current message */
188 if (i != MAX_CHAT_MESSAGES - 1) memmove(cmsg, cmsg + 1, sizeof(*cmsg) * (MAX_CHAT_MESSAGES - i - 1));
189
190 /* Mark the last item as empty */
191 _chatmsg_list[MAX_CHAT_MESSAGES - 1].message[0] = '\0';
192 _chatmessage_dirty = true;
193
194 /* Go one item back, because we moved the array 1 to the left */
195 i--;
196 }
197 }
198 }
199
201 void NetworkDrawChatMessage()
202 {
203 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
204 if (!_chatmessage_dirty) return;
205
206 /* First undraw if needed */
207 NetworkUndrawChatMessage();
208
209 if (_iconsole_mode == ICONSOLE_FULL) return;
210
211 /* Check if we have anything to draw at all */
212 uint count = GetChatMessageCount();
213 if (count == 0) return;
214
215 int x = _chatmsg_box.x;
216 int y = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
217 int width = _chatmsg_box.width;
218 int height = _chatmsg_box.height;
219 if (y < 0) {
220 height = max(height + y, min(_chatmsg_box.height, _screen.height));
221 y = 0;
222 }
223 if (x + width >= _screen.width) {
224 width = _screen.width - x;
225 }
226 if (width <= 0 || height <= 0) return;
227
228 assert(blitter->BufferSize(width, height) <= (int)(_chatmsg_box.width * _chatmsg_box.height * blitter->GetBytesPerPixel()));
229
230 /* Make a copy of the screen as it is before painting (for undraw) */
231 blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
232
233 _cur_dpi = &_screen; // switch to _screen painting
234
235 int string_height = 0;
236 for (uint i = 0; i < count; i++) {
237 SetDParamStr(0, _chatmsg_list[i].message);
238 string_height += GetStringLineCount(STR_JUST_RAW_STRING, width - 1) * FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING;
239 }
240
241 string_height = min(string_height, MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING));
242
243 int top = _screen.height - _chatmsg_box.y - string_height - 2;
244 int bottom = _screen.height - _chatmsg_box.y - 2;
245 /* Paint a half-transparent box behind the chat messages */
246 GfxFillRect(_chatmsg_box.x, top - 2, _chatmsg_box.x + _chatmsg_box.width - 1, bottom,
247 PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
248 );
249
250 /* Paint the chat messages starting with the lowest at the bottom */
251 int ypos = bottom - 2;
252
253 for (int i = count - 1; i >= 0; i--) {
254 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;
255 if (ypos < top) break;
256 }
257
258 /* Make sure the data is updated next flush */
259 VideoDriver::GetInstance()->MakeDirty(x, y, width, height);
260
261 _chatmessage_visible = true;
262 _chatmessage_dirty = false;
263 }
264
271 static void SendChat(const char *buf, DestType type, int dest)
272 {
273 if (StrEmpty(buf)) return;
274 if (!_network_server) {
275 MyClient::SendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0);
276 } else {
277 NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER);
278 }
279 }
280
282 struct NetworkChatWindow : public Window {
283 DestType dtype;
284 StringID dest_string;
285 int dest;
286 QueryString message_editbox;
287
294 NetworkChatWindow(WindowDesc *desc, DestType type, int dest) : Window(desc), message_editbox(NETWORK_CHAT_LENGTH)
295 {
296 this->dtype = type;
297 this->dest = dest;
298 this->querystrings[WID_NC_TEXTBOX] = &this->message_editbox;
299 this->message_editbox.cancel_button = WID_NC_CLOSE;
300 this->message_editbox.ok_button = WID_NC_SENDBUTTON;
301
302 static const StringID chat_captions[] = {
303 STR_NETWORK_CHAT_ALL_CAPTION,
304 STR_NETWORK_CHAT_COMPANY_CAPTION,
305 STR_NETWORK_CHAT_CLIENT_CAPTION
306 };
307 assert((uint)this->dtype < lengthof(chat_captions));
308 this->dest_string = chat_captions[this->dtype];
309
310 this->InitNested(type);
311
312 this->SetFocusedWidget(WID_NC_TEXTBOX);
313 InvalidateWindowData(WC_NEWS_WINDOW, 0, this->height);
314 _chat_tab_completion_active = false;
315
316 PositionNetworkChatWindow(this);
317 }
318
319 ~NetworkChatWindow()
320 {
321 InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
322 }
323
330 const char *ChatTabCompletionNextItem(uint *item)
331 {
332 static char chat_tab_temp_buffer[64];
333
334 /* First, try clients */
335 if (*item < MAX_CLIENT_SLOTS) {
336 /* Skip inactive clients */
337 NetworkClientInfo *ci;
338 FOR_ALL_CLIENT_INFOS_FROM(ci, *item) {
339 *item = ci->index;
340 return ci->client_name;
341 }
342 *item = MAX_CLIENT_SLOTS;
343 }
344
345 /* Then, try townnames
346 * Not that the following assumes all town indices are adjacent, ie no
347 * towns have been deleted. */
348 if (*item < (uint)MAX_CLIENT_SLOTS + Town::GetPoolSize()) {
349 const Town *t;
350
351 FOR_ALL_TOWNS_FROM(t, *item - MAX_CLIENT_SLOTS) {
352 /* Get the town-name via the string-system */
353 SetDParam(0, t->index);
354 GetString(chat_tab_temp_buffer, STR_TOWN_NAME, lastof(chat_tab_temp_buffer));
355 return &chat_tab_temp_buffer[0];
356 }
357 }
358
359 return NULL;
360 }
361
367 static char *ChatTabCompletionFindText(char *buf)
368 {
369 char *p = strrchr(buf, ' ');
370 if (p == NULL) return buf;
371
372 *p = '\0';
373 return p + 1;
374 }
375
379 void ChatTabCompletion()
380 {
381 static char _chat_tab_completion_buf[NETWORK_CHAT_LENGTH];
382 assert(this->message_editbox.text.max_bytes == lengthof(_chat_tab_completion_buf));
383
384 Textbuf *tb = &this->message_editbox.text;
385 size_t len, tb_len;
386 uint item;
387 char *tb_buf, *pre_buf;
388 const char *cur_name;
389 bool second_scan = false;
390
391 item = 0;
392
393 /* Copy the buffer so we can modify it without damaging the real data */
394 pre_buf = (_chat_tab_completion_active) ? stredup(_chat_tab_completion_buf) : stredup(tb->buf);
395
396 tb_buf = ChatTabCompletionFindText(pre_buf);
397 tb_len = strlen(tb_buf);
398
399 while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
400 item++;
401
402 if (_chat_tab_completion_active) {
403 /* We are pressing TAB again on the same name, is there another name
404 * that starts with this? */
405 if (!second_scan) {
406 size_t offset;
407 size_t length;
408
409 /* If we are completing at the begin of the line, skip the ': ' we added */
410 if (tb_buf == pre_buf) {
411 offset = 0;
412 length = (tb->bytes - 1) - 2;
413 } else {
414 /* Else, find the place we are completing at */
415 offset = strlen(pre_buf) + 1;
416 length = (tb->bytes - 1) - offset;
417 }
418
419 /* Compare if we have a match */
420 if (strlen(cur_name) == length && strncmp(cur_name, tb->buf + offset, length) == 0) second_scan = true;
421
422 continue;
423 }
424
425 /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
426 }
427
428 len = strlen(cur_name);
429 if (tb_len < len && strncasecmp(cur_name, tb_buf, tb_len) == 0) {
430 /* Save the data it was before completion */
431 if (!second_scan) seprintf(_chat_tab_completion_buf, lastof(_chat_tab_completion_buf), "%s", tb->buf);
432 _chat_tab_completion_active = true;
433
434 /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
435 if (pre_buf == tb_buf) {
436 this->message_editbox.text.Print("%s: ", cur_name);
437 } else {
438 this->message_editbox.text.Print("%s %s", pre_buf, cur_name);
439 }
440
441 this->SetDirty();
442 free(pre_buf);
443 return;
444 }
445 }
446
447 if (second_scan) {
448 /* We walked all possibilities, and the user presses tab again.. revert to original text */
449 this->message_editbox.text.Assign(_chat_tab_completion_buf);
450 _chat_tab_completion_active = false;
451
452 this->SetDirty();
453 }
454 free(pre_buf);
455 }
456
457 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
458 {
459 Point pt = { 0, _screen.height - sm_height - FindWindowById(WC_STATUS_BAR, 0)->height };
460 return pt;
461 }
462
463 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
464 {
465 if (widget != WID_NC_DESTINATION) return;
466
467 if (this->dtype == DESTTYPE_CLIENT) {
468 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
469 }
470 Dimension d = GetStringBoundingBox(this->dest_string);
471 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
472 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
473 *size = maxdim(*size, d);
474 }
475
476 virtual void DrawWidget(const Rect &r, int widget) const
477 {
478 if (widget != WID_NC_DESTINATION) return;
479
480 if (this->dtype == DESTTYPE_CLIENT) {
481 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
482 }
483 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, this->dest_string, TC_BLACK, SA_RIGHT);
484 }
485
486 virtual void OnClick(Point pt, int widget, int click_count)
487 {
488 switch (widget) {
489 /* Send */
490 case WID_NC_SENDBUTTON: SendChat(this->message_editbox.text.buf, this->dtype, this->dest);
491 /* FALL THROUGH */
492 case WID_NC_CLOSE: /* Cancel */ delete this; break;
493 }
494 }
495
496 virtual EventState OnKeyPress(WChar key, uint16 keycode)
497 {
498 EventState state = ES_NOT_HANDLED;
499 if (keycode == WKC_TAB) {
500 ChatTabCompletion();
501 state = ES_HANDLED;
502 }
503 return state;
504 }
505
506 virtual void OnEditboxChanged(int wid)
507 {
508 _chat_tab_completion_active = false;
509 }
510
516 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
517 {
518 if (data == this->dest) delete this;
519 }
520 };
521
523 static const NWidgetPart _nested_chat_window_widgets[] = {
524 NWidget(NWID_HORIZONTAL),
525 NWidget(WWT_CLOSEBOX, COLOUR_GREY, WID_NC_CLOSE),
526 NWidget(WWT_PANEL, COLOUR_GREY, WID_NC_BACKGROUND),
527 NWidget(NWID_HORIZONTAL),
528 NWidget(WWT_TEXT, COLOUR_GREY, WID_NC_DESTINATION), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NULL, STR_NULL),
529 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_NC_TEXTBOX), SetMinimalSize(100, 12), SetPadding(1, 0, 1, 0), SetResize(1, 0),
530 SetDataTip(STR_NETWORK_CHAT_OSKTITLE, STR_NULL),
531 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NC_SENDBUTTON), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NETWORK_CHAT_SEND, STR_NULL),
532 EndContainer(),
533 EndContainer(),
534 EndContainer(),
535 };
536
538 static WindowDesc _chat_window_desc(
539 WDP_MANUAL, NULL, 640, 14, // x, y, width, height
540 WC_SEND_NETWORK_MSG, WC_NONE,
541 0,
542 _nested_chat_window_widgets, lengthof(_nested_chat_window_widgets)
543 );
544
545
551 void ShowNetworkChatQueryWindow(DestType type, int dest)
552 {
553 DeleteWindowByClass(WC_SEND_NETWORK_MSG);
554 new NetworkChatWindow(&_chat_window_desc, type, dest);
555 }
556
557 #endif /* ENABLE_NETWORK */