PageRenderTime 83ms CodeModel.GetById 14ms app.highlight 61ms RepoModel.GetById 1ms app.codeStats 0ms

/indra/newview/llnearbychatbar.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 672 lines | 474 code | 108 blank | 90 comment | 79 complexity | ac98df0e205fcf5ed55d4eec63a405e9 MD5 | raw file
  1/** 
  2 * @file llnearbychatbar.cpp
  3 * @brief LLNearbyChatBar class implementation
  4 *
  5 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
  6 * Second Life Viewer Source Code
  7 * Copyright (C) 2010, Linden Research, Inc.
  8 * 
  9 * This library is free software; you can redistribute it and/or
 10 * modify it under the terms of the GNU Lesser General Public
 11 * License as published by the Free Software Foundation;
 12 * version 2.1 of the License only.
 13 * 
 14 * This library is distributed in the hope that it will be useful,
 15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 17 * Lesser General Public License for more details.
 18 * 
 19 * You should have received a copy of the GNU Lesser General Public
 20 * License along with this library; if not, write to the Free Software
 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 22 * 
 23 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 24 * $/LicenseInfo$
 25 */
 26
 27#include "llviewerprecompiledheaders.h"
 28
 29#include "message.h"
 30
 31#include "llappviewer.h"
 32#include "llfloaterreg.h"
 33#include "lltrans.h"
 34
 35#include "llfirstuse.h"
 36#include "llnearbychatbar.h"
 37#include "llagent.h"
 38#include "llgesturemgr.h"
 39#include "llmultigesture.h"
 40#include "llkeyboard.h"
 41#include "llanimationstates.h"
 42#include "llviewerstats.h"
 43#include "llcommandhandler.h"
 44#include "llviewercontrol.h"
 45#include "llnavigationbar.h"
 46#include "llwindow.h"
 47#include "llviewerwindow.h"
 48#include "llrootview.h"
 49#include "llviewerchat.h"
 50#include "llnearbychat.h"
 51#include "lltranslate.h"
 52
 53#include "llresizehandle.h"
 54
 55S32 LLNearbyChatBar::sLastSpecialChatChannel = 0;
 56
 57const S32 EXPANDED_HEIGHT = 300;
 58const S32 COLLAPSED_HEIGHT = 60;
 59const S32 EXPANDED_MIN_HEIGHT = 150;
 60
 61// legacy callback glue
 62void send_chat_from_viewer(const std::string& utf8_out_text, EChatType type, S32 channel);
 63
 64struct LLChatTypeTrigger {
 65	std::string name;
 66	EChatType type;
 67};
 68
 69static LLChatTypeTrigger sChatTypeTriggers[] = {
 70	{ "/whisper"	, CHAT_TYPE_WHISPER},
 71	{ "/shout"	, CHAT_TYPE_SHOUT}
 72};
 73
 74LLNearbyChatBar::LLNearbyChatBar(const LLSD& key)
 75:	LLFloater(key),
 76	mChatBox(NULL),
 77	mNearbyChat(NULL),
 78	mOutputMonitor(NULL),
 79	mSpeakerMgr(NULL),
 80	mExpandedHeight(COLLAPSED_HEIGHT + EXPANDED_HEIGHT)
 81{
 82	mSpeakerMgr = LLLocalSpeakerMgr::getInstance();
 83}
 84
 85//virtual
 86BOOL LLNearbyChatBar::postBuild()
 87{
 88	mChatBox = getChild<LLLineEditor>("chat_box");
 89
 90	mChatBox->setCommitCallback(boost::bind(&LLNearbyChatBar::onChatBoxCommit, this));
 91	mChatBox->setKeystrokeCallback(&onChatBoxKeystroke, this);
 92	mChatBox->setFocusLostCallback(boost::bind(&onChatBoxFocusLost, _1, this));
 93	mChatBox->setFocusReceivedCallback(boost::bind(&LLNearbyChatBar::onChatBoxFocusReceived, this));
 94
 95	mChatBox->setIgnoreArrowKeys( FALSE ); 
 96	mChatBox->setCommitOnFocusLost( FALSE );
 97	mChatBox->setRevertOnEsc( FALSE );
 98	mChatBox->setIgnoreTab(TRUE);
 99	mChatBox->setPassDelete(TRUE);
100	mChatBox->setReplaceNewlinesWithSpaces(FALSE);
101	mChatBox->setEnableLineHistory(TRUE);
102	mChatBox->setFont(LLViewerChat::getChatFont());
103
104	mNearbyChat = getChildView("nearby_chat");
105
106	LLUICtrl* show_btn = getChild<LLUICtrl>("show_nearby_chat");
107	show_btn->setCommitCallback(boost::bind(&LLNearbyChatBar::onToggleNearbyChatPanel, this));
108
109	mOutputMonitor = getChild<LLOutputMonitorCtrl>("chat_zone_indicator");
110	mOutputMonitor->setVisible(FALSE);
111
112	gSavedSettings.declareBOOL("nearbychat_history_visibility", mNearbyChat->getVisible(), "Visibility state of nearby chat history", TRUE);
113
114	mNearbyChat->setVisible(gSavedSettings.getBOOL("nearbychat_history_visibility"));
115
116	// Register for font change notifications
117	LLViewerChat::setFontChangedCallback(boost::bind(&LLNearbyChatBar::onChatFontChange, this, _1));
118
119	enableResizeCtrls(true, true, false);
120
121	return TRUE;
122}
123
124// virtual
125void LLNearbyChatBar::onOpen(const LLSD& key)
126{
127	enableTranslationCheckbox(LLTranslate::isTranslationConfigured());
128}
129
130bool LLNearbyChatBar::applyRectControl()
131{
132	bool rect_controlled = LLFloater::applyRectControl();
133
134	if (!mNearbyChat->getVisible())
135	{
136		reshape(getRect().getWidth(), getMinHeight());
137		enableResizeCtrls(true, true, false);
138	}
139	else
140	{
141		enableResizeCtrls(true);
142		setResizeLimits(getMinWidth(), EXPANDED_MIN_HEIGHT);
143	}
144	
145	return rect_controlled;
146}
147
148void LLNearbyChatBar::onChatFontChange(LLFontGL* fontp)
149{
150	// Update things with the new font whohoo
151	if (mChatBox)
152	{
153		mChatBox->setFont(fontp);
154	}
155}
156
157//static
158LLNearbyChatBar* LLNearbyChatBar::getInstance()
159{
160	return LLFloaterReg::getTypedInstance<LLNearbyChatBar>("chat_bar");
161}
162
163void LLNearbyChatBar::showHistory()
164{
165	openFloater();
166
167	if (!getChildView("nearby_chat")->getVisible())
168	{
169		onToggleNearbyChatPanel();
170	}
171}
172
173void LLNearbyChatBar::enableTranslationCheckbox(BOOL enable)
174{
175	getChild<LLUICtrl>("translate_chat_checkbox")->setEnabled(enable);
176}
177
178void LLNearbyChatBar::draw()
179{
180	displaySpeakingIndicator();
181	LLFloater::draw();
182}
183
184std::string LLNearbyChatBar::getCurrentChat()
185{
186	return mChatBox ? mChatBox->getText() : LLStringUtil::null;
187}
188
189// virtual
190BOOL LLNearbyChatBar::handleKeyHere( KEY key, MASK mask )
191{
192	BOOL handled = FALSE;
193
194	if( KEY_RETURN == key && mask == MASK_CONTROL)
195	{
196		// shout
197		sendChat(CHAT_TYPE_SHOUT);
198		handled = TRUE;
199	}
200
201	return handled;
202}
203
204BOOL LLNearbyChatBar::matchChatTypeTrigger(const std::string& in_str, std::string* out_str)
205{
206	U32 in_len = in_str.length();
207	S32 cnt = sizeof(sChatTypeTriggers) / sizeof(*sChatTypeTriggers);
208	
209	for (S32 n = 0; n < cnt; n++)
210	{
211		if (in_len > sChatTypeTriggers[n].name.length())
212			continue;
213
214		std::string trigger_trunc = sChatTypeTriggers[n].name;
215		LLStringUtil::truncate(trigger_trunc, in_len);
216
217		if (!LLStringUtil::compareInsensitive(in_str, trigger_trunc))
218		{
219			*out_str = sChatTypeTriggers[n].name;
220			return TRUE;
221		}
222	}
223
224	return FALSE;
225}
226
227void LLNearbyChatBar::onChatBoxKeystroke(LLLineEditor* caller, void* userdata)
228{
229	LLFirstUse::otherAvatarChatFirst(false);
230
231	LLNearbyChatBar* self = (LLNearbyChatBar *)userdata;
232
233	LLWString raw_text = self->mChatBox->getWText();
234
235	// Can't trim the end, because that will cause autocompletion
236	// to eat trailing spaces that might be part of a gesture.
237	LLWStringUtil::trimHead(raw_text);
238
239	S32 length = raw_text.length();
240
241	if( (length > 0) && (raw_text[0] != '/') )  // forward slash is used for escape (eg. emote) sequences
242	{
243		gAgent.startTyping();
244	}
245	else
246	{
247		gAgent.stopTyping();
248	}
249
250	/* Doesn't work -- can't tell the difference between a backspace
251	   that killed the selection vs. backspace at the end of line.
252	if (length > 1 
253		&& text[0] == '/'
254		&& key == KEY_BACKSPACE)
255	{
256		// the selection will already be deleted, but we need to trim
257		// off the character before
258		std::string new_text = raw_text.substr(0, length-1);
259		self->mInputEditor->setText( new_text );
260		self->mInputEditor->setCursorToEnd();
261		length = length - 1;
262	}
263	*/
264
265	KEY key = gKeyboard->currentKey();
266
267	// Ignore "special" keys, like backspace, arrows, etc.
268	if (length > 1 
269		&& raw_text[0] == '/'
270		&& key < KEY_SPECIAL)
271	{
272		// we're starting a gesture, attempt to autocomplete
273
274		std::string utf8_trigger = wstring_to_utf8str(raw_text);
275		std::string utf8_out_str(utf8_trigger);
276
277		if (LLGestureMgr::instance().matchPrefix(utf8_trigger, &utf8_out_str))
278		{
279			std::string rest_of_match = utf8_out_str.substr(utf8_trigger.size());
280			self->mChatBox->setText(utf8_trigger + rest_of_match); // keep original capitalization for user-entered part
281			S32 outlength = self->mChatBox->getLength(); // in characters
282
283			// Select to end of line, starting from the character
284			// after the last one the user typed.
285			self->mChatBox->setSelection(length, outlength);
286		}
287		else if (matchChatTypeTrigger(utf8_trigger, &utf8_out_str))
288		{
289			std::string rest_of_match = utf8_out_str.substr(utf8_trigger.size());
290			self->mChatBox->setText(utf8_trigger + rest_of_match + " "); // keep original capitalization for user-entered part
291			self->mChatBox->setCursorToEnd();
292		}
293
294		//llinfos << "GESTUREDEBUG " << trigger 
295		//	<< " len " << length
296		//	<< " outlen " << out_str.getLength()
297		//	<< llendl;
298	}
299}
300
301// static
302void LLNearbyChatBar::onChatBoxFocusLost(LLFocusableElement* caller, void* userdata)
303{
304	// stop typing animation
305	gAgent.stopTyping();
306}
307
308void LLNearbyChatBar::onChatBoxFocusReceived()
309{
310	mChatBox->setEnabled(!gDisconnected);
311}
312
313EChatType LLNearbyChatBar::processChatTypeTriggers(EChatType type, std::string &str)
314{
315	U32 length = str.length();
316	S32 cnt = sizeof(sChatTypeTriggers) / sizeof(*sChatTypeTriggers);
317	
318	for (S32 n = 0; n < cnt; n++)
319	{
320		if (length >= sChatTypeTriggers[n].name.length())
321		{
322			std::string trigger = str.substr(0, sChatTypeTriggers[n].name.length());
323
324			if (!LLStringUtil::compareInsensitive(trigger, sChatTypeTriggers[n].name))
325			{
326				U32 trigger_length = sChatTypeTriggers[n].name.length();
327
328				// It's to remove space after trigger name
329				if (length > trigger_length && str[trigger_length] == ' ')
330					trigger_length++;
331
332				str = str.substr(trigger_length, length);
333
334				if (CHAT_TYPE_NORMAL == type)
335					return sChatTypeTriggers[n].type;
336				else
337					break;
338			}
339		}
340	}
341
342	return type;
343}
344
345void LLNearbyChatBar::sendChat( EChatType type )
346{
347	if (mChatBox)
348	{
349		LLWString text = mChatBox->getConvertedText();
350		if (!text.empty())
351		{
352			// store sent line in history, duplicates will get filtered
353			mChatBox->updateHistory();
354			// Check if this is destined for another channel
355			S32 channel = 0;
356			stripChannelNumber(text, &channel);
357			
358			std::string utf8text = wstring_to_utf8str(text);
359			// Try to trigger a gesture, if not chat to a script.
360			std::string utf8_revised_text;
361			if (0 == channel)
362			{
363				// discard returned "found" boolean
364				LLGestureMgr::instance().triggerAndReviseString(utf8text, &utf8_revised_text);
365			}
366			else
367			{
368				utf8_revised_text = utf8text;
369			}
370
371			utf8_revised_text = utf8str_trim(utf8_revised_text);
372
373			type = processChatTypeTriggers(type, utf8_revised_text);
374
375			if (!utf8_revised_text.empty())
376			{
377				// Chat with animation
378				sendChatFromViewer(utf8_revised_text, type, TRUE);
379			}
380		}
381
382		mChatBox->setText(LLStringExplicit(""));
383	}
384
385	gAgent.stopTyping();
386
387	// If the user wants to stop chatting on hitting return, lose focus
388	// and go out of chat mode.
389	if (gSavedSettings.getBOOL("CloseChatOnReturn"))
390	{
391		stopChat();
392	}
393}
394
395
396void LLNearbyChatBar::onToggleNearbyChatPanel()
397{
398	LLView* nearby_chat = getChildView("nearby_chat");
399
400	if (nearby_chat->getVisible())
401	{
402		if (!isMinimized())
403		{
404			mExpandedHeight = getRect().getHeight();
405		}
406		setResizeLimits(getMinWidth(), COLLAPSED_HEIGHT);
407		nearby_chat->setVisible(FALSE);
408		reshape(getRect().getWidth(), COLLAPSED_HEIGHT);
409		enableResizeCtrls(true, true, false);
410		storeRectControl();
411	}
412	else
413	{
414		nearby_chat->setVisible(TRUE);
415		setResizeLimits(getMinWidth(), EXPANDED_MIN_HEIGHT);
416		reshape(getRect().getWidth(), mExpandedHeight);
417		enableResizeCtrls(true);
418		storeRectControl();
419	}
420
421	gSavedSettings.setBOOL("nearbychat_history_visibility", mNearbyChat->getVisible());
422}
423
424void LLNearbyChatBar::setMinimized(BOOL b)
425{
426	LLNearbyChat* nearby_chat = getChild<LLNearbyChat>("nearby_chat");
427	// when unminimizing with nearby chat visible, go ahead and kill off screen chats
428	if (!b && nearby_chat->getVisible())
429	{
430		nearby_chat->removeScreenChat();
431	}
432		LLFloater::setMinimized(b);
433}
434
435void LLNearbyChatBar::onChatBoxCommit()
436{
437	if (mChatBox->getText().length() > 0)
438	{
439		sendChat(CHAT_TYPE_NORMAL);
440	}
441
442	gAgent.stopTyping();
443}
444
445void LLNearbyChatBar::displaySpeakingIndicator()
446{
447	LLSpeakerMgr::speaker_list_t speaker_list;
448	LLUUID id;
449
450	id.setNull();
451	mSpeakerMgr->update(TRUE);
452	mSpeakerMgr->getSpeakerList(&speaker_list, FALSE);
453
454	for (LLSpeakerMgr::speaker_list_t::iterator i = speaker_list.begin(); i != speaker_list.end(); ++i)
455	{
456		LLPointer<LLSpeaker> s = *i;
457		if (s->mSpeechVolume > 0 || s->mStatus == LLSpeaker::STATUS_SPEAKING)
458		{
459			id = s->mID;
460			break;
461		}
462	}
463
464	if (!id.isNull())
465	{
466		mOutputMonitor->setVisible(TRUE);
467		mOutputMonitor->setSpeakerId(id);
468	}
469	else
470	{
471		mOutputMonitor->setVisible(FALSE);
472	}
473}
474
475void LLNearbyChatBar::sendChatFromViewer(const std::string &utf8text, EChatType type, BOOL animate)
476{
477	sendChatFromViewer(utf8str_to_wstring(utf8text), type, animate);
478}
479
480void LLNearbyChatBar::sendChatFromViewer(const LLWString &wtext, EChatType type, BOOL animate)
481{
482	// Look for "/20 foo" channel chats.
483	S32 channel = 0;
484	LLWString out_text = stripChannelNumber(wtext, &channel);
485	std::string utf8_out_text = wstring_to_utf8str(out_text);
486	std::string utf8_text = wstring_to_utf8str(wtext);
487
488	utf8_text = utf8str_trim(utf8_text);
489	if (!utf8_text.empty())
490	{
491		utf8_text = utf8str_truncate(utf8_text, MAX_STRING - 1);
492	}
493
494	// Don't animate for chats people can't hear (chat to scripts)
495	if (animate && (channel == 0))
496	{
497		if (type == CHAT_TYPE_WHISPER)
498		{
499			lldebugs << "You whisper " << utf8_text << llendl;
500			gAgent.sendAnimationRequest(ANIM_AGENT_WHISPER, ANIM_REQUEST_START);
501		}
502		else if (type == CHAT_TYPE_NORMAL)
503		{
504			lldebugs << "You say " << utf8_text << llendl;
505			gAgent.sendAnimationRequest(ANIM_AGENT_TALK, ANIM_REQUEST_START);
506		}
507		else if (type == CHAT_TYPE_SHOUT)
508		{
509			lldebugs << "You shout " << utf8_text << llendl;
510			gAgent.sendAnimationRequest(ANIM_AGENT_SHOUT, ANIM_REQUEST_START);
511		}
512		else
513		{
514			llinfos << "send_chat_from_viewer() - invalid volume" << llendl;
515			return;
516		}
517	}
518	else
519	{
520		if (type != CHAT_TYPE_START && type != CHAT_TYPE_STOP)
521		{
522			lldebugs << "Channel chat: " << utf8_text << llendl;
523		}
524	}
525
526	send_chat_from_viewer(utf8_out_text, type, channel);
527}
528
529// static 
530void LLNearbyChatBar::startChat(const char* line)
531{
532	LLNearbyChatBar* cb = LLNearbyChatBar::getInstance();
533
534	if (!cb )
535		return;
536
537	cb->setVisible(TRUE);
538	cb->setFocus(TRUE);
539	cb->mChatBox->setFocus(TRUE);
540
541	if (line)
542	{
543		std::string line_string(line);
544		cb->mChatBox->setText(line_string);
545	}
546
547	cb->mChatBox->setCursorToEnd();
548}
549
550// Exit "chat mode" and do the appropriate focus changes
551// static
552void LLNearbyChatBar::stopChat()
553{
554	LLNearbyChatBar* cb = LLNearbyChatBar::getInstance();
555
556	if (!cb)
557		return;
558
559	cb->mChatBox->setFocus(FALSE);
560
561 	// stop typing animation
562 	gAgent.stopTyping();
563}
564
565// If input of the form "/20foo" or "/20 foo", returns "foo" and channel 20.
566// Otherwise returns input and channel 0.
567LLWString LLNearbyChatBar::stripChannelNumber(const LLWString &mesg, S32* channel)
568{
569	if (mesg[0] == '/'
570		&& mesg[1] == '/')
571	{
572		// This is a "repeat channel send"
573		*channel = sLastSpecialChatChannel;
574		return mesg.substr(2, mesg.length() - 2);
575	}
576	else if (mesg[0] == '/'
577			 && mesg[1]
578			 && LLStringOps::isDigit(mesg[1]))
579	{
580		// This a special "/20" speak on a channel
581		S32 pos = 0;
582
583		// Copy the channel number into a string
584		LLWString channel_string;
585		llwchar c;
586		do
587		{
588			c = mesg[pos+1];
589			channel_string.push_back(c);
590			pos++;
591		}
592		while(c && pos < 64 && LLStringOps::isDigit(c));
593		
594		// Move the pointer forward to the first non-whitespace char
595		// Check isspace before looping, so we can handle "/33foo"
596		// as well as "/33 foo"
597		while(c && iswspace(c))
598		{
599			c = mesg[pos+1];
600			pos++;
601		}
602		
603		sLastSpecialChatChannel = strtol(wstring_to_utf8str(channel_string).c_str(), NULL, 10);
604		*channel = sLastSpecialChatChannel;
605		return mesg.substr(pos, mesg.length() - pos);
606	}
607	else
608	{
609		// This is normal chat.
610		*channel = 0;
611		return mesg;
612	}
613}
614
615void send_chat_from_viewer(const std::string& utf8_out_text, EChatType type, S32 channel)
616{
617	LLMessageSystem* msg = gMessageSystem;
618	msg->newMessageFast(_PREHASH_ChatFromViewer);
619	msg->nextBlockFast(_PREHASH_AgentData);
620	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
621	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
622	msg->nextBlockFast(_PREHASH_ChatData);
623	msg->addStringFast(_PREHASH_Message, utf8_out_text);
624	msg->addU8Fast(_PREHASH_Type, type);
625	msg->addS32("Channel", channel);
626
627	gAgent.sendReliableMessage();
628
629	LLViewerStats::getInstance()->incStat(LLViewerStats::ST_CHAT_COUNT);
630}
631
632class LLChatCommandHandler : public LLCommandHandler
633{
634public:
635	// not allowed from outside the app
636	LLChatCommandHandler() : LLCommandHandler("chat", UNTRUSTED_BLOCK) { }
637
638    // Your code here
639	bool handle(const LLSD& tokens, const LLSD& query_map,
640				LLMediaCtrl* web)
641	{
642		bool retval = false;
643		// Need at least 2 tokens to have a valid message.
644		if (tokens.size() < 2)
645		{
646			retval = false;
647		}
648		else
649		{
650		S32 channel = tokens[0].asInteger();
651			// VWR-19499 Restrict function to chat channels greater than 0.
652			if ((channel > 0) && (channel < CHAT_CHANNEL_DEBUG))
653			{
654				retval = true;
655		// Send unescaped message, see EXT-6353.
656		std::string unescaped_mesg (LLURI::unescape(tokens[1].asString()));
657		send_chat_from_viewer(unescaped_mesg, CHAT_TYPE_NORMAL, channel);
658			}
659			else
660			{
661				retval = false;
662				// Tell us this is an unsupported SLurl.
663			}
664		}
665		return retval;
666	}
667};
668
669// Creating the object registers with the dispatcher.
670LLChatCommandHandler gChatHandler;
671
672