Ejemplo n.º 1
0
        private static string GetModAssemblyFileName(TmodFile modFile, bool?xna = null)
        {
            string variant  = modFile.HasFile($"{modFile.name}.All.dll") ? "All" : (xna ?? PlatformUtilities.IsXNA) ? "XNA" : "FNA";
            string fileName = $"{modFile.name}.{variant}.dll";

            if (!modFile.HasFile(fileName)) // legacy compatibility
            {
                fileName = modFile.HasFile("All.dll") ? "All.dll" : (xna ?? FrameworkVersion.Framework == Framework.NetFramework) ? "Windows.dll" : "Mono.dll";
            }

            return(fileName);
        }
Ejemplo n.º 2
0
        public override bool UseItem(Player player)
        {
            Main.NewText("WUT csproj : " + mod.FileExists("WUT.csproj"));
            Main.NewText("WUT sln : " + mod.FileExists("WUT.sln"));

            TmodFile f = mod.File;

            Main.NewText("PsychoWUTKnife : " + f.HasFile("WUT.csproj.user"));

            //string door = System.Text.Encoding.UTF8.GetString(mod.GetFileBytes("structure/door.txt"));
            //print(door);
            Mod psycho = ModLoader.GetMod("Psycho");

            if (psycho != null)
            {
                return(base.UseItem(player));
            }
            return(false);
        }
Ejemplo n.º 3
0
 internal static bool CreateModReferenceDlls(BuildProperties properties)
 {
     TmodFile[] refFiles = new TmodFile[properties.modReferences.Length];
     for (int k = 0; k < properties.modReferences.Length; k++)
     {
         string   modReference = properties.modReferences[k];
         string   filePath     = ModLoader.ModPath + Path.DirectorySeparatorChar + modReference + ".tmod";
         TmodFile refFile      = new TmodFile(filePath);
         refFile = new TmodFile(filePath);
         refFile.Read();
         if (!refFile.ValidMod())
         {
             ErrorLogger.LogModReferenceError(refFile.Name);
             return(false);
         }
         refFiles[k] = refFile;
     }
     for (int k = 0; k < refFiles.Length; k++)
     {
         TmodFile refFile      = refFiles[k];
         string   modReference = properties.modReferences[k];
         byte[]   data1;
         byte[]   data2;
         if (refFile.HasFile("All"))
         {
             data1 = refFile.GetFile("All");
             data2 = refFile.GetFile("All");
         }
         else
         {
             data1 = refFile.GetFile("Windows");
             data2 = refFile.GetFile("Other");
         }
         string refFileName = ModLoader.ModSourcePath + Path.DirectorySeparatorChar + modReference;
         File.WriteAllBytes(refFileName + "1.dll", data1);
         File.WriteAllBytes(refFileName + "2.dll", data2);
     }
     return(true);
 }
Ejemplo n.º 4
0
        private static void PublishModInner(TmodFile modFile, BuildProperties bp, bool commandLine = false)
        {
            var files = new List <UploadFile>();

            files.Add(new UploadFile {
                Name     = "file",
                Filename = Path.GetFileName(modFile.path),
                //    ContentType = "text/plain",
                Content = File.ReadAllBytes(modFile.path)
            });
            if (modFile.HasFile("icon.png"))               // Test this on server
            {
                using (modFile.Open())
                    files.Add(new UploadFile {
                        Name     = "iconfile",
                        Filename = "icon.png",
                        Content  = modFile.GetBytes("icon.png")
                    });
            }
            //if (bp.beta)
            //	throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
            if (bp.buildVersion != modFile.TModLoaderVersion)
            {
                throw new WebException(Language.GetTextValue("OutdatedModCantPublishError.BetaModCantPublishError"));
            }

            var values = new NameValueCollection
            {
                { "displayname", bp.displayName },
                { "displaynameclean", string.Join("", ChatManager.ParseMessage(bp.displayName, Color.White).Where(x => x.GetType() == typeof(TextSnippet)).Select(x => x.Text)) },
                { "name", modFile.Name },
                { "version", "v" + bp.version },
                { "author", bp.author },
                { "homepage", bp.homepage },
                { "description", bp.description },
                { "steamid64", ModLoader.SteamID64 },
                { "modloaderversion", "tModLoader v" + modFile.TModLoaderVersion },
                { "passphrase", ModLoader.modBrowserPassphrase },
                { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                { "modside", bp.side.ToFriendlyString() },
            };

            if (values["steamid64"].Length != 17)
            {
                throw new WebException($"The steamid64 '{values["steamid64"]}' is invalid, verify that you are logged into Steam and don't have a pirated copy of Terraria.");
            }
            if (string.IsNullOrEmpty(values["author"]))
            {
                throw new WebException($"You need to specify an author in build.txt");
            }
            ServicePointManager.Expect100Continue = false;
            string url = "http://javid.ddns.net/tModLoader/publishmod.php";

            using (PatientWebClient client = new PatientWebClient()) {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, policyErrors) => true;
                Interface.progress.Show(displayText: $"Uploading: {modFile.Name}", gotoMenu: Interface.modSourcesID, cancel: client.CancelAsync);

                var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                //boundary = "--" + boundary;
                byte[] data = UploadFile.GetUploadFilesRequestData(files, values, boundary);
                if (commandLine)
                {
                    var    result   = client.UploadData(new Uri(url), data);                // could use async version for progress output maybe
                    string response = HandlePublishResponse(modFile, result);
                    Console.WriteLine(Language.GetTextValue("tModLoader.MBServerResponse", response));
                    if (result.Length <= 256 || result[result.Length - 256 - 1] != '~')
                    {
                        throw new Exception("Publish failed due to invalid response from server");
                    }
                }
                else
                {
                    client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, modFile);
                    client.UploadProgressChanged += (s, e) => Interface.progress.Progress = (float)e.BytesSent / e.TotalBytesToSend;
                    client.UploadDataAsync(new Uri(url), data);
                }
            }
        }
