network_chat_gui.cpp

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

Generated on Sat Jul 31 21:37:48 2010 for OpenTTD by  doxygen 1.6.1