Files
SabreTools/SabreTools.DatFiles/Formats/SabreXML.cs

362 lines
12 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
2020-12-08 00:13:22 -08:00
using System.Xml.Schema;
2020-09-07 22:21:02 -07:00
using System.Xml.Serialization;
2020-12-08 15:15:41 -08:00
using SabreTools.DatItems;
namespace SabreTools.DatFiles.Formats
{
2019-01-11 13:43:15 -08:00
/// <summary>
/// Represents parsing and writing of a SabreDAT XML
2019-01-11 13:43:15 -08:00
/// </summary>
internal class SabreXML : DatFile
2019-01-11 13:43:15 -08:00
{
/// <summary>
/// Constructor designed for casting a base DatFile
/// </summary>
/// <param name="datFile">Parent DatFile to copy from</param>
public SabreXML(DatFile datFile)
: base(datFile)
2019-01-11 13:43:15 -08:00
{
}
/// <inheritdoc/>
2020-12-10 13:30:08 -08:00
public override void ParseFile(string filename, int indexId, bool keep, bool throwOnError = false)
2019-01-11 13:43:15 -08:00
{
// Prepare all internal variables
2020-12-08 00:13:22 -08:00
XmlReader xtr = XmlReader.Create(filename, new XmlReaderSettings
{
CheckCharacters = false,
DtdProcessing = DtdProcessing.Ignore,
IgnoreComments = true,
IgnoreWhitespace = true,
ValidationFlags = XmlSchemaValidationFlags.None,
ValidationType = ValidationType.None,
});
2019-01-11 13:43:15 -08:00
// If we got a null reader, just return
if (xtr == null)
return;
// Otherwise, read the file to the end
try
{
xtr.MoveToContent();
while (!xtr.EOF)
{
// We only want elements
if (xtr.NodeType != XmlNodeType.Element)
{
xtr.Read();
continue;
}
switch (xtr.Name)
{
case "header":
2020-09-07 22:21:02 -07:00
XmlSerializer xs = new XmlSerializer(typeof(DatHeader));
DatHeader header = xs.Deserialize(xtr.ReadSubtree()) as DatHeader;
Header.ConditionalCopy(header);
2019-01-11 13:43:15 -08:00
xtr.Skip();
break;
2019-01-11 13:43:15 -08:00
case "directory":
2020-09-07 22:21:02 -07:00
ReadDirectory(xtr.ReadSubtree(), filename, indexId);
2019-01-11 13:43:15 -08:00
// Skip the directory node now that we've processed it
xtr.Read();
break;
default:
xtr.Read();
break;
}
}
}
catch (Exception ex)
{
logger.Warning(ex, $"Exception found while parsing '{filename}'");
if (throwOnError)
{
xtr.Dispose();
throw ex;
}
2019-01-11 13:43:15 -08:00
// For XML errors, just skip the affected node
xtr?.Read();
}
xtr.Dispose();
}
/// <summary>
/// Read directory information
/// </summary>
2020-09-07 22:21:02 -07:00
/// <param name="xtr">XmlReader to use to parse the header</param>
2019-01-11 13:43:15 -08:00
/// <param name="filename">Name of the file to be parsed</param>
/// <param name="indexId">Index ID for the DAT</param>
2020-09-07 22:21:02 -07:00
private void ReadDirectory(XmlReader xtr, string filename, int indexId)
2019-01-11 13:43:15 -08:00
{
2020-09-07 22:21:02 -07:00
// If the reader is invalid, skip
if (xtr == null)
return;
2019-01-11 13:43:15 -08:00
2020-09-07 22:21:02 -07:00
// Prepare internal variables
Machine machine = null;
2019-01-11 13:43:15 -08:00
2020-09-07 22:21:02 -07:00
// Otherwise, read the directory
xtr.MoveToContent();
while (!xtr.EOF)
2019-01-11 13:43:15 -08:00
{
// We only want elements
if (xtr.NodeType != XmlNodeType.Element)
2019-01-11 13:43:15 -08:00
{
xtr.Read();
continue;
}
2019-01-11 13:43:15 -08:00
switch (xtr.Name)
{
case "machine":
XmlSerializer xs = new XmlSerializer(typeof(Machine));
machine = xs.Deserialize(xtr.ReadSubtree()) as Machine;
xtr.Skip();
break;
2020-09-01 13:36:32 -07:00
case "files":
ReadFiles(xtr.ReadSubtree(), machine, filename, indexId);
2020-09-01 13:36:32 -07:00
// Skip the directory node now that we've processed it
xtr.Read();
break;
default:
xtr.Read();
break;
2020-09-01 13:36:32 -07:00
}
}
}
/// <summary>
2020-09-07 22:21:02 -07:00
/// Read Files information
2020-09-01 13:36:32 -07:00
/// </summary>
2020-09-07 22:21:02 -07:00
/// <param name="xtr">XmlReader to use to parse the header</param>
/// <param name="machine">Machine to copy information from</param>
/// <param name="filename">Name of the file to be parsed</param>
/// <param name="indexId">Index ID for the DAT</param>
private void ReadFiles(XmlReader xtr, Machine machine, string filename, int indexId)
2020-09-01 13:36:32 -07:00
{
2020-09-07 22:21:02 -07:00
// If the reader is invalid, skip
if (xtr == null)
2020-09-01 13:36:32 -07:00
return;
2020-09-07 22:21:02 -07:00
// Otherwise, read the items
xtr.MoveToContent();
while (!xtr.EOF)
2020-09-01 13:36:32 -07:00
{
// We only want elements
if (xtr.NodeType != XmlNodeType.Element)
2020-09-01 13:36:32 -07:00
{
xtr.Read();
continue;
2020-09-01 13:36:32 -07:00
}
switch (xtr.Name)
{
case "datitem":
XmlSerializer xs = new XmlSerializer(typeof(DatItem));
DatItem item = xs.Deserialize(xtr.ReadSubtree()) as DatItem;
item.CopyMachineInformation(machine);
item.Source = new Source { Name = filename, Index = indexId };
ParseAddHelper(item);
xtr.Skip();
break;
default:
xtr.Read();
break;
}
2020-09-01 13:36:32 -07:00
}
}
/// <inheritdoc/>
public override bool WriteToFile(string outfile, bool ignoreblanks = false, bool throwOnError = false)
2019-01-11 13:43:15 -08:00
{
try
{
logger.User($"Opening file for writing: {outfile}");
2020-12-08 00:13:22 -08:00
FileStream fs = File.Create(outfile);
2019-01-11 13:43:15 -08:00
// If we get back null for some reason, just log and return
if (fs == null)
{
logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable");
2019-01-11 13:43:15 -08:00
return false;
}
XmlTextWriter xtw = new XmlTextWriter(fs, new UTF8Encoding(false))
{
Formatting = Formatting.Indented,
IndentChar = '\t',
2020-09-07 22:21:02 -07:00
Indentation = 1,
};
2019-01-11 13:43:15 -08:00
// Write out the header
WriteHeader(xtw);
2019-01-11 13:43:15 -08:00
// Write out each of the machines and roms
string lastgame = null;
2020-07-26 21:00:30 -07:00
// Use a sorted list of games to output
2020-07-26 22:34:45 -07:00
foreach (string key in Items.SortedKeys)
2019-01-11 13:43:15 -08:00
{
2020-08-28 15:06:07 -07:00
List<DatItem> datItems = Items.FilteredItems(key);
2019-01-11 13:43:15 -08:00
2020-09-25 20:25:29 -07:00
// If this machine doesn't contain any writable items, skip
if (!ContainsWritable(datItems))
continue;
2019-01-11 13:43:15 -08:00
// Resolve the names in the block
2020-08-28 15:06:07 -07:00
datItems = DatItem.ResolveNames(datItems);
2019-01-11 13:43:15 -08:00
2020-08-28 15:06:07 -07:00
for (int index = 0; index < datItems.Count; index++)
2019-01-11 13:43:15 -08:00
{
2020-08-28 15:06:07 -07:00
DatItem datItem = datItems[index];
2019-01-11 13:43:15 -08:00
// If we have a different game and we're not at the start of the list, output the end of last item
2020-08-28 15:06:07 -07:00
if (lastgame != null && lastgame.ToLowerInvariant() != datItem.Machine.Name.ToLowerInvariant())
2020-09-07 22:21:02 -07:00
WriteEndGame(xtw);
2019-01-11 13:43:15 -08:00
// If we have a new game, output the beginning of the new item
2020-08-28 15:06:07 -07:00
if (lastgame == null || lastgame.ToLowerInvariant() != datItem.Machine.Name.ToLowerInvariant())
2020-09-07 22:21:02 -07:00
WriteStartGame(xtw, datItem);
2019-01-11 13:43:15 -08:00
2020-08-28 15:06:07 -07:00
// Check for a "null" item
datItem = ProcessNullifiedItem(datItem);
2019-01-11 13:43:15 -08:00
2020-08-28 15:06:07 -07:00
// Write out the item if we're not ignoring
if (!ShouldIgnore(datItem, ignoreblanks))
2020-09-07 22:21:02 -07:00
WriteDatItem(xtw, datItem);
2019-01-11 13:43:15 -08:00
// Set the new data to compare against
2020-08-28 15:06:07 -07:00
lastgame = datItem.Machine.Name;
2019-01-11 13:43:15 -08:00
}
}
// Write the file footer out
2020-09-07 22:21:02 -07:00
WriteFooter(xtw);
2019-01-11 13:43:15 -08:00
logger.Verbose("File written!" + Environment.NewLine);
xtw.Dispose();
2019-01-11 13:43:15 -08:00
fs.Dispose();
}
catch (Exception ex)
{
logger.Error(ex);
if (throwOnError) throw ex;
2019-01-11 13:43:15 -08:00
return false;
}
return true;
}
/// <summary>
/// Write out DAT header using the supplied StreamWriter
/// </summary>
/// <param name="xtw">XmlTextWriter to output to</param>
private void WriteHeader(XmlTextWriter xtw)
2019-01-11 13:43:15 -08:00
{
xtw.WriteStartDocument();
xtw.WriteStartElement("datafile");
XmlSerializer xs = new XmlSerializer(typeof(DatHeader));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(xtw, Header, ns);
xtw.WriteStartElement("data");
xtw.Flush();
2019-01-11 13:43:15 -08:00
}
/// <summary>
/// Write out Game start using the supplied StreamWriter
/// </summary>
/// <param name="xtw">XmlTextWriter to output to</param>
/// <param name="datItem">DatItem object to be output</param>
private void WriteStartGame(XmlTextWriter xtw, DatItem datItem)
2019-01-11 13:43:15 -08:00
{
// No game should start with a path separator
datItem.Machine.Name = datItem.Machine.Name?.TrimStart(Path.DirectorySeparatorChar) ?? string.Empty;
2019-01-11 13:43:15 -08:00
// Write the machine
xtw.WriteStartElement("directory");
XmlSerializer xs = new XmlSerializer(typeof(Machine));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(xtw, datItem.Machine, ns);
xtw.WriteStartElement("files");
2019-01-11 13:43:15 -08:00
xtw.Flush();
2019-01-11 13:43:15 -08:00
}
/// <summary>
/// Write out Game start using the supplied StreamWriter
/// </summary>
/// <param name="xtw">XmlTextWriter to output to</param>
private void WriteEndGame(XmlTextWriter xtw)
2019-01-11 13:43:15 -08:00
{
// End files
xtw.WriteEndElement();
2019-01-11 13:43:15 -08:00
// End directory
xtw.WriteEndElement();
2019-01-11 13:43:15 -08:00
xtw.Flush();
2019-01-11 13:43:15 -08:00
}
/// <summary>
/// Write out DatItem using the supplied StreamWriter
/// </summary>
/// <param name="xtw">XmlTextWriter to output to</param>
/// <param name="datItem">DatItem object to be output</param>
private void WriteDatItem(XmlTextWriter xtw, DatItem datItem)
2019-01-11 13:43:15 -08:00
{
// Pre-process the item name
ProcessItemName(datItem, true);
2020-09-15 12:12:13 -07:00
// Write the DatItem
XmlSerializer xs = new XmlSerializer(typeof(DatItem));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(xtw, datItem, ns);
2019-01-11 13:43:15 -08:00
xtw.Flush();
2019-01-11 13:43:15 -08:00
}
/// <summary>
/// Write out DAT footer using the supplied StreamWriter
/// </summary>
/// <param name="xtw">XmlTextWriter to output to</param>
private void WriteFooter(XmlTextWriter xtw)
2019-01-11 13:43:15 -08:00
{
// End files
xtw.WriteEndElement();
// End directory
xtw.WriteEndElement();
// End data
xtw.WriteEndElement();
2020-09-15 12:12:13 -07:00
// End datafile
xtw.WriteEndElement();
2019-01-11 13:43:15 -08:00
xtw.Flush();
2019-01-11 13:43:15 -08:00
}
}
}