using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using UnityEngine; namespace AllocsFixes.NetConnections.Servers.Web.Handlers { public class ItemIconHandler : PathHandler { private string staticPart; private bool logMissingFiles; private Dictionary icons = new Dictionary (); private bool loaded = false; public ItemIconHandler (string staticPart, bool logMissingFiles, string moduleName = null) : base(moduleName) { this.staticPart = staticPart; this.logMissingFiles = logMissingFiles; } public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { if (!loaded) { if (!LoadIcons ()) { resp.StatusCode = (int)HttpStatusCode.NotFound; Log.Out ("Web:IconHandler: Could not load icons"); return; } } string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length); fn = fn.Remove (fn.LastIndexOf ('.')); if (icons.ContainsKey (fn)) { resp.ContentType = MimeType.GetMimeType (".png"); resp.ContentLength64 = icons [fn].Length; resp.OutputStream.Write (icons [fn], 0, icons [fn].Length); } else { resp.StatusCode = (int)HttpStatusCode.NotFound; if (logMissingFiles) Log.Out ("Web:IconHandler:FileNotFound: \"" + req.Url.AbsolutePath + "\" "); return; } } private bool LoadIcons () { lock (icons) { if (loaded) { return true; } GameObject atlasObj = GameObject.Find ("/NGUI Root (2D)/ItemIconAtlas"); if (atlasObj == null) { Log.Error ("Web:IconHandler: Atlas object not found"); loaded = true; return false; } DynamicUIAtlas atlas = atlasObj.GetComponent (); if (atlas == null) { Log.Error ("Web:IconHandler: Atlas component not found"); loaded = true; return false; } Texture2D atlasTex = atlas.texture as Texture2D; foreach (UISpriteData data in atlas.spriteList) { string name = data.name; Texture2D tex = new Texture2D (data.width, data.height, TextureFormat.ARGB32, false); tex.SetPixels (atlasTex.GetPixels (data.x, atlasTex.height - data.height - data.y, data.width, data.height)); byte[] pixData = tex.EncodeToPNG (); icons.Add (name, pixData); UnityEngine.Object.Destroy (tex); } loaded = true; Log.Out ("Web:IconHandler: Icons loaded"); return true; } } } }