using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.Tools; using NaturalSort; namespace SabreTools.Library.DatFiles { /// /// Represents parsing and writing of a DosCenter DAT /// internal class DosCenter : DatFile { /// /// Constructor designed for casting a base DatFile /// /// Parent DatFile to copy from public DosCenter(DatFile datFile) : base(datFile, cloneHeader: false) { } /// /// Parse a DosCenter 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) /// TODO: Pull parsing into this file instead of relying on CMP public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // ClrMamePro and DosCenter parsing are identical so it just calls one implementation new ClrMamePro(this).ParseFile(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 override bool WriteToFile(string outfile, bool ignoreblanks = false) { try { Globals.Logger.User($"Opening file for writing: {outfile}"); FileStream fs = Utilities.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false)); // Write out the header WriteHeader(sw); // Write out each of the machines and roms string lastgame = null; // Get a properly sorted set of keys List keys = Keys; 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()) WriteEndGame(sw, rom); // If we have a new game, output the beginning of the new item if (lastgame == null || lastgame.ToLowerInvariant() != rom.MachineName.ToLowerInvariant()) WriteStartGame(sw, rom); // If we have a "null" game (created by DATFromDir or something similar), log it to file if (rom.ItemType == ItemType.Rom && ((Rom)rom).Size == -1 && ((Rom)rom).CRC == "null") { Globals.Logger.Verbose($"Empty folder found: {rom.MachineName}"); rom.Name = (rom.Name == "null" ? "-" : rom.Name); ((Rom)rom).Size = Constants.SizeZero; ((Rom)rom).CRC = ((Rom)rom).CRC == "null" ? Constants.CRCZero : null; ((Rom)rom).MD5 = ((Rom)rom).MD5 == "null" ? Constants.MD5Zero : null; ((Rom)rom).RIPEMD160 = ((Rom)rom).RIPEMD160 == "null" ? Constants.RIPEMD160Zero : null; ((Rom)rom).SHA1 = ((Rom)rom).SHA1 == "null" ? Constants.SHA1Zero : null; ((Rom)rom).SHA256 = ((Rom)rom).SHA256 == "null" ? Constants.SHA256Zero : null; ((Rom)rom).SHA384 = ((Rom)rom).SHA384 == "null" ? Constants.SHA384Zero : null; ((Rom)rom).SHA512 = ((Rom)rom).SHA512 == "null" ? Constants.SHA512Zero : null; } // Now, output the rom data WriteDatItem(sw, rom, ignoreblanks); // Set the new data to compare against lastgame = rom.MachineName; } } // Write the file footer out WriteFooter(sw); 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 = "DOSCenter (\n"; header += $"\tName: {Name}\n"; header += $"\tDescription: {Description}\n"; header += $"\tVersion: {Version}\n"; header += $"\tDate: {Date}\n"; header += $"\tAuthor: {Author}\n"; header += $"\tHomepage: {Homepage}\n"; header += $"\tComment: {Comment}\n"; header += ")\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 /// DatItem object to be output /// True if the data was written, false on error private bool WriteStartGame(StreamWriter sw, DatItem datItem) { try { // No game should start with a path separator datItem.MachineName = datItem.MachineName.TrimStart(Path.DirectorySeparatorChar); // Build the state based on excluded fields string state = $"game (\n\tname \"{datItem.GetField(Field.MachineName, ExcludeFields)}.zip\n"; sw.Write(state); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } /// /// Write out Game end using the supplied StreamWriter /// /// StreamWriter to output to /// DatItem object to be output /// True if the data was written, false on error private bool WriteEndGame(StreamWriter sw, DatItem datItem) { try { string state = string.Empty; // Build the state based on excluded fields if (!string.IsNullOrWhiteSpace(datItem.GetField(Field.SampleOf, ExcludeFields))) state += $"\tsampleof \"{datItem.SampleOf}\"\n"; state += ")\n"; sw.Write(state); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } /// /// Write out DatItem using the supplied StreamWriter /// /// StreamWriter to output to /// DatItem object to be output /// True if blank roms should be skipped on output, false otherwise (default) /// True if the data was written, false on error private bool WriteDatItem(StreamWriter sw, DatItem datItem, bool ignoreblanks = false) { // If we are in ignore blanks mode AND we have a blank (0-size) rom, skip if (ignoreblanks && (datItem.ItemType == ItemType.Rom && ((datItem as Rom).Size == 0 || (datItem as Rom).Size == -1))) return true; try { string state = string.Empty; // Pre-process the item name ProcessItemName(datItem, true); // Build the state based on excluded fields switch (datItem.ItemType) { case ItemType.Archive: case ItemType.BiosSet: case ItemType.Disk: case ItemType.Release: case ItemType.Sample: // We don't output these at all for DosCenter break; case ItemType.Rom: var rom = datItem as Rom; state += $"\file ( name \"{datItem.GetField(Field.Name, ExcludeFields)}\""; if (!ExcludeFields[(int)Field.Size] && rom.Size != -1) state += $" size \"{rom.Size}\""; if (!string.IsNullOrWhiteSpace(datItem.GetField(Field.Date, ExcludeFields))) state += $" date \"{rom.Date}\""; if (!string.IsNullOrWhiteSpace(datItem.GetField(Field.CRC, ExcludeFields))) state += $" crc \"{rom.CRC.ToLowerInvariant()}\""; 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 /// True if the data was written, false on error private bool WriteFooter(StreamWriter sw) { try { string footer = ")\n"; // Write the footer out sw.Write(footer); sw.Flush(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return false; } return true; } } }