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/>.
10 /** @file network_chat_gui.cpp GUI for handling chat messages. */
12 #include <stdarg.h> /* va_list */
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"
23 #include "../window_func.h"
24 #include "../toolbar_gui.h"
25 #include "../core/geometry_func.hpp"
27 #include "network_client.h"
28 #include "network_base.h"
30 #include "../widgets/network_chat_widget.h"
32 #include "table/strings.h"
34 #include "../safeguards.h"
36 /** The draw buffer must be able to contain the chat message, client name and the "[All]" message,
37 * some spaces and possible translations of [All] to other languages. */
38 assert_compile((int)DRAW_STRING_BUFFER
>= (int)NETWORK_CHAT_LENGTH
+ NETWORK_NAME_LENGTH
+ 40);
40 /** Spacing between chat lines. */
41 static const uint NETWORK_CHAT_LINE_SPACING
= 3;
43 /** Container for a message. */
45 char message
[DRAW_STRING_BUFFER
]; ///< The action message.
46 TextColour colour
; ///< The colour of the message.
47 uint32 remove_time
; ///< The time to remove the message.
50 /* used for chat window */
51 static ChatMessage
*_chatmsg_list
= NULL
; ///< The actual chat message list.
52 static bool _chatmessage_dirty
= false; ///< Does the chat message need repainting?
53 static bool _chatmessage_visible
= false; ///< Is a chat message visible.
54 static bool _chat_tab_completion_active
; ///< Whether tab completion is active.
55 static uint MAX_CHAT_MESSAGES
= 0; ///< The limit of chat messages to show.
58 * The chatbox grows from the bottom so the coordinates are pixels from
59 * the left and pixels from the bottom. The height is the maximum height.
61 static PointDimension _chatmsg_box
;
62 static uint8
*_chatmessage_backup
= NULL
; ///< Backup in case text is moved.
65 * Count the chat messages.
66 * @return The number of chat messages.
68 static inline uint
GetChatMessageCount()
71 for (; i
< MAX_CHAT_MESSAGES
; i
++) {
72 if (_chatmsg_list
[i
].message
[0] == '\0') break;
79 * Add a text message to the 'chat window' to be shown
80 * @param colour The colour this message is to be shown in
81 * @param duration The duration of the chat message in seconds
82 * @param message message itself in printf() style
84 void CDECL
NetworkAddChatMessage(TextColour colour
, uint duration
, const char *message
, ...)
86 char buf
[DRAW_STRING_BUFFER
];
89 va_start(va
, message
);
90 vseprintf(buf
, lastof(buf
), message
, va
);
93 Utf8TrimString(buf
, DRAW_STRING_BUFFER
);
95 uint msg_count
= GetChatMessageCount();
96 if (MAX_CHAT_MESSAGES
== msg_count
) {
97 memmove(&_chatmsg_list
[0], &_chatmsg_list
[1], sizeof(_chatmsg_list
[0]) * (msg_count
- 1));
98 msg_count
= MAX_CHAT_MESSAGES
- 1;
101 ChatMessage
*cmsg
= &_chatmsg_list
[msg_count
++];
102 strecpy(cmsg
->message
, buf
, lastof(cmsg
->message
));
103 cmsg
->colour
= (colour
& TC_IS_PALETTE_COLOUR
) ? colour
: TC_WHITE
;
104 cmsg
->remove_time
= _realtime_tick
+ duration
* 1000;
106 _chatmessage_dirty
= true;
109 /** Initialize all font-dependent chat box sizes. */
110 void NetworkReInitChatBoxSize()
112 _chatmsg_box
.y
= 3 * FONT_HEIGHT_NORMAL
;
113 _chatmsg_box
.height
= MAX_CHAT_MESSAGES
* (FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
) + 4;
114 _chatmessage_backup
= ReallocT(_chatmessage_backup
, _chatmsg_box
.width
* _chatmsg_box
.height
* BlitterFactory::GetCurrentBlitter()->GetBytesPerPixel());
117 /** Initialize all buffers of the chat visualisation. */
118 void NetworkInitChatMessage()
120 MAX_CHAT_MESSAGES
= _settings_client
.gui
.network_chat_box_height
;
122 _chatmsg_list
= ReallocT(_chatmsg_list
, _settings_client
.gui
.network_chat_box_height
);
124 _chatmsg_box
.width
= _settings_client
.gui
.network_chat_box_width_pct
* _screen
.width
/ 100;
125 NetworkReInitChatBoxSize();
126 _chatmessage_visible
= false;
128 for (uint i
= 0; i
< MAX_CHAT_MESSAGES
; i
++) {
129 _chatmsg_list
[i
].message
[0] = '\0';
133 /** Hide the chatbox */
134 void NetworkUndrawChatMessage()
136 /* Sometimes we also need to hide the cursor
137 * This is because both textmessage and the cursor take a shot of the
138 * screen before drawing.
139 * Now the textmessage takes his shot and paints his data before the cursor
140 * does, so in the shot of the cursor is the screen-data of the textmessage
141 * included when the cursor hangs somewhere over the textmessage. To
142 * avoid wrong repaints, we undraw the cursor in that case, and everything
144 * (and now hope this story above makes sense to you ;))
146 if (_cursor
.visible
&&
147 _cursor
.draw_pos
.x
+ _cursor
.draw_size
.x
>= _chatmsg_box
.x
&&
148 _cursor
.draw_pos
.x
<= _chatmsg_box
.x
+ _chatmsg_box
.width
&&
149 _cursor
.draw_pos
.y
+ _cursor
.draw_size
.y
>= _screen
.height
- _chatmsg_box
.y
- _chatmsg_box
.height
&&
150 _cursor
.draw_pos
.y
<= _screen
.height
- _chatmsg_box
.y
) {
154 if (_chatmessage_visible
) {
155 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
156 int x
= _chatmsg_box
.x
;
157 int y
= _screen
.height
- _chatmsg_box
.y
- _chatmsg_box
.height
;
158 int width
= _chatmsg_box
.width
;
159 int height
= _chatmsg_box
.height
;
161 height
= max(height
+ y
, min(_chatmsg_box
.height
, _screen
.height
));
164 if (x
+ width
>= _screen
.width
) {
165 width
= _screen
.width
- x
;
167 if (width
<= 0 || height
<= 0) return;
169 _chatmessage_visible
= false;
170 /* Put our 'shot' back to the screen */
171 blitter
->CopyFromBuffer(blitter
->MoveTo(_screen
.dst_ptr
, x
, y
), _chatmessage_backup
, width
, height
);
172 /* And make sure it is updated next time */
173 VideoDriver::GetInstance()->MakeDirty(x
, y
, width
, height
);
175 _chatmessage_dirty
= true;
179 /** Check if a message is expired. */
180 void NetworkChatMessageLoop()
182 for (uint i
= 0; i
< MAX_CHAT_MESSAGES
; i
++) {
183 ChatMessage
*cmsg
= &_chatmsg_list
[i
];
184 if (cmsg
->message
[0] == '\0') continue;
186 /* Message has expired, remove from the list */
187 if (cmsg
->remove_time
< _realtime_tick
) {
188 /* Move the remaining messages over the current message */
189 if (i
!= MAX_CHAT_MESSAGES
- 1) memmove(cmsg
, cmsg
+ 1, sizeof(*cmsg
) * (MAX_CHAT_MESSAGES
- i
- 1));
191 /* Mark the last item as empty */
192 _chatmsg_list
[MAX_CHAT_MESSAGES
- 1].message
[0] = '\0';
193 _chatmessage_dirty
= true;
195 /* Go one item back, because we moved the array 1 to the left */
201 /** Draw the chat message-box */
202 void NetworkDrawChatMessage()
204 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
205 if (!_chatmessage_dirty
) return;
207 /* First undraw if needed */
208 NetworkUndrawChatMessage();
210 if (_iconsole_mode
== ICONSOLE_FULL
) return;
212 /* Check if we have anything to draw at all */
213 uint count
= GetChatMessageCount();
214 if (count
== 0) return;
216 int x
= _chatmsg_box
.x
;
217 int y
= _screen
.height
- _chatmsg_box
.y
- _chatmsg_box
.height
;
218 int width
= _chatmsg_box
.width
;
219 int height
= _chatmsg_box
.height
;
221 height
= max(height
+ y
, min(_chatmsg_box
.height
, _screen
.height
));
224 if (x
+ width
>= _screen
.width
) {
225 width
= _screen
.width
- x
;
227 if (width
<= 0 || height
<= 0) return;
229 assert(blitter
->BufferSize(width
, height
) <= (int)(_chatmsg_box
.width
* _chatmsg_box
.height
* blitter
->GetBytesPerPixel()));
231 /* Make a copy of the screen as it is before painting (for undraw) */
232 blitter
->CopyToBuffer(blitter
->MoveTo(_screen
.dst_ptr
, x
, y
), _chatmessage_backup
, width
, height
);
234 _cur_dpi
= &_screen
; // switch to _screen painting
236 int string_height
= 0;
237 for (uint i
= 0; i
< count
; i
++) {
238 SetDParamStr(0, _chatmsg_list
[i
].message
);
239 string_height
+= GetStringLineCount(STR_JUST_RAW_STRING
, width
- 1) * FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
;
242 string_height
= min(string_height
, MAX_CHAT_MESSAGES
* (FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
));
244 int top
= _screen
.height
- _chatmsg_box
.y
- string_height
- 2;
245 int bottom
= _screen
.height
- _chatmsg_box
.y
- 2;
246 /* Paint a half-transparent box behind the chat messages */
247 GfxFillRect(_chatmsg_box
.x
, top
- 2, _chatmsg_box
.x
+ _chatmsg_box
.width
- 1, bottom
,
248 PALETTE_TO_TRANSPARENT
, FILLRECT_RECOLOUR
// black, but with some alpha for background
251 /* Paint the chat messages starting with the lowest at the bottom */
252 int ypos
= bottom
- 2;
254 for (int i
= count
- 1; i
>= 0; i
--) {
255 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
;
256 if (ypos
< top
) break;
259 /* Make sure the data is updated next flush */
260 VideoDriver::GetInstance()->MakeDirty(x
, y
, width
, height
);
262 _chatmessage_visible
= true;
263 _chatmessage_dirty
= false;
267 * Send an actual chat message.
268 * @param buf The message to send.
269 * @param type The type of destination.
270 * @param dest The actual destination index.
272 static void SendChat(const char *buf
, DestType type
, int dest
)
274 if (StrEmpty(buf
)) return;
275 if (!_network_server
) {
276 MyClient::SendChat((NetworkAction
)(NETWORK_ACTION_CHAT
+ type
), type
, dest
, buf
, 0);
278 NetworkServerSendChat((NetworkAction
)(NETWORK_ACTION_CHAT
+ type
), type
, dest
, buf
, CLIENT_ID_SERVER
);
282 /** Window to enter the chat message in. */
283 struct NetworkChatWindow
: public Window
{
284 DestType dtype
; ///< The type of destination.
285 StringID dest_string
; ///< String representation of the destination.
286 int dest
; ///< The identifier of the destination.
287 QueryString message_editbox
; ///< Message editbox.
290 * Create a chat input window.
291 * @param desc Description of the looks of the window.
292 * @param type The type of destination.
293 * @param dest The actual destination index.
295 NetworkChatWindow(WindowDesc
*desc
, DestType type
, int dest
) : Window(desc
), message_editbox(NETWORK_CHAT_LENGTH
)
299 this->querystrings
[WID_NC_TEXTBOX
] = &this->message_editbox
;
300 this->message_editbox
.cancel_button
= WID_NC_CLOSE
;
301 this->message_editbox
.ok_button
= WID_NC_SENDBUTTON
;
303 static const StringID chat_captions
[] = {
304 STR_NETWORK_CHAT_ALL_CAPTION
,
305 STR_NETWORK_CHAT_COMPANY_CAPTION
,
306 STR_NETWORK_CHAT_CLIENT_CAPTION
308 assert((uint
)this->dtype
< lengthof(chat_captions
));
309 this->dest_string
= chat_captions
[this->dtype
];
311 this->InitNested(type
);
313 this->SetFocusedWidget(WID_NC_TEXTBOX
);
314 InvalidateWindowData(WC_NEWS_WINDOW
, 0, this->height
);
315 _chat_tab_completion_active
= false;
317 PositionNetworkChatWindow(this);
322 InvalidateWindowData(WC_NEWS_WINDOW
, 0, 0);
325 virtual void FindWindowPlacementAndResize(int def_width
, int def_height
)
327 Window::FindWindowPlacementAndResize(_toolbar_width
, def_height
);
331 * Find the next item of the list of things that can be auto-completed.
332 * @param item The current indexed item to return. This function can, and most
333 * likely will, alter item, to skip empty items in the arrays.
334 * @return Returns the char that matched to the index.
336 const char *ChatTabCompletionNextItem(uint
*item
)
338 static char chat_tab_temp_buffer
[64];
340 /* First, try clients */
341 if (*item
< MAX_CLIENT_SLOTS
) {
342 /* Skip inactive clients */
343 NetworkClientInfo
*ci
;
344 FOR_ALL_CLIENT_INFOS_FROM(ci
, *item
) {
346 return ci
->client_name
;
348 *item
= MAX_CLIENT_SLOTS
;
351 /* Then, try townnames
352 * Not that the following assumes all town indices are adjacent, ie no
353 * towns have been deleted. */
354 if (*item
< (uint
)MAX_CLIENT_SLOTS
+ Town::GetPoolSize()) {
357 FOR_ALL_TOWNS_FROM(t
, *item
- MAX_CLIENT_SLOTS
) {
358 /* Get the town-name via the string-system */
359 SetDParam(0, t
->index
);
360 GetString(chat_tab_temp_buffer
, STR_TOWN_NAME
, lastof(chat_tab_temp_buffer
));
361 return &chat_tab_temp_buffer
[0];
369 * Find what text to complete. It scans for a space from the left and marks
370 * the word right from that as to complete. It also writes a \0 at the
371 * position of the space (if any). If nothing found, buf is returned.
373 static char *ChatTabCompletionFindText(char *buf
)
375 char *p
= strrchr(buf
, ' ');
376 if (p
== NULL
) return buf
;
383 * See if we can auto-complete the current text of the user.
385 void ChatTabCompletion()
387 static char _chat_tab_completion_buf
[NETWORK_CHAT_LENGTH
];
388 assert(this->message_editbox
.text
.max_bytes
== lengthof(_chat_tab_completion_buf
));
390 Textbuf
*tb
= &this->message_editbox
.text
;
393 char *tb_buf
, *pre_buf
;
394 const char *cur_name
;
395 bool second_scan
= false;
399 /* Copy the buffer so we can modify it without damaging the real data */
400 pre_buf
= (_chat_tab_completion_active
) ? stredup(_chat_tab_completion_buf
) : stredup(tb
->buf
);
402 tb_buf
= ChatTabCompletionFindText(pre_buf
);
403 tb_len
= strlen(tb_buf
);
405 while ((cur_name
= ChatTabCompletionNextItem(&item
)) != NULL
) {
408 if (_chat_tab_completion_active
) {
409 /* We are pressing TAB again on the same name, is there another name
410 * that starts with this? */
415 /* If we are completing at the begin of the line, skip the ': ' we added */
416 if (tb_buf
== pre_buf
) {
418 length
= (tb
->bytes
- 1) - 2;
420 /* Else, find the place we are completing at */
421 offset
= strlen(pre_buf
) + 1;
422 length
= (tb
->bytes
- 1) - offset
;
425 /* Compare if we have a match */
426 if (strlen(cur_name
) == length
&& strncmp(cur_name
, tb
->buf
+ offset
, length
) == 0) second_scan
= true;
431 /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
434 len
= strlen(cur_name
);
435 if (tb_len
< len
&& strncasecmp(cur_name
, tb_buf
, tb_len
) == 0) {
436 /* Save the data it was before completion */
437 if (!second_scan
) seprintf(_chat_tab_completion_buf
, lastof(_chat_tab_completion_buf
), "%s", tb
->buf
);
438 _chat_tab_completion_active
= true;
440 /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
441 if (pre_buf
== tb_buf
) {
442 this->message_editbox
.text
.Print("%s: ", cur_name
);
444 this->message_editbox
.text
.Print("%s %s", pre_buf
, cur_name
);
454 /* We walked all possibilities, and the user presses tab again.. revert to original text */
455 this->message_editbox
.text
.Assign(_chat_tab_completion_buf
);
456 _chat_tab_completion_active
= false;
463 virtual Point
OnInitialPosition(int16 sm_width
, int16 sm_height
, int window_number
)
465 Point pt
= { 0, _screen
.height
- sm_height
- FindWindowById(WC_STATUS_BAR
, 0)->height
};
469 virtual void UpdateWidgetSize(int widget
, Dimension
*size
, const Dimension
&padding
, Dimension
*fill
, Dimension
*resize
)
471 if (widget
!= WID_NC_DESTINATION
) return;
473 if (this->dtype
== DESTTYPE_CLIENT
) {
474 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID
)this->dest
)->client_name
);
476 Dimension d
= GetStringBoundingBox(this->dest_string
);
477 d
.width
+= WD_FRAMERECT_LEFT
+ WD_FRAMERECT_RIGHT
;
478 d
.height
+= WD_FRAMERECT_TOP
+ WD_FRAMERECT_BOTTOM
;
479 *size
= maxdim(*size
, d
);
482 virtual void DrawWidget(const Rect
&r
, int widget
) const
484 if (widget
!= WID_NC_DESTINATION
) return;
486 if (this->dtype
== DESTTYPE_CLIENT
) {
487 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID
)this->dest
)->client_name
);
489 DrawString(r
.left
+ WD_FRAMERECT_LEFT
, r
.right
- WD_FRAMERECT_RIGHT
, r
.top
+ WD_FRAMERECT_TOP
, this->dest_string
, TC_BLACK
, SA_RIGHT
);
492 virtual void OnClick(Point pt
, int widget
, int click_count
)
495 case WID_NC_SENDBUTTON
: /* Send */
496 SendChat(this->message_editbox
.text
.buf
, this->dtype
, this->dest
);
499 case WID_NC_CLOSE
: /* Cancel */
505 virtual EventState
OnKeyPress(WChar key
, uint16 keycode
)
507 EventState state
= ES_NOT_HANDLED
;
508 if (keycode
== WKC_TAB
) {
515 virtual void OnEditboxChanged(int wid
)
517 _chat_tab_completion_active
= false;
521 * Some data on this window has become invalid.
522 * @param data Information about the changed data.
523 * @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.
525 virtual void OnInvalidateData(int data
= 0, bool gui_scope
= true)
527 if (data
== this->dest
) delete this;
531 /** The widgets of the chat window. */
532 static const NWidgetPart _nested_chat_window_widgets
[] = {
533 NWidget(NWID_HORIZONTAL
),
534 NWidget(WWT_CLOSEBOX
, COLOUR_GREY
, WID_NC_CLOSE
),
535 NWidget(WWT_PANEL
, COLOUR_GREY
, WID_NC_BACKGROUND
),
536 NWidget(NWID_HORIZONTAL
),
537 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_NC_DESTINATION
), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NULL
, STR_NULL
),
538 NWidget(WWT_EDITBOX
, COLOUR_GREY
, WID_NC_TEXTBOX
), SetMinimalSize(100, 12), SetPadding(1, 0, 1, 0), SetResize(1, 0),
539 SetDataTip(STR_NETWORK_CHAT_OSKTITLE
, STR_NULL
),
540 NWidget(WWT_PUSHTXTBTN
, COLOUR_GREY
, WID_NC_SENDBUTTON
), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NETWORK_CHAT_SEND
, STR_NULL
),
546 /** The description of the chat window. */
547 static WindowDesc
_chat_window_desc(
548 WDP_MANUAL
, NULL
, 0, 0,
549 WC_SEND_NETWORK_MSG
, WC_NONE
,
551 _nested_chat_window_widgets
, lengthof(_nested_chat_window_widgets
)
556 * Show the chat window.
557 * @param type The type of destination.
558 * @param dest The actual destination index.
560 void ShowNetworkChatQueryWindow(DestType type
, int dest
)
562 DeleteWindowByClass(WC_SEND_NETWORK_MSG
);
563 new NetworkChatWindow(&_chat_window_desc
, type
, dest
);
566 #endif /* ENABLE_NETWORK */