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

Generated on Sun Jun 5 04:19:58 2011 for OpenTTD by  doxygen 1.6.1