# network_chat_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: network_chat_gui.cpp 15723 2009-03-15 15:12:06Z rubidium $ */
    00002
    00005 #include <stdarg.h> /* va_list */
    00006
    00007 #ifdef ENABLE_NETWORK
    00008
    00009 #include "../stdafx.h"
    00010 #include "../date_func.h"
    00011 #include "../gfx_func.h"
    00012 #include "../strings_func.h"
    00013 #include "../blitter/factory.hpp"
    00014 #include "../console_func.h"
    00015 #include "../video/video_driver.hpp"
    00016 #include "../table/sprites.h"
    00017 #include "../querystring_gui.h"
    00018 #include "../town.h"
    00019 #include "../window_func.h"
    00020 #include "network_internal.h"
    00021 #include "network_client.h"
    00022
    00023 #include "table/strings.h"
    00024
    00025 /* The draw buffer must be able to contain the chat message, client name and the "[All]" message,
    00026  * some spaces and possible translations of [All] to other languages. */
    00027 assert_compile((int)DRAW_STRING_BUFFER >= (int)NETWORK_CHAT_LENGTH + NETWORK_NAME_LENGTH + 40);
    00028
    00029 enum {
    00030   NETWORK_CHAT_LINE_HEIGHT = 13,
    00031 };
    00032
    00033 struct ChatMessage {
    00034   char message[DRAW_STRING_BUFFER];
    00035   TextColour colour;
    00036   Date end_date;
    00037 };
    00038
    00039 /* used for chat window */
    00040 static ChatMessage *_chatmsg_list = NULL;
    00041 static bool _chatmessage_dirty = false;
    00042 static bool _chatmessage_visible = false;
    00043 static bool _chat_tab_completion_active;
    00044 static uint MAX_CHAT_MESSAGES = 0;
    00045
    00046 /* The chatbox grows from the bottom so the coordinates are pixels from
    00047  * the left and pixels from the bottom. The height is the maximum height */
    00048 static PointDimension _chatmsg_box;
    00049 static uint8 *_chatmessage_backup = NULL;
    00050
    00051 static inline uint GetChatMessageCount()
    00052 {
    00053   uint i = 0;
    00054   for (; i < MAX_CHAT_MESSAGES; i++) {
    00055     if (_chatmsg_list[i].message[0] == '\0') break;
    00056   }
    00057
    00058   return i;
    00059 }
    00060
    00067 void CDECL NetworkAddChatMessage(TextColour colour, uint8 duration, const char *message, ...)
    00068 {
    00069   char buf[DRAW_STRING_BUFFER];
    00070   const char *bufp;
    00071   va_list va;
    00072   uint msg_count;
    00073   uint16 lines;
    00074
    00075   va_start(va, message);
    00076   vsnprintf(buf, lengthof(buf), message, va);
    00077   va_end(va);
    00078
    00079   Utf8TrimString(buf, DRAW_STRING_BUFFER);
    00080
    00081   /* Force linebreaks for strings that are too long */
    00082   lines = GB(FormatStringLinebreaks(buf, _chatmsg_box.width - 8), 0, 16) + 1;
    00083   if (lines >= MAX_CHAT_MESSAGES) return;
    00084
    00085   msg_count = GetChatMessageCount();
    00086   /* We want to add more chat messages than there is free space for, remove 'old' */
    00087   if (lines > MAX_CHAT_MESSAGES - msg_count) {
    00088     int i = lines - (MAX_CHAT_MESSAGES - msg_count);
    00089     memmove(&_chatmsg_list[0], &_chatmsg_list[i], sizeof(_chatmsg_list[0]) * (msg_count - i));
    00090     msg_count = MAX_CHAT_MESSAGES - lines;
    00091   }
    00092
    00093   for (bufp = buf; lines != 0; lines--) {
    00094     ChatMessage *cmsg = &_chatmsg_list[msg_count++];
    00095     strecpy(cmsg->message, bufp, lastof(cmsg->message));
    00096
    00097     /* The default colour for a message is company colour. Replace this with
    00098      * white for any additional lines */
    00099     cmsg->colour = (bufp == buf && colour & IS_PALETTE_COLOUR) ? colour : TC_WHITE;
    00100     cmsg->end_date = _date + duration;
    00101
    00102     bufp += strlen(bufp) + 1; // jump to 'next line' in the formatted string
    00103   }
    00104
    00105   _chatmessage_dirty = true;
    00106 }
    00107
    00108 void NetworkInitChatMessage()
    00109 {
    00110   MAX_CHAT_MESSAGES   = _settings_client.gui.network_chat_box_height;
    00111
    00112   _chatmsg_list       = ReallocT(_chatmsg_list, _settings_client.gui.network_chat_box_height);
    00113   _chatmsg_box.x      = 10;
    00114   _chatmsg_box.y      = 30;
    00115   _chatmsg_box.width  = _settings_client.gui.network_chat_box_width;
    00116   _chatmsg_box.height = _settings_client.gui.network_chat_box_height * NETWORK_CHAT_LINE_HEIGHT + 2;
    00117   _chatmessage_backup = ReallocT(_chatmessage_backup, _chatmsg_box.width * _chatmsg_box.height * BlitterFactoryBase::GetCurrentBlitter()->GetBytesPerPixel());
    00118
    00119   for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
    00120     _chatmsg_list[i].message[0] = '\0';
    00121   }
    00122 }
    00123
    00125 void NetworkUndrawChatMessage()
    00126 {
    00127   if (_chatmessage_visible) {
    00128     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00129     /* Sometimes we also need to hide the cursor
    00130      *   This is because both textmessage and the cursor take a shot of the
    00131      *   screen before drawing.
    00132      *   Now the textmessage takes his shot and paints his data before the cursor
    00133      *   does, so in the shot of the cursor is the screen-data of the textmessage
    00134      *   included when the cursor hangs somewhere over the textmessage. To
    00135      *   avoid wrong repaints, we undraw the cursor in that case, and everything
    00136      *   looks nicely ;)
    00137      * (and now hope this story above makes sense to you ;))
    00138      */
    00139
    00140     if (_cursor.visible) {
    00141       if (_cursor.draw_pos.x + _cursor.draw_size.x >= _chatmsg_box.x &&
    00142         _cursor.draw_pos.x <= _chatmsg_box.x + _chatmsg_box.width &&
    00143         _cursor.draw_pos.y + _cursor.draw_size.y >= _screen.height - _chatmsg_box.y - _chatmsg_box.height &&
    00144         _cursor.draw_pos.y <= _screen.height - _chatmsg_box.y) {
    00145         UndrawMouseCursor();
    00146       }
    00147     }
    00148
    00149     int x      = _chatmsg_box.x;
    00150     int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
    00151     int width  = _chatmsg_box.width;
    00152     int height = _chatmsg_box.height;
    00153     if (y < 0) {
    00154       height = max(height + y, min(_chatmsg_box.height, _screen.height));
    00155       y = 0;
    00156     }
    00157     if (x + width >= _screen.width) {
    00158       width = _screen.width - x;
    00159     }
    00160     if (width <= 0 || height <= 0) return;
    00161
    00162     _chatmessage_visible = false;
    00163     /* Put our 'shot' back to the screen */
    00164     blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
    00165     /* And make sure it is updated next time */
    00166     _video_driver->MakeDirty(x, y, width, height);
    00167
    00168     _chatmessage_dirty = true;
    00169   }
    00170 }
    00171
    00173 void NetworkChatMessageDailyLoop()
    00174 {
    00175   for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
    00176     ChatMessage *cmsg = &_chatmsg_list[i];
    00177     if (cmsg->message[0] == '\0') continue;
    00178
    00179     /* Message has expired, remove from the list */
    00180     if (cmsg->end_date < _date) {
    00181       /* Move the remaining messages over the current message */
    00182       if (i != MAX_CHAT_MESSAGES - 1) memmove(cmsg, cmsg + 1, sizeof(*cmsg) * (MAX_CHAT_MESSAGES - i - 1));
    00183
    00184       /* Mark the last item as empty */
    00185       _chatmsg_list[MAX_CHAT_MESSAGES - 1].message[0] = '\0';
    00186       _chatmessage_dirty = true;
    00187
    00188       /* Go one item back, because we moved the array 1 to the left */
    00189       i--;
    00190     }
    00191   }
    00192 }
    00193
    00195 void NetworkDrawChatMessage()
    00196 {
    00197   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00198   if (!_chatmessage_dirty) return;
    00199
    00200   /* First undraw if needed */
    00201   NetworkUndrawChatMessage();
    00202
    00203   if (_iconsole_mode == ICONSOLE_FULL) return;
    00204
    00205   /* Check if we have anything to draw at all */
    00206   uint count = GetChatMessageCount();
    00207   if (count == 0) return;
    00208
    00209   int x      = _chatmsg_box.x;
    00210   int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
    00211   int width  = _chatmsg_box.width;
    00212   int height = _chatmsg_box.height;
    00213   if (y < 0) {
    00214     height = max(height + y, min(_chatmsg_box.height, _screen.height));
    00215     y = 0;
    00216   }
    00217   if (x + width >= _screen.width) {
    00218     width = _screen.width - x;
    00219   }
    00220   if (width <= 0 || height <= 0) return;
    00221
    00222   assert(blitter->BufferSize(width, height) <= (int)(_chatmsg_box.width * _chatmsg_box.height * blitter->GetBytesPerPixel()));
    00223
    00224   /* Make a copy of the screen as it is before painting (for undraw) */
    00225   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
    00226
    00227   _cur_dpi = &_screen; // switch to _screen painting
    00228
    00229   /* Paint a half-transparent box behind the chat messages */
    00230   GfxFillRect(
    00231       _chatmsg_box.x,
    00232       _screen.height - _chatmsg_box.y - count * NETWORK_CHAT_LINE_HEIGHT - 2,
    00233       _chatmsg_box.x + _chatmsg_box.width - 1,
    00234       _screen.height - _chatmsg_box.y - 2,
    00235       PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
    00236     );
    00237
    00238   /* Paint the chat messages starting with the lowest at the bottom */
    00239   for (uint y = NETWORK_CHAT_LINE_HEIGHT; count-- != 0; y += NETWORK_CHAT_LINE_HEIGHT) {
    00240     DoDrawString(_chatmsg_list[count].message, _chatmsg_box.x + 3, _screen.height - _chatmsg_box.y - y + 1, _chatmsg_list[count].colour);
    00241   }
    00242
    00243   /* Make sure the data is updated next flush */
    00244   _video_driver->MakeDirty(x, y, width, height);
    00245
    00246   _chatmessage_visible = true;
    00247   _chatmessage_dirty = false;
    00248 }
    00249
    00250
    00251 static void SendChat(const char *buf, DestType type, int dest)
    00252 {
    00253   if (StrEmpty(buf)) return;
    00254   if (!_network_server) {
    00255     SEND_COMMAND(PACKET_CLIENT_CHAT)((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0);
    00256   } else {
    00257     NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER);
    00258   }
    00259 }
    00260
    00261 struct NetworkChatWindow : public QueryStringBaseWindow {
    00262 private:
    00263   enum NetWorkChatWidgets {
    00264     NWCW_CLOSE,
    00265     NWCW_BACKGROUND,
    00266     NWCW_TEXTBOX,
    00267     NWCW_SENDBUTTON,
    00268   };
    00269
    00270 public:
    00271   DestType dtype;
    00272   int dest;
    00273
    00274   NetworkChatWindow (const WindowDesc *desc, DestType type, int dest) : QueryStringBaseWindow(NETWORK_CHAT_LENGTH, desc)
    00275   {
    00276     this->LowerWidget(NWCW_TEXTBOX);
    00277     this->dtype   = type;
    00278     this->dest    = dest;
    00279     this->afilter = CS_ALPHANUMERAL;
    00280     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 0);
    00281     this->SetFocusedWidget(NWCW_TEXTBOX);
    00282
    00283     InvalidateWindowData(WC_NEWS_WINDOW, 0, this->height);
    00284
    00285     _chat_tab_completion_active = false;
    00286
    00287     this->FindWindowPlacementAndResize(desc);
    00288   }
    00289
    00290   ~NetworkChatWindow ()
    00291   {
    00292     InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
    00293   }
    00294
    00301   const char *ChatTabCompletionNextItem(uint *item)
    00302   {
    00303     static char chat_tab_temp_buffer[64];
    00304
    00305     /* First, try clients */
    00306     if (*item < MAX_CLIENT_SLOTS) {
    00307       if (*item < GetNetworkClientInfoPoolSize()) {
    00308         /* Skip inactive clients */
    00309         NetworkClientInfo *ci;
    00310         FOR_ALL_CLIENT_INFOS_FROM(ci, *item) break;
    00311         if (ci != NULL) {
    00312           *item = ci->index;
    00313           return ci->client_name;
    00314         }
    00315       }
    00316       *item = MAX_CLIENT_SLOTS;
    00317     }
    00318
    00319     /* Then, try townnames
    00320      * Not that the following assumes all town indices are adjacent, ie no
    00321      * towns have been deleted. */
    00322     if (*item <= (uint)MAX_CLIENT_SLOTS + GetMaxTownIndex()) {
    00323       const Town *t;
    00324
    00325       FOR_ALL_TOWNS_FROM(t, *item - MAX_CLIENT_SLOTS) {
    00326         /* Get the town-name via the string-system */
    00327         SetDParam(0, t->index);
    00328         GetString(chat_tab_temp_buffer, STR_TOWN, lastof(chat_tab_temp_buffer));
    00329         return &chat_tab_temp_buffer[0];
    00330       }
    00331     }
    00332
    00333     return NULL;
    00334   }
    00335
    00341   static char *ChatTabCompletionFindText(char *buf)
    00342   {
    00343     char *p = strrchr(buf, ' ');
    00344     if (p == NULL) return buf;
    00345
    00346     *p = '\0';
    00347     return p + 1;
    00348   }
    00349
    00353   void ChatTabCompletion()
    00354   {
    00355     static char _chat_tab_completion_buf[NETWORK_CHAT_LENGTH];
    00356     assert(this->edit_str_size == lengthof(_chat_tab_completion_buf));
    00357
    00358     Textbuf *tb = &this->text;
    00359     size_t len, tb_len;
    00360     uint item;
    00361     char *tb_buf, *pre_buf;
    00362     const char *cur_name;
    00363     bool second_scan = false;
    00364
    00365     item = 0;
    00366
    00367     /* Copy the buffer so we can modify it without damaging the real data */
    00368     pre_buf = (_chat_tab_completion_active) ? strdup(_chat_tab_completion_buf) : strdup(tb->buf);
    00369
    00370     tb_buf  = ChatTabCompletionFindText(pre_buf);
    00371     tb_len  = strlen(tb_buf);
    00372
    00373     while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
    00374       item++;
    00375
    00376       if (_chat_tab_completion_active) {
    00377         /* We are pressing TAB again on the same name, is there an other name
    00378          *  that starts with this? */
    00379         if (!second_scan) {
    00380           size_t offset;
    00381           size_t length;
    00382
    00383           /* If we are completing at the begin of the line, skip the ': ' we added */
    00384           if (tb_buf == pre_buf) {
    00385             offset = 0;
    00386             length = (tb->size - 1) - 2;
    00387           } else {
    00388             /* Else, find the place we are completing at */
    00389             offset = strlen(pre_buf) + 1;
    00390             length = (tb->size - 1) - offset;
    00391           }
    00392
    00393           /* Compare if we have a match */
    00394           if (strlen(cur_name) == length && strncmp(cur_name, tb->buf + offset, length) == 0) second_scan = true;
    00395
    00396           continue;
    00397         }
    00398
    00399         /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
    00400       }
    00401
    00402       len = strlen(cur_name);
    00403       if (tb_len < len && strncasecmp(cur_name, tb_buf, tb_len) == 0) {
    00404         /* Save the data it was before completion */
    00405         if (!second_scan) snprintf(_chat_tab_completion_buf, lengthof(_chat_tab_completion_buf), "%s", tb->buf);
    00406         _chat_tab_completion_active = true;
    00407
    00408         /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
    00409         if (pre_buf == tb_buf) {
    00410           snprintf(tb->buf, this->edit_str_size, "%s: ", cur_name);
    00411         } else {
    00412           snprintf(tb->buf, this->edit_str_size, "%s %s", pre_buf, cur_name);
    00413         }
    00414
    00415         /* Update the textbuffer */
    00416         UpdateTextBufferSize(&this->text);
    00417
    00418         this->SetDirty();
    00419         free(pre_buf);
    00420         return;
    00421       }
    00422     }
    00423
    00424     if (second_scan) {
    00425       /* We walked all posibilities, and the user presses tab again.. revert to original text */
    00426       strcpy(tb->buf, _chat_tab_completion_buf);
    00427       _chat_tab_completion_active = false;
    00428
    00429       /* Update the textbuffer */
    00430       UpdateTextBufferSize(&this->text);
    00431
    00432       this->SetDirty();
    00433     }
    00434     free(pre_buf);
    00435   }
    00436
    00437   virtual void OnPaint()
    00438   {
    00439     static const StringID chat_captions[] = {
    00440       STR_NETWORK_CHAT_ALL_CAPTION,
    00441       STR_NETWORK_CHAT_COMPANY_CAPTION,
    00442       STR_NETWORK_CHAT_CLIENT_CAPTION
    00443     };
    00444
    00445     this->DrawWidgets();
    00446
    00447     assert((uint)this->dtype < lengthof(chat_captions));
    00448     DrawStringRightAligned(this->widget[NWCW_TEXTBOX].left - 2, this->widget[NWCW_TEXTBOX].top + 1, chat_captions[this->dtype], TC_BLACK);
    00449     this->DrawEditBox(NWCW_TEXTBOX);
    00450   }
    00451
    00452   virtual void OnClick(Point pt, int widget)
    00453   {
    00454     switch (widget) {
    00455       /* Send */
    00456       case NWCW_SENDBUTTON: SendChat(this->text.buf, this->dtype, this->dest);
    00457       /* FALLTHROUGH */
    00458       case NWCW_CLOSE: /* Cancel */ delete this; break;
    00459     }
    00460   }
    00461
    00462   virtual void OnMouseLoop()
    00463   {
    00464     this->HandleEditBox(NWCW_TEXTBOX);
    00465   }
    00466
    00467   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
    00468   {
    00469     EventState state = ES_NOT_HANDLED;
    00470     if (keycode == WKC_TAB) {
    00471       ChatTabCompletion();
    00472     } else {
    00473       _chat_tab_completion_active = false;
    00474       switch (this->HandleEditBoxKey(NWCW_TEXTBOX, key, keycode, state)) {
    00475         default: NOT_REACHED();
    00476         case HEBR_EDITING: {
    00477           Window *osk = FindWindowById(WC_OSK, 0);
    00478           if (osk != NULL && osk->parent == this) osk->OnInvalidateData();
    00479         } break;
    00480         case HEBR_CONFIRM:
    00481           SendChat(this->text.buf, this->dtype, this->dest);
    00482         /* FALLTHROUGH */
    00483         case HEBR_CANCEL: delete this; break;
    00484         case HEBR_NOT_FOCUSED: break;
    00485       }
    00486     }
    00487     return state;
    00488   }
    00489
    00490   virtual void OnOpenOSKWindow(int wid)
    00491   {
    00492     ShowOnScreenKeyboard(this, wid, 0, 3);
    00493   }
    00494 };
    00495
    00496 static const Widget _chat_window_widgets[] = {
    00497 {   WWT_CLOSEBOX, RESIZE_NONE,   COLOUR_GREY,   0,  10,  0, 13, STR_00C5,                  STR_018B_CLOSE_WINDOW},
    00498 {      WWT_PANEL, RESIZE_RIGHT,  COLOUR_GREY,  11, 319,  0, 13, 0x0,                       STR_NULL}, // background
    00499 {    WWT_EDITBOX, RESIZE_RIGHT,  COLOUR_GREY,  75, 257,  1, 12, STR_NETWORK_CHAT_OSKTITLE, STR_NULL}, // text box
    00500 { WWT_PUSHTXTBTN, RESIZE_LR,     COLOUR_GREY, 258, 319,  1, 12, STR_NETWORK_SEND,          STR_NULL}, // send button
    00501 {   WIDGETS_END},
    00502 };
    00503
    00504 static const WindowDesc _chat_window_desc(
    00505   WDP_CENTER, -26, 320, 14, 640, 14, // x, y, width, height
    00506   WC_SEND_NETWORK_MSG, WC_NONE,
    00507   WDF_STD_TOOLTIPS | WDF_DEF_WIDGET,
    00508   _chat_window_widgets
    00509 );
    00510
    00511 void ShowNetworkChatQueryWindow(DestType type, int dest)
    00512 {
    00513   DeleteWindowById(WC_SEND_NETWORK_MSG, 0);
    00514   new NetworkChatWindow (&_chat_window_desc, type, dest);
    00515 }
    00516
    00517 #endif /* ENABLE_NETWORK */