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

371 lines
13 KiB
C#
Raw Normal View History

using System;
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;
using SabreTools.Core;
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/>
public override void ParseFile(string filename, int indexId, bool keep, bool statsOnly = false, bool throwOnError = false)
2019-01-11 13:43:15 -08:00
{
// Prepare all internal variables
XmlReader? xtr = XmlReader.Create(filename, new XmlReaderSettings
2020-12-08 00:13:22 -08:00
{
CheckCharacters = false,
2024-02-28 22:54:56 -05:00
#if NET40_OR_GREATER
2020-12-08 00:13:22 -08:00
DtdProcessing = DtdProcessing.Ignore,
2024-02-28 22:54:56 -05:00
#endif
2020-12-08 00:13:22 -08:00
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":
XmlSerializer xs = new(typeof(DatHeader));
DatHeader? header = xs.Deserialize(xtr.ReadSubtree()) as DatHeader;
2020-09-07 22:21:02 -07:00
Header.ConditionalCopy(header);
2019-01-11 13:43:15 -08:00
xtr.Skip();
break;
2019-01-11 13:43:15 -08:00
case "directory":
ReadDirectory(xtr.ReadSubtree(), statsOnly, 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) when (!throwOnError)
2019-01-11 13:43:15 -08:00
{
logger.Warning(ex, $"Exception found while parsing '{filename}'");
2019-01-11 13:43:15 -08:00
// For XML errors, just skip the affected node
xtr?.Read();
}
2024-02-28 22:54:56 -05:00
#if NET452_OR_GREATER
xtr?.Dispose();
2024-02-28 22:54:56 -05:00
#endif
2019-01-11 13:43:15 -08:00
}
/// <summary>
/// Read directory information
/// </summary>
2020-09-07 22:21:02 -07:00
/// <param name="xtr">XmlReader to use to parse the header</param>
/// <param name="statsOnly">True to only add item statistics while parsing, false otherwise</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>
private void ReadDirectory(XmlReader xtr, bool statsOnly, 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;
long machineIndex = -1;
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(typeof(Machine));
machine = xs?.Deserialize(xtr.ReadSubtree()) as Machine;
if (machine != null)
machineIndex = ItemsDB.AddMachine(machine);
xtr.Skip();
break;
2020-09-01 13:36:32 -07:00
case "files":
ReadFiles(xtr.ReadSubtree(), machine, machineIndex, statsOnly, 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="machineIndex">Index of the Machine to add to the parsed items</param>
/// <param name="statsOnly">True to only add item statistics while parsing, false otherwise</param>
2020-09-07 22:21:02 -07:00
/// <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, long machineIndex, bool statsOnly, 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(typeof(DatItem));
if (xs.Deserialize(xtr.ReadSubtree()) is DatItem item)
{
item.CopyMachineInformation(machine);
2024-03-10 16:49:07 -04:00
item.SetFieldValue<Source?>(DatItem.SourceKey, new Source { Index = indexId, Name = filename });
ParseAddHelper(item, statsOnly);
ParseAddHelper(item, machineIndex, statsOnly);
}
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
{
2021-02-03 11:22:09 -08:00
logger.User($"Writing to '{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(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;
2019-01-11 13:43:15 -08:00
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
{
ConcurrentList<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
if (lastgame != null && !string.Equals(lastgame, datItem.GetFieldValue<Machine>(DatItem.MachineKey)!.GetStringFieldValue(Models.Metadata.Machine.NameKey), StringComparison.OrdinalIgnoreCase))
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
if (lastgame == null || !string.Equals(lastgame, datItem.GetFieldValue<Machine>(DatItem.MachineKey)!.GetStringFieldValue(Models.Metadata.Machine.NameKey), StringComparison.OrdinalIgnoreCase))
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
lastgame = datItem.GetFieldValue<Machine>(DatItem.MachineKey)!.GetStringFieldValue(Models.Metadata.Machine.NameKey);
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
2021-02-03 11:22:09 -08:00
logger.User($"'{outfile}' written!{Environment.NewLine}");
2024-02-28 22:54:56 -05:00
#if NET452_OR_GREATER
xtw.Dispose();
2024-02-28 22:54:56 -05:00
#endif
2019-01-11 13:43:15 -08:00
fs.Dispose();
}
catch (Exception ex) when (!throwOnError)
2019-01-11 13:43:15 -08:00
{
logger.Error(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(typeof(DatHeader));
XmlSerializerNamespaces ns = new();
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>
2024-02-28 19:19:50 -05:00
private static void WriteStartGame(XmlTextWriter xtw, DatItem datItem)
2019-01-11 13:43:15 -08:00
{
// No game should start with a path separator
datItem.GetFieldValue<Machine>(DatItem.MachineKey)!.SetFieldValue<string?>(Models.Metadata.Machine.NameKey, datItem.GetFieldValue<Machine>(DatItem.MachineKey)!.GetStringFieldValue(Models.Metadata.Machine.NameKey)?.TrimStart(Path.DirectorySeparatorChar) ?? string.Empty);
2019-01-11 13:43:15 -08:00
// Write the machine
xtw.WriteStartElement("directory");
XmlSerializer xs = new(typeof(Machine));
XmlSerializerNamespaces ns = new();
ns.Add("", "");
2024-03-10 16:49:07 -04:00
xs.Serialize(xtw, datItem.GetFieldValue<Machine>(DatItem.MachineKey), 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>
2024-02-28 19:19:50 -05:00
private static 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(typeof(DatItem));
XmlSerializerNamespaces ns = new();
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>
2024-02-28 19:19:50 -05:00
private static 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
}
}
}