Skip to content

Commit

Permalink
Add project settings, name and icon replacing (#48)
Browse files Browse the repository at this point in the history
Co-authored-by: jonko0493 <[email protected]>
  • Loading branch information
WiIIiam278 and jonko0493 authored Mar 15, 2023
1 parent b1ccb4e commit 2708cef
Show file tree
Hide file tree
Showing 9 changed files with 282 additions and 13 deletions.
15 changes: 14 additions & 1 deletion src/SerialLoops.Lib/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,23 @@ private static async Task<bool> DoBuild(string directory, Project project, Confi
}
tracker.Finished+= 3;

var ndsProjectFile = Path.Combine(directory, "rom", $"{project.Name}.xml");
tracker.Focus("Writing NitroPacker Project File", 1);
try
{
File.WriteAllBytes(ndsProjectFile, project.Settings.File.Write());
}
catch (IOException exc)
{
log.LogError($"Failed to write NitroPacker NDS project file to disk: {exc.Message}\n\n{exc.StackTrace}");
return false;
}
tracker.Finished++;

tracker.Focus("Packing ROM", 1);
try
{
NdsProjectFile.Pack(Path.Combine(project.MainDirectory, $"{project.Name}.nds"), Path.Combine(directory, "rom", $"{project.Name}.xml"));
NdsProjectFile.Pack(Path.Combine(project.MainDirectory, $"{project.Name}.nds"), ndsProjectFile);
}
catch (Exception exc)
{
Expand Down
23 changes: 20 additions & 3 deletions src/SerialLoops.Lib/Project.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using HaruhiChokuretsuLib.Archive;
using HaroohieClub.NitroPacker.Core;
using HaruhiChokuretsuLib.Archive;
using HaruhiChokuretsuLib.Archive.Data;
using HaruhiChokuretsuLib.Archive.Event;
using HaruhiChokuretsuLib.Archive.Graphics;
Expand Down Expand Up @@ -29,7 +30,8 @@ public class Project
public string IterativeDirectory => Path.Combine(MainDirectory, "iterative");
[JsonIgnore]
public string ProjectFile => Path.Combine(MainDirectory, $"{Name}.{PROJECT_FORMAT}");

[JsonIgnore]
public ProjectSettings Settings { get; set; }
[JsonIgnore]
public List<ItemDescription> Items { get; set; } = new();

Expand Down Expand Up @@ -75,7 +77,21 @@ public Project(string name, string langCode, Config config, ILogger log)
log.LogError($"Exception occurred while attempting to create project directories.\n{exc.Message}\n\n{exc.StackTrace}");
}
}

public void Load(ILogger log, IProgressTracker tracker)
{
LoadProjectSettings(log, tracker);
LoadArchives(log, tracker);
}

public void LoadProjectSettings(ILogger log, IProgressTracker tracker)
{
tracker.Focus("Project Settings", 1);
byte[] projectFile = File.ReadAllBytes(Path.Combine(IterativeDirectory, "rom", $"{Name}.xml"));
Settings = new(NdsProjectFile.FromByteArray<NdsProjectFile>(projectFile), log);
tracker.Finished++;
}

public void LoadArchives(ILogger log, IProgressTracker tracker)
{
tracker.Focus("dat.bin", 3);
Expand Down Expand Up @@ -223,7 +239,7 @@ public static Project OpenProject(string projFile, Config config, ILogger log, I
tracker.Focus($"{Path.GetFileNameWithoutExtension(projFile)} Project Data", 1);
Project project = JsonSerializer.Deserialize<Project>(File.ReadAllText(projFile));
tracker.Finished++;
project.LoadArchives(log, tracker);
project.Load(log, tracker);
return project;
}
catch (Exception exc)
Expand All @@ -249,5 +265,6 @@ public List<ItemDescription> GetSearchResults(string searchTerm, bool titlesOnly
item.SearchableText.Contains(searchTerm.Trim(), StringComparison.OrdinalIgnoreCase))).ToList();
}
}

}
}
68 changes: 68 additions & 0 deletions src/SerialLoops.Lib/ProjectSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using HaroohieClub.NitroPacker.Core;
using HaroohieClub.NitroPacker.Nitro.Gx;
using HaruhiChokuretsuLib.Archive.Graphics;
using HaruhiChokuretsuLib.Util;
using SkiaSharp;
using System;
using System.Linq;
using static HaroohieClub.NitroPacker.Nitro.Card.Rom.RomBanner;

