using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
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 StreamReader = System.IO.StreamReader;
using StreamWriter = System.IO.StreamWriter;
#endif
using NaturalSort;
namespace SabreTools.Library.DatFiles
{
///
/// Represents parsing and writing of an SabreDat XML DAT
///
public class SabreDat
{
///
/// Parse an SabreDat XML DAT and return all found games and roms within
///
/// DatFile to populate with the read information
/// 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 static void Parse(
DatFile datFile,
// 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
Logiqx.Parse(datFile, filename, sysid, srcid, keep, clean, remUnicode);
}
///
/// Create and open an output file for writing direct from a dictionary
///
/// DatFile to write out from
/// Name of the file to write to
/// True if games should only be compared on game and file name (default), false if system and source are counted
/// True if DAT statistics should be output on write, false otherwise (default)
/// True if blank roms should be skipped on output, false otherwise (default)
/// True if files should be overwritten (default), false if they should be renamed instead
/// True if the DAT was written correctly, false otherwise
public static bool WriteToFile(DatFile datFile, string outfile, bool norename = true, bool stats = false, bool ignoreblanks = false, bool overwrite = true)
{
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(datFile, 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 = datFile.Keys.ToList();
keys.Sort(new NaturalComparer());
foreach (string key in keys)
{
List roms = datFile[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
///
/// DatFile to write out from
/// StreamWriter to output to
/// True if the data was written, false on error
private static bool WriteHeader(DatFile datFile, StreamWriter sw)
{
try
{
string header = "\n" +
"\n\n" +
"\n" +
"\t\n" +
"\t\t" + HttpUtility.HtmlEncode(datFile.Name) + "\n" +
"\t\t" + HttpUtility.HtmlEncode(datFile.Description) + "\n" +
(!String.IsNullOrEmpty(datFile.RootDir) ? "\t\t" + HttpUtility.HtmlEncode(datFile.RootDir) + "\n" : "") +
(!String.IsNullOrEmpty(datFile.Category) ? "\t\t" + HttpUtility.HtmlEncode(datFile.Category) + "\n" : "") +
"\t\t" + HttpUtility.HtmlEncode(datFile.Version) + "\n" +
(!String.IsNullOrEmpty(datFile.Date) ? "\t\t" + HttpUtility.HtmlEncode(datFile.Date) + "\n" : "") +
"\t\t" + HttpUtility.HtmlEncode(datFile.Author) + "\n" +
(!String.IsNullOrEmpty(datFile.Comment) ? "\t\t" + HttpUtility.HtmlEncode(datFile.Comment) + "\n" : "") +
(!String.IsNullOrEmpty(datFile.Type) || datFile.ForcePacking != ForcePacking.None || datFile.ForceMerging != ForceMerging.None || datFile.ForceNodump != ForceNodump.None ?
"\t\t\n" +
(!String.IsNullOrEmpty(datFile.Type) ? "\t\t\t\n" : "") +
(datFile.ForcePacking == ForcePacking.Unzip ? "\t\t\t\n" : "") +
(datFile.ForcePacking == ForcePacking.Zip ? "\t\t\t\n" : "") +
(datFile.ForceMerging == ForceMerging.Full ? "\t\t\t\n" : "") +
(datFile.ForceMerging == ForceMerging.Split ? "\t\t\t\n" : "") +
(datFile.ForceMerging == ForceMerging.Merged ? "\t\t\t\n" : "") +
(datFile.ForceMerging == ForceMerging.NonMerged ? "\t\t\t\n" : "") +
(datFile.ForceNodump == ForceNodump.Ignore ? "\t\t\t\n" : "") +
(datFile.ForceNodump == ForceNodump.Obsolete ? "\t\t\t\n" : "") +
(datFile.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 static 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 static 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 static 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 static 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;
}
}
}