Initial segregation of Core and WinForms

There's still several uses of System.Drawing and System.Windows.Forms which will take more time to segregate
This commit is contained in:
Evan Dixon 2017-06-18 15:02:09 -05:00
parent f8a2d34111
commit 76fb98f849
1657 changed files with 25576 additions and 25451 deletions

View File

@ -13,10 +13,33 @@ public static class GARC
public const ushort VER_6 = 0x0600;
public const ushort VER_4 = 0x0400;
public static bool garcPackMS(string folderPath, string garcPath, int version, int bytesPadding, ProgressBar pBar1 = null, Label label = null, bool supress = false)
public class FileCountDeterminedEventArgs : EventArgs
{
public int Total { get; set; }
}
public class PackProgressedEventArgs : EventArgs
{
public int Current { get; set; }
public int Total { get; set; }
public string CurrentFile { get; set; }
}
public class UnpackProgressedEventArgs : EventArgs
{
public int Current { get; set; }
public int Total { get; set; }
}
public static event EventHandler<FileCountDeterminedEventArgs> FileCountDetermined;
public static event EventHandler<PackProgressedEventArgs> PackProgressed;
public static event EventHandler<UnpackProgressedEventArgs> UnpackProgressed;
public static int garcPackMS(string folderPath, string garcPath, int version, int bytesPadding)
{
// Check to see if our input folder exists.
if (!new DirectoryInfo(folderPath).Exists) { Util.Error("Folder does not exist."); return false; }
if (!new DirectoryInfo(folderPath).Exists) throw new DirectoryNotFoundException("Folder does not exist");
if (version != VER_4 && version != VER_6)
throw new FormatException("Invalid GARC Version: 0x" + version.ToString("X4"));
@ -48,18 +71,10 @@ public static bool garcPackMS(string folderPath, string garcPath, int version, i
filectr += Directory.GetFiles(f).Length;
}
}
catch (Exception e) { Util.Error("Invalid packing filenames", e.ToString()); return false; }
#endregion
catch (Exception e) { throw new Exception("Invalid packing filenames", e); }
#region Initialize Progress Update Display
if (pBar1 == null) pBar1 = new ProgressBar();
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)delegate { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = filectr; });
else { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = filectr; }
if (label == null) label = new Label();
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = true; });
#endregion
FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = filectr });
#endregion
// Set Up the GARC template.
GARCFile garc = new GARCFile
@ -128,16 +143,9 @@ public static bool garcPackMS(string folderPath, string garcPath, int version, i
od += actualLength;
op += 12;
#region Step
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else { pBar1.PerformStep(); }
string update = $"{(float) index/(float) filectr:P2} - {index}/{filectr} - {packOrder[i]}";
index++;
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
#endregion
// Step
PackProgressed?.Invoke(null, new PackProgressedEventArgs { Current = index++, Total = filectr, CurrentFile = packOrder[i] });
}
else
{
@ -171,16 +179,9 @@ public static bool garcPackMS(string folderPath, string garcPath, int version, i
od += actualLength;
op += 12;
#region Step
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else { pBar1.PerformStep(); }
string update = $"{(float) index/(float) filectr:P2} - {index}/{filectr} - {f}";
index++;
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
#endregion
// Step
PackProgressed?.Invoke(null, new PackProgressedEventArgs { Current = index++, Total = filectr, CurrentFile = packOrder[i] });
}
}
garc.fatb.Entries[i].Vector = (uint)v;
@ -311,26 +312,14 @@ public static bool garcPackMS(string folderPath, string garcPath, int version, i
gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
gw.Write(garc.ContentPadToNearest);
}
}
try
{
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = false; });
else { label.Visible = false; }
// We're done.
SystemSounds.Exclamation.Play();
if (!supress) Util.Alert("Pack Successful!", filectr + " files packed to the GARC!");
return true;
}
catch (Exception e) { Util.Error("Packing Failed!", e.ToString()); return false; }
return filectr;
}
}
public static bool garcUnpack(string garcPath, string outPath, bool skipDecompression, ProgressBar pBar1 = null, Label label = null, bool supress = false, bool bypassExt = false)
public static int garcUnpack(string garcPath, string outPath, bool skipDecompression)
{
if (!File.Exists(garcPath) && !supress) { Util.Alert("File does not exist"); return false; }
if (!File.Exists(garcPath)) throw new FileNotFoundException("File does not exist");
// Unpack the GARC
GARCFile garc = unpackGARC(garcPath);
@ -340,17 +329,7 @@ public static bool garcUnpack(string garcPath, string outPath, bool skipDecompre
if (outPath == "gametext")
format = "D3";
#region Display
// Initialize ProgressBar
if (pBar1 == null) pBar1 = new ProgressBar();
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)delegate { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = fileCount; });
else { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = garc.fatb.FileCount; }
if (label == null) label = new Label();
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = true; });
#endregion
FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = fileCount });
using (BinaryReader br = new BinaryReader(File.OpenRead(garcPath)))
{
@ -405,39 +384,23 @@ public static bool garcUnpack(string garcPath, string outPath, bool skipDecompre
{
LZSS.Decompress(fileOut, decout);
try { File.Delete(fileOut); }
catch (Exception e) { Util.Error("A compressed file could not be deleted.", fileOut, e.ToString()); }
catch (Exception e) { throw new Exception("A compressed file could not be deleted: " + fileOut, e); }
}
catch
{
// File is really not encrypted.
try { File.Delete(decout); }
catch (Exception e) { Util.Error("This shouldn't happen", e.ToString()); }
File.Delete(decout);
}
}
#endregion
#region Step
if (pBar1.InvokeRequired) pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else pBar1.PerformStep();
string update = $"{filectr/fileCount:P2} - {filectr}/{fileCount}";
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
#endregion
UnpackProgressed?.Invoke(null, new UnpackProgressedEventArgs { Current = filectr, Total = fileCount });
if ((vector >>= 1) == 0) break;
}
}
}
#region Updates
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = false; });
else { label.Visible = false; }
SystemSounds.Exclamation.Play();
if (!supress) Util.Alert("Unpack Successful!", fileCount + " files unpacked from the GARC!");
#endregion
return true;
return fileCount;
}
public static GARCFile unpackGARC(string path)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,109 +1,14 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace pk3DS.Core
{
public class Util
{ // Image Layering/Blending Utility
public static Bitmap LayerImage(Image baseLayer, Image overLayer, int x, int y, double trans)
{
if (baseLayer == null)
return overLayer as Bitmap;
Bitmap img = new Bitmap(baseLayer.Width, baseLayer.Height);
using (Graphics gr = Graphics.FromImage(img))
{
gr.DrawImage(baseLayer, new Point(0, 0));
Bitmap o = ChangeOpacity(overLayer, trans);
gr.DrawImage(o, new Rectangle(x, y, overLayer.Width, overLayer.Height));
}
return img;
}
public static Bitmap ChangeOpacity(Image img, double trans)
{
if (img == null)
return null;
if (img.PixelFormat.HasFlag(PixelFormat.Indexed))
return (Bitmap)img;
Bitmap bmp = (Bitmap)img.Clone();
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
IntPtr ptr = bmpData.Scan0;
int len = bmp.Width * bmp.Height * 4;
byte[] data = new byte[len];
Marshal.Copy(ptr, data, 0, len);
for (int i = 0; i < data.Length; i += 4)
data[i + 3] = (byte)(data[i + 3] * trans);
Marshal.Copy(data, 0, ptr, len);
bmp.UnlockBits(bmpData);
return bmp;
}
public static Bitmap getSprite(int species, int form, int gender, int item, GameConfig config, bool shiny = false)
{
string file;
if (species == 0) // fix with SM release
{ return (Bitmap)Properties.Resources.ResourceManager.GetObject("_0"); }
if (species > 802)
{
return (Bitmap)Properties.Resources.unknown;
}
{
file = "_" + species;
if (form > 0) // Alt Form Handling
file = file + "_" + form;
else if (gender == 1 && (species == 592 || species == 593)) // Frillish & Jellicent
file = file + "_" + gender;
else if (gender == 1 && (species == 521 || species == 668)) // Unfezant & Pyroar
file = "_" + species + "f";
}
// Redrawing logic
Bitmap baseImage = (Bitmap)Properties.Resources.ResourceManager.GetObject(file);
if (baseImage == null)
{
if (species < config.MaxSpeciesID)
{
baseImage = LayerImage(
(Image)Properties.Resources.ResourceManager.GetObject("_" + species),
Properties.Resources.unknown,
0, 0, .5);
}
else
baseImage = Properties.Resources.unknown;
}
if (shiny)
{
// Add shiny star to top left of image.
baseImage = Util.LayerImage(baseImage, Properties.Resources.rare_icon, 0, 0, 0.7);
}
if (item > 0)
{
Bitmap itemimg = (Bitmap)Properties.Resources.ResourceManager.GetObject("item_" + item) ?? Properties.Resources.helditem;
// Redraw
baseImage = LayerImage(baseImage, itemimg, 22 + (15 - itemimg.Width) / 2, 15 + (15 - itemimg.Height), 1);
}
return baseImage;
}
public static Bitmap scaleImage(Bitmap rawImg, int s)
{
Bitmap bigImg = new Bitmap(rawImg.Width * s, rawImg.Height * s);
for (int x = 0; x < bigImg.Width; x++)
for (int y = 0; y < bigImg.Height; y++)
bigImg.SetPixel(x, y, rawImg.GetPixel(x / s, y / s));
return bigImg;
}
public static class Util
{
// Strings and Paths
public static FileInfo GetNewestFile(DirectoryInfo directory)
{
@ -129,28 +34,7 @@ public static string TrimFromZero(string input)
return input.Substring(0, index);
}
public static string[] getStringList(string f, string l)
{
object txt = Properties.Resources.ResourceManager.GetObject("text_" + f + "_" + l); // Fetch File, \n to list.
List<string> rawlist = ((string)txt).Split('\n').ToList();
string[] stringdata = new string[rawlist.Count];
for (int i = 0; i < rawlist.Count; i++)
stringdata[i] = rawlist[i].Trim();
return stringdata;
}
public static string[] getSimpleStringList(string f)
{
object txt = Properties.Resources.ResourceManager.GetObject(f); // Fetch File, \n to list.
List<string> rawlist = ((string)txt).Split('\n').ToList();
string[] stringdata = new string[rawlist.Count];
for (int i = 0; i < rawlist.Count; i++)
stringdata[i] = rawlist[i].Trim();
return stringdata;
}
// Randomization
public static Random rand = new Random();
public static uint rnd32()
@ -159,26 +43,6 @@ public static uint rnd32()
}
// Data Retrieval
public static int ToInt32(TextBox tb)
{
string value = tb.Text;
return ToInt32(value);
}
public static uint ToUInt32(TextBox tb)
{
string value = tb.Text;
return ToUInt32(value);
}
public static int ToInt32(MaskedTextBox tb)
{
string value = tb.Text;
return ToInt32(value);
}
public static uint ToUInt32(MaskedTextBox tb)
{
string value = tb.Text;
return ToUInt32(value);
}
public static int ToInt32(string value)
{
string val = value?.Replace(" ", "").Replace("_", "").Trim();
@ -188,45 +52,7 @@ public static uint ToUInt32(string value)
{
string val = value?.Replace(" ", "").Replace("_", "").Trim();
return string.IsNullOrWhiteSpace(val) ? 0 : uint.Parse(val);
}
public static uint getHEXval(TextBox tb)
{
if (tb.Text == null)
return 0;
string str = getOnlyHex(tb.Text);
return uint.Parse(str, NumberStyles.HexNumber);
}
public static int getIndex(ComboBox cb)
{
int val;
if (cb.SelectedValue == null)
return 0;
try
{ val = (int)cb.SelectedValue; }
catch
{ val = cb.SelectedIndex; if (val < 0) val = 0; }
return val;
}
public static string getOnlyHex(string str)
{
if (str == null) return "0";
string s = "";
foreach (char t in str)
{
var c = t;
// filter for hex
if ((c < 0x0047 && c > 0x002F) || (c < 0x0067 && c > 0x0060))
s += c;
else
System.Media.SystemSounds.Beep.Play();
}
if (s.Length == 0)
s = "0";
return s;
}
}
// Data Manipulation
public static void Shuffle<T>(T[] array)
@ -239,255 +65,7 @@ public static void Shuffle<T>(T[] array)
array[r] = array[i];
array[i] = t;
}
}
// Form Translation
public static void TranslateInterface(Control form, string lang)
{
// Check to see if a the translation file exists in the same folder as the executable
string externalLangPath = "lang_" + lang + ".txt";
string[] rawlist;
if (File.Exists(externalLangPath))
rawlist = File.ReadAllLines(externalLangPath);
else
{
object txt = Properties.Resources.ResourceManager.GetObject("lang_" + lang);
if (txt == null) return; // Translation file does not exist as a resource; abort this function and don't translate UI.
rawlist = ((string)txt).Split(new[] { "\n" }, StringSplitOptions.None);
rawlist = rawlist.Select(i => i.Trim()).ToArray(); // Remove trailing spaces
}
string[] stringdata = new string[rawlist.Length];
int itemsToRename = 0;
for (int i = 0; i < rawlist.Length; i++)
{
// Find our starting point
if (!rawlist[i].Contains("! " + form.Name)) continue;
// Allow renaming of the Window Title
string[] WindowName = rawlist[i].Split(new[] { " = " }, StringSplitOptions.None);
if (WindowName.Length > 1) form.Text = WindowName[1];
// Copy our Control Names and Text to a new array for later processing.
for (int j = i + 1; j < rawlist.Length; j++)
{
if (rawlist[j].Length == 0) continue; // Skip Over Empty Lines, errhandled
if (rawlist[j][0].ToString() == "-") continue; // Keep translating if line is a comment line
if (rawlist[j][0].ToString() == "!") // Stop if we have reached the end of translation
goto rename;
stringdata[itemsToRename] = rawlist[j]; // Add the entry to process later.
itemsToRename++;
}
}
return; // Not Found
// Now that we have our items to rename in: Control = Text format, let's execute the changes!
rename:
for (int i = 0; i < itemsToRename; i++)
{
string[] SplitString = stringdata[i].Split(new[] { " = " }, StringSplitOptions.None);
if (SplitString.Length < 2)
continue; // Error in Input, errhandled
string ctrl = SplitString[0]; // Control to change the text of...
string text = SplitString[1]; // Text to set Control.Text to...
Control[] controllist = form.Controls.Find(ctrl, true);
if (controllist.Length != 0) // If Control is found
{ controllist[0].Text = text; goto next; }
// Check MenuStrips
foreach (MenuStrip menu in form.Controls.OfType<MenuStrip>())
{
// Menu Items aren't in the Form's Control array. Find within the menu's Control array.
ToolStripItem[] TSI = menu.Items.Find(ctrl, true);
if (TSI.Length <= 0) continue;
TSI[0].Text = text; goto next;
}
// Check ContextMenuStrips
foreach (ContextMenuStrip cs in FindContextMenuStrips(form.Controls.OfType<Control>()).Distinct())
{
ToolStripItem[] TSI = cs.Items.Find(ctrl, true);
if (TSI.Length <= 0) continue;
TSI[0].Text = text; goto next;
}
next:;
}
}
public static List<ContextMenuStrip> FindContextMenuStrips(IEnumerable<Control> c)
{
List<ContextMenuStrip> cs = new List<ContextMenuStrip>();
foreach (Control control in c)
{
if (control.ContextMenuStrip != null)
cs.Add(control.ContextMenuStrip);
else if (control.Controls.Count > 0)
cs.AddRange(FindContextMenuStrips(control.Controls.OfType<Control>()));
}
return cs;
}
// Message Displays
public static DialogResult Error(params string[] lines)
{
System.Media.SystemSounds.Exclamation.Play();
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public static DialogResult Alert(params string[] lines)
{
System.Media.SystemSounds.Asterisk.Play();
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
public static DialogResult Prompt(MessageBoxButtons btn, params string[] lines)
{
System.Media.SystemSounds.Question.Play();
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Prompt", btn, MessageBoxIcon.Asterisk);
}
// DataSource Providing
public class cbItem
{
public string Text { get; set; }
public object Value { get; set; }
}
public static List<cbItem> getCBList(string textfile, string lang)
{
// Set up
string[] inputCSV = getSimpleStringList(textfile);
// Get Language we're fetching for
int index = Array.IndexOf(new[] { "ja", "en", "fr", "de", "it", "es", "ko", "zh", }, lang);
// Set up our Temporary Storage
string[] unsortedList = new string[inputCSV.Length - 1];
int[] indexes = new int[inputCSV.Length - 1];
// Gather our data from the input file
for (int i = 1; i < inputCSV.Length; i++)
{
string[] countryData = inputCSV[i].Split(',');
indexes[i - 1] = Convert.ToInt32(countryData[0]);
unsortedList[i - 1] = countryData[index + 1];
}
// Sort our input data
string[] sortedList = new string[inputCSV.Length - 1];
Array.Copy(unsortedList, sortedList, unsortedList.Length);
Array.Sort(sortedList);
// Arrange the input data based on original number
return sortedList.Select(t => new cbItem
{
Text = t, Value = indexes[Array.IndexOf(unsortedList, t)]
}).ToList();
}
public static List<cbItem> getCBList(string[] inStrings, params int[][] allowed)
{
List<cbItem> cbList = new List<cbItem>();
if (allowed == null)
allowed = new[] { Enumerable.Range(0, inStrings.Length).ToArray() };
foreach (int[] list in allowed)
{
// Sort the Rest based on String Name
string[] unsortedChoices = new string[list.Length];
for (int i = 0; i < list.Length; i++)
unsortedChoices[i] = inStrings[list[i]];
string[] sortedChoices = new string[unsortedChoices.Length];
Array.Copy(unsortedChoices, sortedChoices, unsortedChoices.Length);
Array.Sort(sortedChoices);
// Add the rest of the items
cbList.AddRange(sortedChoices.Select(t => new cbItem
{
Text = t, Value = list[Array.IndexOf(unsortedChoices, t)]
}));
}
return cbList;
}
public static List<cbItem> getOffsetCBList(List<cbItem> cbList, string[] inStrings, int offset, int[] allowed)
{
if (allowed == null)
allowed = Enumerable.Range(0, inStrings.Length).ToArray();
int[] list = (int[])allowed.Clone();
for (int i = 0; i < list.Length; i++)
list[i] -= offset;
{
// Sort the Rest based on String Name
string[] unsortedChoices = new string[allowed.Length];
for (int i = 0; i < allowed.Length; i++)
unsortedChoices[i] = inStrings[list[i]];
string[] sortedChoices = new string[unsortedChoices.Length];
Array.Copy(unsortedChoices, sortedChoices, unsortedChoices.Length);
Array.Sort(sortedChoices);
// Add the rest of the items
cbList.AddRange(sortedChoices.Select(t => new cbItem
{
Text = t, Value = allowed[Array.IndexOf(unsortedChoices, t)]
}));
}
return cbList;
}
public static List<cbItem> getVariedCBList(List<cbItem> cbList, string[] inStrings, int[] stringNum, int[] stringVal)
{
// Set up
List<cbItem> newlist = new List<cbItem>();
for (int i = 4; i > 1; i--) // add 4,3,2
{
// First 3 Balls are always first
cbItem ncbi = new cbItem
{
Text = inStrings[i],
Value = i
};
newlist.Add(ncbi);
}
// Sort the Rest based on String Name
string[] ballnames = new string[stringNum.Length];
for (int i = 0; i < stringNum.Length; i++)
ballnames[i] = inStrings[stringNum[i]];
string[] sortedballs = new string[stringNum.Length];
Array.Copy(ballnames, sortedballs, ballnames.Length);
Array.Sort(sortedballs);
// Add the rest of the balls
newlist.AddRange(sortedballs.Select(t => new cbItem
{
Text = t, Value = stringVal[Array.IndexOf(ballnames, t)]
}));
return newlist;
}
public static List<cbItem> getUnsortedCBList(string textfile)
{
// Set up
List<cbItem> cbList = new List<cbItem>();
string[] inputCSV = getSimpleStringList(textfile);
// Gather our data from the input file
for (int i = 1; i < inputCSV.Length; i++)
{
string[] inputData = inputCSV[i].Split(',');
cbItem ncbi = new cbItem
{
Value = Convert.ToInt32(inputData[0]),
Text = inputData[1]
};
cbList.Add(ncbi);
}
return cbList;
}
}
// GARCTool Utility
public static string GuessExtension(BinaryReader br, string defaultExt, bool bypass)
@ -629,136 +207,7 @@ public static byte[] StringToByteArray(string hex)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static int highlightText(RichTextBox RTB, string word, Color hlColor)
{
int ctr = 0;
int s_start = RTB.SelectionStart, startIndex = 0, index;
while ((index = RTB.Text.IndexOf(word, startIndex, StringComparison.Ordinal)) != -1)
{
RTB.Select(index, word.Length);
RTB.SelectionColor = hlColor;
startIndex = index + word.Length;
ctr++;
}
RTB.SelectionStart = s_start;
RTB.SelectionLength = 0;
RTB.SelectionColor = Color.Black;
return ctr;
}
// http://stackoverflow.com/questions/4820212/automatically-trim-a-bitmap-to-minimum-size
public static Bitmap TrimBitmap(Bitmap source)
{
Rectangle srcRect;
BitmapData data = null;
try
{
data = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] buffer = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
int xMin = int.MaxValue,
xMax = int.MinValue,
yMin = int.MaxValue,
yMax = int.MinValue;
bool foundPixel = false;
// Find xMin
for (int x = 0; x < data.Width; x++)
{
bool stop = false;
for (int y = 0; y < data.Height; y++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
xMin = x;
stop = true;
foundPixel = true;
break;
}
}
if (stop)
break;
}
// Image is empty...
if (!foundPixel)
return null;
// Find yMin
for (int y = 0; y < data.Height; y++)
{
bool stop = false;
for (int x = xMin; x < data.Width; x++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
yMin = y;
stop = true;
break;
}
}
if (stop)
break;
}
// Find xMax
for (int x = data.Width - 1; x >= xMin; x--)
{
bool stop = false;
for (int y = yMin; y < data.Height; y++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
xMax = x;
stop = true;
break;
}
}
if (stop)
break;
}
// Find yMax
for (int y = data.Height - 1; y >= yMin; y--)
{
bool stop = false;
for (int x = xMin; x <= xMax; x++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
yMax = y;
stop = true;
break;
}
}
if (stop)
break;
}
srcRect = Rectangle.FromLTRB(xMin, yMin, xMax + 1, yMax + 1); // fixed; was cropping 1px too much on the max end
}
finally
{
if (data != null)
source.UnlockBits(data);
}
Bitmap dest = new Bitmap(srcRect.Width, srcRect.Height);
Rectangle destRect = new Rectangle(0, 0, srcRect.Width, srcRect.Height);
using (Graphics graphics = Graphics.FromImage(dest))
{
graphics.DrawImage(source, destRect, srcRect, GraphicsUnit.Pixel);
}
return dest;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -578,7 +578,7 @@ internal static void repackDARC(string path, string fileName, string outfolder =
//if (dr != DialogResult.Yes)
return;
}
Util.Alert("Not finished.");
WinFormsUtil.Alert("Not finished.");
}
// Generic Utility