namespace SerialLoops.Lib
{
public class ProjectSettings
{
public NdsProjectFile File { get; }
private BannerV1 Banner => File.RomInfo.Banner.Banner;
private readonly ILogger _log;

public string Name {
get => Banner.GameName[0];
set
{
string name = value.Length > 128 ? value[..63] : value;
for (int i = 0; i < Banner.GameName.Length; i++)
{
Banner.GameName[i] = name;
}
}
}

public SKBitmap Icon
{
get
{
Rgba8Bitmap bitmap = Banner.GetIcon();
return new(bitmap.Width, bitmap.Height)
{
Pixels = bitmap.Pixels.Select(p => new SKColor(p)).ToArray()
};
}
set
{
GraphicsFile grp = new()
{
Name = "ICON",
PixelData = new(),
PaletteData = new(),
};
grp.Initialize(Array.Empty<byte>(), 0, _log);
grp.FileFunction = GraphicsFile.Function.SHTX;
grp.ImageForm = GraphicsFile.Form.TILE;
grp.ImageTileForm = GraphicsFile.TileForm.GBA_4BPP;
grp.Width = 32;
grp.Height = 32;
grp.Palette = new(new SKColor[16]);
grp.SetImage(value, setPalette: true, transparentIndex: 0, newSize: true);

Banner.Image = grp.PixelData.ToArray();
Banner.Pltt = grp.PaletteData.ToArray();
}
}
public ProjectSettings(NdsProjectFile file, ILogger log)
{
File = file;
_log = log;
}

}
}
14 changes: 13 additions & 1 deletion src/SerialLoops/MainForm.eto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ void InitializeComponent()
Command saveProject = new() { MenuText = "Save Project", ToolBarText = "Save Project", Shortcut = Application.Instance.CommonModifier | Keys.S };
saveProject.Executed += SaveProject_Executed;

Command projectSettings = new() { MenuText = "Project Settings", ToolBarText = "Project Settings" };
projectSettings.Executed += ProjectSettings_Executed;

// Tools
Command searchProject = new() { MenuText = "Search", ToolBarText = "Search", Shortcut = Application.Instance.CommonModifier | Keys.F, Image = ControlGenerator.GetIcon("Search", _log) };
searchProject.Executed += Search_Executed;
Expand Down Expand Up @@ -80,7 +83,7 @@ void InitializeComponent()
Items =
{
// File submenu
new SubMenuItem { Text = "&File", Items = { newProject, openProject, _recentProjects, saveProject } },
new SubMenuItem { Text = "&File", Items = { newProject, openProject, _recentProjects, saveProject, projectSettings } },
new SubMenuItem { Text = "&Tools", Items = { searchProject, findOrphanedItems } },
// new SubMenuItem { Text = "&Edit", Items = { /* commands/items */ } },
// new SubMenuItem { Text = "&View", Items = { /* commands/items */ } },
Expand Down Expand Up @@ -268,6 +271,15 @@ private void SaveProject_Executed(object sender, EventArgs e)
}
}

private void ProjectSettings_Executed(object sender, EventArgs e)
{
if (OpenProject is not null)
{
ProjectSettingsDialog projectSettingsDialog = new(OpenProject, _log);
projectSettingsDialog.ShowModal(this);
}
}

private void Search_Executed(object sender, EventArgs e)
{
if (OpenProject is not null)
Expand Down
2 changes: 1 addition & 1 deletion src/SerialLoops/ProjectCreationDialog.eto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ private void CreateCommand_Executed(object sender, EventArgs e)
((IProgressTracker)tracker).Focus("Creating Project", 1);
IO.OpenRom(NewProject, romPath, includeFontHack, tracker);
tracker.Finished++;
NewProject.LoadArchives(Log, tracker);
NewProject.Load(Log, tracker);
}, Close, tracker, "Creating Project");
}
}
Expand Down
159 changes: 159 additions & 0 deletions src/SerialLoops/ProjectSettingsDialog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
using Eto.Forms;
using HaruhiChokuretsuLib.Util;
using SerialLoops.Lib;
using SerialLoops.Utility;
using SkiaSharp;
using System;

