Beispiel #1
0
        /// <summary>
        /// Creates a copy of the specified workshop item in the staging folder and an editor that can be used to edit and update the item
        /// </summary>
        public static void CreateWorkshopItemStaging(Workshop.Item existingItem, out Workshop.Editor itemEditor, out ContentPackage contentPackage)
        {
            if (!existingItem.Installed)
            {
                itemEditor     = null;
                contentPackage = null;
                DebugConsole.ThrowError("Cannot edit the workshop item \"" + existingItem.Title + "\" because it has not been installed.");
                return;
            }

            var stagingFolder = new DirectoryInfo(WorkshopItemStagingFolder);

            if (stagingFolder.Exists)
            {
                SaveUtil.ClearFolder(stagingFolder.FullName);
            }
            else
            {
                stagingFolder.Create();
            }

            itemEditor                     = instance.client.Workshop.EditItem(existingItem.Id);
            itemEditor.Visibility          = Workshop.Editor.VisibilityType.Public;
            itemEditor.Title               = existingItem.Title;
            itemEditor.Tags                = existingItem.Tags.ToList();
            itemEditor.Description         = existingItem.Description;
            itemEditor.WorkshopUploadAppId = AppID;
            itemEditor.Folder              = stagingFolder.FullName;

            string previewImagePath = Path.GetFullPath(Path.Combine(itemEditor.Folder, PreviewImageName));

            itemEditor.PreviewImage = previewImagePath;

            using (WebClient client = new WebClient())
            {
                if (File.Exists(previewImagePath))
                {
                    File.Delete(previewImagePath);
                }
                client.DownloadFile(new Uri(existingItem.PreviewImageUrl), previewImagePath);
            }

            ContentPackage tempContentPackage = new ContentPackage(Path.Combine(existingItem.Directory.FullName, MetadataFileName));

            //item already installed, copy it from the game folder
            if (existingItem != null && CheckWorkshopItemEnabled(existingItem, checkContentFiles: false))
            {
                string installedItemPath = GetWorkshopItemContentPackagePath(tempContentPackage);
                if (File.Exists(installedItemPath))
                {
                    tempContentPackage = new ContentPackage(installedItemPath);
                }
            }
            if (File.Exists(tempContentPackage.Path))
            {
                string newContentPackagePath = Path.Combine(WorkshopItemStagingFolder, MetadataFileName);
                File.Copy(tempContentPackage.Path, newContentPackagePath, overwrite: true);
                contentPackage = new ContentPackage(newContentPackagePath);
                foreach (ContentFile contentFile in tempContentPackage.Files)
                {
                    string sourceFile;
                    if (contentFile.Type == ContentType.Submarine && File.Exists(contentFile.Path))
                    {
                        sourceFile = contentFile.Path;
                    }
                    else
                    {
                        sourceFile = Path.Combine(existingItem.Directory.FullName, contentFile.Path);
                    }
                    if (!File.Exists(sourceFile))
                    {
                        continue;
                    }
                    //make sure the destination directory exists
                    string destinationPath = Path.Combine(WorkshopItemStagingFolder, contentFile.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                    File.Copy(sourceFile, destinationPath, overwrite: true);
                    contentPackage.AddFile(contentFile.Path, contentFile.Type);
                }
            }
            else
            {
                contentPackage = ContentPackage.CreatePackage(existingItem.Title, Path.Combine(WorkshopItemStagingFolder, MetadataFileName), false);
                contentPackage.Save(contentPackage.Path);
            }
        }
Beispiel #2
0
        private void diffSaves()
        {
            if (!File.Exists(TB_OldSAV.Text))
            {
                WinFormsUtil.Alert("Save 1 path invalid."); return;
            }
            if (!File.Exists(TB_NewSAV.Text))
            {
                WinFormsUtil.Alert("Save 2 path invalid."); return;
            }
            if (new FileInfo(TB_OldSAV.Text).Length > 0x100000)
            {
                WinFormsUtil.Alert("Save 1 file invalid."); return;
            }
            if (new FileInfo(TB_NewSAV.Text).Length > 0x100000)
            {
                WinFormsUtil.Alert("Save 2 file invalid."); return;
            }

            SaveFile s1 = SaveUtil.getVariantSAV(File.ReadAllBytes(TB_OldSAV.Text));
            SaveFile s2 = SaveUtil.getVariantSAV(File.ReadAllBytes(TB_NewSAV.Text));

            if (s1.GetType() != s2.GetType())
            {
                WinFormsUtil.Alert("Save types are different.", $"S1: {s1.GetType().Name}", $"S2: {s2.GetType().Name}"); return;
            }
            if (s1.Version != s2.Version)
            {
                WinFormsUtil.Alert("Save versions are different.", $"S1: {s1.Version}", $"S2: {s2.Version}"); return;
            }

            string tbIsSet = "";
            string tbUnSet = "";

            try
            {
                bool[] oldBits = s1.EventFlags;
                bool[] newBits = s2.EventFlags;
                if (oldBits.Length != newBits.Length)
                {
                    WinFormsUtil.Alert("Event flag lengths for games are different.", $"S1: {(GameVersion)s1.Game}", $"S2: {(GameVersion)s2.Game}"); return;
                }

                for (int i = 0; i < oldBits.Length; i++)
                {
                    if (oldBits[i] == newBits[i])
                    {
                        continue;
                    }
                    if (newBits[i])
                    {
                        tbIsSet += i.ToString("0000") + ",";
                    }
                    else
                    {
                        tbUnSet += i.ToString("0000") + ",";
                    }
                }
            }
            catch (Exception e)
            {
                WinFormsUtil.Error("An unexpected error has occurred.", e);
                Console.Write(e);
            }
            TB_IsSet.Text = tbIsSet;
            TB_UnSet.Text = tbUnSet;

            string r = "";

            try
            {
                ushort[] oldConst = s1.EventConsts;
                ushort[] newConst = s2.EventConsts;
                if (oldConst.Length != newConst.Length)
                {
                    WinFormsUtil.Alert("Event flag lengths for games are different.", $"S1: {(GameVersion)s1.Game}", $"S2: {(GameVersion)s2.Game}"); return;
                }

                for (int i = 0; i < newConst.Length; i++)
                {
                    if (oldConst[i] != newConst[i])
                    {
                        r += $"{i}: {oldConst[i]}->{newConst[i]}{Environment.NewLine}";
                    }
                }
            }
            catch (Exception e)
            {
                WinFormsUtil.Error("An unexpected error has occurred.", e);
                Console.Write(e);
            }

            if (string.IsNullOrEmpty(r))
            {
                WinFormsUtil.Alert("No Event Constant diff found.");
                return;
            }

            if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Copy Event Constant diff to clipboard?"))
            {
                return;
            }
            Clipboard.SetText(r);
        }
Beispiel #3
0
        public SAV_Database(PKMEditor f1, SAVEditor saveditor)
        {
            SAV       = saveditor.SAV;
            BoxView   = saveditor;
            PKME_Tabs = f1;
            InitializeComponent();

            // Preset Filters to only show PKM available for loaded save
            CB_FormatComparator.SelectedIndex = 3; // <=

            PKXBOXES = new[]
            {
                bpkx1, bpkx2, bpkx3, bpkx4, bpkx5, bpkx6,
                bpkx7, bpkx8, bpkx9, bpkx10, bpkx11, bpkx12,
                bpkx13, bpkx14, bpkx15, bpkx16, bpkx17, bpkx18,
                bpkx19, bpkx20, bpkx21, bpkx22, bpkx23, bpkx24,
                bpkx25, bpkx26, bpkx27, bpkx28, bpkx29, bpkx30,

                bpkx31, bpkx32, bpkx33, bpkx34, bpkx35, bpkx36,
                bpkx37, bpkx38, bpkx39, bpkx40, bpkx41, bpkx42,
                bpkx43, bpkx44, bpkx45, bpkx46, bpkx47, bpkx48,
                bpkx49, bpkx50, bpkx51, bpkx52, bpkx53, bpkx54,
                bpkx55, bpkx56, bpkx57, bpkx58, bpkx59, bpkx60,
                bpkx61, bpkx62, bpkx63, bpkx64, bpkx65, bpkx66,
            };

            // Enable Scrolling when hovered over
            PAN_Box.MouseWheel += (sender, e) =>
            {
                if (ActiveForm == this)
                {
                    SCR_Box.Focus();
                }
            };
            foreach (var slot in PKXBOXES)
            {
                slot.MouseWheel += (sender, e) =>
                {
                    if (ActiveForm == this)
                    {
                        SCR_Box.Focus();
                    }
                };
                // Enable Click
                slot.MouseClick += (sender, e) =>
                {
                    if (ModifierKeys == Keys.Control)
                    {
                        ClickView(sender, e);
                    }
                    else if (ModifierKeys == Keys.Alt)
                    {
                        ClickDelete(sender, e);
                    }
                    else if (ModifierKeys == Keys.Shift)
                    {
                        ClickSet(sender, e);
                    }
                };
            }

            Counter       = L_Count.Text;
            Viewed        = L_Viewed.Text;
            L_Viewed.Text = ""; // invis for now
            var hover = new ToolTip();

            L_Viewed.MouseEnter += (sender, e) => hover.SetToolTip(L_Viewed, L_Viewed.Text);
            PopulateComboBoxes();

            ContextMenuStrip  mnu       = new ContextMenuStrip();
            ToolStripMenuItem mnuView   = new ToolStripMenuItem("View");
            ToolStripMenuItem mnuDelete = new ToolStripMenuItem("Delete");

            // Assign event handlers
            mnuView.Click   += ClickView;
            mnuDelete.Click += ClickDelete;

            // Add to main context menu
            mnu.Items.AddRange(new ToolStripItem[] { mnuView, mnuDelete });

            // Assign to datagridview
            foreach (PictureBox p in PKXBOXES)
            {
                p.ContextMenuStrip = mnu;
            }

            // Load Data
            var dbTemp = new ConcurrentBag <PKM>();
            var files  = Directory.GetFiles(DatabasePath, "*", SearchOption.AllDirectories);

            Parallel.ForEach(files, file =>
            {
                FileInfo fi = new FileInfo(file);
                if (!fi.Extension.Contains(".pk") || !PKX.IsPKM(fi.Length))
                {
                    return;
                }
                var pk = PKMConverter.GetPKMfromBytes(File.ReadAllBytes(file), file, prefer: (fi.Extension.Last() - 0x30) & 7);
                if (pk != null)
                {
                    dbTemp.Add(pk);
                }
            });

#if DEBUG
            if (SaveUtil.GetSavesFromFolder(Main.BackupPath, false, out IEnumerable <string> result))
            {
                Parallel.ForEach(result, file =>
                {
                    var sav  = SaveUtil.GetVariantSAV(File.ReadAllBytes(file));
                    var path = EXTERNAL_SAV + new FileInfo(file).Name;
                    if (sav.HasBox)
                    {
                        foreach (var pk in sav.BoxData)
                        {
                            addPKM(pk);
                        }
                    }

                    void addPKM(PKM pk)
                    {
                        pk.Identifier = Path.Combine(path, pk.Identifier);
                        dbTemp.Add(pk);
                    }
                });
            }
#endif

            // Prepare Database
            RawDB = new List <PKM>(dbTemp.OrderBy(pk => pk.Identifier)
                                   .Concat(SAV.BoxData.Where(pk => pk.Species != 0))      // Fetch from save file
                                   .Where(pk => pk.ChecksumValid && pk.Species != 0 && pk.Sanity == 0)
                                   .Distinct());
            SetResults(RawDB);

            Menu_SearchSettings.DropDown.Closing += (sender, e) =>
            {
                if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
                {
                    e.Cancel = true;
                }
            };
            CenterToParent();
        }
Beispiel #4
0
        private void LoadDatabase()
        {
            var dbTemp = new ConcurrentBag <PKM>();
            var files  = Directory.EnumerateFiles(DatabasePath, "*", SearchOption.AllDirectories);

            Parallel.ForEach(files, file =>
            {
                FileInfo fi = new FileInfo(file);
                if (!fi.Extension.Contains(".pk") || !PKX.IsPKM(fi.Length))
                {
                    return;
                }
                var data   = File.ReadAllBytes(file);
                var prefer = PKX.GetPKMFormatFromExtension(fi.Extension, SAV.Generation);
                var pk     = PKMConverter.GetPKMfromBytes(data, file, prefer);
                if (pk != null)
                {
                    dbTemp.Add(pk);
                }
            });

#if LOADALL
            if (SaveUtil.GetSavesFromFolder(Main.BackupPath, false, out IEnumerable <string> result))
            {
                Parallel.ForEach(result, file =>
                {
                    var sav  = SaveUtil.GetVariantSAV(file);
                    var path = EXTERNAL_SAV + new FileInfo(file).Name;
                    if (sav.HasBox)
                    {
                        foreach (var pk in sav.BoxData)
                        {
                            addPKM(pk);
                        }
                    }

                    void addPKM(PKM pk)
                    {
                        pk.Identifier = Path.Combine(path, pk.Identifier);
                        dbTemp.Add(pk);
                    }
                });
            }
#endif

            // Prepare Database
            RawDB = new List <PKM>(dbTemp.OrderBy(pk => pk.Identifier)
                                   .Concat(SAV.BoxData.Where(pk => pk.Species != 0)) // Fetch from save file
                                   .Where(pk => pk.ChecksumValid && pk.Species != 0 && pk.Sanity == 0)
                                   .Distinct());

            // Load stats for pkm who do not have any
            foreach (var pk in RawDB.Where(z => z.Stat_Level == 0))
            {
                pk.Stat_Level = pk.CurrentLevel;
                pk.SetStats(pk.GetStats(pk.PersonalInfo));
            }

            try
            {
                BeginInvoke(new MethodInvoker(() => SetResults(RawDB)));
            }
            catch { /* Window Closed? */ }
        }
Beispiel #5
0
 protected SAV_STADIUM(bool japanese, int size) : base(size)
 {
     Japanese = japanese;
     OT       = SaveUtil.GetSafeTrainerName(this, (LanguageID)Language);
 }
Beispiel #6
0
        private void GetEntry()
        {
            // Load Bools for the data
            int pk = species;

            // Load Partitions
            for (int i = 0; i < 9; i++)
            {
                CP[i].Checked = specbools[i, pk - 1];
            }

            if (species > 493)
            {
                for (int i = 0; i < 7; i++)
                {
                    CL[i].Checked = false;
                }
                GB_Language.Enabled = false;
            }
            else
            {
                for (int i = 0; i < 7; i++)
                {
                    CL[i].Checked = langbools[i, pk - 1];
                }
                GB_Language.Enabled = true;
            }

            int gt = SAV.Personal[pk].Gender;

            CHK_P2.Enabled = CHK_P4.Enabled = CHK_P6.Enabled = CHK_P8.Enabled = gt != 254;                 // Not Female-Only
            CHK_P3.Enabled = CHK_P5.Enabled = CHK_P7.Enabled = CHK_P9.Enabled = !(gt == 0 || (gt == 255)); // Not Male-Only and Not Genderless

            CLB_FormsSeen.Items.Clear();
            CLB_FormDisplayed.Items.Clear();

            int fc = SAV.Personal[species].FormeCount;
            int f  = SAV.B2W2 ? SaveUtil.GetDexFormIndexB2W2(species, fc) : SaveUtil.GetDexFormIndexBW(species, fc);

            if (f < 0)
            {
                return;
            }
            string[] forms = PKX.GetFormList(species, GameInfo.Strings.types, GameInfo.Strings.forms, Main.GenderSymbols);
            if (forms.Length < 1)
            {
                return;
            }

            for (int i = 0; i < forms.Length; i++) // Seen
            {
                CLB_FormsSeen.Items.Add(forms[i], formbools[f + i + 0 * FormLen * 8]);
            }
            for (int i = 0; i < forms.Length; i++) // Seen Shiny
            {
                CLB_FormsSeen.Items.Add("* " + forms[i], formbools[f + i + 1 * FormLen * 8]);
            }

            for (int i = 0; i < forms.Length; i++) // Displayed
            {
                CLB_FormDisplayed.Items.Add(forms[i], formbools[f + i + 2 * FormLen * 8]);
            }
            for (int i = 0; i < forms.Length; i++) // Displayed Shiny
            {
                CLB_FormDisplayed.Items.Add("* " + forms[i], formbools[f + i + 3 * FormLen * 8]);
            }
        }
 public static bool SaveScenario(DMEnv env, Scenario sce)
 {
     SaveUtil.Save(sce);
     env.Append("保存完毕:" + sce.Name);
     return(false);
 }
Beispiel #8
0
 public void Delete()
 {
     SaveUtil.DeleteObject(fileName, fileDir, fileExtension);
     dataObject = default(T);
 }
Beispiel #9
0
 public static string Control(DMEnv env, long selfId, Scenario sce, Investigator inv)
 {
     sce.Control(selfId, inv.Name);
     SaveUtil.Save(sce);
     return(env.Next = $"早啊,{inv.Name}!");
 }
Beispiel #10
0
        public override void OnRegister(CmdDispatcher <DMEnv> dispatcher)
        {
            dispatcher.Register("全局").Then(
                PresetNodes.Literal <DMEnv>("配置").Then(
                    PresetNodes.Literal <DMEnv>("载入")
                    .Executes((env, args, dict) => ("载入" + (SaveUtil.LoadGlobal() ? "成功" : "失败")))
                    ).Then(
                    PresetNodes.Literal <DMEnv>("保存")
                    .Executes((env, args, dict) => ("保存" + (SaveUtil.SaveGlobal() ? "成功" : "失败")))
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("调试").Then(
                    PresetNodes.Bool <DMEnv>("开关", "开", "关")
                    .Executes((env, args, dict) => {
                Global.Debug = args.GetBool("开关");
                env.Next     = "调试模式:" + (Global.Debug ? "开" : "关");
            })
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("回复").Then(
                    PresetNodes.Bool <DMEnv>("开关", "开", "关")
                    .Executes((env, args, dict) => {
                Global.DoAt = args.GetBool("开关");
                SaveUtil.SaveGlobal();
                env.Next = "回复:" + (Global.DoAt ? "开" : "关");
            })
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("自动载入").Then(
                    PresetNodes.Bool <DMEnv>("开关", "开", "关")
                    .Executes((env, args, dict) => {
                Global.AutoLoad = args.GetBool("开关");
                SaveUtil.SaveGlobal();
                env.Next = "自动载入:" + (Global.AutoLoad ? "开" : "关");
            })
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("翻译腔").Then(
                    PresetNodes.Bool <DMEnv>("开关", "开", "关")
                    .Executes((env, args, dict) => {
                Global.TranslatorTone = args.GetBool("开关");
                //SaveUtil.SaveGlobal();
                env.Next = "翻译腔:" + (Global.TranslatorTone ? "开" : "关");
            })
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("睡眠").Then(
                    PresetNodes.Bool <DMEnv>("开关", "开", "关")
                    .Executes((env, args, dict) => {
                Global.Sleep = args.GetBool("开关");
                SaveUtil.SaveGlobal();
                env.Next = (Global.Sleep ? "那我去睡觉觉咯~w" : "爷来啦!");
            })
                    )
                ).Then(
                PresetNodes.Literal <DMEnv>("灌铅")
                .Then(
                    PresetNodes.Int <DMEnv>("数值")
                    .Executes((env, args, dict) => {
                env.Next = !Global.AllowedLead ? "禁止给老娘灌铅!喵~o( =▼ω▼= )m!" : "当前铅量:" + (Global.SetLead(args.GetInt("数值")));
                SaveUtil.SaveGlobal();
            })
                    ).Then(
                    PresetNodes.Literal <DMEnv>("重置")
                    .Executes((env, args, dict) => {
                Global.SetLead(50);
                env.Next = "铅量已重置为" + Global.Lead;
                SaveUtil.SaveGlobal();
            })
                    )
                );

            dispatcher.SetAlias("配置", "全局 配置");
            dispatcher.SetAlias("调试", "全局 调试");
            dispatcher.SetAlias("回复", "全局 回复");
            dispatcher.SetAlias("自动载入", "全局 自动载入");
            dispatcher.SetAlias("闭嘴", "全局 睡眠 开");
            dispatcher.SetAlias("说话", "全局 睡眠 关");
            dispatcher.SetAlias("翻译腔", "全局 翻译腔");
            dispatcher.SetAlias("灌铅", "全局 灌铅");
        }
Beispiel #11
0
 public void Save()
 {
     SaveUtil.SaveObject(dataObject, fileName, fileDir, fileExtension);
 }
Beispiel #12
0
    public void CanMakeBlankSAV8()
    {
        var sav = SaveUtil.GetBlankSAV(GameVersion.SW, "PKHeX");

        sav.Should().NotBeNull();
    }
Beispiel #13
0
        private bool ValidateReceivedData(FileTransferIn fileTransfer, out string ErrorMessage)
        {
            ErrorMessage = "";
            switch (fileTransfer.FileType)
            {
            case FileTransferType.Submarine:
                System.IO.Stream stream;
                try
                {
                    stream = SaveUtil.DecompressFiletoStream(fileTransfer.FilePath);
                }
                catch (Exception e)
                {
                    ErrorMessage = "Loading received submarine \"" + fileTransfer.FileName + "\" failed! {" + e.Message + "}";
                    return(false);
                }

                if (stream == null)
                {
                    ErrorMessage = "Decompressing received submarine file \"" + fileTransfer.FilePath + "\" failed!";
                    return(false);
                }

                try
                {
                    stream.Position = 0;

                    XmlReaderSettings settings = new XmlReaderSettings
                    {
                        DtdProcessing = DtdProcessing.Prohibit,
                        IgnoreProcessingInstructions = true
                    };

                    using (var reader = XmlReader.Create(stream, settings))
                    {
                        while (reader.Read())
                        {
                            ;
                        }
                    }
                }
                catch
                {
                    stream?.Close();
                    ErrorMessage = "Parsing file \"" + fileTransfer.FilePath + "\" failed! The file may not be a valid submarine file.";
                    return(false);
                }

                stream?.Close();
                break;

            case FileTransferType.CampaignSave:
                try
                {
                    var files = SaveUtil.EnumerateContainedFiles(fileTransfer.FilePath);
                    foreach (var file in files)
                    {
                        string extension = Path.GetExtension(file);
                        if ((!extension.Equals(".sub", StringComparison.OrdinalIgnoreCase) &&
                             !file.Equals("gamesession.xml")) ||
                            file.CleanUpPathCrossPlatform(correctFilenameCase: false).Contains('/'))
                        {
                            ErrorMessage = $"Found unexpected file in \"{fileTransfer.FileName}\"! ({file})";
                            return(false);
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorMessage = $"Loading received campaign save \"{fileTransfer.FileName}\" failed! {{{e.Message}}}";
                    return(false);
                }
                break;
            }

            return(true);
        }
Beispiel #14
0
 public UnitAIs(string aggrKey, string defKey, string neuKey)
 {
     AggressiveAI = SaveUtil.LoadSafeList <ConditionalItem>(aggrKey);
     DefensiveAI  = SaveUtil.LoadSafeList <ConditionalItem>(defKey);
     NeutralAI    = SaveUtil.LoadSafeList <ConditionalItem>(neuKey);
 }
Beispiel #15
0
        /// <summary>
        /// Creates a copy of the specified workshop item in the staging folder and an editor that can be used to edit and update the item
        /// </summary>
        public static void CreateWorkshopItemStaging(Workshop.Item existingItem, out Workshop.Editor itemEditor, out ContentPackage contentPackage)
        {
            if (!existingItem.Installed)
            {
                itemEditor     = null;
                contentPackage = null;
                DebugConsole.ThrowError("Cannot edit the workshop item \"" + existingItem.Title + "\" because it has not been installed.");
                return;
            }

            var stagingFolder = new DirectoryInfo(WorkshopItemStagingFolder);

            if (stagingFolder.Exists)
            {
                SaveUtil.ClearFolder(stagingFolder.FullName);
            }
            else
            {
                stagingFolder.Create();
            }

            itemEditor                     = instance.client.Workshop.EditItem(existingItem.Id);
            itemEditor.Visibility          = Workshop.Editor.VisibilityType.Public;
            itemEditor.Title               = existingItem.Title;
            itemEditor.Tags                = existingItem.Tags.ToList();
            itemEditor.Description         = existingItem.Description;
            itemEditor.WorkshopUploadAppId = AppID;
            itemEditor.Folder              = stagingFolder.FullName;

            string previewImagePath = Path.GetFullPath(Path.Combine(itemEditor.Folder, PreviewImageName));

            itemEditor.PreviewImage = previewImagePath;

            try
            {
                if (File.Exists(previewImagePath))
                {
                    File.Delete(previewImagePath);
                }

                Uri    baseAddress = new Uri(existingItem.PreviewImageUrl);
                Uri    directory   = new Uri(baseAddress, "."); // "." == current dir, like MS-DOS
                string fileName    = Path.GetFileName(baseAddress.LocalPath);

                IRestClient client   = new RestClient(directory);
                var         request  = new RestRequest(fileName, Method.GET);
                var         response = client.Execute(request);

                if (response.ResponseStatus == ResponseStatus.Completed)
                {
                    File.WriteAllBytes(previewImagePath, response.RawBytes);
                }
            }

            catch (Exception e)
            {
                string errorMsg = "Failed to save workshop item preview image to \"" + previewImagePath + "\" when creating workshop item staging folder.";
                GameAnalyticsManager.AddErrorEventOnce("SteamManager.CreateWorkshopItemStaging:WriteAllBytesFailed" + previewImagePath,
                                                       GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + e.Message);
            }

            ContentPackage tempContentPackage = new ContentPackage(Path.Combine(existingItem.Directory.FullName, MetadataFileName));

            //item already installed, copy it from the game folder
            if (existingItem != null && CheckWorkshopItemEnabled(existingItem, checkContentFiles: false))
            {
                string installedItemPath = GetWorkshopItemContentPackagePath(tempContentPackage);
                if (File.Exists(installedItemPath))
                {
                    tempContentPackage = new ContentPackage(installedItemPath);
                }
            }
            if (File.Exists(tempContentPackage.Path))
            {
                string newContentPackagePath = Path.Combine(WorkshopItemStagingFolder, MetadataFileName);
                File.Copy(tempContentPackage.Path, newContentPackagePath, overwrite: true);
                contentPackage = new ContentPackage(newContentPackagePath);
                foreach (ContentFile contentFile in tempContentPackage.Files)
                {
                    string sourceFile;
                    if (contentFile.Type == ContentType.Submarine && File.Exists(contentFile.Path))
                    {
                        sourceFile = contentFile.Path;
                    }
                    else
                    {
                        sourceFile = Path.Combine(existingItem.Directory.FullName, contentFile.Path);
                    }
                    if (!File.Exists(sourceFile))
                    {
                        continue;
                    }
                    //make sure the destination directory exists
                    string destinationPath = Path.Combine(WorkshopItemStagingFolder, contentFile.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                    File.Copy(sourceFile, destinationPath, overwrite: true);
                    contentPackage.AddFile(contentFile.Path, contentFile.Type);
                }
            }
            else
            {
                contentPackage = ContentPackage.CreatePackage(existingItem.Title, Path.Combine(WorkshopItemStagingFolder, MetadataFileName), false);
                contentPackage.Save(contentPackage.Path);
            }
        }
        private void ChangeLBForms(object sender, EventArgs e)
        {
            if (allModifying)
            {
                return;
            }
            if (editing)
            {
                return;
            }
            SetEntry();

            editing = true;
            int fspecies = LB_Species.SelectedIndex + 1;
            var bspecies = fspecies <= SAV.MaxSpeciesID ? fspecies : baseSpecies[fspecies - SAV.MaxSpeciesID - 1];
            int form     = LB_Forms.SelectedIndex;

            if (form > 0)
            {
                int fc = SAV.Personal[bspecies].FormeCount;
                if (fc > 1) // actually has forms
                {
                    int f = SAV.USUM ? SaveUtil.GetDexFormIndexUSUM(bspecies, fc, SAV.MaxSpeciesID - 1) : SaveUtil.GetDexFormIndexSM(bspecies, fc, SAV.MaxSpeciesID - 1);
                    if (f >= 0) // bit index valid
                    {
                        species = f + form + 1;
                    }
                    else
                    {
                        species = bspecies;
                    }
                }
                else
                {
                    species = bspecies;
                }
            }
            else
            {
                species = bspecies;
            }
            CB_Species.SelectedValue = species;
            LB_Species.SelectedIndex = species - 1;
            LB_Species.TopIndex      = LB_Species.SelectedIndex;
            GetEntry();
            editing = false;
        }
Beispiel #17
0
 public int GetDexFormStart(int spec, int fc)
 {
     return(Parent.USUM
         ? SaveUtil.GetDexFormIndexUSUM(spec, fc, Parent.MaxSpeciesID - 1)
         : SaveUtil.GetDexFormIndexSM(spec, fc, Parent.MaxSpeciesID - 1));
 }
        private bool FillLBForms()
        {
            if (allModifying)
            {
                return(false);
            }
            LB_Forms.DataSource = null;
            LB_Forms.Items.Clear();

            int  fspecies = LB_Species.SelectedIndex + 1;
            var  bspecies = fspecies <= SAV.MaxSpeciesID ? fspecies : baseSpecies[fspecies - SAV.MaxSpeciesID - 1];
            bool hasForms = SAV.Personal[bspecies].HasFormes || new[] { 201, 664, 665, 414 }.Contains(bspecies);

            LB_Forms.Enabled = hasForms;
            if (!hasForms)
            {
                return(false);
            }
            var ds = PKX.GetFormList(bspecies, GameInfo.Strings.types, GameInfo.Strings.forms, Main.GenderSymbols, SAV.Generation).ToList();

            if (ds.Count == 1 && string.IsNullOrEmpty(ds[0]))
            {
                // empty
                LB_Forms.Enabled = false;
                return(false);
            }

            LB_Forms.DataSource = ds;
            if (fspecies <= SAV.MaxSpeciesID)
            {
                LB_Forms.SelectedIndex = 0;
            }
            else
            {
                int fc = SAV.Personal[bspecies].FormeCount;
                if (fc <= 1)
                {
                    return(true);
                }

                int f = SAV.USUM ? SaveUtil.GetDexFormIndexUSUM(bspecies, fc, SAV.MaxSpeciesID - 1) : SaveUtil.GetDexFormIndexSM(bspecies, fc, SAV.MaxSpeciesID - 1);
                if (f < 0)
                {
                    return(true); // bit index valid
                }
                if (f > fspecies - LB_Forms.Items.Count - 1)
                {
                    LB_Forms.SelectedIndex = fspecies - f - 1;
                }
                else
                {
                    LB_Forms.SelectedIndex = -1;
                }
            }
            return(true);
        }
Beispiel #19
0
        private void DiffSaves()
        {
            if (!File.Exists(TB_OldSAV.Text))
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 1)); return;
            }
            if (!File.Exists(TB_NewSAV.Text))
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 2)); return;
            }
            if (new FileInfo(TB_OldSAV.Text).Length > 0x100000)
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 1)); return;
            }
            if (new FileInfo(TB_NewSAV.Text).Length > 0x100000)
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 2)); return;
            }

            var s1 = SaveUtil.GetVariantSAV(TB_OldSAV.Text);
            var s2 = SaveUtil.GetVariantSAV(TB_NewSAV.Text);

            if (s1 == null)
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 1)); return;
            }
            if (s2 == null)
            {
                WinFormsUtil.Alert(string.Format(MsgSaveNumberInvalid, 2)); return;
            }

            if (s1.GetType() != s2.GetType())
            {
                WinFormsUtil.Alert(MsgSaveDifferentTypes, $"S1: {s1.GetType().Name}", $"S2: {s2.GetType().Name}"); return;
            }
            if (s1.Version != s2.Version)
            {
                WinFormsUtil.Alert(MsgSaveDifferentVersions, $"S1: {s1.Version}", $"S2: {s2.Version}"); return;
            }

            var tbIsSet = new List <int>();
            var tbUnSet = new List <int>();
            var result  = new List <string>();

            bool[] oldBits  = s1.EventFlags;
            bool[] newBits  = s2.EventFlags;
            var    oldConst = s1.EventConsts;
            var    newConst = s2.EventConsts;

            for (int i = 0; i < oldBits.Length; i++)
            {
                if (oldBits[i] != newBits[i])
                {
                    (newBits[i] ? tbIsSet : tbUnSet).Add(i);
                }
            }
            TB_IsSet.Text = string.Join(", ", tbIsSet.Select(z => $"{z:0000}"));
            TB_UnSet.Text = string.Join(", ", tbUnSet.Select(z => $"{z:0000}"));

            for (int i = 0; i < newConst.Length; i++)
            {
                if (oldConst[i] != newConst[i])
                {
                    result.Add($"{i}: {oldConst[i]}->{newConst[i]}");
                }
            }

            if (result.Count == 0)
            {
                WinFormsUtil.Alert("No Event Constant diff found.");
                return;
            }

            if (DialogResult.Yes == WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Copy Event Constant diff to clipboard?"))
            {
                Clipboard.SetText(string.Join(Environment.NewLine, result));
            }
        }
