public static void MakeCommonPic(IWin32Window parent) { string inputFolder = MainForm.PickFolder(parent, "Pick directory to create CommonPic.dat from...", null); if (String.IsNullOrEmpty(inputFolder)) { return; } string outputFileName = MainForm.GetSaveFileName(parent, "Save CommonPic.dat", "CommonPic.dat (*.dat)|commonpic.dat|All Files (*.*)|*.*", Path.GetDirectoryName(inputFolder)); if (String.IsNullOrEmpty(outputFileName)) { return; } DebugLogger.Log("Tools", "Creating Commonpic.dat from {0} to {1}", inputFolder, outputFileName); string[] files = Directory.GetFiles(inputFolder, "*.gtmp"); if (files.Length < 10) { string[] moreFiles = Directory.GetFiles(inputFolder); if (moreFiles.Length > files.Length) { files = moreFiles; } } MergeFiles(new List <string>(files), outputFileName, "Making CommonPic.dat", 0, 0, parent); }
public static void Save( string fileName, Image bg, byte[] fgGMLL, List <IBox> boxes, GTMP.GMFile.GMMetadata metadata, IconImgType fileVersion ) { Debug.Assert(fileVersion != IconImgType.Invalid); DebugLogger.Log("Project", "Saving project to {0}", fileName); GMSerializedProject gmp = new GMSerializedProject(); gmp.foreground = (fgGMLL != null) ? Convert.ToBase64String(fgGMLL) : String.Empty; byte[] imageData = Images.GetBytes(bg, System.Drawing.Imaging.ImageFormat.Png); gmp.background = Convert.ToBase64String(imageData); gmp.fileMetadata = metadata; gmp.gt2BoxVersion = fileVersion; SeparateBoxes(boxes, out gmp.boxes, out gmp.iconBoxes); string projectFile = Json.Serialize(gmp); #if DEBUG File.WriteAllText(@"T:\gmpproj.txt", projectFile); #endif MemoryStream compProj = Compress.ZipCompressString(projectFile); File.WriteAllBytes(fileName, compProj.ToArray()); if (DebugLogger.DoDebugActions()) { string projectCopy = Globals.MakeDebugSaveName(true, Path.GetFileName(fileName)); File.WriteAllBytes(projectCopy, compProj.ToArray()); } }
static internal void ReportUnhandledException(Exception e, string titleLine) { string tempPath = Path.Combine(Path.GetTempPath(), "gmcreatorerror.txt"); StringBuilder sb = new StringBuilder(2048); sb.AppendLine(titleLine); sb.AppendLine("[email protected] attaching a screen cap of this message or"); sb.AppendFormat("the file at \"{0}\"", tempPath); sb.AppendLine(); sb.AppendLine("Exception Message:"); sb.AppendLine(e.Message); sb.AppendLine(); sb.AppendLine("Stack Trace:"); sb.AppendLine(e.StackTrace); string message = sb.ToString(); DebugLogger.Log("Program", "Caught top level exception:\n" + message); using (StreamWriter sw = new StreamWriter(tempPath, false, Encoding.UTF8)) { sw.WriteLine(message); sw.WriteLine("Debug Log:"); sw.WriteLine(DebugLogger.GetContents()); } MessageBox.Show(message, "GMCreator", MessageBoxButtons.OK, MessageBoxIcon.Error); }
internal static void DeleteFileLoop(string fileName) { // this should be necessary, but anti-virus on demand scanning // is a thing, and they sometimes don't let go of the file for a little while // and trying to delete causes an exception because its still 'in use', // even though we've stopped using it. // so we have to loop on it for (int i = 0; i < 3; ++i) { try { File.Delete(fileName); break; } catch (FileNotFoundException) { break; } catch (Exception e) { DebugLogger.Log("Project", "Caught exception {0} deleting {1}", e.Message, fileName); System.Threading.Thread.Sleep(300); } } }
private void ThrowInvalidState(string reason) { string message = String.Format("Box '{0}' has an invalid state: {1}", Name, reason); DebugLogger.Log("Box", "Throwing invalid box exception: " + message); throw new InvalidBoxStateException(message, this); }
public static DialogResult DisplayMsgBox(MessageBoxButtons buttons, MessageBoxIcon icon, string messageFmt, params object[] p) { string message = String.Format(messageFmt, p); DebugLogger.Log("Main", message); return(MessageBox.Show(message, "GMCreator", buttons, icon)); }
private void BGImageLoad(string fileName, Images.ImageLoadResult info) { Image origBG = canvasBgImage; DebugLogger.Log("Main", "Loaded BG of type {0} from {1}", info.type.ToString(), fileName); if (DebugLogger.DoDebugActions()) { string newBGName = Globals.MakeDebugSaveName(true, Path.GetFileName(fileName)); File.Copy(fileName, newBGName, true); string newConvertedBG = Globals.MakeDebugSaveName(false, "newconvertedbg.png"); info.image.Save(newConvertedBG, System.Drawing.Imaging.ImageFormat.Png); } layerState.On(LayerStateManager.Layers.Background); canvasBgImage = info.image; RecompositeCanvasImage(); if (origBG != null) { if (DebugLogger.DoDebugActions()) { string previousBG = Globals.MakeDebugSaveName(false, "previousbg.png"); origBG.Save(previousBG, System.Drawing.Imaging.ImageFormat.Png); } origBG.Dispose(); } }
private static void MergeThread(object o) { #if TEST_AS_FRENCH Tools.SetThreadToFrench(); #endif MergeThreadParams mtp = (MergeThreadParams)o; WaitDlg dlg = mtp.dlg; List <string> inFiles = mtp.files; string fileDir = Path.GetDirectoryName(inFiles[0]); inFiles.Sort(new LogicalComparer(fileDir.Length)); try { Stopwatch sw = new Stopwatch(); using (Archiver archive = new Archiver(mtp.outFile, mtp.fileAlignment)) { sw.Start(); dlg.UpdateStatus("Adding {0} files", inFiles.Count); archive.AddFiles(inFiles, mtp.compression); dlg.UpdateStatus("Waiting for completion"); archive.Finish(); sw.Stop(); } dlg.AllowClose("Completed in {0:F2} seconds", sw.Elapsed.TotalSeconds); } catch (Exception e) { string exception = String.Format("Failed with exception {0} during merge of {1} files", e.Message, inFiles.Count); dlg.AllowClose(exception); DebugLogger.Log("Merge", exception + "{0}{1}", Environment.NewLine, e.StackTrace); } GC.Collect(); }
public static void MakeGTMenuDat(IWin32Window parent) { string inputFolder = MainForm.PickFolder(parent, "Pick directory to create GTMenuDat.dat from...", null); if (String.IsNullOrEmpty(inputFolder)) { return; } string outputFileName = MainForm.GetSaveFileName(parent, "Save GTMenuDat.dat", "GTMenuDat.dat (*.dat)|gtmenudat.dat|All Files (*.*)|*.*", Path.GetDirectoryName(inputFolder)); if (String.IsNullOrEmpty(outputFileName)) { return; } DebugLogger.Log("Tools", "Creating GTMenuDat.dat from {0} to {1}", inputFolder, outputFileName); string[] files = Directory.GetFiles(inputFolder, "*.gm"); if (files.Length < 10) { string[] moreFiles = Directory.GetFiles(inputFolder); if (moreFiles.Length > files.Length) { files = moreFiles; } } MergeFiles(new List <string>(files), outputFileName, "Making GTMenuDat.dat", Globals.App.CompressionLevel, 4, parent); }
public static bool ConvertImageTo(string inputFile, string outputFile, ConvertType type) { string converterExe = Path.Combine(Application.StartupPath, "GT2ImageConverter.exe"); if (!File.Exists(converterExe)) { MainForm.DisplayMsgBox(MessageBoxButtons.OK, MessageBoxIcon.Error, "Converter tool {0} wasn't found!", converterExe); return(false); } ProcessStartInfo psi = new ProcessStartInfo(converterExe, String.Format("\"{0}\" \"{1}\" {2}", inputFile, outputFile, type.ToString())); psi.RedirectStandardOutput = true; psi.CreateNoWindow = true; psi.UseShellExecute = false; bool success = false; DebugLogger.Log("Tools", "Converting to {0} with command line {1}", type.ToString(), psi.Arguments); try { using (Process p = Process.Start(psi)) { string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if (!(success = (p.ExitCode == 0))) { MainForm.DisplayMsgBox(MessageBoxButtons.OK, MessageBoxIcon.Error, "Conversion failed. GT2ImagePConverter output was:{0}{1}", Environment.NewLine, output); } } } catch (Exception e) { MainForm.DisplayMsgBox(MessageBoxButtons.OK, MessageBoxIcon.Error, "Caught exception {0} trying to run GT2ImageConverter", e.Message); } return(success); }
private void toggleBoxContentsToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem toggle = (ToolStripMenuItem)sender; LayerStateManager.Layers state = layerState.Toggle(LayerStateManager.Layers.BoxContents); Globals.App.ShowInnerContent = ((state & LayerStateManager.Layers.BoxContents) != 0); DebugLogger.Log("Main", "Global inner content toggle to {0}", Globals.App.ShowInnerContent); RedrawCanvas(); }
internal static void Refresh(IconImgData imageData, IconImgType version, string directory) { Debug.Assert(version != IconImgType.Invalid); DebugLogger.Log("Hardcoded", "Refreshing IconImages of version {0}", version); int stride = imageData.ByteStride; IconImgFile iconFileInfo = imageData.Versions[(int)version]; string iconImgFile = Path.Combine(directory, version.ToString() + "Icon.dat"); byte[] fileData = File.ReadAllBytes(iconImgFile); IconImgEntry[] imageEntries = iconFileInfo.Entries; int id = 0; images = new List <IconImgEntry>(); foreach (IconImgEntry entry in imageEntries) { Size imageSize = entry.ImageSize; Bitmap bm = new Bitmap(imageSize.Width, imageSize.Height, System.Drawing.Imaging.PixelFormat.Format4bppIndexed); System.Drawing.Imaging.ColorPalette imgPalette = bm.Palette; Color[] entries = imgPalette.Entries; for (int i = 0, colourOffset = entry.PaletteLocation; i < 16; ++i, colourOffset += sizeof(ushort)) { ushort colour = BitConverter.ToUInt16(fileData, colourOffset); entries[i] = ((colour & 0x7fff) == 0) ? Color.Transparent : MakeColorFromBGR555(colour); } bm.Palette = imgPalette; System.Drawing.Imaging.BitmapData bmData = bm.LockBits(new Rectangle(Point.Empty, bm.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format4bppIndexed); // These are 4bpp, so the 1 X byte = 2 X pixels, so we half it int lineBytes = imageSize.Width / 2; int height = imageSize.Height; int lockDataStride = bmData.Stride; byte[] imageBuffer = new byte[lockDataStride * height]; int fileIter = (entry.ImageLocation.Y * stride) + (entry.ImageLocation.X / 2); int imageBufferIter = 0; // the image buffer in the file is Big endian, like this (pixel numbers within each byte) // [2, 1], [4, 3], [6, 5] // we need it in little endian so this copies the data while swizzling it into // [1, 2], [3, 4], [5, 6] // for (int y = 0; y < height; ++y, fileIter += stride, imageBufferIter += lockDataStride) { Buffer.BlockCopy(fileData, fileIter, imageBuffer, imageBufferIter, lineBytes); for (int x = 0; x < lineBytes; ++x) { byte pixels = imageBuffer[imageBufferIter + x]; byte swizzedPixels = (byte)(((pixels << 4) & 0xF0) | (pixels >> 4)); imageBuffer[imageBufferIter + x] = swizzedPixels; } } // blit it to the real bitmap data System.Runtime.InteropServices.Marshal.Copy(imageBuffer, 0, bmData.Scan0, imageBuffer.Length); bm.UnlockBits(bmData); entry.Image = bm; entry.Id = id++; images.Add(entry); } }
void RecompressGMFiles(object o) { RecompressThreadArgs rta = (RecompressThreadArgs)o; string inDir = rta.inDir; string[] allFiles = Directory.GetFiles(inDir); int numFiles = allFiles.Length; WaitDlg dlg = rta.dlg; string pngDirectory = Path.Combine(inDir, "bmp"); dlg.UpdateStatus("Recompressing {0} files", numFiles); string outDir = rta.outDir; string gmllFile = @"T:\out.gmll"; for (int i = 0; i < numFiles; ++i) { Box.ResetIndexCount(); string currentFile = allFiles[i]; byte[] gmFileData; MemoryStream decompGM; using (FileStream fs = File.OpenRead(currentFile)) { decompGM = Compress.GZipDecompress(fs); gmFileData = decompGM.ToArray(); } string curFile = Path.GetFileName(currentFile); string pngFile = Path.Combine(pngDirectory, curFile + ".bmp"); GTMP.GMFile.GMFileInfo fi = GTMP.GMFile.Parse(decompGM); List <IBox> boxes = ConvertGMFileBoxes(fi.Boxes); if (!Tools.ConvertImageTo(pngFile, gmllFile, Tools.ConvertType.GM)) { dlg.UpdateStatus(String.Format("Couldn't convert {0} to GT2 foreground, skipping", pngFile)); continue; } try { byte[] gmllData = Images.LoadGMLLData(gmllFile); string newFileName = Path.Combine(outDir, curFile); GMProject.ExportGM(newFileName, boxes, fi.Metadata, gmllData); } catch (InvalidBoxStateException ibse) { DebugLogger.Log("Debug", "Exception was from {0}", currentFile); dlg.UpdateStatus("Caught invalid box exception {0} for {1} in file {2}", ibse.Message, ibse.InvalidBox.Name, currentFile); File.Delete(gmllFile); } if ((i != 0) && ((i % 100) == 0)) { dlg.UpdateStatus(String.Format("Tested {0} files", i)); } } dlg.AllowClose("All done"); }
private void InsertBoxMenuItemClick(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; DebugLogger.Log("Main", "Adding icon {0} by menu", item.Text); IconImgBox imb = new IconImgBox(item.Text.Replace("&", String.Empty), (int)item.Tag); allBoxes.Add(imb); imb.DisplayChanged += new BoxDisplayChange(BoxInvalidation); SetUnsavedChanges(); RedrawCanvas(imb.Bounds); }
static public void Refresh(string appDir) { DebugLogger.Log("Hardcoded", "Refreshing hardcoded data"); string dataDir = Path.Combine(appDir, "data") + Path.DirectorySeparatorChar; string dataFile = dataDir + "hardcoded.json"; string fileText = File.ReadAllText(dataFile); Measurements m = JsonConvert.DeserializeObject <Measurements>(fileText); if (UpgradeHPTextColour != null) { DebugLogger.Log("Hardcoded", "Disposing previously loaded data"); UsedCarListMeasurements.TextFont.Dispose(); GarageCarListMeasurements.TextFont.Dispose(); UpgradeHPTextColour.Dispose(); DealershipPriceColour.Dispose(); StandardFontColour.Dispose(); PartFontColour.Dispose(); EquippedPartFontColour.Dispose(); StandardFont.Dispose(); BigFont.Dispose(); PartFont.Dispose(); SmallLicenseGraphic.Dispose(); LargeLicenseGraphic.Dispose(); CarPicture.Dispose(); CarLogo.Dispose(); LicenseTrophyGraphic.Dispose(); DrivetrainGraphic.Dispose(); IconImages.Dispose(); } UsedCarListMeasurements = m.usedCarList; GarageCarListMeasurements = m.garageCarList; EquippedPartsListMeasurements = m.installedCarPartsList; UpgradeHPTextColour = new SolidBrush(m.upgradeHPColour); DealershipPriceColour = new SolidBrush(m.dealershipPriceColour); StandardFontColour = new SolidBrush(m.standardFontColour); PartFontColour = new SolidBrush(m.partFontColour); EquippedPartFontColour = new SolidBrush(m.installedCarPartsList.TextColour); ColourSwatchSize = m.colourSwatchSize; StandardFont = m.standardFont; BigFont = m.bigFont; PartFont = m.partNameFont; DumpFontInfo("Standard Font", StandardFont); DumpFontInfo("Big Font", BigFont); DumpFontInfo("Part Font", PartFont); DumpFontInfo("Installed Part Font", m.installedCarPartsList.TextFont); SmallLicenseGraphic = new Bitmap(dataDir + "smalllicense.png"); LargeLicenseGraphic = new Bitmap(dataDir + "biglicense.png"); CarPicture = new Bitmap(dataDir + "carpicture.png"); CarLogo = MakeBlackTransparentAndDispose(new Bitmap(dataDir + "carlogo.png")); LicenseTrophyGraphic = MakeBlackTransparentAndDispose(new Bitmap(dataDir + "licensetrophy.png")); DrivetrainGraphic = MakeBlackTransparentAndDispose(new Bitmap(dataDir + "drivetrain.png")); IconImages.Refresh(m.iconImageData, Globals.App.GT2Version, dataDir); }
private List <IBox> ConvertGMFileBoxes(List <GTMP.GMFile.DrawRectInfo> boxes) { List <IBox> newBoxes = new List <IBox>(boxes.Count); Dictionary <string, int> iconImages = Hardcoded.IconImages.GetNamesAndIndexes(); foreach (GTMP.GMFile.DrawRectInfo dri in boxes) { IBox toAdd; if (dri.infoBox != null) { GTMP.GMFile.InfoBox infoBox = dri.infoBox; Box newBox = new Box(dri.rect); newBox.BehaviourAttributes = infoBox.attributes; newBox.LinkToScreen = infoBox.GetScreenLink(); newBox.PrizeMoneyPosition = infoBox.GetSpecificPlaceNumber(); newBox.RaceOrWheelOrCarId = infoBox.GetWheelRaceOrCarIdName(); newBox.Contents = infoBox.contents; newBox.QueryAttributes = infoBox.queryType; newBox.ArrowEnabler = infoBox.GetArrowEnablingLicense(); toAdd = newBox; } else { Debug.Assert(dri.iconImgBox != null); GTMP.GMFile.IconImageBox imgBox = dri.iconImgBox; IconImgEntry foundIcon = Hardcoded.IconImages.FindFromData(imgBox.imgMapX, imgBox.imgMapY); if (foundIcon != null) { IconImgBox newBox = new IconImgBox(foundIcon); newBox.Location = new Point(imgBox.screenX, imgBox.screenY); toAdd = newBox; } else { DebugLogger.Log("GMFileLoader", "Couldn't find iconimg with location {0}x{1}, not adding", imgBox.imgMapX, imgBox.imgMapY); DisplayMsgBox( MessageBoxButtons.OK, MessageBoxIcon.Warning, "Loading the foreground file has stopped because it contained an unknown icon image at image map location {0}. " + "Did you forget to change the GT2 Version in Settings before loading?", new Point(imgBox.imgMapX, imgBox.imgMapY) ); break; } } toAdd.DisplayChanged += new BoxDisplayChange(BoxInvalidation); newBoxes.Add(toAdd); } return(newBoxes); }
private void clearAllToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult res = MessageBox.Show("Clear all boxes, are you sure?", "GM Creator", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (res != DialogResult.Yes) { return; } DebugLogger.Log("Main", "Clearing all boxes"); allBoxes.Clear(); Box.ResetIndexCount(); RedrawCanvas(); SetUnsavedChanges(); }
static public void Save(string fileDir, Rectangle windowBounds) { string filePath = Path.Combine(fileDir, SETTINGS_FILE); try { App.WindowLocation = windowBounds; string json = Json.Serialize(App); File.WriteAllText(filePath, json); } catch (Exception e) { DebugLogger.Log("Settings", "Caught exception {0} saving settings file to {1}", e.Message, filePath); } }
static public void Load(string fileDir) { string filePath = Path.Combine(fileDir, SETTINGS_FILE); try { string json = File.ReadAllText(filePath); App = Json.Parse <AppSettings>(json); } catch (Exception e) { DebugLogger.Log("Settings", "Caught exception {0} loading settings file from {1}", e.Message, filePath); App = new AppSettings(); } App.RefreshNonSerialised(); }
void CheckGMFileValidity(object o) { ValidityThreadArgs vta = (ValidityThreadArgs)o; string dir = vta.dir; string[] allFiles = Directory.GetFiles(dir); int numFiles = allFiles.Length; WaitDlg dlg = vta.dlg; dlg.UpdateStatus("Checking {0} files", numFiles); int exceptions = 0; for (int i = 0; i < numFiles; ++i) { Box.ResetIndexCount(); string currentFile = allFiles[i]; GTMP.GMFile.GMFileInfo fi = GTMP.GMFile.Parse(currentFile); List <IBox> boxes = ConvertGMFileBoxes(fi.Boxes); try { MemoryStream ms = new MemoryStream(boxes.Count * 0x4c); using (BinaryWriter bw = new BinaryWriter(ms)) { foreach (IBox b in boxes) { b.Serialize(bw); } } } catch (InvalidBoxStateException ibse) { if (++exceptions == 50) { break; } DebugLogger.Log("Debug", "Exception was from {0}", currentFile); dlg.UpdateStatus("Caught invalid box exception {0} for {1} in file {2}", ibse.Message, ibse.InvalidBox.Name, currentFile); } if ((i != 0) && ((i % 10) == 0)) { dlg.UpdateStatus(String.Format("Tested {0} files", i)); } } dlg.AllowClose("All checked"); }
static internal byte[] LoadGMLLData(string gmllFileName) { byte[] gmFileData = null; try { using (FileStream gmStream = File.OpenRead(gmllFileName)) { MemoryStream decompGMStream = Compress.DecompressStream(gmStream); gmFileData = TrimToGMLLData(decompGMStream.ToArray()); } } catch (Exception e) { DebugLogger.Log("Images", "Caught exception trying to load GMLL data - {0}", e.Message); } return(gmFileData); }
public static void ConvertImageToGTMP(IWin32Window parent) { string inputFileName = MainForm.GetOpenFileName(parent, "Open Image To Convert", "Image Files (*.bmp, *.png, *.jpg)|*.bmp;*.png;*.jpg", null); if (String.IsNullOrEmpty(inputFileName)) { return; } string outputFileName = MainForm.GetSaveFileName(parent, "Save Converted Image As...", "GT2 Background (*.gtmp)|*.gtmp|All Files (*.*)|*.*", Path.GetDirectoryName(inputFileName)); if (String.IsNullOrEmpty(outputFileName)) { return; } DebugLogger.Log("Tools", "Converting {0} to GTMP {1}", inputFileName, outputFileName); ConvertImageTo(inputFileName, outputFileName, ConvertType.GTMP); }
private void canvas_DragDrop(object sender, DragEventArgs e) { IDataObject obj = e.Data; if (obj.GetDataPresent(DataFormats.FileDrop, true)) { string[] files = (string[])obj.GetData(DataFormats.FileDrop, true); if (files.Length >= 1) { string loadedFile = files[0]; loadedFile = System.IO.Path.GetFullPath(loadedFile); DebugLogger.Log("Main", "Loading file {0} by drag and drop", loadedFile); LoadAndDisplaySelectedFile(loadedFile, new PostImageLoad(FGImageLoad)); } } else { e.Effect = DragDropEffects.None; } }
public static void SplitCommonPic(IWin32Window parent) { string inputFileName = MainForm.GetOpenFileName(parent, "Open CommonPic.dat", "CommonPic.dat (*.dat)|commonpic*.*|All Files (*.*)|*.*", null); if (String.IsNullOrEmpty(inputFileName)) { return; } string outputFolder = MainForm.PickFolder(parent, "Pick directory to split to...", Path.GetDirectoryName(inputFileName)); if (String.IsNullOrEmpty(outputFolder)) { return; } DebugLogger.Log("Tools", "Splitting and decomping CommonPic {0} to {1}", inputFileName, outputFolder); FileSplitter fs = () => { GTMP.GTMPFile.ExplodeCommonPic(inputFileName, outputFolder, GTMP.GTMPFile.SplitCommonPicArgs.OutputPngPicture); }; SplitFiles(fs, "Splitting " + Path.GetFileName(inputFileName)); }
private void LoadAndDisplaySelectedFile(string fileName, PostImageLoad afterLoadFn) { DebugLogger.Log("Main", "Loading {0} with afterloader {1}...", fileName, afterLoadFn.Method.Name); try { Images.ImageLoadResult imageload = Images.LoadFile(fileName); DebugLogger.Log("Main", "...Image was a {0}", imageload.type.ToString()); Bitmap image = imageload.image; if ((image.Width != CANVAS_WIDTH) || (image.Height != CANVAS_HEIGHT)) { DisplayMsgBox(MessageBoxButtons.OK, MessageBoxIcon.Warning, "'{0}' was loaded, but it's the wrong size {1}. Should be {2}x{3}", Path.GetFileName(fileName), image.Size, CANVAS_WIDTH, CANVAS_HEIGHT); image.Dispose(); return; } afterLoadFn(fileName, imageload); } catch (Exception e) { DisplayMsgBox(MessageBoxButtons.OK, MessageBoxIcon.Error, "Failed to load {0} because of error {1}", fileName, e.Message); } }
public static void SplitGTMenuDat(IWin32Window parent) { string inputFileName = MainForm.GetOpenFileName(parent, "Open GTMenuDat.dat", "GTMenuDat.dat (*.dat)|gtmenudat*.*|All Files (*.*)|*.*", null); if (String.IsNullOrEmpty(inputFileName)) { return; } string outputFolder = MainForm.PickFolder(parent, "Pick directory to split to...", Path.GetDirectoryName(inputFileName)); if (String.IsNullOrEmpty(outputFolder)) { return; } DebugLogger.Log("Tools", "Splitting and decomping GTMenuDat {0} to {1}", inputFileName, outputFolder); FileSplitter fs = () => { const GTMP.GMFile.SplitGTMenuFlags flags = GTMP.GMFile.SplitGTMenuFlags.OutputPngPicture; GTMP.GMFile.SplitGTMenuDat(inputFileName, outputFolder, flags); }; SplitFiles(fs, "Splitting " + Path.GetFileName(inputFileName)); }
private void canvas_MouseClick(object sender, MouseEventArgs e) { switch (mouseState) { case MouseState.Normal: { if (e.Button != MouseButtons.Right) { anchorClick = e.Location; mouseState = MouseState.DrawSizingRect; DebugLogger.Log("Main", "Started drawing rectangle at {0}", anchorClick); } } break; case MouseState.DrawSizingRect: { // right click cancels any drawing if (e.Button != MouseButtons.Right) { layerState.On(LayerStateManager.Layers.Boxes); Box b = allBoxes.AddNewBox(MakeGoodRectangle(anchorClick, e.Location)); b.DisplayChanged += new BoxDisplayChange(BoxInvalidation); ChangeSelectedBox(b); SetUnsavedChanges(); DebugLogger.Log("Main", "Drew rectangle at {0}", b.Location); } else { UpdateDirtyRect(e.Location); DebugLogger.Log("Main", "Reset rectangle drawing"); } ResetToNormalCanvas(); } break; } }
private static void SplitThread(object o) { #if TEST_AS_FRENCH Tools.SetThreadToFrench(); #endif SplitThreadParams stp = (SplitThreadParams)o; WaitDlg dlg = stp.dlg; Stopwatch sw = new Stopwatch(); sw.Start(); try { stp.splitter(); sw.Stop(); dlg.AllowClose("Completed in {0:F2} seconds", sw.Elapsed.TotalSeconds); } catch (Exception e) { string exception = String.Format("Failed with exception {0} during split ", e.Message); dlg.AllowClose(exception); DebugLogger.Log("Split", exception + "{0}{1}", Environment.NewLine, e.StackTrace); } sw.Stop(); GC.Collect(); }
static internal byte[] TrimToGMLLData(byte[] gmFile) { byte[] retData = null; try { int gmllOffset = FindGMLLOffset(gmFile); if (gmllOffset > 0) { int dataLen = gmFile.Length - gmllOffset; Buffer.BlockCopy(gmFile, gmllOffset, gmFile, 0, dataLen); Array.Resize(ref gmFile, dataLen); retData = gmFile; } else if (gmllOffset == 0) { retData = gmFile; } } catch (Exception e) { DebugLogger.Log("Images", "Caught exception trying to trim input to GMLL data - {0}", e.Message); } return(retData); }
private void FGImageLoad(string fileName, Images.ImageLoadResult info) { if (DebugLogger.DoDebugActions()) { string fgImageName = Globals.MakeDebugSaveName(true, Path.GetFileName(fileName)); File.Copy(fileName, fgImageName, true); } if (info.type != Images.ImageType.GM) { byte[] newForegroundData; if (info.type != Images.ImageType.GMLL) { newForegroundData = Tools.CheckConvertImageTo(info.image, Tools.ConvertType.GM); if (newForegroundData == null) { info.image.Dispose(); return; } } else { newForegroundData = File.ReadAllBytes(fileName); } DebugLogger.Log("Main", "Got {0} bytes of non-GM GMLL data", newForegroundData.Length); if (DebugLogger.DoDebugActions()) { string nonGMDataFile = Globals.MakeDebugSaveName(false, "{0}nongm-fg.gmll", Path.GetFileNameWithoutExtension(fileName)); File.WriteAllBytes(nonGMDataFile, newForegroundData); } layerState.On(LayerStateManager.Layers.Foreground); ReplaceForegroundImage(newForegroundData, info.image); } else // (info.type == Images.ImageType.GM) { // This is a hack since CloseCurrentFile() resets everything // and disposes the images, but when we're reloading the foreground // only, we should preserve the background, so lets do this // rather than bool-ing it up just for this one case Image bgBackup = null; if (canvasBgImage != null) { bgBackup = (Image)canvasBgImage.Clone(); } if (!CloseCurrentFile()) { // didn't need it anyway if (bgBackup != null) { bgBackup.Dispose(); } info.image.Dispose(); return; } canvasBgImage = bgBackup; layerState.On(LayerStateManager.Layers.Foreground); byte[] gmllData = Images.LoadGMLLData(fileName); ReplaceForegroundImage(gmllData, info.image); GTMP.GMFile.GMFileInfo fileInf = info.gmInfo; DebugLogger.Log("Main", "Got {0} bytes of GM-GMLL data from {1}, file had {2} boxes", gmllData.Length, fileName, fileInf.Boxes == null ? -1 : fileInf.Boxes.Count); if (fileInf.Boxes != null) { boxList.BeginUpdate(); try { allBoxes.Clear(); List <IBox> boxes = ConvertGMFileBoxes(fileInf.Boxes); allBoxes.Load(boxes); } finally { boxList.EndUpdate(); } } metadataPropertyList.SelectedObject = fileInf.Metadata; } SetTitleFileName(fileName); }