From aaec3eb1f2ef921deeb4691e081f613cf9eafc64 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:19:52 +0200 Subject: [PATCH 1/8] PckStudio - Enabled 'Treat all warnings as errors' --- PCK-Studio/Classes/Models/ModelView.Designer.cs | 2 -- PCK-Studio/Forms/Skins-And-Textures/generateModel.cs | 4 ---- PCK-Studio/PckStudio.csproj | 2 ++ 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/PCK-Studio/Classes/Models/ModelView.Designer.cs b/PCK-Studio/Classes/Models/ModelView.Designer.cs index 25d398b1..bfedcec8 100644 --- a/PCK-Studio/Classes/Models/ModelView.Designer.cs +++ b/PCK-Studio/Classes/Models/ModelView.Designer.cs @@ -57,8 +57,6 @@ namespace PckStudio.Models private System.Drawing.Image backgroundTexture; - private System.Drawing.Image usernameImage; - internal PckStudio.Models.Matrix3D GlobalTransformation = PckStudio.Models.Matrix3D.Identity; private System.Collections.Generic.List texelList = new System.Collections.Generic.List(); diff --git a/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs b/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs index a912fa34..6d318052 100644 --- a/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs +++ b/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs @@ -20,12 +20,8 @@ using System.Text; namespace PckStudio.Forms { - [Obsolete] public partial class generateModel : MetroForm { - [Obsolete("We don't need a full control to get an image")] - private PictureBox _skinPreview = new PictureBox(); - private Image _previewImage; public Image PreviewImage => _previewImage; diff --git a/PCK-Studio/PckStudio.csproj b/PCK-Studio/PckStudio.csproj index e92f8580..0c7fe072 100644 --- a/PCK-Studio/PckStudio.csproj +++ b/PCK-Studio/PckStudio.csproj @@ -45,6 +45,8 @@ prompt 4 true + CS0618 + true AnyCPU From ea1a427c2a3be9550cde1df1a5bb75e0b3b6f3ee Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:20:33 +0200 Subject: [PATCH 2/8] generateModel - Remove Import/Export buttons --- .../generateModel.Designer.cs | 33 ---- .../Forms/Skins-And-Textures/generateModel.cs | 176 ------------------ .../Skins-And-Textures/generateModel.resx | 118 ++---------- 3 files changed, 14 insertions(+), 313 deletions(-) diff --git a/PCK-Studio/Forms/Skins-And-Textures/generateModel.Designer.cs b/PCK-Studio/Forms/Skins-And-Textures/generateModel.Designer.cs index f4864d91..3639d52c 100644 --- a/PCK-Studio/Forms/Skins-And-Textures/generateModel.Designer.cs +++ b/PCK-Studio/Forms/Skins-And-Textures/generateModel.Designer.cs @@ -61,10 +61,7 @@ this.buttonEXPORT = new System.Windows.Forms.Button(); this.buttonIMPORT = new System.Windows.Forms.Button(); this.uvPictureBox = new PckStudio.ToolboxItems.InterpolationPictureBox(); - this.buttonImportModel = new System.Windows.Forms.Button(); this.displayBox = new System.Windows.Forms.PictureBox(); - this.buttonExportModel = new System.Windows.Forms.Button(); - this.OpenJSONButton = new System.Windows.Forms.Button(); this.buttonTemplate = new MetroFramework.Controls.MetroButton(); this.generateTextureCheckBox = new MetroFramework.Controls.MetroCheckBox(); this.checkGuide = new MetroFramework.Controls.MetroCheckBox(); @@ -333,14 +330,6 @@ this.uvPictureBox.Name = "uvPictureBox"; this.uvPictureBox.TabStop = false; // - // buttonImportModel - // - resources.ApplyResources(this.buttonImportModel, "buttonImportModel"); - this.buttonImportModel.ForeColor = System.Drawing.Color.White; - this.buttonImportModel.Name = "buttonImportModel"; - this.buttonImportModel.UseVisualStyleBackColor = true; - this.buttonImportModel.Click += new System.EventHandler(this.buttonImportModel_Click); - // // displayBox // this.displayBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); @@ -349,22 +338,6 @@ this.displayBox.Name = "displayBox"; this.displayBox.TabStop = false; // - // buttonExportModel - // - resources.ApplyResources(this.buttonExportModel, "buttonExportModel"); - this.buttonExportModel.ForeColor = System.Drawing.Color.White; - this.buttonExportModel.Name = "buttonExportModel"; - this.buttonExportModel.UseVisualStyleBackColor = true; - this.buttonExportModel.Click += new System.EventHandler(this.buttonExportModel_Click); - // - // OpenJSONButton - // - resources.ApplyResources(this.OpenJSONButton, "OpenJSONButton"); - this.OpenJSONButton.ForeColor = System.Drawing.Color.White; - this.OpenJSONButton.Name = "OpenJSONButton"; - this.OpenJSONButton.UseVisualStyleBackColor = true; - this.OpenJSONButton.Click += new System.EventHandler(this.OpenJSONButton_Click); - // // buttonTemplate // resources.ApplyResources(this.buttonTemplate, "buttonTemplate"); @@ -573,9 +546,6 @@ this.Controls.Add(this.buttonTemplate); this.Controls.Add(this.displayBox); this.Controls.Add(this.listViewBoxes); - this.Controls.Add(this.OpenJSONButton); - this.Controls.Add(this.buttonExportModel); - this.Controls.Add(this.buttonImportModel); this.Controls.Add(this.buttonEXPORT); this.Controls.Add(labelTextureMappingPreview); this.Controls.Add(this.uvPictureBox); @@ -625,10 +595,7 @@ private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem changeColorToolStripMenuItem; private System.Windows.Forms.Button buttonDone; - private System.Windows.Forms.Button OpenJSONButton; - private System.Windows.Forms.Button buttonExportModel; private System.Windows.Forms.PictureBox displayBox; - private System.Windows.Forms.Button buttonImportModel; private PckStudio.ToolboxItems.InterpolationPictureBox uvPictureBox; private System.Windows.Forms.Button buttonIMPORT; private System.Windows.Forms.Button buttonEXPORT; diff --git a/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs b/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs index 6d318052..6f125949 100644 --- a/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs +++ b/PCK-Studio/Forms/Skins-And-Textures/generateModel.cs @@ -1166,62 +1166,6 @@ namespace PckStudio.Forms } } - // Exports model as csm file - private void buttonExportModel_Click(object sender, EventArgs e) - { - SaveFileDialog saveFileDialog = new SaveFileDialog(); - saveFileDialog.Filter = "Custom Skin Model File | *.CSM"; - if (saveFileDialog.ShowDialog(this) != DialogResult.OK) - return; - string contents = ""; - foreach (ListViewItem listViewItem in listViewBoxes.Items) - { - string str = ""; - foreach (ListViewItem.ListViewSubItem subItem in listViewItem.SubItems) - { - if (subItem.Text != "unchecked") - str = str + subItem.Text + Environment.NewLine; - } - contents += (listViewItem.Text + Environment.NewLine + listViewItem.Tag) + Environment.NewLine + str; - } - - File.WriteAllText(saveFileDialog.FileName, contents); - } - - - // Imports model from csm file - private void buttonImportModel_Click(object sender, EventArgs e) - { - OpenFileDialog openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "Custom Skin Model File | *.CSM"; - openFileDialog.Title = "Select Custom Skin Model File"; - if (MessageBox.Show(this, "Import custom model project file? Your current work will be lost!", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes && openFileDialog.ShowDialog(this) == DialogResult.OK) - { - listViewBoxes.Items.Clear(); - modelBoxes.Clear(); - StreamReader reader = new StreamReader(openFileDialog.FileName); - while (!reader.EndOfStream) - { - reader.ReadLine(); - string part = reader.ReadLine(); - reader.ReadLine(); - var posX = reader.ReadLine(); - var posY = reader.ReadLine(); - var posZ = reader.ReadLine(); - var sizeX = reader.ReadLine(); - var sizeY = reader.ReadLine(); - var sizeZ = reader.ReadLine(); - var uvX = reader.ReadLine(); - var uvY = reader.ReadLine(); - modelBoxes.Add(SkinBOX.FromString($"{part} {posX} {posY} {posZ} {sizeX} {sizeY} {sizeZ} {uvX} {uvY}")); - } - - } - comboParent.Enabled = true; - UpdateListView(); - Rerender(); - } - private void cloneToolStripMenuItem_Click(object sender, EventArgs e) { try @@ -1341,7 +1285,6 @@ namespace PckStudio.Forms e.Cancel = false;*/ } - //Del stuff using key private void delStuffUsingDelKey(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete && listViewBoxes.SelectedItems.Count != 0 && @@ -1357,124 +1300,5 @@ namespace PckStudio.Forms { Rerender(); } - - // TODO - private void OpenJSONButton_Click(object sender, EventArgs e) - { - OpenFileDialog openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "JSON Model File | *.JSON"; - openFileDialog.Title = "Select JSON Model File"; - if (MessageBox.Show(this, "Import custom model project file? Your current work will be lost!", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes && openFileDialog.ShowDialog(this) == DialogResult.OK) - { - listViewBoxes.Items.Clear(); - string str1 = JSONToCSM(openFileDialog.FileName); - int x = 0; - foreach (string str2 in str1.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) - ++x; - int y = x / 11; - ListView listView = new ListView(); - int num3 = 0; - do - { - listView.Items.Add("BOX"); - ++num3; - } - while (num3 < y); - - - foreach (ListViewItem current in listView.Items) - { - ListViewItem listViewItem = new ListViewItem(); - int num4 = 0; - foreach (string text in str1.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) - { - ++num4; - if (num4 == 1 + 11 * current.Index) - listViewItem.Text = text; - else if (num4 == 2 + 11 * current.Index) - listViewItem.Tag = text; - else if (num4 == 4 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 5 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 6 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 7 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 8 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 9 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 10 + 11 * current.Index) - listViewItem.SubItems.Add(text); - else if (num4 == 11 + 11 * current.Index) - { - listViewItem.SubItems.Add(text); - listViewBoxes.Items.Add(listViewItem); - } - } - } - } - Rerender(); - } - - [Obsolete("Just whyyyyy")] - public string JSONToCSM(string inputFilePath) - { - CSMJObject jsonDe = JsonConvert.DeserializeObject(File.ReadAllText(inputFilePath)); - StringBuilder sb = new StringBuilder(); - foreach (CSMJObjectGroup group in jsonDe.Groups) - { - string parent = group.Name; - foreach (int i in group.children) - { - string name = jsonDe.Elements[i].Name; - float posX = jsonDe.Elements[i].from[0] + group.origin[0]; - float posY = jsonDe.Elements[i].from[1] + group.origin[1]; - float posZ = jsonDe.Elements[i].from[2] + group.origin[2]; - float sizeX = jsonDe.Elements[i].to[0] - jsonDe.Elements[i].from[0]; - float sizeY = jsonDe.Elements[i].to[1] - jsonDe.Elements[i].from[1]; - float sizeZ = jsonDe.Elements[i].to[2] - jsonDe.Elements[i].from[2]; - float u = 0; - float v = 0; - - sb.AppendLine(name + "\n" + parent + "\n" + name + "\n" + posX + "\n" + posY + "\n" + posZ + "\n" + sizeX + "\n" + sizeY + "\n" + sizeZ + "\n" + u + "\n" + v); - } - } - return sb.ToString(); - } - } - - class CSMJObject - { - [JsonProperty("credit")] - public string Credit { get; set; } - - [JsonProperty("texture_size")] - public int[] TextureSize; - - [JsonProperty("elements")] - public CSMJObjectElement[] Elements; - - [JsonProperty("groups")] - public CSMJObjectGroup[] Groups; - } - - class CSMJObjectElement - { - [JsonProperty("name")] - public string Name { get; set; } - - public float[] from; - public float[] to; - } - - class CSMJObjectGroup - { - [JsonProperty("name")] - public string Name { get; set; } - - public float[] origin; - public int[] children; } } \ No newline at end of file diff --git a/PCK-Studio/Forms/Skins-And-Textures/generateModel.resx b/PCK-Studio/Forms/Skins-And-Textures/generateModel.resx index 1fa4fc59..da2157ab 100644 --- a/PCK-Studio/Forms/Skins-And-Textures/generateModel.resx +++ b/PCK-Studio/Forms/Skins-And-Textures/generateModel.resx @@ -151,7 +151,7 @@ $this - 22 + 19 False @@ -184,7 +184,7 @@ $this - 31 + 28 False @@ -217,7 +217,7 @@ $this - 30 + 27 False @@ -250,7 +250,7 @@ $this - 25 + 22 False @@ -283,7 +283,7 @@ $this - 19 + 16 17, 17 @@ -394,7 +394,7 @@ $this - 29 + 26 True @@ -424,7 +424,7 @@ $this - 28 + 25 Flat @@ -454,7 +454,7 @@ $this - 27 + 24 Flat @@ -484,7 +484,7 @@ $this - 26 + 23 4, 22 @@ -859,7 +859,7 @@ $this - 24 + 21 HEAD @@ -898,7 +898,7 @@ $this - 21 + 18 Flat @@ -928,7 +928,7 @@ $this - 18 + 15 Flat @@ -958,7 +958,7 @@ $this - 23 + 20 NoControl @@ -979,42 +979,12 @@ uvPictureBox - PckStudio.PictureBoxWithInterpolationMode, PCK-Studio, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null + PckStudio.ToolboxItems.InterpolationPictureBox, PCK-Studio, Version=7.0.0.2, Culture=neutral, PublicKeyToken=null $this - 20 - - - Flat - - - NoControl - - - 306, 677 - - - 106, 21 - - - 96 - - - OPEN CSM - - - buttonImportModel - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - $this - - 17 @@ -1044,66 +1014,6 @@ 13 - - Flat - - - NoControl - - - 418, 677 - - - 89, 21 - - - 97 - - - EXPORT CSM - - - buttonExportModel - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - $this - - - 16 - - - Flat - - - NoControl - - - 194, 677 - - - 106, 21 - - - 145 - - - OPEN JSON - - - OpenJSONButton - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - $this - - - 15 - 23, 511 From 751b7fb5f54cbd9a99bdb492599449554877d658 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:22:08 +0200 Subject: [PATCH 3/8] MainForm - Remove 'IsSubPCKNode' & 'RebuildSubPCK' --- PCK-Studio/MainForm.cs | 69 ++++++++++-------------------------------- 1 file changed, 16 insertions(+), 53 deletions(-) diff --git a/PCK-Studio/MainForm.cs b/PCK-Studio/MainForm.cs index 888355e3..96e5b295 100644 --- a/PCK-Studio/MainForm.cs +++ b/PCK-Studio/MainForm.cs @@ -735,27 +735,10 @@ namespace PckStudio string selectedFolder = node.FullPath; - if (IsSubPCKNode(node.FullPath)) - { - GetAllChildNodes(node.Nodes).ForEach(fileNode => - { - if (fileNode.TryGetTagData(out PckAsset asset)) - { - extractFolderFile(outPath, asset); - } - } - ); - } - else - { - foreach (PckAsset asset in currentPCK.GetAssets()) - { - if (asset.Filename.StartsWith(selectedFolder)) - { - extractFolderFile(outPath, asset); - } - } - } + foreach (PckAsset asset in currentPCK.GetAssets().Where(asset => asset.Filename.StartsWith(selectedFolder))) + { + extractFolderFile(outPath, asset); + } } private void extractToolStripMenuItem_Click(object sender, EventArgs e) @@ -848,7 +831,6 @@ namespace PckStudio string newFileExt = Path.GetExtension(ofd.FileName); asset.SetData(File.ReadAllBytes(ofd.FileName)); asset.Filename = asset.Filename.Replace(fileExt, newFileExt); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); wasModified = true; BuildMainTreeView(); } @@ -914,7 +896,6 @@ namespace PckStudio node.Remove(); wasModified = true; } - RebuildSubPCK(path); } private void renameFileToolStripMenuItem_Click(object sender, EventArgs e) @@ -953,7 +934,6 @@ namespace PckStudio } } wasModified = true; - RebuildSubPCK(path); BuildMainTreeView(); } } @@ -1221,7 +1201,6 @@ namespace PckStudio if (diag.ShowDialog(this) == DialogResult.OK) { asset.SetProperty(asset.GetPropertyIndex(property), new KeyValuePair("ANIM", diag.ResultAnim.ToString())); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } @@ -1238,11 +1217,10 @@ namespace PckStudio case "BOX" when asset.Type == PckAssetType.SkinFile: try { - using BoxEditor diag = new BoxEditor(property.Value, IsSubPCKNode(treeViewMain.SelectedNode.FullPath)); + using BoxEditor diag = new BoxEditor(property.Value, false); if (diag.ShowDialog(this) == DialogResult.OK) { asset.SetProperty(asset.GetPropertyIndex(property), new KeyValuePair("BOX", diag.Result.ToString())); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } @@ -1266,7 +1244,6 @@ namespace PckStudio if (addProperty.ShowDialog(this) == DialogResult.OK) { asset.SetProperty(asset.GetPropertyIndex(property), addProperty.Property); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } @@ -1320,10 +1297,7 @@ namespace PckStudio else node.Parent.Nodes.Insert(node.Index + 1, newNode); - if (!IsSubPCKNode(node.FullPath)) - currentPCK.InsertAsset(node.Index + 1, newFile); - else - RebuildSubPCK(node.FullPath); + currentPCK.InsertAsset(node.Index + 1, newFile); BuildMainTreeView(); wasModified = true; } @@ -1337,7 +1311,6 @@ namespace PckStudio asset.RemoveProperty(property)) { treeMeta.SelectedNode.Remove(); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); wasModified = true; } } @@ -1364,7 +1337,6 @@ namespace PckStudio if (addProperty.ShowDialog(this) == DialogResult.OK) { asset.AddProperty(addProperty.Property); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } @@ -2012,23 +1984,23 @@ namespace PckStudio break; case PckAssetType.TexturePackInfoFile: goto default; - node.ImageIndex = 4; - node.SelectedImageIndex = 4; - break; + //node.ImageIndex = 4; + //node.SelectedImageIndex = 4; + //break; case PckAssetType.ColourTableFile: node.ImageIndex = 6; node.SelectedImageIndex = 6; break; case PckAssetType.ModelsFile: goto default; - node.ImageIndex = 8; - node.SelectedImageIndex = 8; - break; + //node.ImageIndex = 8; + //node.SelectedImageIndex = 8; + //break; case PckAssetType.SkinDataFile: goto default; - node.ImageIndex = 7; - node.SelectedImageIndex = 7; - break; + //node.ImageIndex = 7; + //node.SelectedImageIndex = 7; + //break; case PckAssetType.GameRulesFile: node.ImageIndex = 9; node.SelectedImageIndex = 9; @@ -2075,11 +2047,9 @@ namespace PckStudio Debug.WriteLine($"Setting {asset.Type} to {type}"); asset.Type = type; SetNodeIcon(treeViewMain.SelectedNode, type); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); } } - [Obsolete()] private void addTextureToolStripMenuItem_Click(object sender, EventArgs e) { using OpenFileDialog fileDialog = new OpenFileDialog(); @@ -2217,7 +2187,6 @@ namespace PckStudio asset.AddProperty(line.Substring(0, idx), line.Substring(idx + 1)); } ReloadMetaTreeView(); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); wasModified = true; } } @@ -2235,7 +2204,6 @@ namespace PckStudio asset.SetProperty(asset.GetPropertyIndex(p), new KeyValuePair(p.Key, p.Value.Replace(',', '.'))); } ReloadMetaTreeView(); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); wasModified = true; } } @@ -2272,7 +2240,6 @@ namespace PckStudio asset.AddProperty(line.Substring(0, idx).Replace(":", string.Empty), line.Substring(idx + 1)); } ReloadMetaTreeView(); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); wasModified = true; } } @@ -2299,8 +2266,6 @@ namespace PckStudio } PckAsset asset = currentPCK.CreateNewAsset(diag.Filepath, diag.Filetype, () => File.ReadAllBytes(ofd.FileName)); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); - BuildMainTreeView(); wasModified = true; } @@ -2396,11 +2361,10 @@ namespace PckStudio { if (treeViewMain.SelectedNode is TreeNode t && t.Tag is PckAsset asset) { - using BoxEditor diag = new BoxEditor(SkinBOX.Empty, IsSubPCKNode(treeViewMain.SelectedNode.FullPath)); + using BoxEditor diag = new BoxEditor(SkinBOX.Empty, false); if (diag.ShowDialog(this) == DialogResult.OK) { asset.AddProperty("BOX", diag.Result); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } @@ -2416,7 +2380,6 @@ namespace PckStudio if (diag.ShowDialog(this) == DialogResult.OK) { asset.AddProperty("ANIM", diag.ResultAnim); - RebuildSubPCK(treeViewMain.SelectedNode.FullPath); ReloadMetaTreeView(); wasModified = true; } From f04977feb8a920de76b28606ab0cf01a80e1a217 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:22:32 +0200 Subject: [PATCH 4/8] Update OMI submodule ref --- Vendor/OMI-Lib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Vendor/OMI-Lib b/Vendor/OMI-Lib index 02d37596..8da46067 160000 --- a/Vendor/OMI-Lib +++ b/Vendor/OMI-Lib @@ -1 +1 @@ -Subproject commit 02d37596d071f8fa7b0fb98f6d7c989c7a98e774 +Subproject commit 8da46067972139bb68334c80da3914893b5aeca7 From 2751425113bbe97c8b5eaaafa3fdc44525cd8023 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 16:28:45 +0200 Subject: [PATCH 5/8] PckAssetExtensions - Update 'DeserializeProperties' & 'SerializeProperties' --- PCK-Studio/Extensions/PckAssetExtensions.cs | 31 +-- .../Additional-Popups/MultiTextPrompt.cs | 14 +- PCK-Studio/MainForm.cs | 262 +++++------------- 3 files changed, 90 insertions(+), 217 deletions(-) diff --git a/PCK-Studio/Extensions/PckAssetExtensions.cs b/PCK-Studio/Extensions/PckAssetExtensions.cs index 5e445c3a..841a5a86 100644 --- a/PCK-Studio/Extensions/PckAssetExtensions.cs +++ b/PCK-Studio/Extensions/PckAssetExtensions.cs @@ -1,10 +1,13 @@ using System; -using System.Collections.Generic; -using System.Drawing; using System.IO; +using System.Linq; using System.Text; +using System.Drawing; +using System.Collections.Generic; + using OMI.Formats.Pck; using OMI.Workers; + using PckStudio.Interfaces; using PckStudio.Internal.Deserializer; using PckStudio.Internal.Serializer; @@ -85,26 +88,22 @@ namespace PckStudio.Extensions return asset.Filename.Remove(asset.Filename.Length - (MipMap.Length + 1) - ext.Length) + ext; } - internal static void DeserializePropertiesFromString(this PckAsset asset, string serializedData) + internal static void DeserializeProperties(this PckAsset asset, IEnumerable serializedData) { - string[] lines = serializedData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); - foreach (string line in lines) + IEnumerable> lines = serializedData + .Select(line => line.Split([' '], 2)) + .Where (keyValue => keyValue.Length == 2) + .Select(keyValue => new KeyValuePair(keyValue[0].Replace(":", ""), keyValue[1])); + foreach (KeyValuePair kv in lines) { - int idx = line.IndexOf(' '); - if (idx == -1 || line.Length - 1 == idx) - continue; - asset.AddProperty(line.Substring(0, idx).Replace(":", string.Empty), line.Substring(idx + 1)); + asset.AddProperty(kv); } } - internal static string SerializePropertiesToString(this PckAsset asset) + internal static IEnumerable SerializeProperties(this PckAsset asset, string seperater = ":") { - StringBuilder builder = new StringBuilder(asset.PropertyCount * 20); - foreach (KeyValuePair property in asset.GetProperties()) - { - builder.AppendLine(property.Key + ": " + property.Value); - } - return builder.ToString(); + IReadOnlyList> properties = asset.GetProperties(); + return properties.Select(property => property.Key + seperater + property.Value); } } } diff --git a/PCK-Studio/Forms/Additional-Popups/MultiTextPrompt.cs b/PCK-Studio/Forms/Additional-Popups/MultiTextPrompt.cs index 2231b054..deb7639d 100644 --- a/PCK-Studio/Forms/Additional-Popups/MultiTextPrompt.cs +++ b/PCK-Studio/Forms/Additional-Popups/MultiTextPrompt.cs @@ -1,15 +1,23 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Windows.Forms; namespace PckStudio.Forms.Additional_Popups { public partial class MultiTextPrompt : MetroFramework.Forms.MetroForm { - public string[] TextOutput => DialogResult == DialogResult.OK ? PromptTextBox.Lines : Array.Empty(); - public MultiTextPrompt(string[] list = null) + public IEnumerable TextOutput => DialogResult == DialogResult.OK ? PromptTextBox.Lines : Array.Empty(); + + public MultiTextPrompt(IEnumerable textLines) { InitializeComponent(); - PromptTextBox.Lines = list; + PromptTextBox.Lines = textLines.ToArray(); + } + + public MultiTextPrompt() + : this(Enumerable.Empty()) + { } private void okBtn_Click(object sender, EventArgs e) diff --git a/PCK-Studio/MainForm.cs b/PCK-Studio/MainForm.cs index 96e5b295..e4bf7f10 100644 --- a/PCK-Studio/MainForm.cs +++ b/PCK-Studio/MainForm.cs @@ -709,7 +709,7 @@ namespace PckStudio File.WriteAllBytes(outFilePath, asset.Data); if (asset.PropertyCount > 0) { - File.WriteAllText($"{outFilePath}.txt", asset.SerializePropertiesToString()); + File.WriteAllLines($"{outFilePath}.txt", asset.SerializeProperties()); } } @@ -1047,121 +1047,7 @@ namespace PckStudio BuildMainTreeView(); ReloadMetaTreeView(); } - } - - [Obsolete()] - bool IsSubPCKNode(string nodePath, string extention = ".pck") - { - // written by miku, implemented and modified by MattNL - if (nodePath.EndsWith(extention)) - return false; - - string[] subpaths = nodePath.Split('/'); - - bool isSubFile = subpaths.Any(s => Path.GetExtension(s).Equals(extention)); - - Debug.WriteLineIf(isSubFile, $"{nodePath} is a Sub-PCK File", category: nameof(IsSubPCKNode)); - - return isSubFile; - } - - List GetAllChildNodes(TreeNodeCollection root) - { - List childNodes = new List(); - foreach (TreeNode node in root) - { - childNodes.Add(node); - if (node.Nodes.Count > 0) - { - childNodes.AddRange(GetAllChildNodes(node.Nodes)); - } } - return childNodes; - } - - [Obsolete()] - TreeNode GetSubPCK(string childPath) - { - string parentPath = childPath.Replace('\\', '/'); - Debug.WriteLine(parentPath); - string[] s = parentPath.Split('/'); - Debug.WriteLine(s.Length); - foreach (string node in s) - { - TreeNode parent = treeViewMain.Nodes.Find(node, true)[0]; - if (parent.TryGetTagData(out PckAsset asset) && - (asset.Type is PckAssetType.TexturePackInfoFile || - asset.Type is PckAssetType.SkinDataFile)) - return parent; - } - - return null; - } - - [Obsolete()] - void RebuildSubPCK(string childPath) - { - // Support for if a file is edited within a nested PCK File (AKA SubPCK) - - if (!IsSubPCKNode(childPath)) - return; - - TreeNode parent = GetSubPCK(childPath); - Debug.WriteLine(parent.Name); - if (parent == null) - return; - - PckAsset parentAsset = parent.Tag as PckAsset; - PckFile parentAssetPck = - new PckFileReader( - LittleEndianCheckBox.Checked ? - OMI.Endianness.LittleEndian : - OMI.Endianness.BigEndian - ).FromStream(new MemoryStream(parentAsset.Data)); - - if (parentAsset.Type is PckAssetType.TexturePackInfoFile || parentAsset.Type is PckAssetType.SkinDataFile) - { - Debug.WriteLine("Rebuilding " + parentAsset.Filename); - PckFile newPCKFile = new PckFile(3, parentAsset.Type is PckAssetType.SkinDataFile); - - bool hasSkinsFolder = false; - - // add original pck files to prevent data loss - foreach (PckAsset asset in parentAssetPck.GetAssets()) - { - PckAsset newAsset = newPCKFile.CreateNewAsset(asset.Filename, asset.Type); - // check for skins folder so files are placed consistently in final pck - if (asset.Filename.StartsWith("Skins/") && parentAsset.Type is PckAssetType.SkinDataFile) - hasSkinsFolder = true; - foreach (KeyValuePair prop in asset.GetProperties()) - newAsset.AddProperty(prop); - newAsset.SetData(asset.Data); - } - - foreach (TreeNode node in GetAllChildNodes(parent.Nodes)) - { - if (node.Tag is PckAsset nodeAsset) - { - PckAsset newAsset = newPCKFile.CreateNewAsset( - (hasSkinsFolder ? "Skins/" : String.Empty) - + nodeAsset.Filename.Replace(parentAsset.Filename + "/", String.Empty), nodeAsset.Type); - foreach (KeyValuePair prop in nodeAsset.GetProperties()) - newAsset.AddProperty(prop); - newAsset.SetData(nodeAsset.Data); - } - } - - parentAsset.SetData(new PckFileWriter(newPCKFile, LittleEndianCheckBox.Checked ? OMI.Endianness.LittleEndian : OMI.Endianness.BigEndian)); - parent.Tag = parentAsset; - - // erase hidden sub-pck nodes to prevent duplication - parent.Nodes.Clear(); - - BuildMainTreeView(); - - MessageBox.Show(this, $"Files added successfully to {parentAsset.Filename}"); - } - } private void treeViewMain_DoubleClick(object sender, EventArgs e) { @@ -1280,7 +1166,7 @@ namespace PckStudio newNode.ImageIndex = node.ImageIndex; newNode.SelectedImageIndex = node.SelectedImageIndex; - if (GetAllChildNodes(treeViewMain.Nodes).Find(n => n.FullPath == diag.NewText) != null) + if (GetAllChildNodes(treeViewMain.Nodes).FirstOrDefault(n => n.FullPath == diag.NewText) is not null) { MessageBox.Show( this, @@ -1290,12 +1176,8 @@ namespace PckStudio return; } - // adds generated file node - if (node.Parent == null) - treeViewMain.Nodes.Insert(node.Index + 1, newNode); - // adds generated file node to selected folder - else - node.Parent.Nodes.Insert(node.Index + 1, newNode); + TreeNodeCollection nodeCollection = node.Parent?.Nodes ?? treeViewMain.Nodes; + nodeCollection.Insert(node.Index + 1, newNode); currentPCK.InsertAsset(node.Index + 1, newFile); BuildMainTreeView(); @@ -1453,7 +1335,7 @@ namespace PckStudio } else { - List pckFiles = GetEndingNodes(draggedNode.Nodes).Where(t => t.IsTagOfType()).Select(t => t.Tag as PckAsset).ToList(); + IEnumerable pckFiles = GetAllChildNodes(draggedNode.Nodes).Where(t => t.IsTagOfType()).Select(t => t.Tag as PckAsset); string oldPath = draggedNode.FullPath; string newPath = Path.Combine(isTargetPckFile ? Path.GetDirectoryName(targetNode.FullPath) : targetNode.FullPath, draggedNode.Text).Replace('\\', '/'); foreach (PckAsset pckFile in pckFiles) @@ -1465,20 +1347,17 @@ namespace PckStudio } } - private IEnumerable GetEndingNodes(TreeNodeCollection collection) + IEnumerable GetAllChildNodes(TreeNodeCollection root) { - List trailingNodes = new List(collection.Count); - foreach (TreeNode node in collection) + List childNodes = new List(root.Count); + foreach (TreeNode childNode in root) { - if (node.Nodes.Count > 0) - { - trailingNodes.AddRange(GetEndingNodes(node.Nodes)); - continue; + childNodes.Add(childNode); + childNodes.AddRange(GetAllChildNodes(childNode.Nodes)); } - trailingNodes.Add(node); + return childNodes; } - return trailingNodes; - } + private void ImportFiles(string[] files) { @@ -1491,14 +1370,14 @@ namespace PckStudio if (currentPCK.Contains(addFile.Filepath, addFile.Filetype)) { - MessageBox.Show(this, $"'{addFile.Filepath}' of type {addFile.Filetype} already exists.", "Import failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, $"'{addFile.Filepath}' of type {addFile.Filetype} already exists.\nSkiping file.", "File already exists", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); continue; } PckAsset importedAsset = currentPCK.CreateNewAsset(addFile.Filepath, addFile.Filetype, () => File.ReadAllBytes(filepath)); string propertyFile = filepath + ".txt"; if (File.Exists(propertyFile)) { - importedAsset.DeserializePropertiesFromString(File.ReadAllText(propertyFile)); + importedAsset.DeserializeProperties(File.ReadAllLines(propertyFile)); } addedCount++; @@ -1689,48 +1568,6 @@ namespace PckStudio deleteEntryToolStripMenuItem_Click(sender, e); } - private void importExtractedSkinsFolder(object sender, EventArgs e) - { - using FolderBrowserDialog contents = new FolderBrowserDialog(); - if (contents.ShowDialog(this) == DialogResult.OK && Directory.Exists(contents.SelectedPath)) - { - string filepath = treeViewMain.SelectedNode?.FullPath ?? ""; - if (treeViewMain.SelectedNode is not null && treeViewMain.SelectedNode.IsTagOfType()) - filepath = treeViewMain.SelectedNode.Parent?.FullPath ?? ""; - - foreach (var fullfilename in Directory.GetFiles(contents.SelectedPath, "dlc*.png")) - { - string filename = Path.GetFileName(fullfilename); - // only accept skin or cape named files - if (!filename.StartsWith("dlcskin") && !filename.StartsWith("dlccape")) - continue; - // sets file type based on wether its a cape or skin - PckAssetType pckfiletype = filename.StartsWith("dlccape", StringComparison.OrdinalIgnoreCase) - ? PckAssetType.CapeFile - : PckAssetType.SkinFile; - string pckfilepath = Path.Combine(filepath, filename); - - if (currentPCK.Contains(pckfilepath, pckfiletype)) - { - Trace.TraceInformation("[{0}] {1} already exists.", nameof(importExtractedSkinsFolder), pckfilepath); - continue; - } - - PckAsset newAsset = currentPCK.CreateNewAsset(pckfilepath, pckfiletype); - byte[] filedata = File.ReadAllBytes(fullfilename); - newAsset.SetData(filedata); - - if (File.Exists(fullfilename + ".txt")) - { - string propertiesFileContent = File.ReadAllText(fullfilename + ".txt"); - newAsset.DeserializePropertiesFromString(propertiesFileContent); - } - } - BuildMainTreeView(); - wasModified = true; - } - } - private bool TryGetLocFile(out LOCFile locFile) { if (!currentPCK.TryGetAsset("localisation.loc", PckAssetType.LocalisationFile, out PckAsset locAsset) && @@ -1773,6 +1610,47 @@ namespace PckStudio return false; } + private void importExtractedSkinsFolder(object sender, EventArgs e) + { + OpenFolderDialog contents = new OpenFolderDialog(); + if (contents.ShowDialog(Handle) == true && Directory.Exists(contents.ResultPath)) + { + string filepath = treeViewMain.SelectedNode?.FullPath ?? ""; + if (treeViewMain.SelectedNode is not null && treeViewMain.SelectedNode.IsTagOfType()) + filepath = treeViewMain.SelectedNode.Parent?.FullPath ?? ""; + + foreach (var fullfilename in Directory.GetFiles(contents.ResultPath, "dlc*.png")) + { + string filename = Path.GetFileName(fullfilename); + // only accept skin or cape named files + if (!filename.StartsWith("dlcskin") && !filename.StartsWith("dlccape")) + continue; + // sets file type based on wether its a cape or skin + PckAssetType pckfiletype = filename.StartsWith("dlccape", StringComparison.OrdinalIgnoreCase) + ? PckAssetType.CapeFile + : PckAssetType.SkinFile; + string pckfilepath = Path.Combine(filepath, filename); + + if (currentPCK.Contains(pckfilepath, pckfiletype)) + { + Trace.TraceInformation("[{0}] {1} already exists.", nameof(importExtractedSkinsFolder), pckfilepath); + continue; + } + + PckAsset newAsset = currentPCK.CreateNewAsset(pckfilepath, pckfiletype); + byte[] filedata = File.ReadAllBytes(fullfilename); + newAsset.SetData(filedata); + + if (File.Exists(fullfilename + ".txt")) + { + string[] propertiesFileContent = File.ReadAllLines(fullfilename + ".txt"); + newAsset.DeserializeProperties(propertiesFileContent); + } + } + BuildMainTreeView(); + wasModified = true; + } + } [Obsolete("Refactor or remove this")] private void importSkinToolStripMenuItem_Click(object sender, EventArgs e) @@ -1798,11 +1676,12 @@ namespace PckStudio string propertyFile = contents.FileName + ".txt"; if (File.Exists(propertyFile)) { - string txtProperties = File.ReadAllText(propertyFile); - importSkinAsset.DeserializePropertiesFromString(txtProperties); + string[] txtProperties = File.ReadAllLines(propertyFile); + importSkinAsset.DeserializeProperties(txtProperties); // Because extracting/exporting an assest doesn't export - // the actual loc value we just get an undefined loc key + // the actual loc value we just get an undefined loc key. + // That's why why remove them after deserializing. // - Miku importSkinAsset.RemoveProperty("DISPLAYNAMEID"); importSkinAsset.RemoveProperty("THEMENAMEID"); @@ -2175,23 +2054,15 @@ namespace PckStudio { if (treeViewMain.SelectedNode.TryGetTagData(out PckAsset asset)) { - using (var input = new MultiTextPrompt()) - { + using var input = new MultiTextPrompt(); if (input.ShowDialog(this) == DialogResult.OK) { - foreach (string line in input.TextOutput) - { - int idx = line.IndexOf(' '); - if (idx == -1 || line.Length - 1 == idx) - continue; - asset.AddProperty(line.Substring(0, idx), line.Substring(idx + 1)); - } + asset.DeserializeProperties(input.TextOutput); ReloadMetaTreeView(); wasModified = true; } } } - } private void correctSkinDecimalsToolStripMenuItem_Click(object sender, EventArgs e) { @@ -2226,19 +2097,13 @@ namespace PckStudio { if (treeViewMain.SelectedNode.TryGetTagData(out PckAsset asset)) { - string[] props = asset.GetProperties().Select(p => p.Key + " " + p.Value).ToArray(); + IEnumerable props = asset.SerializeProperties(seperater:" "); using (var input = new MultiTextPrompt(props)) { if (input.ShowDialog(this) == DialogResult.OK) { asset.ClearProperties(); - foreach (string line in input.TextOutput) - { - int idx = line.IndexOf(' '); - if (idx == -1 || line.Length - 1 == idx) - continue; - asset.AddProperty(line.Substring(0, idx).Replace(":", string.Empty), line.Substring(idx + 1)); - } + asset.DeserializeProperties(input.TextOutput); ReloadMetaTreeView(); wasModified = true; } @@ -2430,6 +2295,7 @@ namespace PckStudio } private void littleEndianToolStripMenuItem_Click(object sender, EventArgs e) => SetPckEndianness(OMI.Endianness.LittleEndian); + private void bigEndianToolStripMenuItem_Click(object sender, EventArgs e) => SetPckEndianness(OMI.Endianness.BigEndian); private void SetModelVersion(int version) From 49353573334a568070d7f4f7609e768c82b4b07f Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 16:29:52 +0200 Subject: [PATCH 6/8] MainForm - Mark 'GetDataPath', 'HasDataFolder' and 'CreateDataFolder' as Obsolete/Needs moving --- PCK-Studio/MainForm.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/PCK-Studio/MainForm.cs b/PCK-Studio/MainForm.cs index e4bf7f10..f139dc3d 100644 --- a/PCK-Studio/MainForm.cs +++ b/PCK-Studio/MainForm.cs @@ -1539,16 +1539,19 @@ namespace PckStudio e.CancelEdit = true; } + [Obsolete("Move this")] public string GetDataPath() { return Path.Combine(Path.GetDirectoryName(saveLocation), "Data"); } + [Obsolete("Move this")] public bool HasDataFolder() { return Directory.Exists(GetDataPath()); } + [Obsolete("Move this")] public bool CreateDataFolder() { if (!HasDataFolder()) From 91623032250f4428b4ed4fca4d7238a75e72ebe8 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 16:31:00 +0200 Subject: [PATCH 7/8] MainForm - Small refactoring of functions --- PCK-Studio/MainForm.cs | 60 +++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/PCK-Studio/MainForm.cs b/PCK-Studio/MainForm.cs index f139dc3d..9c64a624 100644 --- a/PCK-Studio/MainForm.cs +++ b/PCK-Studio/MainForm.cs @@ -263,16 +263,14 @@ namespace PckStudio private void openToolStripMenuItem_Click(object sender, EventArgs e) { - using (var ofd = new OpenFileDialog()) - { - ofd.CheckFileExists = true; - ofd.Filter = "PCK (Minecraft Console Package)|*.pck"; - if (ofd.ShowDialog(this) == DialogResult.OK) - { - LoadPckFromFile(ofd.FileName); - } - } - } + using var ofd = new OpenFileDialog(); + ofd.CheckFileExists = true; + ofd.Filter = "PCK (Minecraft Console Package)|*.pck"; + if (ofd.ShowDialog(this) == DialogResult.OK) + { + LoadPckFromFile(ofd.FileName); + } + } private PckFile OpenPck(string filePath) { @@ -1047,7 +1045,7 @@ namespace PckStudio BuildMainTreeView(); ReloadMetaTreeView(); } - } + } private void treeViewMain_DoubleClick(object sender, EventArgs e) { @@ -1351,12 +1349,12 @@ namespace PckStudio { List childNodes = new List(root.Count); foreach (TreeNode childNode in root) - { + { childNodes.Add(childNode); childNodes.AddRange(GetAllChildNodes(childNode.Nodes)); - } + } return childNodes; - } + } private void ImportFiles(string[] files) @@ -1570,7 +1568,7 @@ namespace PckStudio if (e.KeyData == Keys.Delete) deleteEntryToolStripMenuItem_Click(sender, e); } - + private bool TryGetLocFile(out LOCFile locFile) { if (!currentPCK.TryGetAsset("localisation.loc", PckAssetType.LocalisationFile, out PckAsset locAsset) && @@ -1681,12 +1679,12 @@ namespace PckStudio { string[] txtProperties = File.ReadAllLines(propertyFile); importSkinAsset.DeserializeProperties(txtProperties); - - // Because extracting/exporting an assest doesn't export + + // Because extracting/exporting an assest doesn't export // the actual loc value we just get an undefined loc key. // That's why why remove them after deserializing. - // - Miku - importSkinAsset.RemoveProperty("DISPLAYNAMEID"); + // - Miku + importSkinAsset.RemoveProperty("DISPLAYNAMEID"); importSkinAsset.RemoveProperty("THEMENAMEID"); BuildMainTreeView(); wasModified = true; @@ -1814,13 +1812,9 @@ namespace PckStudio { pckOpen.Image = Resources.pckDrop; string[] files = (string[])e.Data.GetData(DataFormats.FileDrop) ?? Array.Empty(); - foreach (string file in files) - { - string ext = Path.GetExtension(file); - if (ext.Equals(".pck", StringComparison.CurrentCultureIgnoreCase)) - e.Effect = DragDropEffects.Copy; - return; - } + e.Effect = files.Any(file => Path.GetExtension(file).Equals(".pck", StringComparison.CurrentCultureIgnoreCase)) + ? DragDropEffects.Copy + : DragDropEffects.None; } private void OpenPck_DragDrop(object sender, DragEventArgs e) @@ -2058,14 +2052,14 @@ namespace PckStudio if (treeViewMain.SelectedNode.TryGetTagData(out PckAsset asset)) { using var input = new MultiTextPrompt(); - if (input.ShowDialog(this) == DialogResult.OK) - { + if (input.ShowDialog(this) == DialogResult.OK) + { asset.DeserializeProperties(input.TextOutput); - ReloadMetaTreeView(); - wasModified = true; - } - } - } + ReloadMetaTreeView(); + wasModified = true; + } + } + } private void correctSkinDecimalsToolStripMenuItem_Click(object sender, EventArgs e) { From b1bc4eadadc0f5c19f13abfebcd341b02ebb7428 Mon Sep 17 00:00:00 2001 From: miku-666 <74728189+NessieHax@users.noreply.github.com> Date: Thu, 15 Aug 2024 16:57:27 +0200 Subject: [PATCH 8/8] Program - Move Update related initialization into Updater class --- PCK-Studio/Internal/Json/UpdateInformation.cs | 24 +++++++ PCK-Studio/Internal/Updater.cs | 62 +++++++++++++++++++ PCK-Studio/MainForm.cs | 2 +- PCK-Studio/PckStudio.csproj | 2 + PCK-Studio/Program.cs | 60 +----------------- 5 files changed, 91 insertions(+), 59 deletions(-) create mode 100644 PCK-Studio/Internal/Json/UpdateInformation.cs create mode 100644 PCK-Studio/Internal/Updater.cs diff --git a/PCK-Studio/Internal/Json/UpdateInformation.cs b/PCK-Studio/Internal/Json/UpdateInformation.cs new file mode 100644 index 00000000..c6d1fd30 --- /dev/null +++ b/PCK-Studio/Internal/Json/UpdateInformation.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace PckStudio.Internal.Json +{ + internal class UpdateInformation + { + [JsonProperty("version")] + public string Version { get; set; } + + [JsonProperty("url")] + public string Url { get; set; } + + [JsonProperty("changelog")] + public string Changelog { get; set; } + + [JsonProperty("mandatory")] + public bool Mandatory { get; set; } + } +} \ No newline at end of file diff --git a/PCK-Studio/Internal/Updater.cs b/PCK-Studio/Internal/Updater.cs new file mode 100644 index 00000000..84a1b86a --- /dev/null +++ b/PCK-Studio/Internal/Updater.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using System.Windows.Forms; +using AutoUpdaterDotNET; +using Newtonsoft.Json; +using PckStudio.Internal.Json; +using PckStudio.Properties; + +namespace PckStudio.Internal +{ + internal static class Updater + { + private static Uri _appCast; + + internal static void Initialize(Uri appCast) + { + _appCast = appCast; + //AutoUpdater.ClearAppDirectory = true; +#if DEBUG + AutoUpdater.ReportErrors = true; +#endif + AutoUpdater.DownloadPath = Application.StartupPath; + AutoUpdater.ExecutablePath = "./PCK-Studio.exe"; + AutoUpdater.TopMost = true; + + string jsonPath = Path.Combine(Environment.CurrentDirectory, "updates.json"); + AutoUpdater.PersistenceProvider = new JsonFilePersistenceProvider(jsonPath); + AutoUpdater.ParseUpdateInfoEvent += AutoUpdaterOnParseUpdateInfoEvent; + AutoUpdater.Icon = Resources.ProjectLogo.ToBitmap(); + + if (Settings.Default.AutoUpdate) + { + UpdateToLatest(); + } + } + + internal static void SetOwner(Form owner) => AutoUpdater.SetOwner(owner); + + internal static void UpdateToLatest() + { +#if NDEBUG + string url = $"{_appCast}/main/Version.json"; + AutoUpdater.Start(url); +#endif + } + + private static void AutoUpdaterOnParseUpdateInfoEvent(ParseUpdateInfoEventArgs args) + { + UpdateInformation json = JsonConvert.DeserializeObject(args.RemoteData); + args.UpdateInfo = new UpdateInfoEventArgs + { + CurrentVersion = json.Version, + DownloadURL = json.Url, + ChangelogURL = json.Changelog, + Mandatory = new Mandatory() + { + Value = json.Mandatory, + } + }; + } + } +} diff --git a/PCK-Studio/MainForm.cs b/PCK-Studio/MainForm.cs index 9c64a624..92f9182d 100644 --- a/PCK-Studio/MainForm.cs +++ b/PCK-Studio/MainForm.cs @@ -2251,7 +2251,7 @@ namespace PckStudio private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e) { - Program.UpdateToLatest(); + Updater.UpdateToLatest(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) diff --git a/PCK-Studio/PckStudio.csproj b/PCK-Studio/PckStudio.csproj index 0c7fe072..5128d99f 100644 --- a/PCK-Studio/PckStudio.csproj +++ b/PCK-Studio/PckStudio.csproj @@ -157,6 +157,7 @@ + @@ -169,6 +170,7 @@ + True True diff --git a/PCK-Studio/Program.cs b/PCK-Studio/Program.cs index e26bddc9..da41cac4 100644 --- a/PCK-Studio/Program.cs +++ b/PCK-Studio/Program.cs @@ -31,74 +31,18 @@ namespace PckStudio [STAThread] static void Main(string[] args) { - AutoUpdater.SetOwner(MainInstance); - //AutoUpdater.ClearAppDirectory = true; -#if DEBUG - AutoUpdater.ReportErrors = true; -#endif - AutoUpdater.DownloadPath = Application.StartupPath; - AutoUpdater.ExecutablePath = "./PCK-Studio.exe"; - AutoUpdater.TopMost = true; - - string jsonPath = Path.Combine(Environment.CurrentDirectory, "updates.json"); - AutoUpdater.PersistenceProvider = new JsonFilePersistenceProvider(jsonPath); - AutoUpdater.ParseUpdateInfoEvent += AutoUpdaterOnParseUpdateInfoEvent; - AutoUpdater.Icon = Resources.ProjectLogo.ToBitmap(); - - if (Settings.Default.AutoUpdate) - { - UpdateToLatest(); - } + Updater.Initialize(RawProjectUrl); ApplicationScope.Initialize(); Trace.TraceInformation("Startup"); RPC.Initialize(); MainInstance = new MainForm(); + Updater.SetOwner(MainInstance); if (args.Length > 0 && File.Exists(args[0]) && args[0].EndsWith(".pck")) MainInstance.InitPckFromFile(args[0]); Application.ApplicationExit += (sender, e) => { RPC.Deinitialize(); }; MainInstance.FocusMe(); Application.Run(MainInstance); } - - - internal static void UpdateToLatest() - { -#if NDEBUG - string url = $"{RawProjectUrl}/main/Version.json"; - AutoUpdater.Start(url); -#endif - } - - class UpdateInfo - { - [JsonProperty("version")] - public string Version { get; set; } - - [JsonProperty("url")] - public string Url { get; set; } - - [JsonProperty("changelog")] - public string Changelog { get; set; } - - [JsonProperty("mandatory")] - public bool Mandatory { get; set; } - } - - private static void AutoUpdaterOnParseUpdateInfoEvent(ParseUpdateInfoEventArgs args) - { - UpdateInfo json = JsonConvert.DeserializeObject(args.RemoteData); - args.UpdateInfo = new UpdateInfoEventArgs - { - CurrentVersion = json.Version, - DownloadURL = json.Url, - ChangelogURL = json.Changelog, - Mandatory = new Mandatory() - { - Value = json.Mandatory, - } - }; - } - } } \ No newline at end of file