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"
18 #include "../string.h"
19 #include "../strings_func.h"
20 #include "../blitter/blitter.h"
21 #include "../console_func.h"
22 #include "../video/video_driver.hpp"
23 #include "../querystring_gui.h"
25 #include "../window_func.h"
26 #include "../toolbar_gui.h"
27 #include "../core/geometry_func.hpp"
29 #include "network_client.h"
30 #include "network_base.h"
32 #include "../widgets/network_chat_widget.h"
34 #include "table/strings.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 const int _chatmsg_box_x
= 10;
62 static int _chatmsg_box_y
, _chatmsg_box_width
, _chatmsg_box_height
;
63 static Blitter::Buffer _chatmessage_backup
; ///< Backup in case text is moved.
66 * Count the chat messages.
67 * @return The number of chat messages.
69 static inline uint
GetChatMessageCount()
72 for (; i
< MAX_CHAT_MESSAGES
; i
++) {
73 if (_chatmsg_list
[i
].message
[0] == '\0') break;
80 * Add a text message to the 'chat window' to be shown
81 * @param colour The colour this message is to be shown in
82 * @param duration The duration of the chat message in seconds
83 * @param message message itself in printf() style
85 void CDECL
NetworkAddChatMessage(TextColour colour
, uint duration
, const char *message
, ...)
89 uint msg_count
= GetChatMessageCount();
90 if (MAX_CHAT_MESSAGES
== msg_count
) {
91 memmove(&_chatmsg_list
[0], &_chatmsg_list
[1], sizeof(_chatmsg_list
[0]) * (msg_count
- 1));
92 msg_count
= MAX_CHAT_MESSAGES
- 1;
95 ChatMessage
*cmsg
= &_chatmsg_list
[msg_count
++];
97 va_start(va
, message
);
98 bstrvfmt (cmsg
->message
, message
, va
);
100 Utf8TrimString (cmsg
->message
, lengthof(cmsg
->message
));
102 cmsg
->colour
= (colour
& TC_IS_PALETTE_COLOUR
) ? colour
: TC_WHITE
;
103 cmsg
->remove_time
= _realtime_tick
+ duration
* 1000;
105 _chatmessage_dirty
= true;
108 /** Initialize all font-dependent chat box sizes. */
109 void NetworkReInitChatBoxSize()
111 _chatmsg_box_y
= 3 * FONT_HEIGHT_NORMAL
;
112 _chatmsg_box_height
= MAX_CHAT_MESSAGES
* (FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
) + 2;
113 _screen_surface
->copy (&_chatmessage_backup
, -1, -1, _chatmsg_box_width
, _chatmsg_box_height
);
116 /** Initialize all buffers of the chat visualisation. */
117 void NetworkInitChatMessage()
119 MAX_CHAT_MESSAGES
= _settings_client
.gui
.network_chat_box_height
;
121 _chatmsg_list
= xrealloct (_chatmsg_list
, _settings_client
.gui
.network_chat_box_height
);
122 _chatmsg_box_width
= _settings_client
.gui
.network_chat_box_width_pct
* _screen_width
/ 100;
123 NetworkReInitChatBoxSize();
124 _chatmessage_visible
= false;
126 for (uint i
= 0; i
< MAX_CHAT_MESSAGES
; i
++) {
127 _chatmsg_list
[i
].message
[0] = '\0';
131 /** Compute the chat area to copy to/from the blitter buffer. */
132 static inline bool ComputeChatArea (int *px
, int *py
, int *pw
, int *ph
)
134 int y
= _screen_height
- _chatmsg_box_y
- _chatmsg_box_height
;
135 int height
= _chatmsg_box_height
;
137 height
= min (height
, _screen_height
);
140 if (height
<= 0) return false;
144 const int x
= _chatmsg_box_x
;
145 int width
= _chatmsg_box_width
;
146 if (x
+ width
>= _screen_width
) {
147 width
= _screen_width
- x
;
149 if (width
<= 0) return false;
156 /** Hide the chatbox */
157 void NetworkUndrawChatMessage()
159 /* Sometimes we also need to hide the cursor
160 * This is because both textmessage and the cursor take a shot of the
161 * screen before drawing.
162 * Now the textmessage takes his shot and paints his data before the cursor
163 * does, so in the shot of the cursor is the screen-data of the textmessage
164 * included when the cursor hangs somewhere over the textmessage. To
165 * avoid wrong repaints, we undraw the cursor in that case, and everything
167 * (and now hope this story above makes sense to you ;))
169 if (_cursor
.visible
&&
170 _cursor
.draw_pos
.x
+ _cursor
.draw_size
.x
>= _chatmsg_box_x
&&
171 _cursor
.draw_pos
.x
<= _chatmsg_box_x
+ _chatmsg_box_width
&&
172 _cursor
.draw_pos
.y
+ _cursor
.draw_size
.y
>= _screen_height
- _chatmsg_box_y
- _chatmsg_box_height
&&
173 _cursor
.draw_pos
.y
<= _screen_height
- _chatmsg_box_y
) {
177 if (_chatmessage_visible
) {
178 int x
, y
, width
, height
;
179 if (!ComputeChatArea (&x
, &y
, &width
, &height
)) return;
181 _chatmessage_visible
= false;
182 /* Put our 'shot' back to the screen */
183 _screen_surface
->paste (&_chatmessage_backup
, x
, y
);
184 /* And make sure it is updated next time */
185 VideoDriver::GetActiveDriver()->MakeDirty(x
, y
, width
, height
);
187 _chatmessage_dirty
= true;
191 /** Check if a message is expired. */
192 void NetworkChatMessageLoop()
194 for (uint i
= 0; i
< MAX_CHAT_MESSAGES
; i
++) {
195 ChatMessage
*cmsg
= &_chatmsg_list
[i
];
196 if (cmsg
->message
[0] == '\0') continue;
198 /* Message has expired, remove from the list */
199 if (cmsg
->remove_time
< _realtime_tick
) {
200 /* Move the remaining messages over the current message */
201 if (i
!= MAX_CHAT_MESSAGES
- 1) memmove(cmsg
, cmsg
+ 1, sizeof(*cmsg
) * (MAX_CHAT_MESSAGES
- i
- 1));
203 /* Mark the last item as empty */
204 _chatmsg_list
[MAX_CHAT_MESSAGES
- 1].message
[0] = '\0';
205 _chatmessage_dirty
= true;
207 /* Go one item back, because we moved the array 1 to the left */
213 /** Draw the chat message-box */
214 void NetworkDrawChatMessage()
216 if (!_chatmessage_dirty
) return;
218 /* First undraw if needed */
219 NetworkUndrawChatMessage();
221 if (_iconsole_mode
== ICONSOLE_FULL
) return;
223 /* Check if we have anything to draw at all */
224 uint count
= GetChatMessageCount();
225 if (count
== 0) return;
227 int x
, y
, width
, height
;
228 if (!ComputeChatArea (&x
, &y
, &width
, &height
)) return;
230 /* Make a copy of the screen as it is before painting (for undraw) */
231 _screen_surface
->copy (&_chatmessage_backup
, x
, y
, width
, height
);
233 int string_height
= 0;
234 for (uint i
= 0; i
< count
; i
++) {
235 SetDParamStr(0, _chatmsg_list
[i
].message
);
236 string_height
+= GetStringLineCount(STR_JUST_RAW_STRING
, width
- 1) * FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
;
239 string_height
= min(string_height
, MAX_CHAT_MESSAGES
* (FONT_HEIGHT_NORMAL
+ NETWORK_CHAT_LINE_SPACING
));
242 screen
.surface
= _screen_surface
.get();
243 screen
.dst_ptr
= _screen_surface
->ptr
;
244 screen
.left
= screen
.top
= 0;
245 screen
.width
= _screen_width
;
246 screen
.height
= _screen_height
;
248 int bottom
= _screen_height
- _chatmsg_box_y
;
249 int top
= bottom
- string_height
;
250 /* Paint a half-transparent box behind the chat messages */
251 GfxFillRect (&screen
, _chatmsg_box_x
, top
- 2, _chatmsg_box_x
+ _chatmsg_box_width
- 1, bottom
- 1,
252 PALETTE_TO_TRANSPARENT
, FILLRECT_RECOLOUR
// black, but with some alpha for background
255 /* Paint the chat messages starting with the lowest at the bottom */
256 int ypos
= bottom
- 2;
258 for (int i
= count
- 1; i
>= 0; i
--) {
259 ypos
= DrawStringMultiLine (&screen
, _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
;
260 if (ypos
< top
) break;
263 /* Make sure the data is updated next flush */
264 VideoDriver::GetActiveDriver()->MakeDirty(x
, y
, width
, height
);
266 _chatmessage_visible
= true;
267 _chatmessage_dirty
= false;
271 * Send an actual chat message.
272 * @param buf The message to send.
273 * @param type The type of destination.
274 * @param dest The actual destination index.
276 static void SendChat(const char *buf
, DestType type
, int dest
)
278 if (StrEmpty(buf
)) return;
279 if (!_network_server
) {
280 MyClient::SendChat((NetworkAction
)(NETWORK_ACTION_CHAT
+ type
), type
, dest
, buf
, 0);
282 NetworkServerSendChat((NetworkAction
)(NETWORK_ACTION_CHAT
+ type
), type
, dest
, buf
, CLIENT_ID_SERVER
);
286 /** Window to enter the chat message in. */
287 struct NetworkChatWindow
: public Window
{
288 DestType dtype
; ///< The type of destination.
289 StringID dest_string
; ///< String representation of the destination.
290 int dest
; ///< The identifier of the destination.
291 QueryStringN
<NETWORK_CHAT_LENGTH
> message_editbox
; ///< Message editbox.
294 * Create a chat input window.
295 * @param desc Description of the looks of the window.
296 * @param type The type of destination.
297 * @param dest The actual destination index.
299 NetworkChatWindow (const WindowDesc
*desc
, DestType type
, int dest
) :
300 Window (desc
), dtype (type
), dest_string (STR_NULL
),
301 dest (dest
), message_editbox()
303 this->querystrings
[WID_NC_TEXTBOX
] = &this->message_editbox
;
304 this->message_editbox
.cancel_button
= WID_NC_CLOSE
;
305 this->message_editbox
.ok_button
= WID_NC_SENDBUTTON
;
307 static const StringID chat_captions
[] = {
308 STR_NETWORK_CHAT_ALL_CAPTION
,
309 STR_NETWORK_CHAT_COMPANY_CAPTION
,
310 STR_NETWORK_CHAT_CLIENT_CAPTION
312 assert((uint
)this->dtype
< lengthof(chat_captions
));
313 this->dest_string
= chat_captions
[this->dtype
];
315 this->InitNested(type
);
317 this->SetFocusedWidget(WID_NC_TEXTBOX
);
318 InvalidateWindowData(WC_NEWS_WINDOW
, 0, this->height
);
319 _chat_tab_completion_active
= false;
321 PositionNetworkChatWindow(this);
324 void OnDelete (void) FINAL_OVERRIDE
326 InvalidateWindowData(WC_NEWS_WINDOW
, 0, 0);
329 virtual void FindWindowPlacementAndResize(int def_width
, int def_height
)
331 Window::FindWindowPlacementAndResize(_toolbar_width
, def_height
);
335 * Find the next item of the list of things that can be auto-completed.
336 * @param item The current indexed item to return. This function can, and most
337 * likely will, alter item, to skip empty items in the arrays.
338 * @return Returns the char that matched to the index.
340 const char *ChatTabCompletionNextItem(uint
*item
)
342 static char chat_tab_temp_buffer
[64];
344 /* First, try clients */
345 if (*item
< MAX_CLIENT_SLOTS
) {
346 /* Skip inactive clients */
347 NetworkClientInfo
*ci
;
348 FOR_ALL_CLIENT_INFOS_FROM(ci
, *item
) {
350 return ci
->client_name
;
352 *item
= MAX_CLIENT_SLOTS
;
355 /* Then, try townnames
356 * Not that the following assumes all town indices are adjacent, ie no
357 * towns have been deleted. */
358 if (*item
< (uint
)MAX_CLIENT_SLOTS
+ Town::GetPoolSize()) {
361 FOR_ALL_TOWNS_FROM(t
, *item
- MAX_CLIENT_SLOTS
) {
362 /* Get the town-name via the string-system */
363 SetDParam(0, t
->index
);
364 GetString (chat_tab_temp_buffer
, STR_TOWN_NAME
);
365 return &chat_tab_temp_buffer
[0];
373 * Find what text to complete. It scans for a space from the left and marks
374 * the word right from that as to complete. It also writes a \0 at the
375 * position of the space (if any). If nothing found, buf is returned.
377 static char *ChatTabCompletionFindText(char *buf
)
379 char *p
= strrchr(buf
, ' ');
380 if (p
== NULL
) return buf
;
387 * See if we can auto-complete the current text of the user.
389 void ChatTabCompletion()
391 static char _chat_tab_completion_buf
[NETWORK_CHAT_LENGTH
];
392 assert(this->message_editbox
.capacity
== lengthof(_chat_tab_completion_buf
));
394 Textbuf
*tb
= &this->message_editbox
;
397 char *tb_buf
, *pre_buf
;
398 const char *cur_name
;
399 bool second_scan
= false;
403 /* Copy the buffer so we can modify it without damaging the real data */
404 pre_buf
= (_chat_tab_completion_active
) ? xstrdup(_chat_tab_completion_buf
) : xstrdup(tb
->GetText());
406 tb_buf
= ChatTabCompletionFindText(pre_buf
);
407 tb_len
= strlen(tb_buf
);
409 while ((cur_name
= ChatTabCompletionNextItem(&item
)) != NULL
) {
412 if (_chat_tab_completion_active
) {
413 /* We are pressing TAB again on the same name, is there another name
414 * that starts with this? */
419 /* If we are completing at the begin of the line, skip the ': ' we added */
420 if (tb_buf
== pre_buf
) {
422 length
= tb
->length() - 2;
424 /* Else, find the place we are completing at */
425 offset
= strlen(pre_buf
) + 1;
426 length
= tb
->length() - offset
;
429 /* Compare if we have a match */
430 if (strlen(cur_name
) == length
&& strncmp(cur_name
, tb
->GetText() + offset
, length
) == 0) second_scan
= true;
435 /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
438 len
= strlen(cur_name
);
439 if (tb_len
< len
&& strncasecmp(cur_name
, tb_buf
, tb_len
) == 0) {
440 /* Save the data it was before completion */
441 if (!second_scan
) bstrcpy (_chat_tab_completion_buf
, tb
->GetText());
442 _chat_tab_completion_active
= true;
444 /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
445 if (pre_buf
== tb_buf
) {
446 this->message_editbox
.Print("%s: ", cur_name
);
448 this->message_editbox
.Print("%s %s", pre_buf
, cur_name
);
458 /* We walked all possibilities, and the user presses tab again.. revert to original text */
459 this->message_editbox
.Assign(_chat_tab_completion_buf
);
460 _chat_tab_completion_active
= false;
467 virtual Point
OnInitialPosition(int16 sm_width
, int16 sm_height
, int window_number
)
469 Point pt
= { 0, _screen_height
- sm_height
- FindWindowById(WC_STATUS_BAR
, 0)->height
};
473 virtual void UpdateWidgetSize(int widget
, Dimension
*size
, const Dimension
&padding
, Dimension
*fill
, Dimension
*resize
)
475 if (widget
!= WID_NC_DESTINATION
) return;
477 if (this->dtype
== DESTTYPE_CLIENT
) {
478 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID
)this->dest
)->client_name
);
480 Dimension d
= GetStringBoundingBox(this->dest_string
);
481 d
.width
+= WD_FRAMERECT_LEFT
+ WD_FRAMERECT_RIGHT
;
482 d
.height
+= WD_FRAMERECT_TOP
+ WD_FRAMERECT_BOTTOM
;
483 *size
= maxdim(*size
, d
);
486 void DrawWidget (BlitArea
*dpi
, const Rect
&r
, int widget
) const OVERRIDE
488 if (widget
!= WID_NC_DESTINATION
) return;
490 if (this->dtype
== DESTTYPE_CLIENT
) {
491 SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID
)this->dest
)->client_name
);
493 DrawString (dpi
, r
.left
+ WD_FRAMERECT_LEFT
, r
.right
- WD_FRAMERECT_RIGHT
, r
.top
+ WD_FRAMERECT_TOP
, this->dest_string
, TC_BLACK
, SA_RIGHT
);
496 virtual void OnClick(Point pt
, int widget
, int click_count
)
500 case WID_NC_SENDBUTTON
: SendChat(this->message_editbox
.GetText(), this->dtype
, this->dest
);
502 case WID_NC_CLOSE
: /* Cancel */ this->Delete(); break;
506 virtual EventState
OnKeyPress(WChar key
, uint16 keycode
)
508 EventState state
= ES_NOT_HANDLED
;
509 if (keycode
== WKC_TAB
) {
516 virtual void OnEditboxChanged(int wid
)
518 _chat_tab_completion_active
= false;
522 * Some data on this window has become invalid.
523 * @param data Information about the changed data.
524 * @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.
526 virtual void OnInvalidateData(int data
= 0, bool gui_scope
= true)
528 if (data
== this->dest
) this->Delete();
532 /** The widgets of the chat window. */
533 static const NWidgetPart _nested_chat_window_widgets
[] = {
534 NWidget(NWID_HORIZONTAL
),
535 NWidget(WWT_CLOSEBOX
, COLOUR_GREY
, WID_NC_CLOSE
),
536 NWidget(WWT_PANEL
, COLOUR_GREY
, WID_NC_BACKGROUND
),
537 NWidget(NWID_HORIZONTAL
),
538 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_NC_DESTINATION
), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NULL
, STR_NULL
),
539 NWidget(WWT_EDITBOX
, COLOUR_GREY
, WID_NC_TEXTBOX
), SetMinimalSize(100, 12), SetPadding(1, 0, 1, 0), SetResize(1, 0),
540 SetDataTip(STR_NETWORK_CHAT_OSKTITLE
, STR_NULL
),
541 NWidget(WWT_PUSHTXTBTN
, COLOUR_GREY
, WID_NC_SENDBUTTON
), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NETWORK_CHAT_SEND
, STR_NULL
),
547 /** The description of the chat window. */
548 static const WindowDesc
_chat_window_desc(
550 WC_SEND_NETWORK_MSG
, WC_NONE
,
552 _nested_chat_window_widgets
, lengthof(_nested_chat_window_widgets
)
557 * Show the chat window.
558 * @param type The type of destination.
559 * @param dest The actual destination index.
561 void ShowNetworkChatQueryWindow(DestType type
, int dest
)
563 DeleteWindowByClass(WC_SEND_NETWORK_MSG
);
564 new NetworkChatWindow(&_chat_window_desc
, type
, dest
);
567 #endif /* ENABLE_NETWORK */