namespace SerialLoops
{
public class ProjectSettingsDialog : Dialog
{
private readonly Project _project;
private readonly ILogger _log;
private ProjectSettings Settings => _project.Settings;

private TextArea _nameBox;
private SKBitmap _newIcon;

public ProjectSettingsDialog(Project project, ILogger log)
{
_project = project;
_log = log;

InitializeComponent();
}

private void InitializeComponent()
{
Title = "Project Settings";
Padding = 10;
MinimumSize = new(300, 250);

Button applyButton = new() { Text = "Apply" };
applyButton.Click += ApplyButton_OnClick;

Button cancelButton = new() { Text = "Cancel" };
cancelButton.Click += (sender, e) => { Close(); };

Content = new TableLayout(
new TableRow(
new GroupBox
{
Text = "Game Banner",
Padding = 10,
Content = new StackLayout
{
Padding = 10,
Spacing = 10,
Orientation = Orientation.Horizontal,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Items = { GetIconEditor(), GetNameEditor() }
}
}
),
new TableRow(
new StackLayout
{
Padding = 10,
Spacing = 5,
Orientation = Orientation.Horizontal,
HorizontalContentAlignment = HorizontalAlignment.Center,
Items = { applyButton, cancelButton }
}
)
);
}

private Container GetIconEditor()
{
Panel iconPanel = new()
{
Content = GetPreview(Settings.Icon)
};
Button replaceButton = new() { Text = "Replace..." };
replaceButton.Click += (sender, e) =>
{
OpenFileDialog dialog = new()
{
Title = "Select Icon",
Filters = { new FileFilter("Image Files", ".png", ".jpg", ".jpeg", ".bmp", ".gif") }
};

if (dialog.ShowDialog(this) == DialogResult.Ok)
{
SKBitmap newIcon = SKBitmap.Decode(dialog.FileName);
_newIcon = new(32, 32);
newIcon.ScalePixels(_newIcon, SKFilterQuality.High);
iconPanel.Content = GetPreview(_newIcon);
}
};

return new StackLayout
{
Padding = 10,
Spacing = 10,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Items =
{
iconPanel,
replaceButton
}
};
}

private static SKGuiImage GetPreview(SKBitmap icon)
{
SKBitmap preview = new(64, 64);
icon.ScalePixels(preview, SKFilterQuality.None);
return new SKGuiImage(preview);
}

private Container GetNameEditor()
{
_nameBox = new()
{
Text = Settings.Name,
Size = new(190, 50),
SpellCheck = false,
AcceptsTab = false
};

return new StackLayout
{
Padding = 10,
Spacing = 5,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Items = {"Game Title", _nameBox }
};
}

private void ApplyButton_OnClick(object sender, EventArgs e)
{
string text = _nameBox.Text;
if (text.Length is < 1 or > 127)
{
MessageBox.Show("Please enter a game name for the banner, between 1 and 128 characters.", MessageBoxType.Warning);
return;
}

if (text.Split('\n').Length > 3)
{
MessageBox.Show("Game banner can only contain up to three lines.", MessageBoxType.Error);
return;
}
Settings.Name = text;

if (_newIcon is not null)
{
Settings.Icon = _newIcon;
}

_log.Log("Updated NDS Project File settings");
Close();
}

}
}
3 changes: 3 additions & 0 deletions src/SerialLoops/SerialLoops.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@
</ItemGroup>

<ItemGroup>
<Compile Update="ProjectCreationDialog - Copy.eto.cs">
<DependentUpon>$([System.String]::Copy('%(Filename)').Replace('.eto', ''))%(Extension)</DependentUpon>
</Compile>
<Compile Update="SearchDialog.eto.cs">
<DependentUpon>$([System.String]::Copy('%(Filename)').Replace('.eto', ''))%(Extension)</DependentUpon>
</Compile>
Expand Down
2 changes: 1 addition & 1 deletion src/SerialLoops/Utility/SKGuiHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ public class SKGuiImage : Bitmap

public SKGuiImage(SKBitmap skBitmap) : base(skBitmap.Encode(SKEncodedImageFormat.Png, 1).AsStream())
{
SkBitmap = skBitmap;
}


}
}
9 changes: 3 additions & 6 deletions test/SerialLoops.Tests/CoreTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using Eto.Forms;
using HaruhiChokuretsuLib.Archive.Event;
using HaruhiChokuretsuLib.Audio;
using NUnit.Framework;
using NUnit.Framework;
using SerialLoops.Lib;
using SerialLoops.Lib.Items;
using SerialLoops.Lib.Script;
Expand All @@ -11,7 +8,7 @@
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Xml.Linq;
using HaroohieClub.NitroPacker.Core;

namespace SerialLoops.Tests
{
Expand Down Expand Up @@ -51,7 +48,7 @@ public void SetUp()
_log.Log("Creating project...");
_config = Config.LoadConfig(_log);
_project = new("Tester", "en", _config, _log);

string archivesDir = Path.Combine("original", "archives");
string bgmDir = Path.Combine("original", "bgm");
string vceDir = Path.Combine("original", "vce");
Expand Down

0 comments on commit 2708cef

Please sign in to comment.