Beispiel #20
0
 // Use this for initialization
 void Start()
 {
     totalAmountOfLivesSavedOutput.text = SaveUtil.LoadData() + "";
 }
Beispiel #21
0
        private void GetEntry()
        {
            // Load Bools for the data
            int pk = species;

            L_Spinda.Visible = TB_Spinda.Visible = pk == 327;

            // Load Partitions
            for (int i = 0; i < 9; i++)
            {
                CP[i].Checked = specbools[i, pk - 1];
            }
            for (int i = 0; i < 7; i++)
            {
                CL[i].Checked = langbools[i, pk - 1];
            }

            if (pk < 650)
            {
                CHK_F1.Enabled = true; CHK_F1.Checked = foreignbools[pk - 1];
            }
            else
            {
                CHK_F1.Enabled = CHK_F1.Checked = false;
            }

            int gt = SAV.Personal[pk].Gender;

            CHK_P2.Enabled = CHK_P4.Enabled = CHK_P6.Enabled = CHK_P8.Enabled = gt != 254;                 // Not Female-Only
            CHK_P3.Enabled = CHK_P5.Enabled = CHK_P7.Enabled = CHK_P9.Enabled = !(gt == 0 || (gt == 255)); // Not Male-Only and Not Genderless

            CLB_FormsSeen.Items.Clear();
            CLB_FormDisplayed.Items.Clear();

            int fc = SAV.Personal[species].FormeCount;
            int f  = SaveUtil.GetDexFormIndexXY(species, fc);

            if (f < 0)
            {
                return;
            }
            string[] forms = PKX.GetFormList(species, GameInfo.Strings.types, GameInfo.Strings.forms, Main.GenderSymbols, SAV.Generation);
            if (forms.Length < 1)
            {
                return;
            }

            // 0x26 packs of bools
            for (int i = 0; i < forms.Length; i++) // Seen
            {
                CLB_FormsSeen.Items.Add(forms[i], formbools[f + i + 0 * FormLen * 8]);
            }
            for (int i = 0; i < forms.Length; i++) // Seen Shiny
            {
                CLB_FormsSeen.Items.Add($"* {forms[i]}", formbools[f + i + 1 * FormLen * 8]);
            }

            for (int i = 0; i < forms.Length; i++) // Displayed
            {
                CLB_FormDisplayed.Items.Add(forms[i], formbools[f + i + 2 * FormLen * 8]);
            }
            for (int i = 0; i < forms.Length; i++) // Displayed Shiny
            {
                CLB_FormDisplayed.Items.Add($"* {forms[i]}", formbools[f + i + 3 * FormLen * 8]);
            }
        }
