network_chat_gui.cpp

Go to the documentation of this file.
00001 /* $Id: network_chat_gui.cpp 17987 2009-11-06 22:53:21Z 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, lastof(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   /* Sometimes we also need to hide the cursor
00128    *   This is because both textmessage and the cursor take a shot of the
00129    *   screen before drawing.
00130    *   Now the textmessage takes his shot and paints his data before the cursor
00131    *   does, so in the shot of the cursor is the screen-data of the textmessage
00132    *   included when the cursor hangs somewhere over the textmessage. To
00133    *   avoid wrong repaints, we undraw the cursor in that case, and everything
00134    *   looks nicely ;)
00135    * (and now hope this story above makes sense to you ;))
00136    */
00137   if (_cursor.visible &&
00138       _cursor.draw_pos.x + _cursor.draw_size.x >= _chatmsg_box.x &&
00139       _cursor.draw_pos.x <= _chatmsg_box.x + _chatmsg_box.width &&
00140       _cursor.draw_pos.y + _cursor.draw_size.y >= _screen.height - _chatmsg_box.y - _chatmsg_box.height &&
00141       _cursor.draw_pos.y <= _screen.height - _chatmsg_box.y) {
00142     UndrawMouseCursor();
00143   }
00144 
00145   if (_chatmessage_visible) {
00146     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00147     int x      = _chatmsg_box.x;
00148     int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
00149     int width  = _chatmsg_box.width;
00150     int height = _chatmsg_box.height;
00151     if (y < 0) {
00152       height = max(height + y, min(_chatmsg_box.height, _screen.height));
00153       y = 0;
00154     }
00155     if (x + width >= _screen.width) {
00156       width = _screen.width - x;
00157     }
00158     if (width <= 0 || height <= 0) return;
00159 
00160     _chatmessage_visible = false;
00161     /* Put our 'shot' back to the screen */
00162     blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
00163     /* And make sure it is updated next time */
00164     _video_driver->MakeDirty(x, y, width, height);
00165 
00166     _chatmessage_dirty = true;
00167   }
00168 }
00169 
00171 void NetworkChatMessageDailyLoop()
00172 {
00173   for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
00174     ChatMessage *cmsg = &_chatmsg_list[i];
00175     if (cmsg->message[0] == '\0') continue;
00176 
00177     /* Message has expired, remove from the list */
00178     if (cmsg->end_date < _date) {
00179       /* Move the remaining messages over the current message */
00180       if (i != MAX_CHAT_MESSAGES - 1) memmove(cmsg, cmsg + 1, sizeof(*cmsg) * (MAX_CHAT_MESSAGES - i - 1));
00181 
00182       /* Mark the last item as empty */
00183       _chatmsg_list[MAX_CHAT_MESSAGES - 1].message[0] = '\0';
00184       _chatmessage_dirty = true;
00185 
00186       /* Go one item back, because we moved the array 1 to the left */
00187       i--;
00188     }
00189   }
00190 }
00191 
00193 void NetworkDrawChatMessage()
00194 {
00195   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00196   if (!_chatmessage_dirty) return;
00197 
00198   /* First undraw if needed */
00199   NetworkUndrawChatMessage();
00200 
00201   if (_iconsole_mode == ICONSOLE_FULL) return;
00202 
00203   /* Check if we have anything to draw at all */
00204   uint count = GetChatMessageCount();
00205   if (count == 0) return;
00206 
00207   int x      = _chatmsg_box.x;
00208   int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
00209   int width  = _chatmsg_box.width;
00210   int height = _chatmsg_box.height;
00211   if (y < 0) {
00212     height = max(height + y, min(_chatmsg_box.height, _screen.height));
00213     y = 0;
00214   }
00215   if (x + width >= _screen.width) {
00216     width = _screen.width - x;
00217   }
00218   if (width <= 0 || height <= 0) return;
00219 
00220   assert(blitter->BufferSize(width, height) <= (int)(_chatmsg_box.width * _chatmsg_box.height * blitter->GetBytesPerPixel()));
00221 
00222   /* Make a copy of the screen as it is before painting (for undraw) */
00223   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
00224 
00225   _cur_dpi = &_screen; // switch to _screen painting
00226 
00227   /* Paint a half-transparent box behind the chat messages */
00228   GfxFillRect(
00229       _chatmsg_box.x,
00230       _screen.height - _chatmsg_box.y - count * NETWORK_CHAT_LINE_HEIGHT - 2,
00231       _chatmsg_box.x + _chatmsg_box.width - 1,
00232       _screen.height - _chatmsg_box.y - 2,
00233       PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
00234     );
00235 
00236   /* Paint the chat messages starting with the lowest at the bottom */
00237   for (uint y = NETWORK_CHAT_LINE_HEIGHT; count-- != 0; y += NETWORK_CHAT_LINE_HEIGHT) {
00238     DoDrawString(_chatmsg_list[count].message, _chatmsg_box.x + 3, _screen.height - _chatmsg_box.y - y + 1, _chatmsg_list[count].colour);
00239   }
00240 
00241   /* Make sure the data is updated next flush */
00242   _video_driver->MakeDirty(x, y, width, height);
00243 
00244   _chatmessage_visible = true;
00245   _chatmessage_dirty = false;
00246 }
00247 
00248 
00249 static void SendChat(const char *buf, DestType type, int dest)
00250 {
00251   if (StrEmpty(buf)) return;
00252   if (!_network_server) {
00253     SEND_COMMAND(PACKET_CLIENT_CHAT)((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0);
00254   } else {
00255     NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER);
00256   }
00257 }
00258 
00259 struct NetworkChatWindow : public QueryStringBaseWindow {
00260 private:
00261   enum NetWorkChatWidgets {
00262     NWCW_CLOSE,
00263     NWCW_BACKGROUND,
00264     NWCW_TEXTBOX,
00265     NWCW_SENDBUTTON,
00266   };
00267 
00268 public:
00269   DestType dtype;
00270   int dest;
00271 
00272   NetworkChatWindow (const WindowDesc *desc, DestType type, int dest) : QueryStringBaseWindow(NETWORK_CHAT_LENGTH, desc)
00273   {
00274     this->LowerWidget(NWCW_TEXTBOX);
00275     this->dtype   = type;
00276     this->dest    = dest;
00277     this->afilter = CS_ALPHANUMERAL;
00278     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 0);
00279     this->SetFocusedWidget(NWCW_TEXTBOX);
00280 
00281     InvalidateWindowData(WC_NEWS_WINDOW, 0, this->height);
00282 
00283     _chat_tab_completion_active = false;
00284 
00285     this->FindWindowPlacementAndResize(desc);
00286   }
00287 
00288   ~NetworkChatWindow ()
00289   {
00290     InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
00291   }
00292 
00299   const char *ChatTabCompletionNextItem(uint *item)
00300   {
00301     static char chat_tab_temp_buffer[64];
00302 
00303     /* First, try clients */
00304     if (*item < MAX_CLIENT_SLOTS) {
00305       if (*item < GetNetworkClientInfoPoolSize()) {
00306         /* Skip inactive clients */
00307         NetworkClientInfo *ci;
00308         FOR_ALL_CLIENT_INFOS_FROM(ci, *item) break;
00309         if (ci != NULL) {
00310           *item = ci->index;
00311           return ci->client_name;
00312         }
00313       }
00314       *item = MAX_CLIENT_SLOTS;
00315     }
00316 
00317     /* Then, try townnames
00318      * Not that the following assumes all town indices are adjacent, ie no
00319      * towns have been deleted. */
00320     if (*item <= (uint)MAX_CLIENT_SLOTS + GetMaxTownIndex()) {
00321       const Town *t;
00322 
00323       FOR_ALL_TOWNS_FROM(t, *item - MAX_CLIENT_SLOTS) {
00324         /* Get the town-name via the string-system */
00325         SetDParam(0, t->index);
00326         GetString(chat_tab_temp_buffer, STR_TOWN, lastof(chat_tab_temp_buffer));
00327         return &chat_tab_temp_buffer[0];
00328       }
00329     }
00330 
00331     return NULL;
00332   }
00333 
00339   static char *ChatTabCompletionFindText(char *buf)
00340   {
00341     char *p = strrchr(buf, ' ');
00342     if (p == NULL) return buf;
00343 
00344     *p = '\0';
00345     return p + 1;
00346   }
00347 
00351   void ChatTabCompletion()
00352   {
00353     static char _chat_tab_completion_buf[NETWORK_CHAT_LENGTH];
00354     assert(this->edit_str_size == lengthof(_chat_tab_completion_buf));
00355 
00356     Textbuf *tb = &this->text;
00357     size_t len, tb_len;
00358     uint item;
00359     char *tb_buf, *pre_buf;
00360     const char *cur_name;
00361     bool second_scan = false;
00362 
00363     item = 0;
00364 
00365     /* Copy the buffer so we can modify it without damaging the real data */
00366     pre_buf = (_chat_tab_completion_active) ? strdup(_chat_tab_completion_buf) : strdup(tb->buf);
00367 
00368     tb_buf  = ChatTabCompletionFindText(pre_buf);
00369     tb_len  = strlen(tb_buf);
00370 
00371     while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
00372       item++;
00373 
00374       if (_chat_tab_completion_active) {
00375         /* We are pressing TAB again on the same name, is there an other name
00376          *  that starts with this? */
00377         if (!second_scan) {
00378           size_t offset;
00379           size_t length;
00380 
00381           /* If we are completing at the begin of the line, skip the ': ' we added */
00382           if (tb_buf == pre_buf) {
00383             offset = 0;
00384             length = (tb->size - 1) - 2;
00385           } else {
00386             /* Else, find the place we are completing at */
00387             offset = strlen(pre_buf) + 1;
00388             length = (tb->size - 1) - offset;
00389           }
00390 
00391           /* Compare if we have a match */
00392           if (strlen(cur_name) == length && strncmp(cur_name, tb->buf + offset, length) == 0) second_scan = true;
00393 
00394           continue;
00395         }
00396 
00397         /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
00398       }
00399 
00400       len = strlen(cur_name);
00401       if (tb_len < len && strncasecmp(cur_name, tb_buf, tb_len) == 0) {
00402         /* Save the data it was before completion */
00403         if (!second_scan) snprintf(_chat_tab_completion_buf, lengthof(_chat_tab_completion_buf), "%s", tb->buf);
00404         _chat_tab_completion_active = true;
00405 
00406         /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
00407         if (pre_buf == tb_buf) {
00408           snprintf(tb->buf, this->edit_str_size, "%s: ", cur_name);
00409         } else {
00410           snprintf(tb->buf, this->edit_str_size, "%s %s", pre_buf, cur_name);
00411         }
00412 
00413         /* Update the textbuffer */
00414         UpdateTextBufferSize(&this->text);
00415 
00416         this->SetDirty();
00417         free(pre_buf);
00418         return;
00419       }
00420     }
00421 
00422     if (second_scan) {
00423       /* We walked all posibilities, and the user presses tab again.. revert to original text */
00424       strcpy(tb->buf, _chat_tab_completion_buf);
00425       _chat_tab_completion_active = false;
00426 
00427       /* Update the textbuffer */
00428       UpdateTextBufferSize(&this->text);
00429 
00430       this->SetDirty();
00431     }
00432     free(pre_buf);
00433   }
00434 
00435   virtual void OnPaint()
00436   {
00437     static const StringID chat_captions[] = {
00438       STR_NETWORK_CHAT_ALL_CAPTION,
00439       STR_NETWORK_CHAT_COMPANY_CAPTION,
00440       STR_NETWORK_CHAT_CLIENT_CAPTION
00441     };
00442 
00443     this->DrawWidgets();
00444 
00445     assert((uint)this->dtype < lengthof(chat_captions));
00446     DrawStringRightAligned(this->widget[NWCW_TEXTBOX].left - 2, this->widget[NWCW_TEXTBOX].top + 1, chat_captions[this->dtype], TC_BLACK);
00447     this->DrawEditBox(NWCW_TEXTBOX);
00448   }
00449 
00450   virtual void OnClick(Point pt, int widget)
00451   {
00452     switch (widget) {
00453       /* Send */
00454       case NWCW_SENDBUTTON: SendChat(this->text.buf, this->dtype, this->dest);
00455       /* FALLTHROUGH */
00456       case NWCW_CLOSE: /* Cancel */ delete this; break;
00457     }
00458   }
00459 
00460   virtual void OnMouseLoop()
00461   {
00462     this->HandleEditBox(NWCW_TEXTBOX);
00463   }
00464 
00465   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
00466   {
00467     EventState state = ES_NOT_HANDLED;
00468     if (keycode == WKC_TAB) {
00469       ChatTabCompletion();
00470       state = ES_HANDLED;
00471     } else {
00472       _chat_tab_completion_active = false;
00473       switch (this->HandleEditBoxKey(NWCW_TEXTBOX, key, keycode, state)) {
00474         default: NOT_REACHED();
00475         case HEBR_EDITING: {
00476           Window *osk = FindWindowById(WC_OSK, 0);
00477           if (osk != NULL && osk->parent == this) osk->OnInvalidateData();
00478         } break;
00479         case HEBR_CONFIRM:
00480           SendChat(this->text.buf, this->dtype, this->dest);
00481         /* FALLTHROUGH */
00482         case HEBR_CANCEL: delete this; break;
00483         case HEBR_NOT_FOCUSED: break;
00484       }
00485     }
00486     return state;
00487   }
00488 
00489   virtual void OnOpenOSKWindow(int wid)
00490   {
00491     ShowOnScreenKeyboard(this, wid, 0, 3);
00492   }
00493 };
00494 
00495 static const Widget _chat_window_widgets[] = {
00496 {   WWT_CLOSEBOX, RESIZE_NONE,   COLOUR_GREY,   0,  10,  0, 13, STR_00C5,                  STR_018B_CLOSE_WINDOW},
00497 {      WWT_PANEL, RESIZE_RIGHT,  COLOUR_GREY,  11, 319,  0, 13, 0x0,                       STR_NULL}, // background
00498 {    WWT_EDITBOX, RESIZE_RIGHT,  COLOUR_GREY,  75, 257,  1, 12, STR_NETWORK_CHAT_OSKTITLE, STR_NULL}, // text box
00499 { WWT_PUSHTXTBTN, RESIZE_LR,     COLOUR_GREY, 258, 319,  1, 12, STR_NETWORK_SEND,          STR_NULL}, // send button
00500 {   WIDGETS_END},
00501 };
00502 
00503 static const WindowDesc _chat_window_desc(
00504   WDP_CENTER, -26, 320, 14, 640, 14, // x, y, width, height
00505   WC_SEND_NETWORK_MSG, WC_NONE,
00506   WDF_STD_TOOLTIPS | WDF_DEF_WIDGET,
00507   _chat_window_widgets
00508 );
00509 
00510 void ShowNetworkChatQueryWindow(DestType type, int dest)
00511 {
00512   DeleteWindowById(WC_SEND_NETWORK_MSG, 0);
00513   new NetworkChatWindow (&_chat_window_desc, type, dest);
00514 }
00515 
00516 #endif /* ENABLE_NETWORK */

Generated on Mon Dec 14 21:00:00 2009 for OpenTTD by  doxygen 1.5.6