121
pk3DS/GarcUtil.cs Normal file
View File

@ -0,0 +1,121 @@
using pk3DS.Core.CTR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Windows.Forms;
namespace pk3DS
{
/// <summary>
/// Windows-forms friendly wrapper for GARC functions
/// </summary>
public static class GarcUtil
{
private static ProgressBar pBar1;
private static Label label;
private static void GARC_FileCountDetermined(object sender, GARC.FileCountDeterminedEventArgs e)
{
if (pBar1 == null) pBar1 = new ProgressBar();
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)delegate { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = e.Total; });
else { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = e.Total; }
if (label == null) label = new Label();
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = true; });
}
private static void GARC_PackProgressed(object sender, GARC.PackProgressedEventArgs e)
{
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else { pBar1.PerformStep(); }
string update = $"{(float)e.Current / (float)e.Total:P2} - {e.Current}/{e.Total} - {e.CurrentFile}";
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
}
private static void GARC_UnpackProgressed(object sender, GARC.UnpackProgressedEventArgs e)
{
#region Step
if (pBar1.InvokeRequired) pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else pBar1.PerformStep();
string update = $"{e.Current / e.Total:P2} - {e.Current}/{e.Total}";
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
#endregion
}
public static bool garcPackMS(string folderPath, string garcPath, int version, int bytesPadding, ProgressBar pBar1 = null, Label label = null, bool supress = false)
{
GARC.FileCountDetermined += GARC_FileCountDetermined;
GARC.PackProgressed += GARC_PackProgressed;
try
{
var filectr = GARC.garcPackMS(folderPath, garcPath, version, bytesPadding);
if (filectr > 0)
{
// We're done.
SystemSounds.Exclamation.Play();
if (!supress) WinFormsUtil.Alert("Pack Successful!", filectr + " files packed to the GARC!");
}
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = false; });
else { label.Visible = false; }
return true;
}
catch (DirectoryNotFoundException)
{
if (!supress) WinFormsUtil.Error("Folder does not exist.");
}
catch (Exception e)
{
WinFormsUtil.Error("Packing failed", e.ToString());
}
finally
{
GARC.FileCountDetermined -= GARC_FileCountDetermined;
GARC.PackProgressed -= GARC_PackProgressed;
}
return false;
}
public static bool garcUnpack(string garcPath, string outPath, bool skipDecompression, ProgressBar pBar1 = null, Label label = null, bool supress = false, bool bypassExt = false)
{
GARC.FileCountDetermined += GARC_FileCountDetermined;
GARC.UnpackProgressed += GARC_UnpackProgressed;
try
{
var fileCount = GARC.garcUnpack(garcPath, outPath, skipDecompression);
if (fileCount > 0)
{
SystemSounds.Exclamation.Play();
if (!supress) WinFormsUtil.Alert("Unpack Successful!", fileCount + " files unpacked from the GARC!");
}
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Visible = false; });
else { label.Visible = false; }
return true;
}
catch (FileNotFoundException)
{
WinFormsUtil.Alert("File does not exist");
}
finally
{
GARC.FileCountDetermined -= GARC_FileCountDetermined;
GARC.UnpackProgressed -= GARC_UnpackProgressed;
}
return false;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -36,7 +36,7 @@ public ErrorWindow()
public ErrorWindow(string lang) : this()
{
Util.TranslateInterface(this, lang);
WinFormsUtil.TranslateInterface(this, lang);
}
/// <summary>

