public SAV_BoxLayout(SaveFile sav, int box) { InitializeComponent(); WinFormsUtil.TranslateInterface(this, Main.CurrentLanguage); SAV = (Origin = sav).Clone(); editing = true; if (!SAV.HasBoxWallpapers) { CB_BG.Visible = PAN_BG.Visible = false; } else if (!LoadWallpaperNames()) // Repopulate Wallpaper names { WinFormsUtil.Error("Box layout is not supported for this game.", "Please close the window."); } LoadBoxNames(); LoadFlags(); LoadUnlockedCount(); LB_BoxSelect.SelectedIndex = box; editing = false; }
private void ViewGiftData(DataMysteryGift g) { try { // only check if the form is visible (not opening) if (Visible && g.GiftUsed && DialogResult.Yes == WinFormsUtil.Prompt(MessageBoxButtons.YesNo, MsgMsyteryGiftUsedAlert, MsgMysteryGiftUsedFix)) { g.GiftUsed = false; } RTB.Lines = g.GetDescription().ToArray(); PB_Preview.Image = g.Sprite(); mg = g; } // Some user input mystery gifts can have out-of-bounds values. Just swallow any exception. #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { WinFormsUtil.Error(MsgMysteryGiftParseTypeUnknown, e); RTB.Clear(); } }
private void B_ImportPNG_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog { Filter = "PNG File|*.png", FileName = "Background.png", }; if (ofd.ShowDialog() != DialogResult.OK) return; Bitmap img = (Bitmap)Image.FromFile(ofd.FileName); try { bg = CGearExtensions.GetCGearBackground(img); PB_Background.Image = CGearExtensions.GetBitmap(bg); } catch (Exception ex) { WinFormsUtil.Error(ex.Message); } }
private void viewGiftData(MysteryGift g) { try { // only check if the form is visible (not opening) if (Visible && g.GiftUsed && DialogResult.Yes == WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Wonder Card is marked as USED and will not be able to be picked up in-game.", "Do you want to remove the USED flag so that it is UNUSED?")) { g.GiftUsed = false; } RTB.Text = getDescription(g); PB_Preview.Image = g.Sprite(); mg = g; } catch (Exception e) { WinFormsUtil.Error("Loading of data failed... is this really a Wonder Card?", e); RTB.Clear(); } }
private void LoadAllBags() { foreach (var pouch in Pouches) { var dgv = GetGrid(pouch.Type); // Sanity Screen var invalid = pouch.Items.Where(item => item.Index != 0 && !pouch.LegalItems.Contains((ushort)item.Index)).ToArray(); var outOfBounds = invalid.Where(item => item.Index >= itemlist.Length).ToArray(); var incorrectPouch = invalid.Where(item => item.Index < itemlist.Length).ToArray(); if (outOfBounds.Length > 0) { WinFormsUtil.Error(MsgItemPouchUnknown, $"Item ID(s): {string.Join(", ", outOfBounds.Select(item => item.Index))}"); } if (!Main.HaX && incorrectPouch.Length > 0) { WinFormsUtil.Alert(string.Format(MsgItemPouchRemoved, pouch.Type), string.Join(", ", incorrectPouch.Select(item => itemlist[item.Index])), MsgItemPouchWarning); } pouch.Sanitize(Main.HaX, itemlist.Length - 1); GetBag(dgv, pouch); } }
private static void ImportSelectBlock(SCBlock blockTarget) { var key = blockTarget.Key; var data = blockTarget.Data; using var ofd = new OpenFileDialog { FileName = $"{key:X8}.bin" }; if (ofd.ShowDialog() != DialogResult.OK) { return; } var path = ofd.FileName; var file = new FileInfo(path); if (file.Length != data.Length) { WinFormsUtil.Error(string.Format(MessageStrings.MsgFileSize, $"0x{file.Length:X8}")); return; } var bytes = File.ReadAllBytes(path); bytes.CopyTo(data, 0); }
// Main Menu Subfunctions private void openQuick(string path, bool force = false) { // detect if it is a folder (load into boxes or not) if (Directory.Exists(path)) { C_SAV.LoadBoxes(out string _, path); return; } string ext = Path.GetExtension(path); FileInfo fi = new FileInfo(path); if (!fi.Exists) { return; } if (fi.Length > 0x10009C && fi.Length != 0x380000 && !SAV3GCMemoryCard.IsMemoryCardSize(fi.Length)) { WinFormsUtil.Error("Input file is too large." + Environment.NewLine + $"Size: {fi.Length} bytes", path); } else if (fi.Length < 32) { WinFormsUtil.Error("Input file is too small." + Environment.NewLine + $"Size: {fi.Length} bytes", path); } else { byte[] input; try { input = File.ReadAllBytes(path); } catch (Exception e) { WinFormsUtil.Error("Unable to load file. It could be in use by another program.\nPath: " + path, e); return; } #if DEBUG OpenFile(input, path, ext, C_SAV.SAV); #else try { OpenFile(input, path, ext, C_SAV.SAV); } catch (Exception e) { WinFormsUtil.Error("Unable to load file.\nPath: " + path, e); } #endif } }
private static void DeleteSettings() { try { var dr = WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Resetting settings requires the program to exit.", MessageStrings.MsgContinue); if (dr != DialogResult.Yes) { return; } var path = Main.ConfigPath; if (File.Exists(path)) { File.Delete(path); } System.Diagnostics.Process.Start(Application.ExecutablePath); Environment.Exit(0); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { WinFormsUtil.Error("Failed to delete settings.", ex.Message); } }
private void Menu_DeleteClones_Click(object sender, EventArgs e) { var dr = WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Deleting clones from database is not reversible." + Environment.NewLine + "If a PKM is deemed a clone, only the newest file (date modified) will be kept.", "Continue?"); if (dr != DialogResult.Yes) { return; } var hashes = new List <string>(); var deleted = 0; var db = RawDB.Where(pk => pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)) .OrderByDescending(file => new FileInfo(file.Identifier).LastWriteTime); foreach (var pk in db) { var h = hash(pk); if (!hashes.Contains(h)) { hashes.Add(h); continue; } try { File.Delete(pk.Identifier); ++deleted; } catch { WinFormsUtil.Error("Unable to delete clone:" + Environment.NewLine + pk.Identifier); } } if (deleted == 0) { WinFormsUtil.Alert("No clones detected or deleted."); return; } WinFormsUtil.Alert($"{deleted} files deleted.", "The form will now close."); Close(); }
private void GetBags() { foreach (InventoryPouch pouch in Pouches) { DataGridView dgv = Controls.Find(DGVPrefix + pouch.Type, true).FirstOrDefault() as DataGridView; // Sanity Screen var invalid = pouch.Items.Where(item => item.Index != 0 && !pouch.LegalItems.Contains((ushort)item.Index)).ToArray(); var outOfBounds = invalid.Where(item => item.Index >= itemlist.Length).ToArray(); var incorrectPouch = invalid.Where(item => item.Index < itemlist.Length).ToArray(); if (outOfBounds.Length > 0) { WinFormsUtil.Error(MsgItemPouchUnknown, $"Item ID(s): {string.Join(", ", outOfBounds.Select(item => item.Index))}"); } if (!Main.HaX && incorrectPouch.Length > 0) { WinFormsUtil.Alert(string.Format(MsgItemPouchRemoved, pouch.Type), string.Join(", ", incorrectPouch.Select(item => itemlist[item.Index])), MsgItemPouchWarning); } pouch.Sanitize(Main.HaX, itemlist.Length - 1); GetBag(dgv, pouch); } }
private void pbBoxSlot_DragDrop(object sender, DragEventArgs e) { DragInfo.Destination.Parent = this; DragInfo.Destination.Slot = getSlot(sender); DragInfo.Destination.Offset = getPKXOffset(DragInfo.Destination.Slot); DragInfo.Destination.Box = CB_BoxSelect.SelectedIndex; // Check for In-Dropped files (PKX,SAV,ETC) string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (Directory.Exists(files[0])) { return; } if (SAV.getIsSlotLocked(DragInfo.Destination.Box, DragInfo.Destination.Slot)) { DragInfo.Destination.Slot = -1; // Invalidate WinFormsUtil.Alert("Unable to set to locked slot."); return; } if (DragInfo.Source.Offset < 0) // file { if (files.Length <= 0) { return; } string file = files[0]; FileInfo fi = new FileInfo(file); if (!PKX.getIsPKM(fi.Length) && !MysteryGift.getIsMysteryGift(fi.Length)) { return; } byte[] data = File.ReadAllBytes(file); MysteryGift mg = MysteryGift.getMysteryGift(data, fi.Extension); PKM temp = mg != null?mg.convertToPKM(SAV) : PKMConverter.getPKMfromBytes(data, prefer: SAV.Generation); string c; PKM pk = PKMConverter.convertToFormat(temp, SAV.PKMType, out c); if (pk == null) { WinFormsUtil.Error(c); Console.WriteLine(c); return; } string[] errata = SAV.IsPKMCompatible(pk); if (errata.Length > 0) { string concat = string.Join(Environment.NewLine, errata); if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, concat, "Continue?")) { Console.WriteLine(c); Console.WriteLine(concat); return; } } DragInfo.SetPKM(pk, false); getQuickFiller(SlotPictureBoxes[DragInfo.Destination.Slot], pk); Console.WriteLine(c); } else { PKM pkz = DragInfo.GetPKM(true); if (!DragInfo.Source.IsValid) { } // not overwritable, do nothing else if (ModifierKeys == Keys.Alt && DragInfo.Destination.IsValid) // overwrite { // Clear from slot if (DragInfo.SameBox) { getQuickFiller(SlotPictureBoxes[DragInfo.Source.Slot], SAV.BlankPKM); // picturebox } DragInfo.SetPKM(SAV.BlankPKM, true); } else if (ModifierKeys != Keys.Control && DragInfo.Destination.IsValid) // move { // Load data from destination PKM pk = ((PictureBox)sender).Image != null ? DragInfo.GetPKM(false) : SAV.BlankPKM; // Set destination pokemon image to source picture box if (DragInfo.SameBox) { getQuickFiller(SlotPictureBoxes[DragInfo.Source.Slot], pk); } // Set destination pokemon data to source slot DragInfo.SetPKM(pk, true); } else if (DragInfo.SameBox) // clone { getQuickFiller(SlotPictureBoxes[DragInfo.Source.Slot], pkz); } // Copy from temp to destination slot. DragInfo.SetPKM(pkz, false); getQuickFiller(SlotPictureBoxes[DragInfo.Destination.Slot], pkz); e.Effect = DragDropEffects.Link; Cursor = DefaultCursor; } if (DragInfo.Source.IsParty || DragInfo.Destination.IsParty) { parent.setParty(); } if (DragInfo.Source.Parent == null) // another instance or file { parent.notifyBoxViewerRefresh(); DragInfo.Reset(); } }
private void ClickDelete(object sender, EventArgs e) { sender = WinFormsUtil.GetUnderlyingControl(sender); int index = Array.IndexOf(PKXBOXES, sender); if (index >= RES_MAX) { System.Media.SystemSounds.Exclamation.Play(); return; } index += SCR_Box.Value * RES_MIN; if (index >= Results.Count) { System.Media.SystemSounds.Exclamation.Play(); return; } var pk = Results[index]; string path = pk.Identifier; #if LOADALL if (path.StartsWith(EXTERNAL_SAV)) { WinFormsUtil.Alert(MsgDBDeleteFailBackup); return; } #endif if (path.Contains(Path.DirectorySeparatorChar)) { // Data from Database: Delete file from disk if (File.Exists(path)) { File.Delete(path); } } else { // Data from Box: Delete from save file int box = pk.Box - 1; int slot = pk.Slot - 1; int offset = SAV.GetBoxOffset(box) + (slot * SAV.SIZE_STORED); PKM pkSAV = SAV.GetStoredSlot(offset); if (!pkSAV.DecryptedBoxData.SequenceEqual(pk.DecryptedBoxData)) // data still exists in SAV, unmodified { WinFormsUtil.Error(MsgDBDeleteFailModified, MsgDBDeleteFailWarning); return; } var change = new SlotChange { Box = box, Offset = offset, Slot = slot }; BoxView.M.SetPKM(BoxView.SAV.BlankPKM, change, true, Properties.Resources.slotDel); } // Remove from database. RawDB.Remove(pk); Results.Remove(pk); // Refresh database view. L_Count.Text = string.Format(Counter, Results.Count); slotSelected = -1; FillPKXBoxes(SCR_Box.Value); System.Media.SystemSounds.Asterisk.Play(); }
private void B_FAV2SAV(object sender, EventArgs e) { // Write data back to save int index = LB_Favorite.SelectedIndex; // store for restoring if (!GB_PKM.Enabled && index > 0) { WinFormsUtil.Error("Sorry, no overwriting someone else's base with your own data."); return; } if (GB_PKM.Enabled && index == 0) { WinFormsUtil.Error("Sorry, no overwriting of your own base with someone else's."); return; } var name = LB_Favorite.Items[index].ToString(); if (name == "* " || name == $"{index} Empty") { WinFormsUtil.Error("Sorry, no overwriting an empty base with someone else's."); return; } if (index < 0) { return; } int offset = SAV.SecretBase + 0x25A; // Base Offset Changing if (index == 0) { offset = SAV.SecretBase + 0x326; } else { offset += 0x3E0 * index; } string TrainerName = TB_FOT.Text; byte[] tr = Encoding.Unicode.GetBytes(TrainerName); Array.Resize(ref tr, 0x22); Array.Copy(tr, 0, SAV.Data, offset + 0x218, 0x1A); string team1 = TB_FT1.Text; string team2 = TB_FT2.Text; byte[] t1 = Encoding.Unicode.GetBytes(team1); Array.Resize(ref t1, 0x22); Array.Copy(t1, 0, SAV.Data, offset + 0x232 + (0x22 * 0), 0x22); byte[] t2 = Encoding.Unicode.GetBytes(team2); Array.Resize(ref t2, 0x22); Array.Copy(t2, 0, SAV.Data, offset + 0x232 + (0x22 * 1), 0x22); string saying1 = TB_FSay1.Text; string saying2 = TB_FSay2.Text; string saying3 = TB_FSay3.Text; string saying4 = TB_FSay4.Text; byte[] s1 = Encoding.Unicode.GetBytes(saying1); Array.Resize(ref s1, 0x22); Array.Copy(s1, 0, SAV.Data, offset + 0x276 + (0x22 * 0), 0x22); byte[] s2 = Encoding.Unicode.GetBytes(saying2); Array.Resize(ref s2, 0x22); Array.Copy(s2, 0, SAV.Data, offset + 0x276 + (0x22 * 1), 0x22); byte[] s3 = Encoding.Unicode.GetBytes(saying3); Array.Resize(ref s3, 0x22); Array.Copy(s3, 0, SAV.Data, offset + 0x276 + (0x22 * 2), 0x22); byte[] s4 = Encoding.Unicode.GetBytes(saying4); Array.Resize(ref s4, 0x22); Array.Copy(s4, 0, SAV.Data, offset + 0x276 + (0x22 * 3), 0x22); int baseloc = (int)NUD_FBaseLocation.Value; if (baseloc < 3) { baseloc = 0; // skip 1/2 baselocs as they are dummied out ingame. } Array.Copy(BitConverter.GetBytes(baseloc), 0, SAV.Data, offset, 2); TB_FOT.Text = TrainerName; TB_FSay1.Text = saying1; TB_FSay2.Text = saying2; TB_FSay3.Text = saying3; TB_FSay4.Text = saying4; // Copy back Objects for (int i = 0; i < 25; i++) { for (int z = 0; z < 12; z++) { SAV.Data[offset + 2 + (12 * i) + z] = objdata[i, z]; } } if (GB_PKM.Enabled) // Copy pkm data back in { SaveFavPKM(); for (int i = 0; i < 3; i++) { for (int z = 0; z < 0x34; z++) { SAV.Data[offset + 0x32E + (0x34 * i) + z] = pkmdata[i, z]; } } } PopFavorite(); LB_Favorite.SelectedIndex = index; }
private void pbBoxSlot_MouseMove(object sender, MouseEventArgs e) { if (DragInfo.DragDropInProgress) { return; } if (!DragInfo.LeftMouseIsDown) { return; } // The goal is to create a temporary PKX file for the underlying Pokemon // and use that file to perform a drag drop operation. // Abort if there is no Pokemon in the given slot. PictureBox pb = (PictureBox)sender; if (pb.Image == null) { return; } int slot = getSlot(pb); int box = slot >= 30 ? -1 : CB_BoxSelect.SelectedIndex; if (SAV.getIsSlotLocked(box, slot)) { return; } // Set flag to prevent re-entering. DragInfo.DragDropInProgress = true; DragInfo.Source.Parent = this; DragInfo.Source.Slot = slot; DragInfo.Source.Box = box; DragInfo.Source.Offset = getPKXOffset(DragInfo.Source.Slot); // Prepare Data DragInfo.Source.Data = SAV.getData(DragInfo.Source.Offset, SAV.SIZE_STORED); // Make a new file name based off the PID byte[] dragdata = SAV.decryptPKM(DragInfo.Source.Data); Array.Resize(ref dragdata, SAV.SIZE_STORED); PKM pkx = SAV.getPKM(dragdata); string filename = pkx.FileName; // Make File string newfile = Path.Combine(Path.GetTempPath(), Util.CleanFileName(filename)); try { File.WriteAllBytes(newfile, dragdata); var img = (Bitmap)pb.Image; DragInfo.Cursor = Cursor.Current = new Cursor(img.GetHicon()); pb.Image = null; pb.BackgroundImage = Resources.slotDrag; // Thread Blocks on DoDragDrop DragInfo.CurrentPath = newfile; DragDropEffects result = pb.DoDragDrop(new DataObject(DataFormats.FileDrop, new[] { newfile }), DragDropEffects.Move); if (!DragInfo.Source.IsValid || result != DragDropEffects.Link) // not dropped to another box slot, restore img { pb.Image = img; } else // refresh image { getQuickFiller(pb, SAV.getStoredSlot(DragInfo.Source.Offset)); } pb.BackgroundImage = null; if (DragInfo.SameBox && DragInfo.Destination.IsValid) { if (SAV.getIsTeamSet(box, DragInfo.Destination.Slot) ^ SAV.getIsTeamSet(box, DragInfo.Source.Slot)) { getQuickFiller(SlotPictureBoxes[DragInfo.Destination.Slot], SAV.getStoredSlot(DragInfo.Destination.Offset)); } else { SlotPictureBoxes[DragInfo.Destination.Slot].Image = img; } } } catch (Exception x) { WinFormsUtil.Error("Drag & Drop Error", x); } parent.notifyBoxViewerRefresh(); DragInfo.Reset(); Cursor = DefaultCursor; // Browser apps need time to load data since the file isn't moved to a location on the user's local storage. // Tested 10ms -> too quick, 100ms was fine. 500ms should be safe? new Thread(() => { Thread.Sleep(500); if (File.Exists(newfile) && DragInfo.CurrentPath == null) { File.Delete(newfile); } }).Start(); }
public SAV_BoxLayout(int box) { InitializeComponent(); WinFormsUtil.TranslateInterface(this, Main.curlanguage); editing = true; // Repopulate Wallpaper names CB_BG.Items.Clear(); switch (SAV.Generation) { case 3: if (SAV.GameCube) { goto default; } CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames.Take(16).ToArray()); break; case 4: case 5: case 6: CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames); break; case 7: CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames.Take(16).ToArray()); break; default: WinFormsUtil.Error("Box layout is not supported for this game.", "Please close the window."); break; } // Go LB_BoxSelect.Items.Clear(); for (int i = 0; i < SAV.BoxCount; i++) { LB_BoxSelect.Items.Add(SAV.getBoxName(i)); } // Flags byte[] flags = SAV.BoxFlags; if (flags != null) { flagArr = new NumericUpDown[flags.Length]; for (int i = 0; i < flags.Length; i++) { flagArr[i] = new NumericUpDown { Minimum = 0, Maximum = 255, Width = CB_Unlocked.Width - 5, Hexadecimal = true, Value = flags[i] }; FLP_Flags.Controls.Add(flagArr[i]); } } else { FLP_Flags.Visible = false; } // Unlocked if (SAV.BoxesUnlocked > 0) { CB_Unlocked.Items.Clear(); for (int i = 0; i <= SAV.BoxCount; i++) { CB_Unlocked.Items.Add(i); } CB_Unlocked.SelectedIndex = Math.Min(SAV.BoxCount, SAV.BoxesUnlocked); } else { FLP_Unlocked.Visible = L_Unlocked.Visible = CB_Unlocked.Visible = false; } LB_BoxSelect.SelectedIndex = box; }
// View Updates private void B_Search_Click(object sender, EventArgs e) { // Populate Search Query Result IEnumerable <MysteryGift> res = RawDB; int format = MAXFORMAT + 1 - CB_Format.SelectedIndex; switch (CB_FormatComparator.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(mg => mg.Format >= format); break; case 2: res = res.Where(mg => mg.Format == format); break; case 3: res = res.Where(mg => mg.Format <= format); break; } // Primary Searchables int species = WinFormsUtil.GetIndex(CB_Species); int item = WinFormsUtil.GetIndex(CB_HeldItem); if (species != -1) { res = res.Where(pk => pk.Species == species); } if (item != -1) { res = res.Where(pk => pk.HeldItem == item); } // Secondary Searchables int move1 = WinFormsUtil.GetIndex(CB_Move1); int move2 = WinFormsUtil.GetIndex(CB_Move2); int move3 = WinFormsUtil.GetIndex(CB_Move3); int move4 = WinFormsUtil.GetIndex(CB_Move4); if (move1 != -1) { res = res.Where(pk => pk.Moves.Contains(move1)); } if (move2 != -1) { res = res.Where(pk => pk.Moves.Contains(move2)); } if (move3 != -1) { res = res.Where(pk => pk.Moves.Contains(move3)); } if (move4 != -1) { res = res.Where(pk => pk.Moves.Contains(move4)); } if (CHK_Shiny.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsShiny); } if (CHK_Shiny.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsShiny); } if (CHK_IsEgg.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsEgg); } slotSelected = -1; // reset the slot last viewed if (RTB_Instructions.Lines.Any(line => line.Length > 0)) { var raw = RTB_Instructions.Lines .Where(line => !string.IsNullOrWhiteSpace(line)) .Where(line => new[] { '!', '=' }.Contains(line[0])); var filters = (from line in raw let eval = line[0] == '=' let split = line.Substring(1).Split('=') where split.Length == 2 && !string.IsNullOrWhiteSpace(split[0]) select new BatchEditor.StringInstruction { PropertyName = split[0], PropertyValue = split[1], Evaluator = eval }).ToArray(); if (filters.Any(z => string.IsNullOrWhiteSpace(z.PropertyValue))) { WinFormsUtil.Error(MsgBEFilterEmpty); return; } res = res.Where(gift => // Compare across all filters { foreach (var cmd in filters) { if (!gift.GetType().HasPropertyAll(cmd.PropertyName)) { return(false); } try { if (gift.GetType().IsValueEqual(gift, cmd.PropertyName, cmd.PropertyValue) == cmd.Evaluator) { continue; } } catch { Debug.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}."); } return(false); } return(true); }); } var results = res.ToArray(); if (results.Length == 0) { WinFormsUtil.Alert(MsgDBSearchNone); } SetResults(new List <MysteryGift>(results)); // updates Count Label as well. System.Media.SystemSounds.Asterisk.Play(); }
private void DiffSaves() { if (!File.Exists(TB_OldSAV.Text)) { WinFormsUtil.Alert("Save 1 path invalid."); return; } if (!File.Exists(TB_NewSAV.Text)) { WinFormsUtil.Alert("Save 2 path invalid."); return; } if (new FileInfo(TB_OldSAV.Text).Length > 0x100000) { WinFormsUtil.Alert("Save 1 file invalid."); return; } if (new FileInfo(TB_NewSAV.Text).Length > 0x100000) { WinFormsUtil.Alert("Save 2 file invalid."); return; } SaveFile s1 = SaveUtil.GetVariantSAV(File.ReadAllBytes(TB_OldSAV.Text)); SaveFile s2 = SaveUtil.GetVariantSAV(File.ReadAllBytes(TB_NewSAV.Text)); if (s1 == null) { WinFormsUtil.Alert("Save 1 file invalid."); return; } if (s2 == null) { WinFormsUtil.Alert("Save 2 file invalid."); return; } if (s1.GetType() != s2.GetType()) { WinFormsUtil.Alert("Save types are different.", $"S1: {s1.GetType().Name}", $"S2: {s2.GetType().Name}"); return; } if (s1.Version != s2.Version) { WinFormsUtil.Alert("Save versions are different.", $"S1: {s1.Version}", $"S2: {s2.Version}"); return; } string tbIsSet = ""; string tbUnSet = ""; try { bool[] oldBits = s1.EventFlags; bool[] newBits = s2.EventFlags; if (oldBits.Length != newBits.Length) { WinFormsUtil.Alert("Event flag lengths for games are different.", $"S1: {(GameVersion)s1.Game}", $"S2: {(GameVersion)s2.Game}"); return; } for (int i = 0; i < oldBits.Length; i++) { if (oldBits[i] == newBits[i]) { continue; } if (newBits[i]) { tbIsSet += $"{i:0000},"; } else { tbUnSet += $"{i:0000},"; } } } catch (Exception e) { WinFormsUtil.Error("An unexpected error has occurred.", e); Debug.WriteLine(e); } TB_IsSet.Text = tbIsSet; TB_UnSet.Text = tbUnSet; string r = ""; try { ushort[] oldConst = s1.EventConsts; ushort[] newConst = s2.EventConsts; if (oldConst.Length != newConst.Length) { WinFormsUtil.Alert("Event flag lengths for games are different.", $"S1: {(GameVersion)s1.Game}", $"S2: {(GameVersion)s2.Game}"); return; } for (int i = 0; i < newConst.Length; i++) { if (oldConst[i] != newConst[i]) { r += $"{i}: {oldConst[i]}->{newConst[i]}{Environment.NewLine}"; } } } catch (Exception e) { WinFormsUtil.Error("An unexpected error has occurred.", e); Debug.WriteLine(e); } if (string.IsNullOrEmpty(r)) { WinFormsUtil.Alert("No Event Constant diff found."); return; } if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Copy Event Constant diff to clipboard?")) { return; } Clipboard.SetText(r); }
private void runBackgroundWorker() { var Filters = getFilters().ToList(); if (Filters.Any(z => string.IsNullOrWhiteSpace(z.PropertyValue))) { WinFormsUtil.Error("Empty Filter Value detected."); return; } var Instructions = getInstructions().ToList(); var emptyVal = Instructions.Where(z => string.IsNullOrWhiteSpace(z.PropertyValue)).ToArray(); if (emptyVal.Any()) { string props = string.Join(", ", emptyVal.Select(z => z.PropertyName)); if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, $"Empty Property Value{(emptyVal.Length > 1 ? "s" : "")} detected:" + Environment.NewLine + props, "Continue?")) { return; } } string destPath = ""; if (RB_Path.Checked) { WinFormsUtil.Alert("Please select the folder where the files will be saved to.", "This can be the same folder as the source of PKM files."); var fbd = new FolderBrowserDialog(); var dr = fbd.ShowDialog(); if (dr != DialogResult.OK) { return; } destPath = fbd.SelectedPath; } FLP_RB.Enabled = RTB_Instructions.Enabled = B_Go.Enabled = false; b = new BackgroundWorker { WorkerReportsProgress = true }; screenStrings(Filters); screenStrings(Instructions); b.DoWork += (sender, e) => { if (RB_SAV.Checked) { var data = Main.SAV.BoxData; setupProgressBar(data.Length); processSAV(data, Filters, Instructions); } else { var files = Directory.GetFiles(TB_Folder.Text, "*", SearchOption.AllDirectories); setupProgressBar(files.Length); processFolder(files, Filters, Instructions, destPath); } }; b.ProgressChanged += (sender, e) => { setProgressBar(e.ProgressPercentage); }; b.RunWorkerCompleted += (sender, e) => { string result = $"Modified {ctr}/{len} files."; if (err > 0) { result += Environment.NewLine + $"{err} files ignored due to an internal error."; } WinFormsUtil.Alert(result); FLP_RB.Enabled = RTB_Instructions.Enabled = B_Go.Enabled = true; setupProgressBar(0); }; b.RunWorkerAsync(); }
private void B_FAV2SAV(object sender, EventArgs e) { // Write data back to save int index = LB_Favorite.SelectedIndex; // store for restoring if (!GB_PKM.Enabled && index > 0) { WinFormsUtil.Error("Sorry, no overwriting someone else's base with your own data."); return; } if (GB_PKM.Enabled && index == 0) { WinFormsUtil.Error("Sorry, no overwriting of your own base with someone else's."); return; } var name = LB_Favorite.Items[index].ToString(); if (name == "* " || name == $"{index} Empty") { WinFormsUtil.Error("Sorry, no overwriting an empty base with someone else's."); return; } if (index < 0) { return; } int offset = GetSecretBaseOffset(index); var bdata = new SecretBase6(SAV.Data, offset); int baseloc = (int)NUD_FBaseLocation.Value; if (baseloc < 3) { baseloc = 0; // skip 1/2 baselocs as they are dummied out ingame. } bdata.BaseLocation = baseloc; bdata.TrainerName = TB_FOT.Text; bdata.FlavorText1 = TB_FT1.Text; bdata.FlavorText2 = TB_FT2.Text; bdata.Saying1 = TB_FSay1.Text; bdata.Saying2 = TB_FSay2.Text; bdata.Saying3 = TB_FSay3.Text; bdata.Saying4 = TB_FSay4.Text; // Copy back Objects for (int i = 0; i < 25; i++) { for (int z = 0; z < 12; z++) { SAV.Data[offset + 2 + (12 * i) + z] = objdata[i, z]; } } if (GB_PKM.Enabled) // Copy pkm data back in { SaveFavPKM(); for (int i = 0; i < 3; i++) { for (int z = 0; z < 0x34; z++) { SAV.Data[offset + 0x32E + (0x34 * i) + z] = pkmdata[i, z]; } } } PopFavorite(); LB_Favorite.SelectedIndex = currentIndex = index; }
private void ClickDelete(object sender, EventArgs e) { sender = ((sender as ToolStripItem)?.Owner as ContextMenuStrip)?.SourceControl ?? sender as PictureBox; int index = Array.IndexOf(PKXBOXES, sender); if (index >= RES_MAX) { System.Media.SystemSounds.Exclamation.Play(); return; } index += SCR_Box.Value * RES_MIN; if (index >= Results.Count) { System.Media.SystemSounds.Exclamation.Play(); return; } var pk = Results[index]; string path = pk.Identifier; #if LOADALL if (path.StartsWith(EXTERNAL_SAV)) { WinFormsUtil.Alert("Can't delete from a backup save."); return; } #endif if (path.Contains(Path.DirectorySeparatorChar)) { // Data from Database: Delete file from disk if (File.Exists(path)) { File.Delete(path); } } else { // Data from Box: Delete from save file int box = pk.Box - 1; int slot = pk.Slot - 1; int offset = SAV.GetBoxOffset(box) + slot * SAV.SIZE_STORED; PKM pkSAV = SAV.GetStoredSlot(offset); if (!pkSAV.Data.SequenceEqual(pk.Data)) // data still exists in SAV, unmodified { WinFormsUtil.Error("Database slot data does not match save data!", "Don't move Pokémon after initializing the Database, please re-open the Database viewer."); return; } var change = new SlotChange { Box = box, Offset = offset, Slot = slot }; BoxView.M.SetPKM(BoxView.SAV.BlankPKM, change, true, Properties.Resources.slotDel); } // Remove from database. RawDB.Remove(pk); Results.Remove(pk); // Refresh database view. L_Count.Text = string.Format(Counter, Results.Count); slotSelected = -1; FillPKXBoxes(SCR_Box.Value); System.Media.SystemSounds.Asterisk.Play(); }
public SAV_Database(PKMEditor f1, SAVEditor saveditor) { InitializeComponent(); WinFormsUtil.TranslateInterface(this, Main.CurrentLanguage); SAV = saveditor.SAV; BoxView = saveditor; PKME_Tabs = f1; // Preset Filters to only show PKM available for loaded save CB_FormatComparator.SelectedIndex = 3; // <= var grid = DatabasePokeGrid; var smallWidth = grid.Width; var smallHeight = grid.Height; grid.InitializeGrid(6, 11, SpriteUtil.Spriter); grid.SetBackground(Resources.box_wp_clean); var newWidth = grid.Width; var newHeight = grid.Height; var wdelta = newWidth - smallWidth; if (wdelta != 0) { Width += wdelta; } var hdelta = newHeight - smallHeight; if (hdelta != 0) { Height += hdelta; } PKXBOXES = grid.Entries.ToArray(); // Enable Scrolling when hovered over foreach (var slot in PKXBOXES) { // Enable Click slot.MouseClick += (sender, e) => { if (sender == null) { return; } switch (ModifierKeys) { case Keys.Control: ClickView(sender, e); break; case Keys.Alt: ClickDelete(sender, e); break; case Keys.Shift: ClickSet(sender, e); break; } }; slot.ContextMenuStrip = mnu; if (Settings.Default.HoverSlotShowText) { slot.MouseEnter += (o, args) => ShowHoverTextForSlot(slot, args); } } Counter = L_Count.Text; Viewed = L_Viewed.Text; L_Viewed.Text = string.Empty; // invisible for now PopulateComboBoxes(); // Load Data B_Search.Enabled = false; L_Count.Text = "Loading..."; var task = new Task(LoadDatabase); task.ContinueWith(z => { if (!z.IsFaulted) { return; } Invoke((MethodInvoker)(() => L_Count.Text = "Failed.")); if (z.Exception == null) { return; } WinFormsUtil.Error("Loading database failed.", z.Exception.InnerException ?? new Exception(z.Exception.Message)); }); task.Start(); Menu_SearchSettings.DropDown.Closing += (sender, e) => { if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { e.Cancel = true; } }; CB_Format.Items[0] = MsgAny; CenterToParent(); }