network_chat_gui.cpp

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

Generated on Fri Feb 4 20:53:42 2011 for OpenTTD by  doxygen 1.6.1