View File

@ -105,11 +105,11 @@ private void B_PatchCIA_Click(object sender, EventArgs e)
if (!patchExeFS(ExeFS, garcPaths, newPaths, oldROM, newROM, ref result, Path.Combine(patchFolder, ".code.bin")))
throw new Exception(result);
Util.Alert("Patch contents saved to:" + Environment.NewLine + exportGARCs(garcPaths, newPaths, Main.RomFSPath, patchFolder), result);
WinFormsUtil.Alert("Patch contents saved to:" + Environment.NewLine + exportGARCs(garcPaths, newPaths, Main.RomFSPath, patchFolder), result);
}
catch (Exception ex)
{
Util.Error("Could not create patch:", ex.ToString());
{
WinFormsUtil.Error("Could not create patch:", ex.ToString());
if (Directory.Exists(patchFolder)) Directory.Delete(patchFolder, true);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

Before

Width:  |  Height:  |  Size: 160 B

After

Width:  |  Height:  |  Size: 160 B

View File

Before

Width:  |  Height:  |  Size: 164 B

After

Width:  |  Height:  |  Size: 164 B

View File

Before

Width:  |  Height:  |  Size: 151 B

After

Width:  |  Height:  |  Size: 151 B

View File

Before

Width:  |  Height:  |  Size: 407 B

After

Width:  |  Height:  |  Size: 407 B

View File

Before

Width:  |  Height:  |  Size: 351 B

After

Width:  |  Height:  |  Size: 351 B

View File

Before

Width:  |  Height:  |  Size: 308 B

After

Width:  |  Height:  |  Size: 308 B

View File

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 327 B

View File

Before

Width:  |  Height:  |  Size: 434 B

After

Width:  |  Height:  |  Size: 434 B

View File

Before

Width:  |  Height:  |  Size: 503 B

After

Width:  |  Height:  |  Size: 503 B

View File

Before

Width:  |  Height:  |  Size: 474 B

After

Width:  |  Height:  |  Size: 474 B

View File

Before

Width:  |  Height:  |  Size: 402 B

After

Width:  |  Height:  |  Size: 402 B

View File

Before

Width:  |  Height:  |  Size: 490 B

After

Width:  |  Height:  |  Size: 490 B

View File

Before

Width:  |  Height:  |  Size: 448 B

After

Width:  |  Height:  |  Size: 448 B

View File

Before

Width:  |  Height:  |  Size: 424 B

After

Width:  |  Height:  |  Size: 424 B

View File

Before

Width:  |  Height:  |  Size: 406 B

After

Width:  |  Height:  |  Size: 406 B

View File

Before

Width:  |  Height:  |  Size: 430 B

After

Width:  |  Height:  |  Size: 430 B

View File

Before

Width:  |  Height:  |  Size: 537 B

After

Width:  |  Height:  |  Size: 537 B

View File

Before

Width:  |  Height:  |  Size: 278 B

After

Width:  |  Height:  |  Size: 278 B

View File

Before

Width:  |  Height:  |  Size: 606 B

After

Width:  |  Height:  |  Size: 606 B

View File

Before

Width:  |  Height:  |  Size: 410 B

After

Width:  |  Height:  |  Size: 410 B

View File

Before

Width:  |  Height:  |  Size: 510 B

After

Width:  |  Height:  |  Size: 510 B

View File

Before

Width:  |  Height:  |  Size: 412 B

After

Width:  |  Height:  |  Size: 412 B

View File

Before

Width:  |  Height:  |  Size: 409 B

After

Width:  |  Height:  |  Size: 409 B

View File

Before

Width:  |  Height:  |  Size: 530 B

After

Width:  |  Height:  |  Size: 530 B

View File

Before

Width:  |  Height:  |  Size: 456 B

After

Width:  |  Height:  |  Size: 456 B

View File

Before

Width:  |  Height:  |  Size: 369 B

After

Width:  |  Height:  |  Size: 369 B

View File

Before

Width:  |  Height:  |  Size: 444 B

After

Width:  |  Height:  |  Size: 444 B

View File

Before

Width:  |  Height:  |  Size: 458 B

After

Width:  |  Height:  |  Size: 458 B

View File

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 470 B

View File

Before

Width:  |  Height:  |  Size: 447 B

After

Width:  |  Height:  |  Size: 447 B

View File

Before

Width:  |  Height:  |  Size: 375 B

After

Width:  |  Height:  |  Size: 375 B

View File

Before

Width:  |  Height:  |  Size: 417 B

After

Width:  |  Height:  |  Size: 417 B

View File

Before

Width:  |  Height:  |  Size: 426 B

After

Width:  |  Height:  |  Size: 426 B

View File

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

View File

Before

Width:  |  Height:  |  Size: 471 B

After

Width:  |  Height:  |  Size: 471 B

View File

Before

Width:  |  Height:  |  Size: 436 B

After

Width:  |  Height:  |  Size: 436 B

View File

Before

Width:  |  Height:  |  Size: 476 B

After

Width:  |  Height:  |  Size: 476 B

View File

Before

Width:  |  Height:  |  Size: 664 B

After

Width:  |  Height:  |  Size: 664 B

View File

Before

Width:  |  Height:  |  Size: 447 B

After

Width:  |  Height:  |  Size: 447 B

View File

Before

Width:  |  Height:  |  Size: 462 B

After

Width:  |  Height:  |  Size: 462 B

View File

Before

Width:  |  Height:  |  Size: 500 B

After

Width:  |  Height:  |  Size: 500 B

View File

Before

Width:  |  Height:  |  Size: 348 B

After

Width:  |  Height:  |  Size: 348 B

View File

Before

Width:  |  Height:  |  Size: 673 B

After

Width:  |  Height:  |  Size: 673 B

View File

Before

Width:  |  Height:  |  Size: 621 B

After

Width:  |  Height:  |  Size: 621 B

View File

Before

Width:  |  Height:  |  Size: 471 B

After

Width:  |  Height:  |  Size: 471 B

View File

Before

Width:  |  Height:  |  Size: 296 B

After

Width:  |  Height:  |  Size: 296 B

View File

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

View File

Before

Width:  |  Height:  |  Size: 496 B

After

Width:  |  Height:  |  Size: 496 B

View File

Before

Width:  |  Height:  |  Size: 441 B

After

Width:  |  Height:  |  Size: 441 B

View File

Before

Width:  |  Height:  |  Size: 453 B

After

Width:  |  Height:  |  Size: 453 B

View File

Before

Width:  |  Height:  |  Size: 418 B

After

Width:  |  Height:  |  Size: 418 B

View File

Before

Width:  |  Height:  |  Size: 370 B

After

Width:  |  Height:  |  Size: 370 B

View File

Before

Width:  |  Height:  |  Size: 423 B

After

Width:  |  Height:  |  Size: 423 B

View File

Before

Width:  |  Height:  |  Size: 321 B

After

Width:  |  Height:  |  Size: 321 B

View File

Before

Width:  |  Height:  |  Size: 326 B

After

Width:  |  Height:  |  Size: 326 B

View File

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

View File

Before

Width:  |  Height:  |  Size: 563 B

After

Width:  |  Height:  |  Size: 563 B

View File

Before

Width:  |  Height:  |  Size: 477 B

After

Width:  |  Height:  |  Size: 477 B

View File

Before

Width:  |  Height:  |  Size: 499 B

After

Width:  |  Height:  |  Size: 499 B

View File

Before

Width:  |  Height:  |  Size: 441 B

After

Width:  |  Height:  |  Size: 441 B

View File

Before

Width:  |  Height:  |  Size: 466 B

After

Width:  |  Height:  |  Size: 466 B

View File

Before

Width:  |  Height:  |  Size: 477 B

After

Width:  |  Height:  |  Size: 477 B

View File

Before

Width:  |  Height:  |  Size: 376 B

After

Width:  |  Height:  |  Size: 376 B

View File

Before

Width:  |  Height:  |  Size: 451 B

After

Width:  |  Height:  |  Size: 451 B

View File

Before

Width:  |  Height:  |  Size: 500 B

After

Width:  |  Height:  |  Size: 500 B

View File

Before

Width:  |  Height:  |  Size: 552 B

After

Width:  |  Height:  |  Size: 552 B

View File

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 470 B

View File

Before

Width:  |  Height:  |  Size: 518 B

After

Width:  |  Height:  |  Size: 518 B

View File

Before

Width:  |  Height:  |  Size: 524 B

After

Width:  |  Height:  |  Size: 524 B

View File

Before

Width:  |  Height:  |  Size: 460 B

After

Width:  |  Height:  |  Size: 460 B

View File

Before

Width:  |  Height:  |  Size: 423 B

After

Width:  |  Height:  |  Size: 423 B

View File

Before

Width:  |  Height:  |  Size: 385 B

After

Width:  |  Height:  |  Size: 385 B

View File

Before

Width:  |  Height:  |  Size: 462 B

After

Width:  |  Height:  |  Size: 462 B

View File

Before

Width:  |  Height:  |  Size: 533 B

After

Width:  |  Height:  |  Size: 533 B

View File

Before

Width:  |  Height:  |  Size: 418 B

After

Width:  |  Height:  |  Size: 418 B

View File

Before

Width:  |  Height:  |  Size: 468 B

After

Width:  |  Height:  |  Size: 468 B

View File

Before

Width:  |  Height:  |  Size: 509 B

After

Width:  |  Height:  |  Size: 509 B

View File

Before

Width:  |  Height:  |  Size: 403 B

After

Width:  |  Height:  |  Size: 403 B

View File

Before

Width:  |  Height:  |  Size: 480 B

After

Width:  |  Height:  |  Size: 480 B

View File

Before

Width:  |  Height:  |  Size: 468 B

After

Width:  |  Height:  |  Size: 468 B

View File

Before

Width:  |  Height:  |  Size: 409 B

After

Width:  |  Height:  |  Size: 409 B

View File

Before

Width:  |  Height:  |  Size: 605 B

After

Width:  |  Height:  |  Size: 605 B

View File

Before

Width:  |  Height:  |  Size: 404 B

After

Width:  |  Height:  |  Size: 404 B

View File

Before

Width:  |  Height:  |  Size: 434 B

After

Width:  |  Height:  |  Size: 434 B

View File

Before

Width:  |  Height:  |  Size: 374 B

After

Width:  |  Height:  |  Size: 374 B

View File

Before

Width:  |  Height:  |  Size: 469 B

After

Width:  |  Height:  |  Size: 469 B

View File

Before

Width:  |  Height:  |  Size: 382 B

After

Width:  |  Height:  |  Size: 382 B

View File

Before

Width:  |  Height:  |  Size: 438 B

After

Width:  |  Height:  |  Size: 438 B

Some files were not shown because too many files have changed in this diff Show More