Ejemplo n.º 5
0
        public UIModItem(TmodFile mod)
        {
            this.mod               = mod;
            this.BorderColor       = new Color(89, 116, 213) * 0.7f;
            this.dividerTexture    = TextureManager.Load("Images/UI/Divider");
            this.innerPanelTexture = TextureManager.Load("Images/UI/InnerPanelBackground");
            this.Height.Set(90f, 0f);
            this.Width.Set(0f, 1f);
            base.SetPadding(6f);
            //base.OnClick += this.ToggleEnabled;
            properties = BuildProperties.ReadModFile(mod);
            string text = properties.displayName.Length > 0 ? properties.displayName : mod.name;

            text += " v" + mod.version;
            if (mod.tModLoaderVersion < new Version(0, 10))
            {
                text += " [c/FF0000:(Old mod, enable at own risk)]";
            }
            int modIconAdjust = 0;

            if (mod.HasFile("icon.png"))
            {
                var modIconTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, new MemoryStream(mod.GetFile("icon.png")));
                if (modIconTexture.Width == 80 && modIconTexture.Height == 80)
                {
                    modIcon = new UIImage(modIconTexture);
                    modIcon.Left.Set(0f, 0f);
                    modIcon.Top.Set(0f, 0f);
                    Append(modIcon);
                    modIconAdjust += 85;
                }
            }
            this.modName = new UIText(text, 1f, false);
            this.modName.Left.Set(modIconAdjust + 10f, 0f);
            this.modName.Top.Set(5f, 0f);
            base.Append(this.modName);
            this.enabled = ModLoader.IsEnabled(mod);
            UITextPanel <string> button = new UITextPanel <string>(Language.GetTextValue("tModLoader.ModsMoreInfo"), 1f, false);

            button.Width.Set(100f, 0f);
            button.Height.Set(30f, 0f);
            button.Left.Set(430f, 0f);
            button.Top.Set(40f, 0f);
            button.PaddingTop    -= 2f;
            button.PaddingBottom -= 2f;
            button.OnMouseOver   += UICommon.FadedMouseOver;
            button.OnMouseOut    += UICommon.FadedMouseOut;
            button.OnClick       += this.Moreinfo;
            base.Append(button);
            button2 = new UITextPanel <string>(this.enabled ? Language.GetTextValue("tModLoader.ModsDisable") : Language.GetTextValue("tModLoader.ModsEnable"), 1f, false);
            button2.Width.Set(100f, 0f);
            button2.Height.Set(30f, 0f);
            button2.Left.Set(button.Left.Pixels - button2.Width.Pixels - 5f, 0f);
            button2.Top.Set(40f, 0f);
            button2.PaddingTop    -= 2f;
            button2.PaddingBottom -= 2f;
            button2.OnMouseOver   += UICommon.FadedMouseOver;
            button2.OnMouseOut    += UICommon.FadedMouseOut;
            button2.OnClick       += this.ToggleEnabled;
            base.Append(button2);
            if (properties.modReferences.Length > 0 && !enabled)
            {
                string    refs = String.Join(", ", properties.modReferences.Select(x => x.mod));
                Texture2D icon = Texture2D.FromStream(Main.instance.GraphicsDevice,
                                                      Assembly.GetExecutingAssembly().GetManifestResourceStream("Terraria.ModLoader.UI.ButtonExclamation.png"));
                UIHoverImage modReferenceIcon = new UIHoverImage(icon, "This mod depends on: " + refs + "\n (click to enable)");
                modReferenceIcon.Left.Set(button2.Left.Pixels - 24f, 0f);
                modReferenceIcon.Top.Set(47f, 0f);
                modReferenceIcon.OnClick += (a, b) =>
                {
                    var referencedMods      = properties.modReferences.Select(x => x.mod);
                    var foundMods           = ModLoader.FindMods();
                    var referencedtModFiles = foundMods.Where(x => referencedMods.Contains(x.name));
                    foreach (var referencedMod in referencedtModFiles)
                    {
                        ModLoader.EnableMod(referencedMod);
                    }
                    Main.menuMode = Interface.modsMenuID;
                    var missingMods = referencedMods.Where(modstring => foundMods.All(modfile => modfile.name != modstring));
                    if (missingMods.Count() > 0)
                    {
                        Interface.infoMessage.SetMessage("The following mods were not found: " + String.Join(",", missingMods));
                        Interface.infoMessage.SetGotoMenu(Interface.modsMenuID);
                        Main.menuMode = Interface.infoMessageID;
                    }
                };
                base.Append(modReferenceIcon);
            }
            if (mod.ValidModBrowserSignature)
            {
                keyImage = new UIHoverImage(Main.itemTexture[ID.ItemID.GoldenKey], Language.GetTextValue("tModLoader.ModsOriginatedFromModBrowser"));
                keyImage.Left.Set(-20, 1f);
                base.Append(keyImage);
            }
            if (ModLoader.ModLoaded(mod.name))
            {
                Mod      loadedMod = ModLoader.GetMod(mod.name);
                int[]    values    = { loadedMod.items.Count, loadedMod.npcs.Count, loadedMod.tiles.Count, loadedMod.walls.Count, loadedMod.buffs.Count, loadedMod.mountDatas.Count };
                string[] strings   = { " items", " NPCs", " tiles", " walls", " buffs", " mounts" };
                int      xOffset   = -40;
                for (int i = 0; i < values.Length; i++)
                {
                    if (values[i] > 0)
                    {
                        Texture2D iconTexture = Main.instance.infoIconTexture[i];
                        keyImage = new UIHoverImage(iconTexture, values[i] + strings[i]);
                        keyImage.Left.Set(xOffset, 1f);
                        base.Append(keyImage);
                        xOffset -= 18;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public UIModData(UITheme theme, int?idx, Mod mod, bool will_draw_own_hover_elements = true)
        {
            var      self    = this;
            TmodFile modfile = mod.File;

            this.Mod = mod;
            this.WillDrawOwnHoverElements = will_draw_own_hover_elements;

            this.Author                 = null;
            this.HomepageUrl            = null;
            this.HasIconLoaded          = false;
            this.LatestAvailableVersion = default(Version);

            if (HamstarHelpersMod.Instance.Config.IsCheckingModVersions)
            {
                BuildPropertiesEditor props = modfile != null?
                                              BuildPropertiesEditor.GetBuildPropertiesForModFile(modfile) :
                                                  (BuildPropertiesEditor)null;

                if (props != null)
                {
                    this.Author      = (string)props.GetField("author");
                    this.HomepageUrl = (string)props.GetField("homepage");
                }
            }

            // Container

            this.SetPadding(4f);
            this.Width.Set(0f, 1f);
            this.Height.Set(64, 0f);

            float title_offset = 72f;

            // Mod index

            if (idx != null)
            {
                var mod_idx_elem = new UIText((int)idx + "");
                mod_idx_elem.Left.Set(title_offset, 0f);
                this.Append((UIElement)mod_idx_elem);

                title_offset += 16f;
            }

            // Mod title

            string mod_title = this.Mod.DisplayName + " " + this.Mod.Version.ToString();

            if (!String.IsNullOrEmpty(this.HomepageUrl))
            {
                this.TitleElem = new UIWebUrl(theme, mod_title, this.HomepageUrl, false);
            }
            else
            {
                this.TitleElem = new UIText(mod_title);
            }
            this.TitleElem.Left.Set(88f, 0f);
            this.Append((UIElement)this.TitleElem);

            // Mod author

            if (this.Author != null)
            {
                this.AuthorElem = new UIText("By: " + this.Author, 0.7f);
                this.AuthorElem.Top.Set(20f, 0f);
                this.AuthorElem.Left.Set(title_offset, 0f);
                this.Append((UIElement)this.AuthorElem);
            }

            // Mod icon

            if (modfile != null && modfile.HasFile("icon.png"))
            {
                var stream   = new MemoryStream(modfile.GetFile("icon.png"));
                var icon_tex = Texture2D.FromStream(Main.graphics.GraphicsDevice, stream);

                if (icon_tex.Width == 80 && icon_tex.Height == 80)
                {
                    this.IconElem = new UIImage(icon_tex);
                    this.IconElem.Top.Set(-4f, 0f);
                    this.IconElem.Left.Set(-4f, 0f);
                    this.IconElem.MarginTop  = -8f;
                    this.IconElem.MarginLeft = -4f;
                    this.IconElem.ImageScale = 0.7f;
                    this.Append(this.IconElem);
                }
            }

            // Mod config button

            if (ModMetaDataManager.HasConfig(mod))
            {
                var config_button = new UITextPanelButton(theme, "Open Config File");
                config_button.Width.Set(160f, 0f);
                config_button.HAlign = 1f;
                config_button.VAlign = 1f;
                this.Append(config_button);

                this.ConfigButton = config_button;

                this.ConfigButton.OnClick += delegate(UIMouseEvent evt, UIElement from_elem) {
                    string path     = ModMetaDataManager.GetConfigRelativePath(mod);
                    string fullpath = Main.SavePath + Path.DirectorySeparatorChar + path;

                    try {
                        Process.Start(fullpath);
                    } catch (Exception e) {
                        try {
                            string dir = new FileInfo(fullpath).Directory.FullName;
                            Process.Start(dir);
                        } catch (Exception) { }

                        Main.NewText("Couldn't open config file " + path + ": " + e.Message, Color.Red);
                    }
                };
            }
        }
Ejemplo n.º 7
0
        private static void LoadMod(TmodFile modFile, BuildProperties properties)
        {
            AddAssemblyResolver();
            string fileName = Path.GetFileNameWithoutExtension(modFile.Name);

            Interface.loadMods.SetProgressReading(fileName, 0, 2);
            Assembly modCode;
            string   rootDirectory;

            if (modFile.HasFile("All"))
            {
                modCode = Assembly.Load(modFile.GetFile("All"));
            }
            else
            {
                modCode = Assembly.Load(modFile.GetFile(windows ? "Windows" : "Other"));
            }
            Interface.loadMods.SetProgressReading(fileName, 1, 2);
            using (MemoryStream memoryStream = new MemoryStream(modFile.GetFile("Resources")))
            {
                using (BinaryReader reader = new BinaryReader(memoryStream))
                {
                    memoryStream.Seek(reader.ReadInt32(), SeekOrigin.Current);
                    rootDirectory = reader.ReadString();
                    for (string path = reader.ReadString(); path != "end"; path = reader.ReadString())
                    {
                        byte[] data = reader.ReadBytes(reader.ReadInt32());
                        files[path] = data;
                        string extension = Path.GetExtension(path);
                        switch (extension)
                        {
                        case ".png":
                            string texturePath = Path.ChangeExtension(path, null);
                            using (MemoryStream buffer = new MemoryStream(data))
                            {
                                textures[texturePath] = Texture2D.FromStream(Main.instance.GraphicsDevice, buffer);
                            }
                            break;

                        case ".wav":
                            string soundPath = Path.ChangeExtension(path, null);
                            using (MemoryStream buffer = new MemoryStream(data))
                            {
                                sounds[soundPath] = SoundEffect.FromStream(buffer);
                            }
                            break;

                        case ".mp3":
                            string       mp3Path    = Path.ChangeExtension(path, null);
                            ushort       wFormatTag = 1;
                            ushort       nChannels;
                            uint         nSamplesPerSec;
                            uint         nAvgBytesPerSec;
                            ushort       nBlockAlign;
                            ushort       wBitsPerSample = 16;
                            MemoryStream output         = new MemoryStream();
                            using (MemoryStream yourMp3FileStream = new MemoryStream(data))
                                using (var input = new MP3Sharp.MP3Stream(yourMp3FileStream))
                                    using (var writer = new BinaryWriter(output, Encoding.UTF8))
                                    {
                                        var headerSize = 44;
                                        output.Position = headerSize;
                                        input.CopyTo(output);
                                        UInt32 wavDataLength = (UInt32)output.Length - 44;
                                        output.Position = 0;
                                        nChannels       = (ushort)input.ChannelCount;
                                        nSamplesPerSec  = (uint)input.Frequency;
                                        nBlockAlign     = (ushort)(nChannels * (wBitsPerSample / 8));
                                        nAvgBytesPerSec = (uint)(nSamplesPerSec * nChannels * (wBitsPerSample / 8));
                                        //write the header
                                        writer.Write("RIFF".ToCharArray());               //4
                                        writer.Write((UInt32)(wavDataLength + 36));       // 4
                                        writer.Write("WAVE".ToCharArray());               //4
                                        writer.Write("fmt ".ToCharArray());               //4
                                        writer.Write(16);                                 //4
                                        writer.Write(wFormatTag);                         //
                                        writer.Write((ushort)nChannels);
                                        writer.Write(nSamplesPerSec);
                                        writer.Write(nAvgBytesPerSec);
                                        writer.Write(nBlockAlign);
                                        writer.Write(wBitsPerSample);
                                        writer.Write("data".ToCharArray());
                                        writer.Write((UInt32)(wavDataLength));
                                        output.Position = 0;
                                        sounds[mp3Path] = SoundEffect.FromStream(output);
                                    }
                            break;
                        }
                    }
                }
            }
            Type[] classes = modCode.GetTypes();
            foreach (Type type in classes)
            {
                if (type.IsSubclassOf(typeof(Mod)))
                {
                    Mod mod = (Mod)Activator.CreateInstance(type);
                    mod.file = modFile.Name;
                    mod.code = modCode;
                    mod.Init();
                    if (mods.ContainsKey(mod.Name))
                    {
                        throw new DuplicateNameException("Two mods share the internal name " + mod.Name);
                    }
                    if (rootDirectory != mod.Name)
                    {
                        throw new MissingResourceException("Mod name " + mod.Name + " does not match source directory name " + rootDirectory);
                    }
                    mods[mod.Name] = mod;
                    loadOrder.Push(mod.Name);
                }
            }
        }
Ejemplo n.º 8
0
 //Assets
 public bool HasAsset(string assetName) => file.HasFile(assetName);        //This one currently doesn't do any extension guessing
Ejemplo n.º 9
0
 private void Publish(UIMouseEvent evt, UIElement listeningElement)
 {
     if (ModLoader.modBrowserPassphrase == "")
     {
         Main.menuMode = Interface.enterPassphraseMenuID;
         Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
         return;
     }
     Main.PlaySound(10, -1, -1, 1);
     try
     {
         TmodFile[] modFiles    = ModLoader.FindMods();
         bool       ok          = false;
         TmodFile   theTModFile = null;
         foreach (TmodFile tModFile in modFiles)
         {
             if (Path.GetFileName(tModFile.path).Equals(@Path.GetFileName(mod) + @".tmod"))
             {
                 ok          = true;
                 theTModFile = tModFile;
             }
         }
         if (!ok)
         {
             throw new Exception();
         }
         System.Net.ServicePointManager.Expect100Continue = false;
         string filename = @ModLoader.ModPath + @Path.DirectorySeparatorChar + @Path.GetFileName(mod) + @".tmod";
         string url      = "http://javid.ddns.net/tModLoader/publishmod.php";
         byte[] result;
         using (var iconStream = theTModFile.HasFile("icon.png") ? new MemoryStream(theTModFile.GetFile("icon.png")) : null)
             using (var stream = File.Open(filename, FileMode.Open))
             {
                 var files = new List <UploadFile>();
                 files.Add(new IO.UploadFile
                 {
                     Name     = "file",
                     Filename = Path.GetFileName(filename),
                     //    ContentType = "text/plain",
                     Stream = stream
                 }
                           );
                 if (iconStream != null)
                 {
                     files.Add(new IO.UploadFile
                     {
                         Name     = "iconfile",
                         Filename = "icon.png",
                         Stream   = iconStream
                     }
                               );
                 }
                 BuildProperties bp     = BuildProperties.ReadModFile(theTModFile);
                 var             values = new NameValueCollection
                 {
                     { "displayname", bp.displayName },
                     { "name", Path.GetFileNameWithoutExtension(filename) },
                     { "version", "v" + bp.version },
                     { "author", bp.author },
                     { "homepage", bp.homepage },
                     { "description", bp.description },
                     { "steamid64", ModLoader.SteamID64 },
                     { "modloaderversion", "tModLoader v" + theTModFile.tModLoaderVersion },
                     { "passphrase", ModLoader.modBrowserPassphrase },
                     { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                     { "modside", bp.side.ToFriendlyString() },
                 };
                 result = IO.UploadFile.UploadFiles(url, files, values);
             }
         int responseLength = result.Length;
         if (result.Length > 256 && result[result.Length - 256 - 1] == '~')
         {
             Array.Copy(result, result.Length - 256, theTModFile.signature, 0, 256);
             theTModFile.Save();
             responseLength -= 257;
         }
         string s = System.Text.Encoding.UTF8.GetString(result, 0, responseLength);
         ErrorLogger.LogModPublish(s);
     }
     catch (WebException e)
     {
         ErrorLogger.LogModBrowserException(e);
     }
 }
Ejemplo n.º 10
0
        private void Publish(UIMouseEvent evt, UIElement listeningElement)
        {
            if (ModLoader.modBrowserPassphrase == "")
            {
                Main.menuMode = Interface.enterPassphraseMenuID;
                Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
                return;
            }
            Main.PlaySound(10, -1, -1, 1);
            try
            {
                TmodFile[] modFiles    = ModLoader.FindMods();
                bool       ok          = false;
                TmodFile   theTModFile = null;
                foreach (TmodFile tModFile in modFiles)
                {
                    if (Path.GetFileName(tModFile.path).Equals(@Path.GetFileName(mod) + @".tmod"))
                    {
                        ok          = true;
                        theTModFile = tModFile;
                    }
                }
                if (!ok)
                {
                    throw new Exception();
                }
                System.Net.ServicePointManager.Expect100Continue = false;
                string filename = @ModLoader.ModPath + @Path.DirectorySeparatorChar + @Path.GetFileName(mod) + @".tmod";
                string url      = "http://javid.ddns.net/tModLoader/publishmod.php";
                using (var iconStream = theTModFile.HasFile("icon.png") ? new MemoryStream(theTModFile.GetFile("icon.png")) : null)
                    using (var stream = File.Open(filename, FileMode.Open))
                    {
                        var files = new List <UploadFile>();
                        files.Add(new IO.UploadFile
                        {
                            Name     = "file",
                            Filename = Path.GetFileName(filename),
                            //    ContentType = "text/plain",
                            Stream = stream
                        }
                                  );
                        if (iconStream != null)
                        {
                            files.Add(new IO.UploadFile
                            {
                                Name     = "iconfile",
                                Filename = "icon.png",
                                Stream   = iconStream
                            }
                                      );
                        }
                        BuildProperties bp     = BuildProperties.ReadModFile(theTModFile);
                        var             values = new NameValueCollection
                        {
                            { "displayname", bp.displayName },
                            { "name", Path.GetFileNameWithoutExtension(filename) },
                            { "version", "v" + bp.version },
                            { "author", bp.author },
                            { "homepage", bp.homepage },
                            { "description", bp.description },
                            { "steamid64", ModLoader.SteamID64 },
                            { "modloaderversion", "tModLoader v" + theTModFile.tModLoaderVersion },
                            { "passphrase", ModLoader.modBrowserPassphrase },
                            { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                            { "modside", bp.side.ToFriendlyString() },
                        };
                        using (PatientWebClient client = new PatientWebClient())
                        {
                            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return(true); });
                            Interface.uploadMod.SetDownloading(Path.GetFileNameWithoutExtension(filename));
                            Interface.uploadMod.SetCancel(() =>
                            {
                                Main.menuMode = Interface.modSourcesID;
                                client.CancelAsync();
                            });
                            client.UploadProgressChanged += (s, e) => Interface.uploadMod.SetProgress(e);
                            client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, theTModFile);

                            var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                            client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                            boundary = "--" + boundary;
                            byte[] data = IO.UploadFile.GetUploadFilesRequestData(files, values);
                            client.UploadDataAsync(new Uri(url), data);
                        }
                        Main.menuMode = Interface.uploadModID;
                    }
            }
            catch (WebException e)
            {
                ErrorLogger.LogModBrowserException(e);
            }
        }
        private void InitializeMe(UITheme theme, int?idx, Mod mod, bool willDrawOwnHoverElements = true)
        {
            var      self    = this;
            TmodFile modfile = mod.File;

            this.Mod = mod;
            this.WillDrawOwnHoverElements = willDrawOwnHoverElements;

            this.Author                 = null;
            this.HomepageUrl            = null;
            this.HasIconLoaded          = false;
            this.LatestAvailableVersion = default(Version);

            if (ModHelpersMod.Instance.Config.IsCheckingModVersions)
            {
                Services.Tml.BuildPropertiesEditor props = modfile != null?
                                                           Services.Tml.BuildPropertiesEditor.GetBuildPropertiesForModFile(modfile) :
                                                               (Services.Tml.BuildPropertiesEditor)null;

                if (props != null)
                {
                    this.Author      = (string)props.GetField("author");
                    this.HomepageUrl = (string)props.GetField("homepage");
                }
            }

            // Container

            this.SetPadding(4f);
            this.Width.Set(0f, 1f);
            this.Height.Set(64, 0f);

            float titleOffset = 72f;

            // Mod index

            if (idx != null)
            {
                var modIdxElem = new UIText((int)idx + "");
                modIdxElem.Left.Set(titleOffset, 0f);
                this.Append((UIElement)modIdxElem);

                titleOffset += 16f;
            }

            // Mod title

            string modTitle = this.Mod.DisplayName + " " + this.Mod.Version.ToString();

            if (!String.IsNullOrEmpty(this.HomepageUrl))
            {
                this.TitleElem = new UIWebUrl(theme, modTitle, this.HomepageUrl, false);
            }
            else
            {
                this.TitleElem = new UIText(modTitle);
            }
            this.TitleElem.Left.Set(88f, 0f);
            this.Append((UIElement)this.TitleElem);

            // Mod author

            if (this.Author != null)
            {
                this.AuthorElem = new UIText("By: " + this.Author, 0.7f);
                this.AuthorElem.Top.Set(20f, 0f);
                this.AuthorElem.Left.Set(titleOffset, 0f);
                this.Append((UIElement)this.AuthorElem);
            }

            // Mod icon

            if (modfile != null && modfile.HasFile("icon.png"))
            {
                if (!Main.dedServ)                      //...?
                {
                    try {
                        var stream  = new MemoryStream(modfile.GetFile("icon.png"));
                        var iconTex = Texture2D.FromStream(Main.graphics.GraphicsDevice, stream);

                        if (iconTex.Width == 80 && iconTex.Height == 80)
                        {
                            this.IconElem = new UIImage(iconTex);
                            this.IconElem.Top.Set(-4f, 0f);
                            this.IconElem.Left.Set(-4f, 0f);
                            this.IconElem.MarginTop  = -8f;
                            this.IconElem.MarginLeft = -4f;
                            this.IconElem.ImageScale = 0.7f;
                            this.Append(this.IconElem);
                        }
                    } catch (Exception e) {
                        LogHelpers.Warn(e.ToString());
                    }
                }
            }

            // Mod config button

            if (ModFeaturesHelpers.HasConfig(mod))
            {
                if (Main.netMode == 0)
                {
                    if (ModFeaturesHelpers.HasConfigDefaultsReset(mod))
                    {
                        this.ConfigResetButton = new UITextPanelButton(theme, "Reset Config File");
                        this.ConfigResetButton.Width.Set(160f, 0f);
                        this.ConfigResetButton.Left.Set(-320f, 1f);
                        this.ConfigResetButton.Top.Set(28, 0f);
                        this.Append(this.ConfigResetButton);

                        this.ConfigResetButton.OnClick += delegate(UIMouseEvent evt, UIElement fromElem) {
                            string msg = mod.DisplayName + " config file reset to defaults.";

                            ModFeaturesHelpers.ResetDefaultsConfig(mod);
                            Main.NewText(msg, Color.Lime);
                            LogHelpers.Log(msg);
                        };
                    }

                    this.ConfigOpenButton = new UITextPanelButton(theme, "Open Config File");
                    this.ConfigOpenButton.Width.Set(160f, 0f);
                    this.ConfigOpenButton.Top.Set(28, 0f);
                    this.ConfigOpenButton.HAlign = 1f;
                    this.Append(this.ConfigOpenButton);

                    this.ConfigOpenButton.OnClick += delegate(UIMouseEvent evt, UIElement fromElem) {
                        string path     = ModFeaturesHelpers.GetConfigRelativePath(mod);
                        string fullpath = Main.SavePath + Path.DirectorySeparatorChar + path;

                        try {
                            Process.Start(fullpath);
                        } catch (Exception e) {
                            try {
                                string dir = new FileInfo(fullpath).Directory.FullName;
                                Process.Start(dir);
                            } catch (Exception) { }

                            Main.NewText("Couldn't open config file " + path + ": " + e.Message, Color.Red);
                        }
                    };
                }
            }
        }
Ejemplo n.º 12
0
        public UIModItem(TmodFile mod)
        {
            this.mod               = mod;
            this.BorderColor       = new Color(89, 116, 213) * 0.7f;
            this.dividerTexture    = TextureManager.Load("Images/UI/Divider");
            this.innerPanelTexture = TextureManager.Load("Images/UI/InnerPanelBackground");
            this.Height.Set(90f, 0f);
            this.Width.Set(0f, 1f);
            base.SetPadding(6f);
            //base.OnClick += this.ToggleEnabled;
            properties = BuildProperties.ReadModFile(mod);
            string text = properties.displayName.Length > 0 ? properties.displayName : mod.name;

            text += " v" + mod.version;
            if (mod.tModLoaderVersion < new Version(0, 10))
            {
                text += " [c/FF0000:(Old mod, enable at own risk)]";
            }
            int modIconAdjust = 0;

            if (mod.HasFile("icon.png"))
            {
                var modIconTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, new MemoryStream(mod.GetFile("icon.png")));
                if (modIconTexture.Width == 80 && modIconTexture.Height == 80)
                {
                    modIcon = new UIImage(modIconTexture);
                    modIcon.Left.Set(0f, 0f);
                    modIcon.Top.Set(0f, 0f);
                    Append(modIcon);
                    modIconAdjust += 85;
                }
            }
            this.modName = new UIText(text, 1f, false);
            this.modName.Left.Set(modIconAdjust + 10f, 0f);
            this.modName.Top.Set(5f, 0f);
            base.Append(this.modName);
            this.enabled = ModLoader.IsEnabled(mod);
            UITextPanel <string> button = new UITextPanel <string>("More info", 1f, false);

            button.Width.Set(100f, 0f);
            button.Height.Set(30f, 0f);
            button.Left.Set(430f, 0f);
            button.Top.Set(40f, 0f);
            button.PaddingTop    -= 2f;
            button.PaddingBottom -= 2f;
            button.OnMouseOver   += UICommon.FadedMouseOver;
            button.OnMouseOut    += UICommon.FadedMouseOut;
            button.OnClick       += this.Moreinfo;
            base.Append(button);
            button2 = new UITextPanel <string>(this.enabled ? "Disable" : "Enable", 1f, false);
            button2.Width.Set(100f, 0f);
            button2.Height.Set(30f, 0f);
            button2.Left.Set(button.Left.Pixels - button2.Width.Pixels - 5f, 0f);
            button2.Top.Set(40f, 0f);
            button2.PaddingTop    -= 2f;
            button2.PaddingBottom -= 2f;
            button2.OnMouseOver   += UICommon.FadedMouseOver;
            button2.OnMouseOut    += UICommon.FadedMouseOut;
            button2.OnClick       += this.ToggleEnabled;
            base.Append(button2);
            if (properties.modReferences.Length > 0 && !enabled)
            {
                string       refs             = String.Join(", ", properties.modReferences.Select(x => x.mod));
                UIHoverImage modReferenceIcon = new UIHoverImage(Main.quicksIconTexture, "This mod depends on: " + refs);
                modReferenceIcon.Left.Set(button2.Left.Pixels - 10f, 0f);
                modReferenceIcon.Top.Set(50f, 0f);
                base.Append(modReferenceIcon);
            }
            if (mod.ValidModBrowserSignature)
            {
                keyImage = new UIHoverImage(Main.itemTexture[ID.ItemID.GoldenKey], "This mod originated from the Mod Browser");
                keyImage.Left.Set(-20, 1f);
                base.Append(keyImage);
            }
            if (ModLoader.ModLoaded(mod.name))
            {
                Mod      loadedMod = ModLoader.GetMod(mod.name);
                int[]    values    = { loadedMod.items.Count, loadedMod.npcs.Count, loadedMod.tiles.Count, loadedMod.walls.Count, loadedMod.buffs.Count, loadedMod.mountDatas.Count };
                string[] strings   = { " items", " NPCs", " tiles", " walls", " buffs", " mounts" };
                int      xOffset   = -40;
                for (int i = 0; i < values.Length; i++)
                {
                    if (values[i] > 0)
                    {
                        Texture2D iconTexture = Main.instance.infoIconTexture[i];
                        keyImage = new UIHoverImage(iconTexture, values[i] + strings[i]);
                        keyImage.Left.Set(xOffset, 1f);
                        base.Append(keyImage);
                        xOffset -= 18;
                    }
                }
            }
        }