2 // Radegast Metaverse Client
\r
3 // Copyright (c) 2009, Radegast Development Team
\r
4 // All rights reserved.
\r
6 // Redistribution and use in source and binary forms, with or without
\r
7 // modification, are permitted provided that the following conditions are met:
\r
9 // * Redistributions of source code must retain the above copyright notice,
\r
10 // this list of conditions and the following disclaimer.
\r
11 // * Redistributions in binary form must reproduce the above copyright
\r
12 // notice, this list of conditions and the following disclaimer in the
\r
13 // documentation and/or other materials provided with the distribution.
\r
14 // * Neither the name of the application "Radegast", nor the names of its
\r
15 // contributors may be used to endorse or promote products derived from
\r
16 // this software without specific prior written permission.
\r
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
\r
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
\r
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
\r
21 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
\r
22 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
\r
23 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
\r
24 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
\r
25 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
\r
26 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
\r
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\r
32 using System.Collections.Generic;
\r
34 using System.Reflection;
\r
35 using System.Threading;
\r
36 using System.Windows.Forms;
\r
37 using Radegast.Commands;
\r
38 using Radegast.Netcom;
\r
39 using Radegast.Media;
\r
40 using OpenMetaverse;
\r
44 public class RadegastInstance
\r
46 #region OnRadegastFormCreated
\r
47 public event Action<RadegastForm> RadegastFormCreated;
\r
49 /// Triggers the RadegastFormCreated event.
\r
51 public virtual void OnRadegastFormCreated(RadegastForm radForm)
\r
53 if (RadegastFormCreated != null) RadegastFormCreated(radForm);
\r
56 private GridClient client;
\r
57 private RadegastNetcom netcom;
\r
59 private StateManager state;
\r
61 private frmMain mainForm;
\r
63 // Singleton, there can be only one instance
\r
64 private static RadegastInstance globalInstance = null;
\r
65 public static RadegastInstance GlobalInstance
\r
69 if (globalInstance == null)
\r
71 globalInstance = new RadegastInstance(new GridClient());
\r
73 return globalInstance;
\r
77 private string userDir;
\r
79 /// System (not grid!) user's dir
\r
81 public string UserDir { get { return userDir; } }
\r
84 /// Grid client's user dir for settings and logs
\r
86 public string ClientDir
\r
90 if (client != null && client.Self != null && !string.IsNullOrEmpty(client.Self.Name))
\r
92 return Path.Combine(userDir, client.Self.Name);
\r
96 return Environment.CurrentDirectory;
\r
101 public string InventoryCacheFileName { get { return Path.Combine(ClientDir, "inventory.cache"); } }
\r
103 private string globalLogFile;
\r
104 public string GlobalLogFile { get { return globalLogFile; } }
\r
106 private bool monoRuntime;
\r
107 public bool MonoRuntime { get { return monoRuntime; } }
\r
109 private Dictionary<UUID, Group> groups = new Dictionary<UUID, Group>();
\r
110 public Dictionary<UUID, Group> Groups { get { return groups; } }
\r
112 private Settings globalSettings;
\r
114 /// Global settings for the entire application
\r
116 public Settings GlobalSettings { get { return globalSettings; } }
\r
118 private Settings clientSettings;
\r
120 /// Per client settings
\r
122 public Settings ClientSettings { get { return clientSettings; } }
\r
124 public Dictionary<UUID, string> nameCache = new Dictionary<UUID, string>();
\r
126 public const string INCOMPLETE_NAME = "Loading...";
\r
128 public readonly bool advancedDebugging = false;
\r
130 public readonly List<IRadegastPlugin> PluginsLoaded = new List<IRadegastPlugin>();
\r
132 private MediaManager mediaManager;
\r
134 /// Radegast media manager for playing streams and in world sounds
\r
136 public MediaManager MediaManager { get { return mediaManager; } }
\r
139 private CommandsManager commandsManager;
\r
141 /// Radegast command manager for executing textual console commands
\r
143 public CommandsManager CommandsManager { get { return commandsManager; } }
\r
146 /// Radegast ContextAction manager for context sensitive actions
\r
148 public ContextActionsManager ContextActionManager { get; private set; }
\r
150 private RadegastMovement movement;
\r
152 /// Allows key emulation for moving avatar around
\r
154 public RadegastMovement Movement { get { return movement; } }
\r
156 private InventoryClipboard inventoryClipboard;
\r
158 /// The last item that was cut or copied in the inventory, used for pasting
\r
159 /// in a different place on the inventory, or other places like profile
\r
160 /// that allow sending copied inventory items
\r
162 public InventoryClipboard InventoryClipboard
\r
164 get { return inventoryClipboard; }
\r
167 inventoryClipboard = value;
\r
168 OnInventoryClipboardUpdated(EventArgs.Empty);
\r
172 private RLVManager rlv;
\r
175 /// Manager for RLV functionality
\r
177 public RLVManager RLV { get { return rlv; } }
\r
181 #region ClientChanged event
\r
182 /// <summary>The event subscribers, null of no subscribers</summary>
\r
183 private EventHandler<ClientChangedEventArgs> m_ClientChanged;
\r
185 ///<summary>Raises the ClientChanged Event</summary>
\r
186 /// <param name="e">A ClientChangedEventArgs object containing
\r
187 /// the old and the new client</param>
\r
188 protected virtual void OnClientChanged(ClientChangedEventArgs e)
\r
190 EventHandler<ClientChangedEventArgs> handler = m_ClientChanged;
\r
191 if (handler != null)
\r
195 /// <summary>Thread sync lock object</summary>
\r
196 private readonly object m_ClientChangedLock = new object();
\r
198 /// <summary>Raised when the GridClient object in the main Radegast instance is changed</summary>
\r
199 public event EventHandler<ClientChangedEventArgs> ClientChanged
\r
201 add { lock (m_ClientChangedLock) { m_ClientChanged += value; } }
\r
202 remove { lock (m_ClientChangedLock) { m_ClientChanged -= value; } }
\r
204 #endregion ClientChanged event
\r
206 #region InventoryClipboardUpdated event
\r
207 /// <summary>The event subscribers, null of no subscribers</summary>
\r
208 private EventHandler<EventArgs> m_InventoryClipboardUpdated;
\r
210 ///<summary>Raises the InventoryClipboardUpdated Event</summary>
\r
211 /// <param name="e">A EventArgs object containing
\r
212 /// the old and the new client</param>
\r
213 protected virtual void OnInventoryClipboardUpdated(EventArgs e)
\r
215 EventHandler<EventArgs> handler = m_InventoryClipboardUpdated;
\r
216 if (handler != null)
\r
220 /// <summary>Thread sync lock object</summary>
\r
221 private readonly object m_InventoryClipboardUpdatedLock = new object();
\r
223 /// <summary>Raised when the GridClient object in the main Radegast instance is changed</summary>
\r
224 public event EventHandler<EventArgs> InventoryClipboardUpdated
\r
226 add { lock (m_InventoryClipboardUpdatedLock) { m_InventoryClipboardUpdated += value; } }
\r
227 remove { lock (m_InventoryClipboardUpdatedLock) { m_InventoryClipboardUpdated -= value; } }
\r
229 #endregion InventoryClipboardUpdated event
\r
234 public RadegastInstance(GridClient client0)
\r
236 // incase something else calls GlobalInstance while we are loading
\r
237 globalInstance = this;
\r
240 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
\r
241 Application.ThreadException += HandleThreadException;
\r
246 // Are we running mono?
\r
247 monoRuntime = Type.GetType("Mono.Runtime") != null;
\r
249 netcom = new RadegastNetcom(this);
\r
250 state = new StateManager(this);
\r
251 mediaManager = new MediaManager(this);
\r
252 commandsManager = new CommandsManager(this);
\r
253 ContextActionManager = new ContextActionsManager(this);
\r
254 movement = new RadegastMovement(this);
\r
256 InitializeLoggingAndConfig();
\r
257 InitializeClient(client);
\r
259 rlv = new RLVManager(this);
\r
261 mainForm = new frmMain(this);
\r
262 mainForm.InitializeControls();
\r
264 mainForm.Load += new EventHandler(mainForm_Load);
\r
265 ScanAndLoadPlugins();
\r
268 private void InitializeClient(GridClient client)
\r
270 client.Settings.MULTIPLE_SIMS = true;
\r
272 client.Settings.USE_INTERPOLATION_TIMER = false;
\r
273 client.Settings.ALWAYS_REQUEST_OBJECTS = true;
\r
274 client.Settings.ALWAYS_DECODE_OBJECTS = true;
\r
275 client.Settings.OBJECT_TRACKING = true;
\r
276 client.Settings.ENABLE_SIMSTATS = true;
\r
277 client.Settings.FETCH_MISSING_INVENTORY = true;
\r
278 client.Settings.SEND_AGENT_THROTTLE = true;
\r
279 client.Settings.SEND_AGENT_UPDATES = true;
\r
281 client.Settings.USE_ASSET_CACHE = true;
\r
282 client.Settings.ASSET_CACHE_DIR = Path.Combine(userDir, "cache");
\r
283 client.Assets.Cache.AutoPruneEnabled = false;
\r
285 client.Throttle.Total = 5000000f;
\r
286 client.Settings.THROTTLE_OUTGOING_PACKETS = true;
\r
287 client.Settings.LOGIN_TIMEOUT = 120 * 1000;
\r
288 client.Settings.SIMULATOR_TIMEOUT = 120 * 1000;
\r
289 client.Settings.MAX_CONCURRENT_TEXTURE_DOWNLOADS = 20;
\r
291 RegisterClientEvents(client);
\r
294 private void RegisterClientEvents(GridClient client)
\r
296 client.Groups.CurrentGroups += new EventHandler<CurrentGroupsEventArgs>(Groups_CurrentGroups);
\r
297 client.Groups.GroupLeaveReply += new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
298 client.Groups.GroupDropped += new EventHandler<GroupDroppedEventArgs>(Groups_GroupsChanged);
\r
299 client.Groups.GroupJoinedReply += new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
300 client.Avatars.UUIDNameReply += new EventHandler<UUIDNameReplyEventArgs>(Avatars_UUIDNameReply);
\r
301 netcom.ClientConnected += new EventHandler<EventArgs>(netcom_ClientConnected);
\r
304 private void UnregisterClientEvents(GridClient client)
\r
306 client.Groups.CurrentGroups -= new EventHandler<CurrentGroupsEventArgs>(Groups_CurrentGroups);
\r
307 client.Groups.GroupLeaveReply -= new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
308 client.Groups.GroupDropped -= new EventHandler<GroupDroppedEventArgs>(Groups_GroupsChanged);
\r
309 client.Groups.GroupJoinedReply -= new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
310 client.Avatars.UUIDNameReply -= new EventHandler<UUIDNameReplyEventArgs>(Avatars_UUIDNameReply);
\r
311 netcom.ClientConnected -= new EventHandler<EventArgs>(netcom_ClientConnected);
\r
314 public void Reconnect()
\r
316 TabConsole.DisplayNotificationInChat("Attempting to reconnect...", ChatBufferTextStyle.StatusDarkBlue);
\r
317 Logger.Log("Attemting to reconnect", Helpers.LogLevel.Info, client);
\r
318 GridClient oldClient = client;
\r
319 client = new GridClient();
\r
320 UnregisterClientEvents(oldClient);
\r
321 InitializeClient(client);
\r
322 OnClientChanged(new ClientChangedEventArgs(oldClient, client));
\r
326 public void CleanUp()
\r
334 if (client != null)
\r
336 UnregisterClientEvents(client);
\r
339 lock (PluginsLoaded)
\r
341 List<IRadegastPlugin> unload = new List<IRadegastPlugin>(PluginsLoaded);
\r
342 unload.ForEach(plug =>
\r
344 PluginsLoaded.Remove(plug);
\r
347 plug.StopPlugin(this);
\r
349 catch (Exception ex)
\r
351 Logger.Log("ERROR in Shutdown Plugin: " + plug + " because " + ex, Helpers.LogLevel.Debug, ex);
\r
356 if (movement != null)
\r
358 movement.Dispose();
\r
361 if (commandsManager != null)
\r
363 commandsManager.Dispose();
\r
364 commandsManager = null;
\r
366 if (ContextActionManager != null)
\r
368 ContextActionManager.Dispose();
\r
369 ContextActionManager = null;
\r
371 if (mediaManager != null)
\r
373 mediaManager.Dispose();
\r
374 mediaManager = null;
\r
381 if (netcom != null)
\r
386 if (mainForm != null)
\r
388 mainForm.Load -= new EventHandler(mainForm_Load);
\r
390 Logger.Log("RadegastInstance finished cleaning up.", Helpers.LogLevel.Debug);
\r
393 void mainForm_Load(object sender, EventArgs e)
\r
398 private void StartPlugins()
\r
400 lock (PluginsLoaded)
\r
402 foreach (IRadegastPlugin plug in PluginsLoaded)
\r
406 plug.StartPlugin(this);
\r
408 catch (Exception ex)
\r
410 Logger.Log("ERROR in Starting Radegast Plugin: " + plug + " because " + ex, Helpers.LogLevel.Debug);
\r
416 private void ScanAndLoadPlugins()
\r
418 string dirName = Application.StartupPath;
\r
420 if (!Directory.Exists(dirName)) return;
\r
422 foreach (string loadfilename in Directory.GetFiles(dirName))
\r
424 if (loadfilename.ToLower().EndsWith(".dll") || loadfilename.ToLower().EndsWith(".exe"))
\r
428 Assembly assembly = Assembly.LoadFile(loadfilename);
\r
429 LoadAssembly(loadfilename, assembly);
\r
431 catch (BadImageFormatException)
\r
435 catch (ReflectionTypeLoadException)
\r
437 // Out of date or dlls missing sub dependencies
\r
439 catch (TypeLoadException)
\r
441 // Another version of: Out of date or dlls missing sub dependencies
\r
443 catch (Exception ex)
\r
445 Logger.Log("ERROR in Radegast Plugin: " + loadfilename + " because " + ex, Helpers.LogLevel.Debug);
\r
451 public void LoadAssembly(string loadfilename, Assembly assembly)
\r
453 foreach (Type type in assembly.GetTypes())
\r
455 if (typeof(IRadegastPlugin).IsAssignableFrom(type))
\r
457 if (type.IsInterface) continue;
\r
460 IRadegastPlugin plug;
\r
461 ConstructorInfo constructorInfo = type.GetConstructor(new Type[] {typeof (RadegastInstance)});
\r
462 if (constructorInfo != null)
\r
463 plug = (IRadegastPlugin) constructorInfo.Invoke(new[] {this});
\r
466 constructorInfo = type.GetConstructor(new Type[] {});
\r
467 if (constructorInfo != null)
\r
468 plug = (IRadegastPlugin) constructorInfo.Invoke(new object[0]);
\r
471 Logger.Log("ERROR Constructing Radegast Plugin: " + loadfilename + " because "+type+ " has no usable constructor.",Helpers.LogLevel.Debug);
\r
475 lock (PluginsLoaded) PluginsLoaded.Add(plug);
\r
477 catch (Exception ex)
\r
479 Logger.Log("ERROR Constructing Radegast Plugin: " + loadfilename + " because " + ex,
\r
480 Helpers.LogLevel.Debug);
\r
487 commandsManager.LoadType(type);
\r
489 catch (Exception ex)
\r
491 Logger.Log("ERROR in Radegast Plugin: " + loadfilename + " Command: " + type +
\r
492 " because " + ex.Message + " " + ex.StackTrace, Helpers.LogLevel.Debug);
\r
498 void netcom_ClientConnected(object sender, EventArgs e)
\r
502 if (!Directory.Exists(ClientDir))
\r
503 Directory.CreateDirectory(ClientDir);
\r
505 catch (Exception ex)
\r
507 Logger.Log("Failed to create client directory", Helpers.LogLevel.Warning, ex);
\r
510 clientSettings = new Settings(Path.Combine(ClientDir, "client_settings.xml"));
\r
514 void Avatars_UUIDNameReply(object sender, UUIDNameReplyEventArgs e)
\r
518 foreach (KeyValuePair<UUID, string> av in e.Names)
\r
520 if (!nameCache.ContainsKey(av.Key))
\r
522 nameCache.Add(av.Key, av.Value);
\r
528 public string getAvatarName(UUID key)
\r
532 if (key == UUID.Zero)
\r
534 return "(???) (???)";
\r
536 if (nameCache.ContainsKey(key))
\r
538 return nameCache[key];
\r
542 client.Avatars.RequestAvatarName(key);
\r
543 return INCOMPLETE_NAME;
\r
548 public void getAvatarNames(List<UUID> keys)
\r
552 List<UUID> newNames = new List<UUID>();
\r
553 foreach (UUID key in keys)
\r
555 if (!nameCache.ContainsKey(key))
\r
560 if (newNames.Count > 0)
\r
562 client.Avatars.RequestAvatarNames(newNames);
\r
567 public bool haveAvatarName(UUID key)
\r
571 if (nameCache.ContainsKey(key))
\r
578 void Groups_GroupsChanged(object sender, EventArgs e)
\r
580 client.Groups.RequestCurrentGroups();
\r
583 public static string SafeFileName(string fileName)
\r
585 foreach (char lDisallowed in Path.GetInvalidFileNameChars())
\r
587 fileName = fileName.Replace(lDisallowed.ToString(), "_");
\r
593 public void LogClientMessage(string fileName, string message)
\r
599 foreach (char lDisallowed in System.IO.Path.GetInvalidFileNameChars())
\r
601 fileName = fileName.Replace(lDisallowed.ToString(), "_");
\r
604 File.AppendAllText(Path.Combine(ClientDir, fileName),
\r
605 DateTime.Now.ToString("yyyy-MM-dd [HH:mm:ss] ") + message + Environment.NewLine);
\r
607 catch (Exception) { }
\r
611 void Groups_CurrentGroups(object sender, CurrentGroupsEventArgs e)
\r
613 this.groups = e.Groups;
\r
616 private void InitializeLoggingAndConfig()
\r
620 userDir = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), Properties.Resources.ProgramName);
\r
621 if (!Directory.Exists(userDir))
\r
623 Directory.CreateDirectory(userDir);
\r
628 userDir = System.Environment.CurrentDirectory;
\r
631 globalLogFile = Path.Combine(userDir, Properties.Resources.ProgramName + ".log");
\r
632 globalSettings = new Settings(Path.Combine(userDir, "settings.xml"));
\r
635 public GridClient Client
\r
637 get { return client; }
\r
640 public RadegastNetcom Netcom
\r
642 get { return netcom; }
\r
645 public StateManager State
\r
647 get { return state; }
\r
650 public frmMain MainForm
\r
652 get { return mainForm; }
\r
655 public TabsConsole TabConsole
\r
657 get { return mainForm.TabConsole; }
\r
660 public void HandleThreadException(object sender, ThreadExceptionEventArgs e)
\r
662 Logger.Log("Unhandled Thread Exception: "
\r
663 + e.Exception.Message + Environment.NewLine
\r
664 + e.Exception.StackTrace + Environment.NewLine,
\r
665 Helpers.LogLevel.Error,
\r
668 Application.Exit();
\r
673 #region Event classes
\r
674 public class ClientChangedEventArgs : EventArgs
\r
676 private GridClient m_OldClient;
\r
677 private GridClient m_Client;
\r
679 public GridClient OldClient { get { return m_OldClient; } }
\r
680 public GridClient Client { get { return m_Client; } }
\r
682 public ClientChangedEventArgs(GridClient OldClient, GridClient Client)
\r
684 m_OldClient = OldClient;
\r
688 #endregion Event classes
\r