OSDN Git Service

Added display names to IM/Group IM.
[radegast/radegast.git] / Radegast / GUI / Consoles / GroupIMTabWindow.cs
1 // 
2 // Radegast Metaverse Client
3 // Copyright (c) 2009-2010, Radegast Development Team
4 // All rights reserved.
5 // 
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are met:
8 // 
9 //     * Redistributions of source code must retain the above copyright notice,
10 //       this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above copyright
12 //       notice, this list of conditions and the following disclaimer in the
13 //       documentation and/or other materials provided with the distribution.
14 //     * Neither the name of the application "Radegast", nor the names of its
15 //       contributors may be used to endorse or promote products derived from
16 //       this software without specific prior written permission.
17 // 
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // $Id$
30 //
31 using System;
32 using System.Drawing;
33 using System.Collections.Generic;
34 using System.Windows.Forms;
35 using System.Threading;
36 using Radegast.Netcom;
37 using OpenMetaverse;
38
39 namespace Radegast
40 {
41     public partial class GroupIMTabWindow : UserControl
42     {
43         private RadegastInstance instance;
44         private GridClient client { get { return instance.Client; } }
45         private RadegastNetcom netcom { get { return instance.Netcom; } }
46         private UUID session;
47         private IMTextManager textManager;
48         private object AvatarListSyncRoot = new object();
49         private List<string> chatHistory = new List<string>();
50         private int chatPointer;
51
52         ManualResetEvent WaitForSessionStart = new ManualResetEvent(false);
53
54         public GroupIMTabWindow(RadegastInstance instance, UUID session, string sessionName)
55         {
56             InitializeComponent();
57             Disposed += new EventHandler(IMTabWindow_Disposed);
58
59             this.instance = instance;
60             this.session = session;
61
62             textManager = new IMTextManager(this.instance, new RichTextBoxPrinter(rtbIMText), IMTextManagerType.Group, this.session, sessionName);
63
64             btnShow.Text = "Show";
65             chatSplit.Panel2Collapsed = true;
66
67             // Callbacks
68             RegisterClientEvents(client);
69             if (!client.Self.GroupChatSessions.ContainsKey(session))
70             {
71                 client.Self.RequestJoinGroupChat(session);
72             }
73             UpdateFontSize();
74             Load += new EventHandler(GroupIMTabWindow_Load);
75         }
76
77         private void RegisterClientEvents(GridClient client)
78         {
79             client.Self.GroupChatJoined += new EventHandler<GroupChatJoinedEventArgs>(Self_GroupChatJoined);
80             client.Self.ChatSessionMemberAdded += new EventHandler<ChatSessionMemberAddedEventArgs>(Self_ChatSessionMemberAdded);
81             client.Self.ChatSessionMemberLeft += new EventHandler<ChatSessionMemberLeftEventArgs>(Self_ChatSessionMemberLeft);
82             instance.Names.NameUpdated += new EventHandler<UUIDNameReplyEventArgs>(Names_NameUpdated);
83             instance.Netcom.ClientConnected += new EventHandler<EventArgs>(Netcom_Connected);
84             instance.Netcom.ClientDisconnected += new EventHandler<DisconnectedEventArgs>(Netcom_Disconnected);
85             instance.GlobalSettings.OnSettingChanged += new Settings.SettingChangedCallback(GlobalSettings_OnSettingChanged);
86             instance.ClientChanged += new EventHandler<ClientChangedEventArgs>(instance_ClientChanged);
87         }
88
89         private void UnregisterClientEvents(GridClient client)
90         {
91             client.Self.GroupChatJoined -= new EventHandler<GroupChatJoinedEventArgs>(Self_GroupChatJoined);
92             client.Self.ChatSessionMemberAdded -= new EventHandler<ChatSessionMemberAddedEventArgs>(Self_ChatSessionMemberAdded);
93             client.Self.ChatSessionMemberLeft -= new EventHandler<ChatSessionMemberLeftEventArgs>(Self_ChatSessionMemberLeft);
94             instance.Names.NameUpdated -= new EventHandler<UUIDNameReplyEventArgs>(Names_NameUpdated);
95             instance.Netcom.ClientConnected -= new EventHandler<EventArgs>(Netcom_Connected);
96             instance.Netcom.ClientDisconnected -= new EventHandler<DisconnectedEventArgs>(Netcom_Disconnected);
97             instance.GlobalSettings.OnSettingChanged -= new Settings.SettingChangedCallback(GlobalSettings_OnSettingChanged);
98             instance.ClientChanged -= new EventHandler<ClientChangedEventArgs>(instance_ClientChanged);
99         }
100
101         void instance_ClientChanged(object sender, ClientChangedEventArgs e)
102         {
103             UnregisterClientEvents(e.OldClient);
104             RegisterClientEvents(client);
105         }
106
107         void GroupIMTabWindow_Load(object sender, EventArgs e)
108         {
109             UpdateParticipantList();
110         }
111
112         private void IMTabWindow_Disposed(object sender, EventArgs e)
113         {
114             if (instance.Netcom.IsLoggedIn)
115             {
116                 client.Self.RequestLeaveGroupChat(session);
117             }
118
119             UnregisterClientEvents(client);
120             CleanUp();
121         }
122
123         void UpdateFontSize()
124         {
125             float size = (float)instance.GlobalSettings["chat_font_size"].AsReal();
126             cbxInput.Font = ChatConsole.ChangeFontSize(cbxInput.Font, size);
127             rtbIMText.Font = ChatConsole.ChangeFontSize(rtbIMText.Font, size);
128             textManager.ReprintAllText();
129         }
130
131         void GlobalSettings_OnSettingChanged(object sender, SettingsEventArgs e)
132         {
133             if (e.Key == "chat_font_size")
134                 UpdateFontSize();
135         }
136
137         void Netcom_Disconnected(object sender, DisconnectedEventArgs e)
138         {
139             RefreshControls();
140         }
141
142         void Netcom_Connected(object sender, EventArgs e)
143         {
144             client.Self.RequestJoinGroupChat(session);
145             RefreshControls();
146         }
147
148         void Names_NameUpdated(object sender, UUIDNameReplyEventArgs e)
149         {
150             if (InvokeRequired)
151             {
152                 if (!instance.MonoRuntime || IsHandleCreated)
153                     BeginInvoke(new MethodInvoker(() => Names_NameUpdated(sender, e)));
154                 return;
155             }
156
157             lock (AvatarListSyncRoot)
158             {
159
160                 Participants.BeginUpdate();
161
162                 foreach (KeyValuePair<UUID, string> kvp in e.Names)
163                 {
164                     if (Participants.Items.ContainsKey(kvp.Key.ToString()))
165                         Participants.Items[kvp.Key.ToString()].Text = kvp.Value;
166                 }
167
168                 Participants.Sort();
169                 Participants.EndUpdate();
170             }
171         }
172
173         void Self_ChatSessionMemberLeft(object sender, ChatSessionMemberLeftEventArgs e)
174         {
175             if (e.SessionID == session)
176                 UpdateParticipantList();
177         }
178
179         void Self_ChatSessionMemberAdded(object sender, ChatSessionMemberAddedEventArgs e)
180         {
181             if (e.SessionID == session)
182                 UpdateParticipantList();
183         }
184
185         void UpdateParticipantList()
186         {
187             if (InvokeRequired)
188             {
189                 if (!instance.MonoRuntime || IsHandleCreated)
190                     BeginInvoke(new MethodInvoker(UpdateParticipantList));
191                 return;
192             }
193
194             try
195             {
196                 lock (AvatarListSyncRoot)
197                 {
198                     Participants.BeginUpdate();
199                     Participants.Items.Clear();
200
201                     List<ChatSessionMember> participants;
202
203                     if (client.Self.GroupChatSessions.TryGetValue(session, out participants))
204                     {
205                         ChatSessionMember[] members = participants.ToArray();
206                         for (int i = 0; i < members.Length; i++)
207                         {
208                             ChatSessionMember participant = members[i];
209                             ListViewItem item = new ListViewItem();
210                             item.Name = participant.AvatarKey.ToString();
211                             item.Text = instance.Names.Get(participant.AvatarKey); 
212                             if (participant.IsModerator)
213                                 item.Font = new Font(item.Font, FontStyle.Bold);
214                             Participants.Items.Add(item);
215                         }
216                     }
217
218                     Participants.Sort();
219                     Participants.EndUpdate();
220                 }
221             }
222             catch (Exception)
223             {
224                 Participants.EndUpdate();
225             }
226         }
227
228         void Self_GroupChatJoined(object sender, GroupChatJoinedEventArgs e)
229         {
230             if (e.SessionID != session && e.TmpSessionID != session)
231             {
232                 return;
233             }
234
235             if (InvokeRequired)
236             {
237                 if (!instance.MonoRuntime || IsHandleCreated)
238                     Invoke(new MethodInvoker(() => Self_GroupChatJoined(sender, e)));
239                 return;
240             }
241
242             if (e.Success)
243             {
244                 textManager.TextPrinter.PrintTextLine("Join Group Chat Success!", Color.Green);
245                 WaitForSessionStart.Set();
246             }
247             else
248             {
249                 textManager.TextPrinter.PrintTextLine("Join Group Chat failed.", Color.Red);
250             }
251         }
252
253         public void CleanUp()
254         {
255             textManager.CleanUp();
256             textManager = null;
257             instance = null;
258         }
259
260         private void btnSend_Click(object sender, EventArgs e)
261         {
262             SendMsg();
263             this.ClearIMInput();
264         }
265
266         private void btnShow_Click(object sender, EventArgs e)
267         {
268             if (chatSplit.Panel2Collapsed)
269             {
270                 chatSplit.Panel2Collapsed = false;
271                 btnShow.Text = "Hide";
272             }
273             else
274             {
275                 chatSplit.Panel2Collapsed = true;
276                 btnShow.Text = "Show";
277             }
278         }
279
280         private void cbxInput_TextChanged(object sender, EventArgs e)
281         {
282             RefreshControls();
283         }
284
285         private void RefreshControls()
286         {
287             if (InvokeRequired)
288             {
289                 if (!instance.MonoRuntime || IsHandleCreated)
290                     BeginInvoke(new MethodInvoker(RefreshControls));
291                 return;
292             }
293
294             if (!netcom.IsLoggedIn)
295             {
296                 cbxInput.Enabled = false;
297                 btnSend.Enabled = false;
298                 btnShow.Enabled = false;
299                 btnShow.Text = "Show";
300                 chatSplit.Panel2Collapsed = true;
301                 return;
302             }
303
304             cbxInput.Enabled = true;
305             btnShow.Enabled = true;
306
307             if (cbxInput.Text.Length > 0)
308             {
309                 btnSend.Enabled = true;
310             }
311             else
312             {
313                 btnSend.Enabled = false;
314             }
315         }
316
317         void ChatHistoryPrev()
318         {
319             if (chatPointer == 0) return;
320             chatPointer--;
321             if (chatHistory.Count > chatPointer)
322             {
323                 cbxInput.Text = chatHistory[chatPointer];
324                 cbxInput.SelectionStart = cbxInput.Text.Length;
325                 cbxInput.SelectionLength = 0;
326             }
327         }
328
329         void ChatHistoryNext()
330         {
331             if (chatPointer == chatHistory.Count) return;
332             chatPointer++;
333             if (chatPointer == chatHistory.Count)
334             {
335                 cbxInput.Text = string.Empty;
336                 return;
337             }
338             cbxInput.Text = chatHistory[chatPointer];
339             cbxInput.SelectionStart = cbxInput.Text.Length;
340             cbxInput.SelectionLength = 0;
341         }
342
343
344         private void cbxInput_KeyDown(object sender, KeyEventArgs e)
345         {
346             if (e.KeyCode == Keys.Up && e.Modifiers == Keys.Control)
347             {
348                 e.Handled = e.SuppressKeyPress = true;
349                 ChatHistoryPrev();
350                 return;
351             }
352
353             if (e.KeyCode == Keys.Down && e.Modifiers == Keys.Control)
354             {
355                 e.Handled = e.SuppressKeyPress = true;
356                 ChatHistoryNext();
357                 return;
358             }
359
360             if (e.KeyCode != Keys.Enter) return;
361             e.Handled = e.SuppressKeyPress = true;
362
363             SendMsg();
364         }
365
366         private void SendMsg()
367         {
368             if (cbxInput.Text.Length == 0) return;
369
370             chatHistory.Add(cbxInput.Text);
371             chatPointer = chatHistory.Count;
372
373             string message = cbxInput.Text.Replace(ChatInputBox.NewlineMarker, "\n");
374
375             if (instance.GlobalSettings["mu_emotes"].AsBoolean() && message.StartsWith(":"))
376             {
377                 message = "/me " + message.Substring(1);
378             }
379
380             this.ClearIMInput();
381
382             if (instance.RLV.RestictionActive("sendim")) return;
383
384             if (message.Length > 1023) message = message.Remove(1023);
385
386             if (!client.Self.GroupChatSessions.ContainsKey(session))
387             {
388                 WaitForSessionStart.Reset();
389                 client.Self.RequestJoinGroupChat(session);
390             }
391             else
392             {
393                 WaitForSessionStart.Set();
394             }
395
396             if (WaitForSessionStart.WaitOne(10000, false))
397             {
398                 client.Self.InstantMessageGroup(session, message);
399             }
400             else
401             {
402                 textManager.TextPrinter.PrintTextLine("Cannot send group IM.", Color.Red);
403             }
404         }
405
406         private void ClearIMInput()
407         {
408             cbxInput.Text = string.Empty;
409         }
410
411         public void SelectIMInput()
412         {
413             cbxInput.Select();
414         }
415
416         private void rtbIMText_LinkClicked(object sender, LinkClickedEventArgs e)
417         {
418             instance.MainForm.ProcessLink(e.LinkText);
419         }
420
421         public UUID SessionId
422         {
423             get { return session; }
424             set { session = value; }
425         }
426
427         public IMTextManager TextManager
428         {
429             get { return textManager; }
430             set { textManager = value; }
431         }
432
433         private void Participants_MouseDoubleClick(object sender, MouseEventArgs e)
434         {
435             ListViewItem item = Participants.GetItemAt(e.X, e.Y);
436             if (item != null)
437             {
438                 try
439                 {
440                     instance.MainForm.ShowAgentProfile(item.Text, new UUID(item.Name));
441                 }
442                 catch (Exception) { }
443             }
444         }
445
446         private void cbxInput_VisibleChanged(object sender, EventArgs e)
447         {
448             if (Visible) cbxInput.Focus();
449         }
450
451         private void cbxInput_SizeChanged(object sender, EventArgs e)
452         {
453             pnlChatInput.Height = cbxInput.Height + 7;
454         }
455     }
456 }