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 private GridClient client;
\r
47 private RadegastNetcom netcom;
\r
49 private StateManager state;
\r
51 private frmMain mainForm;
\r
53 // Singleton, there can be only one instance
\r
54 private static RadegastInstance globalInstance = null;
\r
55 public static RadegastInstance GlobalInstance
\r
59 if (globalInstance == null)
\r
61 globalInstance = new RadegastInstance(new GridClient());
\r
63 return globalInstance;
\r
67 private string userDir;
\r
69 /// System (not grid!) user's dir
\r
71 public string UserDir { get { return userDir; } }
\r
74 /// Grid client's user dir for settings and logs
\r
76 public string ClientDir
\r
80 if (client != null && client.Self != null && !string.IsNullOrEmpty(client.Self.Name))
\r
82 return Path.Combine(userDir, client.Self.Name);
\r
86 return Environment.CurrentDirectory;
\r
91 public string InventoryCacheFileName { get { return Path.Combine(ClientDir, "inventory.cache"); } }
\r
93 private string animCacheDir;
\r
94 public string AnimCacheDir { get { return animCacheDir; } }
\r
96 private string globalLogFile;
\r
97 public string GlobalLogFile { get { return globalLogFile; } }
\r
99 private bool monoRuntime;
\r
100 public bool MonoRuntime { get { return monoRuntime; } }
\r
102 private Dictionary<UUID, Group> groups = new Dictionary<UUID, Group>();
\r
103 public Dictionary<UUID, Group> Groups { get { return groups; } }
\r
105 private Settings globalSettings;
\r
107 /// Global settings for the entire application
\r
109 public Settings GlobalSettings { get { return globalSettings; } }
\r
111 private Settings clientSettings;
\r
113 /// Per client settings
\r
115 public Settings ClientSettings { get { return clientSettings; } }
\r
117 public Dictionary<UUID, string> nameCache = new Dictionary<UUID, string>();
\r
119 public const string INCOMPLETE_NAME = "Loading...";
\r
121 public readonly bool advancedDebugging = false;
\r
123 public readonly List<IRadegastPlugin> PluginsLoaded = new List<IRadegastPlugin>();
\r
125 private MediaManager mediaManager;
\r
127 /// Radegast media manager for playing streams and in world sounds
\r
129 public MediaManager MediaManager { get { return mediaManager; } }
\r
132 private CommandsManager commandsManager;
\r
134 /// Radegast command manager for executing textual console commands
\r
136 public CommandsManager CommandsManager { get { return commandsManager; } }
\r
139 /// Radegast ContextAction manager for context sensitive actions
\r
141 public ContextActionsManager ContextActionManager { get; private set; }
\r
143 private RadegastMovement movement;
\r
145 /// Allows key emulation for moving avatar around
\r
147 public RadegastMovement Movement { get { return movement; } }
\r
150 /// <summary>The event subscribers, null of no subscribers</summary>
\r
151 private EventHandler<ClientChangedEventArgs> m_ClientChanged;
\r
153 ///<summary>Raises the ClientChanged Event</summary>
\r
154 /// <param name="e">A ClientChangedEventArgs object containing
\r
155 /// the old and the new client</param>
\r
156 protected virtual void OnClientChanged(ClientChangedEventArgs e)
\r
158 EventHandler<ClientChangedEventArgs> handler = m_ClientChanged;
\r
159 if (handler != null)
\r
163 /// <summary>Thread sync lock object</summary>
\r
164 private readonly object m_ClientChangedLock = new object();
\r
166 /// <summary>Raised when the GridClient object in the main Radegast instance is changed</summary>
\r
167 public event EventHandler<ClientChangedEventArgs> ClientChanged
\r
169 add { lock (m_ClientChangedLock) { m_ClientChanged += value; } }
\r
170 remove { lock (m_ClientChangedLock) { m_ClientChanged -= value; } }
\r
174 public RadegastInstance(GridClient client0)
\r
176 // incase something else calls GlobalInstance while we are loading
\r
177 globalInstance = this;
\r
179 #if HANDLE_THREAD_EXCEPTIONS
\r
180 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
\r
181 Application.ThreadException += HandleThreadException;
\r
186 // Are we running mono?
\r
187 monoRuntime = Type.GetType("Mono.Runtime") != null;
\r
189 netcom = new RadegastNetcom(this);
\r
190 state = new StateManager(this);
\r
191 mediaManager = new MediaManager(this);
\r
192 commandsManager = new CommandsManager(this);
\r
193 ContextActionManager = new ContextActionsManager(this);
\r
194 movement = new RadegastMovement(this);
\r
196 InitializeLoggingAndConfig();
\r
197 InitializeClient(client);
\r
199 mainForm = new frmMain(this);
\r
200 mainForm.InitializeControls();
\r
202 mainForm.Load += new EventHandler(mainForm_Load);
\r
203 ScanAndLoadPlugins();
\r
206 private void InitializeClient(GridClient client)
\r
208 client.Settings.MULTIPLE_SIMS = true;
\r
210 client.Settings.USE_INTERPOLATION_TIMER = false;
\r
211 client.Settings.ALWAYS_REQUEST_OBJECTS = true;
\r
212 client.Settings.ALWAYS_DECODE_OBJECTS = true;
\r
213 client.Settings.OBJECT_TRACKING = true;
\r
214 client.Settings.ENABLE_SIMSTATS = true;
\r
215 client.Settings.FETCH_MISSING_INVENTORY = true;
\r
216 client.Settings.SEND_AGENT_THROTTLE = true;
\r
217 client.Settings.SEND_AGENT_UPDATES = true;
\r
219 client.Settings.USE_ASSET_CACHE = true;
\r
220 client.Settings.ASSET_CACHE_DIR = Path.Combine(userDir, "cache");
\r
221 client.Assets.Cache.AutoPruneEnabled = false;
\r
223 client.Throttle.Total = 5000000f;
\r
224 client.Settings.THROTTLE_OUTGOING_PACKETS = true;
\r
225 client.Settings.LOGIN_TIMEOUT = 120 * 1000;
\r
226 client.Settings.SIMULATOR_TIMEOUT = 120 * 1000;
\r
227 client.Settings.MAX_CONCURRENT_TEXTURE_DOWNLOADS = 20;
\r
229 RegisterClientEvents(client);
\r
232 private void RegisterClientEvents(GridClient client)
\r
234 client.Groups.CurrentGroups += new EventHandler<CurrentGroupsEventArgs>(Groups_CurrentGroups);
\r
235 client.Groups.GroupLeaveReply += new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
236 client.Groups.GroupDropped += new EventHandler<GroupDroppedEventArgs>(Groups_GroupsChanged);
\r
237 client.Groups.GroupJoinedReply += new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
238 client.Avatars.UUIDNameReply += new EventHandler<UUIDNameReplyEventArgs>(Avatars_UUIDNameReply);
\r
239 client.Network.OnConnected += new NetworkManager.ConnectedCallback(Network_OnConnected);
\r
242 private void UnregisterClientEvents(GridClient client)
\r
244 client.Groups.CurrentGroups -= new EventHandler<CurrentGroupsEventArgs>(Groups_CurrentGroups);
\r
245 client.Groups.GroupLeaveReply -= new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
246 client.Groups.GroupDropped -= new EventHandler<GroupDroppedEventArgs>(Groups_GroupsChanged);
\r
247 client.Groups.GroupJoinedReply -= new EventHandler<GroupOperationEventArgs>(Groups_GroupsChanged);
\r
248 client.Avatars.UUIDNameReply -= new EventHandler<UUIDNameReplyEventArgs>(Avatars_UUIDNameReply);
\r
249 client.Network.OnConnected -= new NetworkManager.ConnectedCallback(Network_OnConnected);
\r
252 public void Reconnect()
\r
254 TabConsole.DisplayNotificationInChat("Attempting to reconnect...", ChatBufferTextStyle.StatusDarkBlue);
\r
255 Logger.Log("Attemting to reconnect", Helpers.LogLevel.Info, client);
\r
256 GridClient oldClient = client;
\r
257 client = new GridClient();
\r
258 UnregisterClientEvents(oldClient);
\r
259 InitializeClient(client);
\r
260 OnClientChanged(new ClientChangedEventArgs(oldClient, client));
\r
264 public void CleanUp()
\r
266 if (client != null)
\r
268 UnregisterClientEvents(client);
\r
271 lock (PluginsLoaded)
\r
273 List<IRadegastPlugin> unload = new List<IRadegastPlugin>(PluginsLoaded);
\r
274 unload.ForEach(plug =>
\r
276 PluginsLoaded.Remove(plug);
\r
279 plug.StopPlugin(this);
\r
281 catch (Exception ex)
\r
283 Logger.Log("ERROR in Shutdown Plugin: " + plug + " because " + ex, Helpers.LogLevel.Debug, ex);
\r
288 if (movement != null)
\r
290 movement.Dispose();
\r
293 if (commandsManager != null)
\r
295 commandsManager.Dispose();
\r
296 commandsManager = null;
\r
298 if (ContextActionManager != null)
\r
300 ContextActionManager.Dispose();
\r
301 ContextActionManager = null;
\r
303 if (mediaManager != null)
\r
305 mediaManager.Dispose();
\r
306 mediaManager = null;
\r
313 if (netcom != null)
\r
318 if (mainForm != null)
\r
320 mainForm.Load -= new EventHandler(mainForm_Load);
\r
322 Logger.Log("RadegastInstance finished cleaning up.", Helpers.LogLevel.Debug);
\r
325 void mainForm_Load(object sender, EventArgs e)
\r
330 private void StartPlugins()
\r
332 lock (PluginsLoaded)
\r
334 foreach (IRadegastPlugin plug in PluginsLoaded)
\r
338 plug.StartPlugin(this);
\r
340 catch (Exception ex)
\r
342 Logger.Log("ERROR in Starting Radegast Plugin: " + plug + " because " + ex, Helpers.LogLevel.Debug);
\r
348 private void ScanAndLoadPlugins()
\r
350 string dirName = Application.StartupPath;
\r
352 if (!Directory.Exists(dirName)) return;
\r
354 foreach (string loadfilename in Directory.GetFiles(dirName))
\r
356 if (loadfilename.ToLower().EndsWith(".dll") || loadfilename.ToLower().EndsWith(".exe"))
\r
360 Assembly assembly = Assembly.LoadFile(loadfilename);
\r
361 LoadAssembly(loadfilename, assembly);
\r
363 catch (BadImageFormatException)
\r
367 catch (ReflectionTypeLoadException)
\r
369 // Out of date or dlls missing sub dependencies
\r
371 catch (TypeLoadException)
\r
373 // Another version of: Out of date or dlls missing sub dependencies
\r
375 catch (Exception ex)
\r
377 Logger.Log("ERROR in Radegast Plugin: " + loadfilename + " because " + ex, Helpers.LogLevel.Debug);
\r
383 public void LoadAssembly(string loadfilename, Assembly assembly)
\r
385 foreach (Type type in assembly.GetTypes())
\r
387 if (typeof(IRadegastPlugin).IsAssignableFrom(type))
\r
389 if (type.IsInterface) continue;
\r
392 IRadegastPlugin plug;
\r
393 ConstructorInfo constructorInfo = type.GetConstructor(new Type[] {typeof (RadegastInstance)});
\r
394 if (constructorInfo != null)
\r
395 plug = (IRadegastPlugin) constructorInfo.Invoke(new[] {this});
\r
398 constructorInfo = type.GetConstructor(new Type[] {});
\r
399 if (constructorInfo != null)
\r
400 plug = (IRadegastPlugin) constructorInfo.Invoke(new object[0]);
\r
403 Logger.Log("ERROR Constructing Radegast Plugin: " + loadfilename + " because "+type+ " has no usable constructor.",Helpers.LogLevel.Debug);
\r
407 lock (PluginsLoaded) PluginsLoaded.Add(plug);
\r
409 catch (Exception ex)
\r
411 Logger.Log("ERROR Constructing Radegast Plugin: " + loadfilename + " because " + ex,
\r
412 Helpers.LogLevel.Debug);
\r
419 commandsManager.LoadType(type);
\r
421 catch (Exception ex)
\r
423 Logger.Log("ERROR in Radegast Plugin: " + loadfilename + " Command: " + type +
\r
424 " because " + ex.Message + " " + ex.StackTrace, Helpers.LogLevel.Debug);
\r
430 void Network_OnConnected(object sender)
\r
434 if (!Directory.Exists(ClientDir))
\r
435 Directory.CreateDirectory(ClientDir);
\r
437 catch (Exception ex)
\r
439 Logger.Log("Failed to create client directory", Helpers.LogLevel.Warning, ex);
\r
442 clientSettings = new Settings(Path.Combine(ClientDir, "client_settings.xml"));
\r
446 void Avatars_UUIDNameReply(object sender, UUIDNameReplyEventArgs e)
\r
450 foreach (KeyValuePair<UUID, string> av in e.Names)
\r
452 if (!nameCache.ContainsKey(av.Key))
\r
454 nameCache.Add(av.Key, av.Value);
\r
460 public string getAvatarName(UUID key)
\r
464 if (key == UUID.Zero)
\r
466 return "(???) (???)";
\r
468 if (nameCache.ContainsKey(key))
\r
470 return nameCache[key];
\r
474 client.Avatars.RequestAvatarName(key);
\r
475 return INCOMPLETE_NAME;
\r
480 public void getAvatarNames(List<UUID> keys)
\r
484 List<UUID> newNames = new List<UUID>();
\r
485 foreach (UUID key in keys)
\r
487 if (!nameCache.ContainsKey(key))
\r
492 if (newNames.Count > 0)
\r
494 client.Avatars.RequestAvatarNames(newNames);
\r
499 public bool haveAvatarName(UUID key)
\r
503 if (nameCache.ContainsKey(key))
\r
510 void Groups_GroupsChanged(object sender, EventArgs e)
\r
512 client.Groups.RequestCurrentGroups();
\r
515 public static string SafeFileName(string fileName)
\r
517 foreach (char lDisallowed in Path.GetInvalidFileNameChars())
\r
519 fileName = fileName.Replace(lDisallowed.ToString(), "_");
\r
525 public void LogClientMessage(string fileName, string message)
\r
531 foreach (char lDisallowed in System.IO.Path.GetInvalidFileNameChars())
\r
533 fileName = fileName.Replace(lDisallowed.ToString(), "_");
\r
536 File.AppendAllText(Path.Combine(ClientDir, fileName),
\r
537 DateTime.Now.ToString("yyyy-MM-dd [HH:mm:ss] ") + message + Environment.NewLine);
\r
539 catch (Exception) { }
\r
543 void Groups_CurrentGroups(object sender, CurrentGroupsEventArgs e)
\r
545 this.groups = e.Groups;
\r
548 private void InitializeLoggingAndConfig()
\r
552 userDir = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), Properties.Resources.ProgramName);
\r
553 if (!Directory.Exists(userDir))
\r
555 Directory.CreateDirectory(userDir);
\r
560 userDir = System.Environment.CurrentDirectory;
\r
563 animCacheDir = Path.Combine(userDir, @"anim_cache");
\r
564 globalLogFile = Path.Combine(userDir, Properties.Resources.ProgramName + ".log");
\r
565 globalSettings = new Settings(Path.Combine(userDir, "settings.xml"));
\r
568 public GridClient Client
\r
570 get { return client; }
\r
573 public RadegastNetcom Netcom
\r
575 get { return netcom; }
\r
578 public StateManager State
\r
580 get { return state; }
\r
583 public frmMain MainForm
\r
585 get { return mainForm; }
\r
588 public TabsConsole TabConsole
\r
590 get { return mainForm.TabConsole; }
\r
593 public void HandleThreadException(object sender, ThreadExceptionEventArgs e)
\r
595 Logger.Log("Unhandled Thread Exception: "
\r
596 + e.Exception.Message + Environment.NewLine
\r
597 + e.Exception.StackTrace + Environment.NewLine,
\r
598 Helpers.LogLevel.Error,
\r
601 Application.Exit();
\r
605 #region Event classes
\r
606 public class ClientChangedEventArgs : EventArgs
\r
608 private GridClient m_OldClient;
\r
609 private GridClient m_Client;
\r
611 public GridClient OldClient { get { return m_OldClient; } }
\r
612 public GridClient Client { get { return m_Client; } }
\r
614 public ClientChangedEventArgs(GridClient OldClient, GridClient Client)
\r
616 m_OldClient = OldClient;
\r
620 #endregion Event classes
\r