using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using SabreTools.Library.Data; using SabreTools.Library.Items; using SabreTools.Library.Tools; #if MONO using System.IO; #else using Alphaleonis.Win32.Filesystem; using FileStream = System.IO.FileStream; using StreamWriter = System.IO.StreamWriter; #endif using NaturalSort; namespace SabreTools.Library.DatFiles { /// /// Represents parsing and writing of an SabreDat XML DAT /// public class SabreDat : DatFile { /// /// Constructor designed for casting a base DatFile /// /// Parent DatFile to copy from public SabreDat(DatFile datFile) { this._datHeader = datFile._datHeader; this._items = datFile._items; this._sortedBy = datFile._sortedBy; this._datStats = datFile._datStats; } /// /// Parse an SabreDat XML DAT and return all found games and roms within /// /// Name of the file to be parsed /// System ID for the DAT /// Source ID for the DAT /// True if full pathnames are to be kept, false otherwise (default) /// True if game names are sanitized, false otherwise (default) /// True if we should remove non-ASCII characters from output, false otherwise (default) /// /// public void Parse( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // All XML-derived DATs share a lot in common so it just calls one implementation (this as DatFile as Logiqx).Parse(filename, sysid, srcid, keep, clean, remUnicode); } /// /// Create and open an output file for writing direct from a dictionary /// /// Name of the file to write to /// True if blank roms should be skipped on output, false otherwise (default) /// True if the DAT was written correctly, false otherwise public bool WriteToFile(string outfile, bool ignoreblanks = false) { try { Globals.Logger.User("Opening file for writing: {0}", outfile); FileStream fs = FileTools.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { Globals.Logger.Warning("File '{0}' could not be created for writing! Please check to see if the file is writable", outfile); return false; } StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(true)); // Write out the header WriteHeader(sw); // Write out each of the machines and roms int depth = 2, last = -1; string lastgame = null; List splitpath = new List(); // Get a properly sorted set of keys List keys = Keys.ToList(); keys.Sort(new NaturalComparer()); foreach (string key in keys) { List roms = this[key]; // Resolve the names in the block roms = DatItem.ResolveNames(roms); for (int index = 0; index < roms.Count; index++) { DatItem rom = roms[index]; // There are apparently times when a null rom can skip by, skip them if (rom.Name == null || rom.MachineName == null) { Globals.Logger.Warning("Null rom found!"); continue; } List newsplit = rom.MachineName.Split('\\').ToList(); // If we have a different game and we're not at the start of the list, output the end of last item if (lastgame != null && lastgame.ToLowerInvariant() != rom.MachineName.ToLowerInvariant()) { depth = WriteEndGame(sw, splitpath, newsplit, depth, out last); } // If we have a new game, output the beginning of the new item if (lastgame == null || lastgame.ToLowerInvariant() != rom.MachineName.ToLowerInvariant()) { depth = WriteStartGame(sw, rom, newsplit, lastgame, depth, last); } // If we have a "null" game (created by DATFromDir or something similar), log it to file if (rom.Type == ItemType.Rom && ((Rom)rom).Size == -1 && ((Rom)rom).CRC == "null") { Globals.Logger.Verbose("Empty folder found: {0}", rom.MachineName); splitpath = newsplit; lastgame = rom.MachineName; continue; } // Now, output the rom data WriteRomData(sw, rom, depth, ignoreblanks); // Set the new data to compare against splitpath = newsplit; lastgame = rom.MachineName; } } // Write the file footer out WriteFooter(sw, depth); Globals.Logger.Verbose("File written!" + Environment.NewLine); sw.Dispose(); fs.Dispose(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } /// /// Write out DAT header using the supplied StreamWriter /// /// StreamWriter to output to /// True if the data was written, false on error private bool WriteHeader(StreamWriter sw) { try { string header = "\n" + "\n\n" + "\n" + "\t
\n" + "\t\t" + HttpUtility.HtmlEncode(Name) + "\n" + "\t\t" + HttpUtility.HtmlEncode(Description) + "\n" + (!String.IsNullOrEmpty(RootDir) ? "\t\t" + HttpUtility.HtmlEncode(RootDir) + "\n" : "") + (!String.IsNullOrEmpty(Category) ? "\t\t" + HttpUtility.HtmlEncode(Category) + "\n" : "") + "\t\t" + HttpUtility.HtmlEncode(Version) + "\n" + (!String.IsNullOrEmpty(Date) ? "\t\t" + HttpUtility.HtmlEncode(Date) + "\n" : "") + "\t\t" + HttpUtility.HtmlEncode(Author) + "\n" + (!String.IsNullOrEmpty(Comment) ? "\t\t" + HttpUtility.HtmlEncode(Comment) + "\n" : "") + (!String.IsNullOrEmpty(Type) || ForcePacking != ForcePacking.None || ForceMerging != ForceMerging.None || ForceNodump != ForceNodump.None ? "\t\t\n" + (!String.IsNullOrEmpty(Type) ? "\t\t\t\n" : "") + (ForcePacking == ForcePacking.Unzip ? "\t\t\t\n" : "") + (ForcePacking == ForcePacking.Zip ? "\t\t\t\n" : "") + (ForceMerging == ForceMerging.Full ? "\t\t\t\n" : "") + (ForceMerging == ForceMerging.Split ? "\t\t\t\n" : "") + (ForceMerging == ForceMerging.Merged ? "\t\t\t\n" : "") + (ForceMerging == ForceMerging.NonMerged ? "\t\t\t\n" : "") + (ForceNodump == ForceNodump.Ignore ? "\t\t\t\n" : "") + (ForceNodump == ForceNodump.Obsolete ? "\t\t\t\n" : "") + (ForceNodump == ForceNodump.Required ? "\t\t\t\n" : "") + "\t\t\n" : "") + "\t
\n" + "\t\n"; // Write the header out sw.Write(header); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } /// /// Write out Game start using the supplied StreamWriter /// /// StreamWriter to output to /// RomData object to be output /// Split path representing the parent game (SabreDAT only) /// The name of the last game to be output /// Current depth to output file at (SabreDAT only) /// Last known depth to cycle back from (SabreDAT only) /// The new depth of the tag private int WriteStartGame(StreamWriter sw, DatItem rom, List newsplit, string lastgame, int depth, int last) { try { // No game should start with a path separator if (rom.MachineName.StartsWith(Path.DirectorySeparatorChar.ToString())) { rom.MachineName = rom.MachineName.Substring(1); } string state = ""; for (int i = (last == -1 ? 0 : last); i < newsplit.Count; i++) { for (int j = 0; j < depth - last + i - (lastgame == null ? 1 : 0); j++) { state += "\t"; } state += "\n"; } depth = depth - (last == -1 ? 0 : last) + newsplit.Count; sw.Write(state); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return depth; } return depth; } /// /// Write out Game start using the supplied StreamWriter /// /// StreamWriter to output to /// Split path representing last kwown parent game (SabreDAT only) /// Split path representing the parent game (SabreDAT only) /// Current depth to output file at (SabreDAT only) /// Last known depth to cycle back from (SabreDAT only) /// The new depth of the tag private int WriteEndGame(StreamWriter sw, List splitpath, List newsplit, int depth, out int last) { last = 0; try { string state = ""; if (splitpath != null) { for (int i = 0; i < newsplit.Count && i < splitpath.Count; i++) { // Always keep track of the last seen item last = i; // If we find a difference, break if (newsplit[i] != splitpath[i]) { break; } } // Now that we have the last known position, take down all open folders for (int i = depth - 1; i > last + 1; i--) { // Print out the number of tabs and the end folder for (int j = 0; j < i; j++) { state += "\t"; } state += "\n"; } // Reset the current depth depth = 2 + last; } sw.Write(state); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return depth; } return depth; } /// /// Write out RomData using the supplied StreamWriter /// /// StreamWriter to output to /// RomData object to be output /// Current depth to output file at (SabreDAT only) /// True if blank roms should be skipped on output, false otherwise (default) /// True if the data was written, false on error private bool WriteRomData(StreamWriter sw, DatItem rom, int depth, bool ignoreblanks = false) { // If we are in ignore blanks mode AND we have a blank (0-size) rom, skip if (ignoreblanks && (rom.Type == ItemType.Rom && (((Rom)rom).Size == 0 || ((Rom)rom).Size == -1))) { return true; } try { string state = "", prefix = ""; for (int i = 0; i < depth; i++) { prefix += "\t"; } state += prefix; switch (rom.Type) { case ItemType.Archive: state += "\n"; break; case ItemType.BiosSet: state += "\n"; break; case ItemType.Disk: state += "\n" + prefix + "\t\n" + prefix + "\t\t\n" + prefix + "\t\n" + prefix + "\n" : "/>\n"); break; case ItemType.Release: state += "\n"; break; case ItemType.Rom: state += "\n" + prefix + "\t\n" + prefix + "\t\t\n" + prefix + "\t\n" + prefix + "\n" : "/>\n"); break; case ItemType.Sample: state += "\n"; break; } sw.Write(state); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } /// /// Write out DAT footer using the supplied StreamWriter /// /// StreamWriter to output to /// Current depth to output file at (SabreDAT only) /// True if the data was written, false on error private bool WriteFooter(StreamWriter sw, int depth) { try { string footer = ""; for (int i = depth - 1; i >= 2; i--) { // Print out the number of tabs and the end folder for (int j = 0; j < i; j++) { footer += "\t"; } footer += "\n"; } footer += "\t\n
\n"; // Write the footer out sw.Write(footer); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } } }