network_chat_gui.cpp

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

Generated on Wed Mar 3 23:32:22 2010 for OpenTTD by  doxygen 1.6.1