Beispiel #22
0
        private bool fillLBForms()
        {
            if (allModifying)
            {
                return(false);
            }
            LB_Forms.DataSource = null;
            LB_Forms.Items.Clear();

            int bspecies;
            int fspecies = LB_Species.SelectedIndex + 1;

            if (fspecies <= SAV.MaxSpeciesID)
            {
                bspecies = fspecies;
            }
            else
            {
                bspecies = baseSpecies[fspecies - SAV.MaxSpeciesID - 1];
            }
            bool hasForms = SAV.Personal[bspecies].HasFormes || new[] { 201, 664, 665, 414 }.Contains(bspecies);

            LB_Forms.Enabled = hasForms;
            if (!hasForms)
            {
                return(false);
            }
            var ds = PKX.getFormList(bspecies, GameInfo.Strings.types, GameInfo.Strings.forms, new[] { "♂", "♀", "-" }, SAV.Generation).ToList();

            if (ds.Count == 1 && string.IsNullOrEmpty(ds[0]))
            { // empty (Alolan Totems)
                LB_Forms.Enabled = false;
                return(false);
            }
            else
            {
                LB_Forms.DataSource = ds;
                if (fspecies <= SAV.MaxSpeciesID)
                {
                    LB_Forms.SelectedIndex = 0;
                }
                else
                {
                    int fc = SAV.Personal[bspecies].FormeCount;
                    if (fc > 1) // actually has forms
                    {
                        int f = SaveUtil.getDexFormIndexSM(bspecies, fc, SAV.MaxSpeciesID - 1);
                        if (f >= 0)
                        { // bit index valid
                            if (f > fspecies - LB_Forms.Items.Count - 1)
                            {
                                LB_Forms.SelectedIndex = fspecies - f - 1;
                            }
                            else
                            {
                                LB_Forms.SelectedIndex = -1;
                            }
                        }
                    }
                }
            }
            return(true);
        }
