network_chat_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include <stdarg.h> /* va_list */
00013 
00014 #ifdef ENABLE_NETWORK
00015 
00016 #include "../stdafx.h"
00017 #include "../gfx_func.h"
00018 #include "../strings_func.h"
00019 #include "../blitter/factory.hpp"
00020 #include "../console_func.h"
00021 #include "../video/video_driver.hpp"
00022 #include "../table/sprites.h"
00023 #include "../querystring_gui.h"
00024 #include "../town.h"
00025 #include "../window_func.h"
00026 #include "../core/geometry_func.hpp"
00027 #include "network.h"
00028 #include "network_client.h"
00029 #include "network_base.h"
00030 
00031 #include "../widgets/network_chat_widget.h"
00032 
00033 #include "table/strings.h"
00034 
00037 assert_compile((int)DRAW_STRING_BUFFER >= (int)NETWORK_CHAT_LENGTH + NETWORK_NAME_LENGTH + 40);
00038 
00040 static const uint NETWORK_CHAT_LINE_SPACING = 3;
00041 
00043 struct ChatMessage {
00044   char message[DRAW_STRING_BUFFER]; 
00045   TextColour colour;  
00046   uint32 remove_time; 
00047 };
00048 
00049 /* used for chat window */
00050 static ChatMessage *_chatmsg_list = NULL; 
00051 static bool _chatmessage_dirty = false;   
00052 static bool _chatmessage_visible = false; 
00053 static bool _chat_tab_completion_active;  
00054 static uint MAX_CHAT_MESSAGES = 0;        
00055 
00060 static PointDimension _chatmsg_box;
00061 static uint8 *_chatmessage_backup = NULL; 
00062 
00067 static inline uint GetChatMessageCount()
00068 {
00069   uint i = 0;
00070   for (; i < MAX_CHAT_MESSAGES; i++) {
00071     if (_chatmsg_list[i].message[0] == '\0') break;
00072   }
00073 
00074   return i;
00075 }
00076 
00083 void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message, ...)
00084 {
00085   char buf[DRAW_STRING_BUFFER];
00086   const char *bufp;
00087   va_list va;
00088   uint msg_count;
00089   uint16 lines;
00090 
00091   va_start(va, message);
00092   vsnprintf(buf, lengthof(buf), message, va);
00093   va_end(va);
00094 
00095   Utf8TrimString(buf, DRAW_STRING_BUFFER);
00096 
00097   /* Force linebreaks for strings that are too long */
00098   lines = GB(FormatStringLinebreaks(buf, lastof(buf), _chatmsg_box.width - 8), 0, 16) + 1;
00099   if (lines >= MAX_CHAT_MESSAGES) return;
00100 
00101   msg_count = GetChatMessageCount();
00102   /* We want to add more chat messages than there is free space for, remove 'old' */
00103   if (lines > MAX_CHAT_MESSAGES - msg_count) {
00104     int i = lines - (MAX_CHAT_MESSAGES - msg_count);
00105     memmove(&_chatmsg_list[0], &_chatmsg_list[i], sizeof(_chatmsg_list[0]) * (msg_count - i));
00106     msg_count = MAX_CHAT_MESSAGES - lines;
00107   }
00108 
00109   for (bufp = buf; lines != 0; lines--) {
00110     ChatMessage *cmsg = &_chatmsg_list[msg_count++];
00111     strecpy(cmsg->message, bufp, lastof(cmsg->message));
00112 
00113     /* The default colour for a message is company colour. Replace this with
00114      * white for any additional lines */
00115     cmsg->colour = (bufp == buf && (colour & TC_IS_PALETTE_COLOUR)) ? colour : TC_WHITE;
00116     cmsg->remove_time = _realtime_tick + duration * 1000;
00117 
00118     bufp += strlen(bufp) + 1; // jump to 'next line' in the formatted string
00119   }
00120 
00121   _chatmessage_dirty = true;
00122 }
00123 
00125 void NetworkReInitChatBoxSize()
00126 {
00127   _chatmsg_box.y       = 3 * FONT_HEIGHT_NORMAL;
00128   _chatmsg_box.height  = MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING) + 2;
00129   _chatmessage_backup  = ReallocT(_chatmessage_backup, _chatmsg_box.width * _chatmsg_box.height * BlitterFactoryBase::GetCurrentBlitter()->GetBytesPerPixel());
00130 }
00131 
00133 void NetworkInitChatMessage()
00134 {
00135   MAX_CHAT_MESSAGES    = _settings_client.gui.network_chat_box_height;
00136 
00137   _chatmsg_list        = ReallocT(_chatmsg_list, _settings_client.gui.network_chat_box_height);
00138   _chatmsg_box.x       = 10;
00139   _chatmsg_box.width   = _settings_client.gui.network_chat_box_width;
00140   NetworkReInitChatBoxSize();
00141   _chatmessage_visible = false;
00142 
00143   for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
00144     _chatmsg_list[i].message[0] = '\0';
00145   }
00146 }
00147 
00149 void NetworkUndrawChatMessage()
00150 {
00151   /* Sometimes we also need to hide the cursor
00152    *   This is because both textmessage and the cursor take a shot of the
00153    *   screen before drawing.
00154    *   Now the textmessage takes his shot and paints his data before the cursor
00155    *   does, so in the shot of the cursor is the screen-data of the textmessage
00156    *   included when the cursor hangs somewhere over the textmessage. To
00157    *   avoid wrong repaints, we undraw the cursor in that case, and everything
00158    *   looks nicely ;)
00159    * (and now hope this story above makes sense to you ;))
00160    */
00161   if (_cursor.visible &&
00162       _cursor.draw_pos.x + _cursor.draw_size.x >= _chatmsg_box.x &&
00163       _cursor.draw_pos.x <= _chatmsg_box.x + _chatmsg_box.width &&
00164       _cursor.draw_pos.y + _cursor.draw_size.y >= _screen.height - _chatmsg_box.y - _chatmsg_box.height &&
00165       _cursor.draw_pos.y <= _screen.height - _chatmsg_box.y) {
00166     UndrawMouseCursor();
00167   }
00168 
00169   if (_chatmessage_visible) {
00170     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00171     int x      = _chatmsg_box.x;
00172     int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
00173     int width  = _chatmsg_box.width;
00174     int height = _chatmsg_box.height;
00175     if (y < 0) {
00176       height = max(height + y, min(_chatmsg_box.height, _screen.height));
00177       y = 0;
00178     }
00179     if (x + width >= _screen.width) {
00180       width = _screen.width - x;
00181     }
00182     if (width <= 0 || height <= 0) return;
00183 
00184     _chatmessage_visible = false;
00185     /* Put our 'shot' back to the screen */
00186     blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
00187     /* And make sure it is updated next time */
00188     _video_driver->MakeDirty(x, y, width, height);
00189 
00190     _chatmessage_dirty = true;
00191   }
00192 }
00193 
00195 void NetworkChatMessageLoop()
00196 {
00197   for (uint i = 0; i < MAX_CHAT_MESSAGES; i++) {
00198     ChatMessage *cmsg = &_chatmsg_list[i];
00199     if (cmsg->message[0] == '\0') continue;
00200 
00201     /* Message has expired, remove from the list */
00202     if (cmsg->remove_time < _realtime_tick) {
00203       /* Move the remaining messages over the current message */
00204       if (i != MAX_CHAT_MESSAGES - 1) memmove(cmsg, cmsg + 1, sizeof(*cmsg) * (MAX_CHAT_MESSAGES - i - 1));
00205 
00206       /* Mark the last item as empty */
00207       _chatmsg_list[MAX_CHAT_MESSAGES - 1].message[0] = '\0';
00208       _chatmessage_dirty = true;
00209 
00210       /* Go one item back, because we moved the array 1 to the left */
00211       i--;
00212     }
00213   }
00214 }
00215 
00217 void NetworkDrawChatMessage()
00218 {
00219   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00220   if (!_chatmessage_dirty) return;
00221 
00222   /* First undraw if needed */
00223   NetworkUndrawChatMessage();
00224 
00225   if (_iconsole_mode == ICONSOLE_FULL) return;
00226 
00227   /* Check if we have anything to draw at all */
00228   uint count = GetChatMessageCount();
00229   if (count == 0) return;
00230 
00231   int x      = _chatmsg_box.x;
00232   int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
00233   int width  = _chatmsg_box.width;
00234   int height = _chatmsg_box.height;
00235   if (y < 0) {
00236     height = max(height + y, min(_chatmsg_box.height, _screen.height));
00237     y = 0;
00238   }
00239   if (x + width >= _screen.width) {
00240     width = _screen.width - x;
00241   }
00242   if (width <= 0 || height <= 0) return;
00243 
00244   assert(blitter->BufferSize(width, height) <= (int)(_chatmsg_box.width * _chatmsg_box.height * blitter->GetBytesPerPixel()));
00245 
00246   /* Make a copy of the screen as it is before painting (for undraw) */
00247   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, x, y), _chatmessage_backup, width, height);
00248 
00249   _cur_dpi = &_screen; // switch to _screen painting
00250 
00251   /* Paint a half-transparent box behind the chat messages */
00252   GfxFillRect(
00253       _chatmsg_box.x,
00254       _screen.height - _chatmsg_box.y - count * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING) - 2,
00255       _chatmsg_box.x + _chatmsg_box.width - 1,
00256       _screen.height - _chatmsg_box.y - 2,
00257       PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
00258     );
00259 
00260   /* Paint the chat messages starting with the lowest at the bottom */
00261   for (uint y = FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING; count-- != 0; y += (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING)) {
00262     DrawString(_chatmsg_box.x + 3, _chatmsg_box.x + _chatmsg_box.width - 1, _screen.height - _chatmsg_box.y - y + 1, _chatmsg_list[count].message, _chatmsg_list[count].colour);
00263   }
00264 
00265   /* Make sure the data is updated next flush */
00266   _video_driver->MakeDirty(x, y, width, height);
00267 
00268   _chatmessage_visible = true;
00269   _chatmessage_dirty = false;
00270 }
00271 
00278 static void SendChat(const char *buf, DestType type, int dest)
00279 {
00280   if (StrEmpty(buf)) return;
00281   if (!_network_server) {
00282     MyClient::SendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, 0);
00283   } else {
00284     NetworkServerSendChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, CLIENT_ID_SERVER);
00285   }
00286 }
00287 
00289 struct NetworkChatWindow : public QueryStringBaseWindow {
00290   DestType dtype;       
00291   StringID dest_string; 
00292   int dest;             
00293 
00300   NetworkChatWindow(const WindowDesc *desc, DestType type, int dest) : QueryStringBaseWindow(NETWORK_CHAT_LENGTH)
00301   {
00302     this->dtype   = type;
00303     this->dest    = dest;
00304     this->afilter = CS_ALPHANUMERAL;
00305     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size);
00306 
00307     static const StringID chat_captions[] = {
00308       STR_NETWORK_CHAT_ALL_CAPTION,
00309       STR_NETWORK_CHAT_COMPANY_CAPTION,
00310       STR_NETWORK_CHAT_CLIENT_CAPTION
00311     };
00312     assert((uint)this->dtype < lengthof(chat_captions));
00313     this->dest_string = chat_captions[this->dtype];
00314 
00315     this->InitNested(desc, type);
00316 
00317     this->SetFocusedWidget(WID_NC_TEXTBOX);
00318     InvalidateWindowData(WC_NEWS_WINDOW, 0, this->height);
00319     _chat_tab_completion_active = false;
00320 
00321     PositionNetworkChatWindow(this);
00322   }
00323 
00324   ~NetworkChatWindow()
00325   {
00326     InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
00327   }
00328 
00335   const char *ChatTabCompletionNextItem(uint *item)
00336   {
00337     static char chat_tab_temp_buffer[64];
00338 
00339     /* First, try clients */
00340     if (*item < MAX_CLIENT_SLOTS) {
00341       /* Skip inactive clients */
00342       NetworkClientInfo *ci;
00343       FOR_ALL_CLIENT_INFOS_FROM(ci, *item) {
00344         *item = ci->index;
00345         return ci->client_name;
00346       }
00347       *item = MAX_CLIENT_SLOTS;
00348     }
00349 
00350     /* Then, try townnames
00351      * Not that the following assumes all town indices are adjacent, ie no
00352      * towns have been deleted. */
00353     if (*item < (uint)MAX_CLIENT_SLOTS + Town::GetPoolSize()) {
00354       const Town *t;
00355 
00356       FOR_ALL_TOWNS_FROM(t, *item - MAX_CLIENT_SLOTS) {
00357         /* Get the town-name via the string-system */
00358         SetDParam(0, t->index);
00359         GetString(chat_tab_temp_buffer, STR_TOWN_NAME, lastof(chat_tab_temp_buffer));
00360         return &chat_tab_temp_buffer[0];
00361       }
00362     }
00363 
00364     return NULL;
00365   }
00366 
00372   static char *ChatTabCompletionFindText(char *buf)
00373   {
00374     char *p = strrchr(buf, ' ');
00375     if (p == NULL) return buf;
00376 
00377     *p = '\0';
00378     return p + 1;
00379   }
00380 
00384   void ChatTabCompletion()
00385   {
00386     static char _chat_tab_completion_buf[NETWORK_CHAT_LENGTH];
00387     assert(this->edit_str_size == lengthof(_chat_tab_completion_buf));
00388 
00389     Textbuf *tb = &this->text;
00390     size_t len, tb_len;
00391     uint item;
00392     char *tb_buf, *pre_buf;
00393     const char *cur_name;
00394     bool second_scan = false;
00395 
00396     item = 0;
00397 
00398     /* Copy the buffer so we can modify it without damaging the real data */
00399     pre_buf = (_chat_tab_completion_active) ? strdup(_chat_tab_completion_buf) : strdup(tb->buf);
00400 
00401     tb_buf  = ChatTabCompletionFindText(pre_buf);
00402     tb_len  = strlen(tb_buf);
00403 
00404     while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
00405       item++;
00406 
00407       if (_chat_tab_completion_active) {
00408         /* We are pressing TAB again on the same name, is there another name
00409          *  that starts with this? */
00410         if (!second_scan) {
00411           size_t offset;
00412           size_t length;
00413 
00414           /* If we are completing at the begin of the line, skip the ': ' we added */
00415           if (tb_buf == pre_buf) {
00416             offset = 0;
00417             length = (tb->bytes - 1) - 2;
00418           } else {
00419             /* Else, find the place we are completing at */
00420             offset = strlen(pre_buf) + 1;
00421             length = (tb->bytes - 1) - offset;
00422           }
00423 
00424           /* Compare if we have a match */
00425           if (strlen(cur_name) == length && strncmp(cur_name, tb->buf + offset, length) == 0) second_scan = true;
00426 
00427           continue;
00428         }
00429 
00430         /* Now any match we make on _chat_tab_completion_buf after this, is perfect */
00431       }
00432 
00433       len = strlen(cur_name);
00434       if (tb_len < len && strncasecmp(cur_name, tb_buf, tb_len) == 0) {
00435         /* Save the data it was before completion */
00436         if (!second_scan) snprintf(_chat_tab_completion_buf, lengthof(_chat_tab_completion_buf), "%s", tb->buf);
00437         _chat_tab_completion_active = true;
00438 
00439         /* Change to the found name. Add ': ' if we are at the start of the line (pretty) */
00440         if (pre_buf == tb_buf) {
00441           snprintf(tb->buf, this->edit_str_size, "%s: ", cur_name);
00442         } else {
00443           snprintf(tb->buf, this->edit_str_size, "%s %s", pre_buf, cur_name);
00444         }
00445 
00446         /* Update the textbuffer */
00447         UpdateTextBufferSize(&this->text);
00448 
00449         this->SetDirty();
00450         free(pre_buf);
00451         return;
00452       }
00453     }
00454 
00455     if (second_scan) {
00456       /* We walked all posibilities, and the user presses tab again.. revert to original text */
00457       strcpy(tb->buf, _chat_tab_completion_buf);
00458       _chat_tab_completion_active = false;
00459 
00460       /* Update the textbuffer */
00461       UpdateTextBufferSize(&this->text);
00462 
00463       this->SetDirty();
00464     }
00465     free(pre_buf);
00466   }
00467 
00468   virtual void OnPaint()
00469   {
00470     this->DrawWidgets();
00471     this->DrawEditBox(WID_NC_TEXTBOX);
00472   }
00473 
00474   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
00475   {
00476     Point pt = { 0, _screen.height - sm_height - FindWindowById(WC_STATUS_BAR, 0)->height };
00477     return pt;
00478   }
00479 
00480   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00481   {
00482     if (widget != WID_NC_DESTINATION) return;
00483 
00484     if (this->dtype == DESTTYPE_CLIENT) {
00485       SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
00486     }
00487     Dimension d = GetStringBoundingBox(this->dest_string);
00488     d.width  += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00489     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00490     *size = maxdim(*size, d);
00491   }
00492 
00493   virtual void DrawWidget(const Rect &r, int widget) const
00494   {
00495     if (widget != WID_NC_DESTINATION) return;
00496 
00497     if (this->dtype == DESTTYPE_CLIENT) {
00498       SetDParamStr(0, NetworkClientInfo::GetByClientID((ClientID)this->dest)->client_name);
00499     }
00500     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, this->dest_string, TC_BLACK, SA_RIGHT);
00501   }
00502 
00503   virtual void OnClick(Point pt, int widget, int click_count)
00504   {
00505     switch (widget) {
00506       /* Send */
00507       case WID_NC_SENDBUTTON: SendChat(this->text.buf, this->dtype, this->dest);
00508         /* FALL THROUGH */
00509       case WID_NC_CLOSE: /* Cancel */ delete this; break;
00510     }
00511   }
00512 
00513   virtual void OnMouseLoop()
00514   {
00515     this->HandleEditBox(WID_NC_TEXTBOX);
00516   }
00517 
00518   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
00519   {
00520     EventState state = ES_NOT_HANDLED;
00521     if (keycode == WKC_TAB) {
00522       ChatTabCompletion();
00523       state = ES_HANDLED;
00524     } else {
00525       _chat_tab_completion_active = false;
00526       switch (this->HandleEditBoxKey(WID_NC_TEXTBOX, key, keycode, state)) {
00527         default: NOT_REACHED();
00528         case HEBR_EDITING: {
00529           Window *osk = FindWindowById(WC_OSK, 0);
00530           if (osk != NULL && osk->parent == this) osk->InvalidateData();
00531           break;
00532         }
00533         case HEBR_CONFIRM:
00534           SendChat(this->text.buf, this->dtype, this->dest);
00535           /* FALL THROUGH */
00536         case HEBR_CANCEL: delete this; break;
00537         case HEBR_NOT_FOCUSED: break;
00538       }
00539     }
00540     return state;
00541   }
00542 
00543   virtual void OnOpenOSKWindow(int wid)
00544   {
00545     ShowOnScreenKeyboard(this, wid, WID_NC_CLOSE, WID_NC_SENDBUTTON);
00546   }
00547 
00553   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00554   {
00555     if (data == this->dest) delete this;
00556   }
00557 };
00558 
00560 static const NWidgetPart _nested_chat_window_widgets[] = {
00561   NWidget(NWID_HORIZONTAL),
00562     NWidget(WWT_CLOSEBOX, COLOUR_GREY, WID_NC_CLOSE),
00563     NWidget(WWT_PANEL, COLOUR_GREY, WID_NC_BACKGROUND),
00564       NWidget(NWID_HORIZONTAL),
00565         NWidget(WWT_TEXT, COLOUR_GREY, WID_NC_DESTINATION), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NULL, STR_NULL),
00566         NWidget(WWT_EDITBOX, COLOUR_GREY, WID_NC_TEXTBOX), SetMinimalSize(100, 12), SetPadding(1, 0, 1, 0), SetResize(1, 0),
00567                                   SetDataTip(STR_NETWORK_CHAT_OSKTITLE, STR_NULL),
00568         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NC_SENDBUTTON), SetMinimalSize(62, 12), SetPadding(1, 0, 1, 0), SetDataTip(STR_NETWORK_CHAT_SEND, STR_NULL),
00569       EndContainer(),
00570     EndContainer(),
00571   EndContainer(),
00572 };
00573 
00575 static const WindowDesc _chat_window_desc(
00576   WDP_MANUAL, 640, 14, // x, y, width, height
00577   WC_SEND_NETWORK_MSG, WC_NONE,
00578   0,
00579   _nested_chat_window_widgets, lengthof(_nested_chat_window_widgets)
00580 );
00581 
00582 
00588 void ShowNetworkChatQueryWindow(DestType type, int dest)
00589 {
00590   DeleteWindowByClass(WC_SEND_NETWORK_MSG);
00591   new NetworkChatWindow(&_chat_window_desc, type, dest);
00592 }
00593 
00594 #endif /* ENABLE_NETWORK */