network_chat_gui.cpp

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

Generated on Sun Jan 9 16:01:56 2011 for OpenTTD by  doxygen 1.6.1