Beispiel #23
0
    public static bool IsFileTooSmall(long length) => length < 0x20; // bigger than PK1

    /// <summary>
    /// Tries to get an <see cref="SaveFile"/> object from the input parameters.
    /// </summary>
    /// <param name="data">Binary data</param>
    /// <param name="sav">Output result</param>
    /// <returns>True if file object reference is valid, false if none found.</returns>
    public static bool TryGetSAV(byte[] data, [NotNullWhen(true)] out SaveFile?sav)
    {
        sav = SaveUtil.GetVariantSAV(data);
        return(sav != null);
    }
 public override int SaveChanges()
 {
     return(SaveUtil.ExecuteDatabaseSave(base.SaveChanges));
 }
Beispiel #25
0
        private bool ValidateReceivedData(FileTransferIn fileTransfer, out string ErrorMessage)
        {
            ErrorMessage = "";
            switch (fileTransfer.FileType)
            {
            case FileTransferType.Submarine:
                Stream stream = null;

                try
                {
                    stream = SaveUtil.DecompressFiletoStream(fileTransfer.FilePath);
                }
                catch (Exception e)
                {
                    ErrorMessage = "Loading received submarine \"" + fileTransfer.FileName + "\" failed! {" + e.Message + "}";
                    return(false);
                }

                if (stream == null)
                {
                    ErrorMessage = "Decompressing received submarine file \"" + fileTransfer.FilePath + "\" failed!";
                    return(false);
                }

                try
                {
                    stream.Position = 0;

                    XmlReaderSettings settings = new XmlReaderSettings
                    {
                        DtdProcessing = DtdProcessing.Prohibit,
                        IgnoreProcessingInstructions = true
                    };

                    using (var reader = XmlReader.Create(stream, settings))
                    {
                        while (reader.Read())
                        {
                            ;
                        }
                    }
                }
                catch
                {
                    stream.Close();
                    stream.Dispose();

                    ErrorMessage = "Parsing file \"" + fileTransfer.FilePath + "\" failed! The file may not be a valid submarine file.";
                    return(false);
                }

                stream.Close();
                stream.Dispose();
                break;

            case FileTransferType.CampaignSave:
                //TODO: verify that the received file is a valid save file
                break;
            }

            return(true);
        }
Beispiel #26
0
 public void Save()
 {
     SaveUtil.Save(Sce);
 }
    private void CreateSave()
    {
        SaveUtil.CreateSave(levelNumber, maxAngleDifference);

        SceneManager.LoadScene(1);
    }
Beispiel #28
0
 public override void OnActivated()
 {
     SaveUtil.SaveData(SceneUtils.FindObject <TransformerGameManager>().GetLivesSaved());
     SceneUtils.FindObject <SpecialBackgroundMusic>().SaveBackgroundMusicTime();
     Loader.LoadSceneQuickly(sceneToLoadOnFinish);
 }