Files
SabreTools/SabreTools.Library/DatItems/DatItem.cs

1143 lines
37 KiB
C#
Raw Normal View History

2016-09-19 20:52:55 -07:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
2020-09-07 14:47:27 -07:00
using System.Xml.Serialization;
2017-05-04 02:41:11 -07:00
using SabreTools.Library.Data;
using SabreTools.Library.FileTypes;
using SabreTools.Library.Filtering;
2017-05-04 02:41:11 -07:00
using SabreTools.Library.Tools;
using NaturalSort;
2020-06-15 21:00:09 -07:00
using Newtonsoft.Json;
2020-08-23 22:23:55 -07:00
using Newtonsoft.Json.Converters;
2016-09-19 20:52:55 -07:00
namespace SabreTools.Library.DatItems
2016-09-19 20:52:55 -07:00
{
/// <summary>
/// Base class for all items included in a set
/// </summary>
2020-08-23 22:23:55 -07:00
[JsonObject("datitem")]
2020-09-07 14:47:27 -07:00
[XmlRoot("datitem")]
[XmlInclude(typeof(Adjuster))]
[XmlInclude(typeof(Analog))]
[XmlInclude(typeof(Archive))]
[XmlInclude(typeof(BiosSet))]
[XmlInclude(typeof(Blank))]
[XmlInclude(typeof(Chip))]
[XmlInclude(typeof(Condition))]
[XmlInclude(typeof(Configuration))]
[XmlInclude(typeof(Control))]
[XmlInclude(typeof(DataArea))]
[XmlInclude(typeof(Device))]
[XmlInclude(typeof(DeviceReference))]
[XmlInclude(typeof(DipSwitch))]
[XmlInclude(typeof(Disk))]
[XmlInclude(typeof(DiskArea))]
[XmlInclude(typeof(Display))]
[XmlInclude(typeof(Driver))]
[XmlInclude(typeof(Extension))]
[XmlInclude(typeof(Feature))]
[XmlInclude(typeof(Info))]
[XmlInclude(typeof(Input))]
[XmlInclude(typeof(Instance))]
[XmlInclude(typeof(Location))]
[XmlInclude(typeof(Media))]
[XmlInclude(typeof(Part))]
[XmlInclude(typeof(PartFeature))]
[XmlInclude(typeof(Port))]
[XmlInclude(typeof(RamOption))]
[XmlInclude(typeof(Release))]
[XmlInclude(typeof(Rom))]
[XmlInclude(typeof(Sample))]
[XmlInclude(typeof(Setting))]
[XmlInclude(typeof(SharedFeature))]
[XmlInclude(typeof(Slot))]
[XmlInclude(typeof(SlotOption))]
[XmlInclude(typeof(SoftwareList))]
[XmlInclude(typeof(Sound))]
public abstract class DatItem : IEquatable<DatItem>, IComparable<DatItem>, ICloneable
{
2020-08-20 13:17:14 -07:00
#region Fields
2020-08-20 21:15:37 -07:00
#region Common Fields
/// <summary>
/// Item type for outputting
/// </summary>
2020-09-07 22:00:02 -07:00
[JsonProperty("itemtype")]
2020-08-23 22:23:55 -07:00
[JsonConverter(typeof(StringEnumConverter))]
2020-09-07 22:00:02 -07:00
[XmlElement("itemtype")]
public ItemType ItemType { get; set; }
/// <summary>
/// Duplicate type when compared to another item
/// </summary>
2020-06-15 21:00:09 -07:00
[JsonIgnore]
2020-09-07 14:47:27 -07:00
[XmlIgnore]
public DupeType DupeType { get; set; }
#endregion
2020-08-20 21:15:37 -07:00
#region Machine Fields
/// <summary>
2020-08-20 13:17:14 -07:00
/// Machine values
/// </summary>
2020-06-15 21:00:09 -07:00
[JsonIgnore]
2020-09-07 14:47:27 -07:00
[XmlIgnore]
2020-08-20 13:17:14 -07:00
public Machine Machine { get; set; } = new Machine();
#endregion
2020-08-20 13:17:14 -07:00
#region Metadata information
/// <summary>
2020-08-20 13:17:14 -07:00
/// Source information
/// </summary>
2020-06-15 21:00:09 -07:00
[JsonIgnore]
2020-09-07 14:47:27 -07:00
[XmlIgnore]
2020-08-20 13:17:14 -07:00
public Source Source { get; set; } = new Source();
/// <summary>
/// Flag if item should be removed
/// </summary>
2020-06-15 21:00:09 -07:00
[JsonIgnore]
2020-09-07 14:47:27 -07:00
[XmlIgnore]
public bool Remove { get; set; }
#endregion
2020-08-19 13:12:42 -07:00
#region Static Values
/// <summary>
/// Fields unique to a DatItem
/// </summary>
public static readonly List<Field> DatItemFields = new List<Field>()
{
2020-08-25 22:48:46 -07:00
#region Common
Field.DatItem_Type,
#endregion
#region Item-Specific
#region Actionable
2020-08-20 21:15:37 -07:00
// Rom
2020-09-03 14:22:15 -07:00
Field.DatItem_Name,
2020-08-25 11:20:50 -07:00
Field.DatItem_Bios,
Field.DatItem_Size,
Field.DatItem_CRC,
Field.DatItem_MD5,
#if NET_FRAMEWORK
Field.DatItem_RIPEMD160,
#endif
Field.DatItem_SHA1,
Field.DatItem_SHA256,
Field.DatItem_SHA384,
Field.DatItem_SHA512,
Field.DatItem_SpamSum,
Field.DatItem_Merge,
Field.DatItem_Region,
2020-08-25 11:20:50 -07:00
Field.DatItem_Offset,
Field.DatItem_Date,
Field.DatItem_Status,
Field.DatItem_Optional,
2020-08-25 11:20:50 -07:00
Field.DatItem_Inverted,
2020-08-25 22:48:46 -07:00
2020-09-03 14:22:15 -07:00
// Rom (AttractMode)
Field.DatItem_AltName,
Field.DatItem_AltTitle,
// Rom (OpenMSX)
Field.DatItem_Original,
Field.DatItem_OpenMSXSubType,
Field.DatItem_OpenMSXType,
Field.DatItem_Remark,
Field.DatItem_Boot,
// Rom (SoftwareList)
2020-09-03 14:22:15 -07:00
Field.DatItem_LoadFlag,
Field.DatItem_Value,
// Disk
Field.DatItem_Index,
Field.DatItem_Writable,
#endregion
#region Auxiliary
2020-09-01 11:34:52 -07:00
// Adjuster
Field.DatItem_Default,
2020-09-03 14:22:15 -07:00
// Analog
Field.DatItem_Analog_Mask,
2020-09-01 11:34:52 -07:00
// BiosSet
Field.DatItem_Description,
// Chip
Field.DatItem_Tag,
Field.DatItem_ChipType,
Field.DatItem_Clock,
2020-09-03 14:22:15 -07:00
// Condition
Field.DatItem_Mask,
Field.DatItem_Relation,
Field.DatItem_Condition_Tag,
Field.DatItem_Condition_Mask,
Field.DatItem_Condition_Relation,
Field.DatItem_Condition_Value,
// Control
Field.DatItem_Control_Type,
Field.DatItem_Control_Player,
Field.DatItem_Control_Buttons,
Field.DatItem_Control_RequiredButtons,
2020-09-03 14:22:15 -07:00
Field.DatItem_Control_Minimum,
Field.DatItem_Control_Maximum,
Field.DatItem_Control_Sensitivity,
Field.DatItem_Control_KeyDelta,
Field.DatItem_Control_Reverse,
Field.DatItem_Control_Ways,
Field.DatItem_Control_Ways2,
Field.DatItem_Control_Ways3,
2020-09-04 14:10:35 -07:00
// DataArea
Field.DatItem_AreaName,
Field.DatItem_AreaSize,
Field.DatItem_AreaWidth,
Field.DatItem_AreaEndianness,
2020-09-03 14:22:15 -07:00
// Device
Field.DatItem_DeviceType,
Field.DatItem_FixedImage,
Field.DatItem_Mandatory,
Field.DatItem_Interface,
// Display
Field.DatItem_DisplayType,
Field.DatItem_Rotate,
Field.DatItem_FlipX,
Field.DatItem_Width,
Field.DatItem_Height,
Field.DatItem_Refresh,
Field.DatItem_PixClock,
Field.DatItem_HTotal,
Field.DatItem_HBEnd,
Field.DatItem_HBStart,
Field.DatItem_VTotal,
Field.DatItem_VBEnd,
Field.DatItem_VBStart,
// Driver
Field.DatItem_SupportStatus,
Field.DatItem_EmulationStatus,
Field.DatItem_CocktailStatus,
Field.DatItem_SaveStateStatus,
// Extension
Field.DatItem_Extension_Name,
// Feature
Field.DatItem_FeatureType,
Field.DatItem_FeatureStatus,
Field.DatItem_FeatureOverall,
// Input
Field.DatItem_Service,
Field.DatItem_Tilt,
Field.DatItem_Players,
Field.DatItem_Coins,
// Instance
Field.DatItem_Instance_Name,
Field.DatItem_Instance_BriefName,
// Location
Field.DatItem_Location_Name,
Field.DatItem_Location_Number,
Field.DatItem_Location_Inverted,
2020-09-04 14:10:35 -07:00
// Part
Field.DatItem_Part_Name,
Field.DatItem_Part_Interface,
// PartFeature
Field.DatItem_Part_Feature_Name,
Field.DatItem_Part_Feature_Value,
2020-09-03 14:22:15 -07:00
// RamOption
2020-09-01 11:34:52 -07:00
Field.DatItem_Content,
2020-09-03 14:22:15 -07:00
// Release
Field.DatItem_Language,
// Setting
Field.DatItem_Setting_Name,
Field.DatItem_Setting_Value,
Field.DatItem_Setting_Default,
// SlotOption
2020-09-01 16:21:55 -07:00
Field.DatItem_SlotOption_Name,
Field.DatItem_SlotOption_DeviceName,
Field.DatItem_SlotOption_Default,
2020-09-03 14:22:15 -07:00
// SoftwareList
Field.DatItem_SoftwareListStatus,
Field.DatItem_Filter,
// Sound
Field.DatItem_Channels,
2020-08-25 22:48:46 -07:00
#endregion
#endregion // Item-Specific
2020-08-19 13:12:42 -07:00
};
/// <summary>
/// Fields unique to a Machine
/// </summary>
public static readonly List<Field> MachineFields = new List<Field>()
{
2020-09-03 14:22:15 -07:00
#region Common
2020-08-24 22:25:47 -07:00
Field.Machine_Name,
Field.Machine_Comment,
Field.Machine_Description,
Field.Machine_Year,
Field.Machine_Manufacturer,
Field.Machine_Publisher,
2020-09-03 14:22:15 -07:00
Field.Machine_Category,
2020-08-24 22:25:47 -07:00
Field.Machine_RomOf,
Field.Machine_CloneOf,
Field.Machine_SampleOf,
Field.Machine_Type,
2020-08-20 14:36:36 -07:00
2020-09-03 14:22:15 -07:00
#endregion
#region AttractMode
2020-08-24 22:25:47 -07:00
Field.Machine_Players,
Field.Machine_Rotation,
Field.Machine_Control,
2020-08-25 11:20:50 -07:00
Field.Machine_Status,
2020-08-24 22:25:47 -07:00
Field.Machine_DisplayCount,
Field.Machine_DisplayType,
Field.Machine_Buttons,
2020-08-20 14:36:36 -07:00
2020-09-03 14:22:15 -07:00
#endregion
#region ListXML
2020-08-24 22:25:47 -07:00
Field.Machine_SourceFile,
Field.Machine_Runnable,
2020-08-20 14:36:36 -07:00
2020-09-03 14:22:15 -07:00
#endregion
#region Logiqx
2020-08-24 22:25:47 -07:00
Field.Machine_Board,
Field.Machine_RebuildTo,
2020-08-20 14:36:36 -07:00
2020-09-03 14:22:15 -07:00
#endregion
#region Logiqx EmuArc
2020-08-24 22:25:47 -07:00
Field.Machine_TitleID,
Field.Machine_Developer,
Field.Machine_Genre,
Field.Machine_Subgenre,
Field.Machine_Ratings,
Field.Machine_Score,
Field.Machine_Enabled,
2020-08-25 12:15:28 -07:00
Field.Machine_CRC,
2020-08-24 22:25:47 -07:00
Field.Machine_RelatedTo,
2020-08-20 22:42:04 -07:00
2020-09-03 14:22:15 -07:00
#endregion
#region OpenMSX
2020-08-24 22:25:47 -07:00
Field.Machine_GenMSXID,
Field.Machine_System,
Field.Machine_Country,
2020-09-03 14:22:15 -07:00
#endregion
#region SoftwareList
2020-08-24 22:25:47 -07:00
Field.Machine_Supported,
2020-09-03 14:22:15 -07:00
#endregion
2020-08-19 13:12:42 -07:00
};
#endregion
#endregion
#region Instance Methods
#region Accessors
2020-09-02 12:19:12 -07:00
/// <summary>
/// Gets the name to use for a DatItem
/// </summary>
/// <returns>Name if available, null otherwise</returns>
public virtual string GetName()
{
return null;
}
2020-08-21 10:16:05 -07:00
/// <summary>
/// Set fields with given values
/// </summary>
/// <param name="mappings">Mappings dictionary</param>
public virtual void SetFields(Dictionary<Field, string> mappings)
{
// Set machine fields
2020-08-25 11:20:50 -07:00
if (Machine == null)
Machine = new Machine();
2020-08-21 10:16:05 -07:00
Machine.SetFields(mappings);
}
#endregion
#region Constructors
/// <summary>
/// Create a specific type of DatItem to be used based on an ItemType
/// </summary>
/// <param name="itemType">Type of the DatItem to be created</param>
/// <returns>DatItem of the specific internal type that corresponds to the inputs</returns>
2020-08-25 11:20:50 -07:00
public static DatItem Create(ItemType? itemType)
{
#if NET_FRAMEWORK
switch (itemType)
{
2020-09-01 11:34:52 -07:00
case ItemType.Adjuster:
return new Adjuster();
case ItemType.Analog:
return new Analog();
case ItemType.Archive:
return new Archive();
case ItemType.BiosSet:
return new BiosSet();
case ItemType.Blank:
return new Blank();
2020-08-25 22:48:46 -07:00
case ItemType.Chip:
return new Chip();
case ItemType.Condition:
return new Condition();
2020-09-01 12:04:35 -07:00
case ItemType.Configuration:
return new Configuration();
2020-09-02 23:02:06 -07:00
case ItemType.Control:
return new Control();
2020-09-01 12:04:35 -07:00
2020-09-04 14:10:35 -07:00
case ItemType.DataArea:
return new DataArea();
2020-09-02 17:09:19 -07:00
case ItemType.Device:
return new Device();
case ItemType.DeviceReference:
return new DeviceReference();
2020-09-01 13:36:32 -07:00
case ItemType.DipSwitch:
return new DipSwitch();
case ItemType.Disk:
return new Disk();
2020-09-04 14:10:35 -07:00
case ItemType.DiskArea:
return new DiskArea();
2020-09-02 21:36:14 -07:00
case ItemType.Display:
return new Display();
2020-09-02 15:38:10 -07:00
case ItemType.Driver:
return new Driver();
2020-09-02 16:37:01 -07:00
case ItemType.Extension:
return new Extension();
2020-09-02 13:31:50 -07:00
case ItemType.Feature:
return new Feature();
2020-09-02 23:31:35 -07:00
case ItemType.Info:
return new Info();
2020-09-02 21:59:26 -07:00
case ItemType.Input:
return new Input();
2020-09-02 16:46:17 -07:00
case ItemType.Instance:
return new Instance();
case ItemType.Location:
return new Location();
case ItemType.Media:
return new Media();
2020-09-04 14:10:35 -07:00
case ItemType.Part:
return new Part();
2020-09-03 13:20:56 -07:00
case ItemType.PartFeature:
return new PartFeature();
2020-09-02 17:22:31 -07:00
case ItemType.Port:
return new Port();
2020-09-01 11:34:52 -07:00
case ItemType.RamOption:
return new RamOption();
case ItemType.Release:
return new Release();
case ItemType.Rom:
return new Rom();
case ItemType.Sample:
return new Sample();
case ItemType.Setting:
return new Setting();
2020-09-03 00:48:07 -07:00
case ItemType.SharedFeature:
return new SharedFeature();
2020-09-01 16:21:55 -07:00
case ItemType.Slot:
return new Slot();
2020-09-02 22:44:54 -07:00
case ItemType.SlotOption:
return new SlotOption();
2020-08-31 23:26:07 -07:00
case ItemType.SoftwareList:
return new SoftwareList();
2020-09-02 12:51:21 -07:00
case ItemType.Sound:
return new Sound();
default:
return new Rom();
}
#else
return itemType switch
{
2020-09-02 12:19:12 -07:00
ItemType.Adjuster => new Adjuster(),
ItemType.Analog => new Analog(),
ItemType.Archive => new Archive(),
ItemType.BiosSet => new BiosSet(),
ItemType.Blank => new Blank(),
2020-09-02 12:19:12 -07:00
ItemType.Chip => new Chip(),
ItemType.Condition => new Condition(),
2020-09-02 12:19:12 -07:00
ItemType.Configuration => new Configuration(),
2020-09-02 17:09:19 -07:00
ItemType.Device => new Device(),
2020-09-02 12:19:12 -07:00
ItemType.DeviceReference => new DeviceReference(),
ItemType.DipSwitch => new DipSwitch(),
ItemType.Disk => new Disk(),
2020-09-02 21:36:14 -07:00
ItemType.Display => new Display(),
2020-09-02 15:38:10 -07:00
ItemType.Driver => new Driver(),
2020-09-02 16:37:01 -07:00
ItemType.Extension => new Extension(),
2020-09-02 13:31:50 -07:00
ItemType.Feature => new Feature(),
2020-09-02 23:31:35 -07:00
ItemType.Info => new Info(),
2020-09-02 16:46:17 -07:00
ItemType.Instance => new Instance(),
ItemType.Location => new Location(),
2020-09-02 12:19:12 -07:00
ItemType.Media => new Media(),
2020-09-03 13:20:56 -07:00
ItemType.PartFeature => new PartFeature(),
2020-09-02 17:22:31 -07:00
ItemType.Port => new Port(),
2020-09-02 12:19:12 -07:00
ItemType.RamOption => new RamOption(),
ItemType.Release => new Release(),
ItemType.Rom => new Rom(),
ItemType.Sample => new Sample(),
2020-09-03 00:48:07 -07:00
ItemType.SharedFeature => new SharedFeature(),
2020-09-02 12:19:12 -07:00
ItemType.Slot => new Slot(),
2020-09-02 22:44:54 -07:00
ItemType.SlotOption => new SlotOption(),
2020-09-02 12:19:12 -07:00
ItemType.SoftwareList => new SoftwareList(),
2020-09-02 12:51:21 -07:00
ItemType.Sound => new Sound(),
_ => new Rom(),
};
#endif
}
/// <summary>
/// Create a specific type of DatItem to be used based on a BaseFile
/// </summary>
/// <param name="baseFile">BaseFile containing information to be created</param>
/// <returns>DatItem of the specific internal type that corresponds to the inputs</returns>
public static DatItem Create(BaseFile baseFile)
{
switch (baseFile.Type)
{
case FileType.AaruFormat:
return new Media(baseFile);
case FileType.CHD:
return new Disk(baseFile);
case FileType.GZipArchive:
case FileType.LRZipArchive:
case FileType.LZ4Archive:
case FileType.None:
case FileType.RarArchive:
case FileType.SevenZipArchive:
case FileType.TapeArchive:
case FileType.XZArchive:
case FileType.ZipArchive:
case FileType.ZPAQArchive:
case FileType.ZstdArchive:
return new Rom(baseFile);
case FileType.Folder:
default:
return null;
}
}
#endregion
#region Cloning Methods
/// <summary>
/// Clone the DatItem
/// </summary>
/// <returns>Clone of the DatItem</returns>
public abstract object Clone();
/// <summary>
/// Copy all machine information over in one shot
/// </summary>
/// <param name="item">Existing item to copy information from</param>
public void CopyMachineInformation(DatItem item)
{
2020-08-20 13:17:14 -07:00
Machine = (Machine)item.Machine.Clone();
}
/// <summary>
/// Copy all machine information over in one shot
/// </summary>
/// <param name="machine">Existing machine to copy information from</param>
public void CopyMachineInformation(Machine machine)
{
2020-08-20 13:17:14 -07:00
Machine = (Machine)machine.Clone();
}
#endregion
#region Comparision Methods
public int CompareTo(DatItem other)
{
try
{
2020-09-02 15:07:25 -07:00
if (GetName() == other.GetName())
return Equals(other) ? 0 : 1;
return string.Compare(GetName(), other.GetName());
}
catch
{
return 1;
}
}
/// <summary>
/// Determine if an item is a duplicate using partial matching logic
/// </summary>
/// <param name="other">DatItem to use as a baseline</param>
/// <returns>True if the roms are duplicates, false otherwise</returns>
public abstract bool Equals(DatItem other);
/// <summary>
/// Return the duplicate status of two items
/// </summary>
/// <param name="lastItem">DatItem to check against</param>
/// <returns>The DupeType corresponding to the relationship between the two</returns>
public DupeType GetDuplicateStatus(DatItem lastItem)
{
DupeType output = 0x00;
// If we don't have a duplicate at all, return none
2020-08-17 17:28:32 -07:00
if (!Equals(lastItem))
return output;
// If the duplicate is external already or should be, set it
2020-08-20 13:17:14 -07:00
if (lastItem.DupeType.HasFlag(DupeType.External) || lastItem.Source.Index != Source.Index)
{
2020-09-02 15:07:25 -07:00
if (lastItem.Machine.Name == Machine.Name && lastItem.GetName() == GetName())
output = DupeType.External | DupeType.All;
else
output = DupeType.External | DupeType.Hash;
}
// Otherwise, it's considered an internal dupe
else
{
2020-09-02 15:07:25 -07:00
if (lastItem.Machine.Name == Machine.Name && lastItem.GetName() == GetName())
output = DupeType.Internal | DupeType.All;
else
output = DupeType.Internal | DupeType.Hash;
}
return output;
}
#endregion
#region Filtering
2020-09-02 12:19:12 -07:00
/// <summary>
/// Clean a DatItem according to the cleaner
/// </summary>
/// <param name="cleaner">Cleaner to implement</param>
public virtual void Clean(Cleaner cleaner)
{
// If we're stripping unicode characters, strip machine name and description
if (cleaner?.RemoveUnicode == true)
{
Machine.Name = Sanitizer.RemoveUnicodeCharacters(Machine.Name);
Machine.Description = Sanitizer.RemoveUnicodeCharacters(Machine.Description);
}
// If we're in cleaning mode, sanitize machine name and description
if (cleaner?.Clean == true)
{
Machine.Name = Sanitizer.CleanGameName(Machine.Name);
Machine.Description = Sanitizer.CleanGameName(Machine.Description);
}
// If we are in single game mode, rename the machine
if (cleaner?.Single == true)
Machine.Name = "!";
}
/// <summary>
/// Check to see if a DatItem passes the filter
/// </summary>
/// <param name="filter">Filter to check against</param>
/// <returns>True if the item passed the filter, false otherwise</returns>
public virtual bool PassesFilter(Filter filter)
{
2020-08-20 13:17:14 -07:00
// Filter on machine fields
if (!Machine.PassesFilter(filter))
return false;
2020-08-20 21:15:37 -07:00
#region Common
// Filter on item type
2020-08-25 14:24:34 -07:00
if (filter.DatItem_Type.MatchesPositiveSet(ItemType.ToString()) == false)
return false;
2020-08-25 14:24:34 -07:00
if (filter.DatItem_Type.MatchesNegativeSet(ItemType.ToString()) == true)
return false;
2020-08-20 21:15:37 -07:00
#endregion
return true;
}
2020-08-17 23:45:23 -07:00
/// <summary>
/// Remove fields from the DatItem
/// </summary>
/// <param name="fields">List of Fields to remove</param>
public virtual void RemoveFields(List<Field> fields)
{
2020-08-20 13:17:14 -07:00
// Remove machine fields
Machine.RemoveFields(fields);
2020-08-17 23:45:23 -07:00
}
2020-09-02 12:19:12 -07:00
/// <summary>
/// Set internal names to match One Rom Per Game (ORPG) logic
/// </summary>
public virtual void SetOneRomPerGame()
{
}
#endregion
#region Sorting and Merging
/// <summary>
2020-07-15 10:47:13 -07:00
/// Get the dictionary key that should be used for a given item and bucketing type
/// </summary>
2020-08-22 23:02:30 -07:00
/// <param name="bucketedBy">Field value representing what key to get</param>
/// <param name="lower">True if the key should be lowercased (default), false otherwise</param>
/// <param name="norename">True if games should only be compared on game and file name, false if system and source are counted</param>
/// <returns>String representing the key to be used for the DatItem</returns>
2020-08-22 23:02:30 -07:00
/// TODO: What other fields can we reasonably allow bucketing on?
public virtual string GetKey(Field bucketedBy, bool lower = true, bool norename = true)
{
// Set the output key as the default blank string
string key = string.Empty;
2020-07-15 10:47:13 -07:00
// Now determine what the key should be based on the bucketedBy value
switch (bucketedBy)
{
2020-08-25 11:20:50 -07:00
case Field.DatItem_CRC:
2020-08-17 17:28:32 -07:00
key = Constants.CRCZero;
break;
2020-08-24 22:25:47 -07:00
case Field.Machine_Name:
key = (norename ? string.Empty
2020-08-20 13:17:14 -07:00
: Source.Index.ToString().PadLeft(10, '0')
+ "-")
2020-08-20 13:17:14 -07:00
+ (string.IsNullOrWhiteSpace(Machine.Name)
? "Default"
2020-08-20 13:17:14 -07:00
: Machine.Name);
if (lower)
key = key.ToLowerInvariant();
if (key == null)
key = "null";
break;
2020-08-25 11:20:50 -07:00
case Field.DatItem_MD5:
2020-08-17 17:28:32 -07:00
key = Constants.MD5Zero;
break;
#if NET_FRAMEWORK
2020-08-25 11:20:50 -07:00
case Field.DatItem_RIPEMD160:
2020-08-17 17:28:32 -07:00
key = Constants.RIPEMD160Zero;
break;
#endif
2020-08-25 11:20:50 -07:00
case Field.DatItem_SHA1:
2020-08-17 17:28:32 -07:00
key = Constants.SHA1Zero;
break;
2020-08-25 11:20:50 -07:00
case Field.DatItem_SHA256:
2020-08-17 17:28:32 -07:00
key = Constants.SHA256Zero;
break;
2020-08-25 11:20:50 -07:00
case Field.DatItem_SHA384:
2020-08-17 17:28:32 -07:00
key = Constants.SHA384Zero;
break;
2020-08-25 11:20:50 -07:00
case Field.DatItem_SHA512:
2020-08-17 17:28:32 -07:00
key = Constants.SHA512Zero;
break;
case Field.DatItem_SpamSum:
key = null;
break;
}
// Double and triple check the key for corner cases
if (key == null)
key = string.Empty;
return key;
}
2020-08-17 22:35:17 -07:00
/// <summary>
/// Replace fields from another item
/// </summary>
/// <param name="item">DatItem to pull new information from</param>
2020-08-17 23:45:23 -07:00
/// <param name="fields">List of Fields representing what should be updated</param>
public virtual void ReplaceFields(DatItem item, List<Field> fields)
2020-08-17 22:35:17 -07:00
{
}
#endregion
#endregion // Instance Methods
#region Static Methods
#region Sorting and Merging
2020-08-17 14:57:54 -07:00
/// <summary>
/// Determine if two hashes are equal for the purposes of merging
/// </summary>
/// <param name="firstHash">First hash to compare</param>
/// <param name="secondHash">Second hash to compare</param>
/// <returns>True if either is empty OR the hashes exactly match, false otherwise</returns>
public static bool ConditionalHashEquals(byte[] firstHash, byte[] secondHash)
{
// If either hash is empty, we say they're equal for merging
if (firstHash.IsNullOrEmpty() || secondHash.IsNullOrEmpty())
return true;
// If they're different sizes, they can't match
if (firstHash.Length != secondHash.Length)
return false;
// Otherwise, they need to match exactly
return Enumerable.SequenceEqual(firstHash, secondHash);
}
/// <summary>
/// Merge an arbitrary set of ROMs based on the supplied information
/// </summary>
/// <param name="infiles">List of File objects representing the roms to be merged</param>
/// <returns>A List of DatItem objects representing the merged roms</returns>
public static List<DatItem> Merge(List<DatItem> infiles)
{
// Check for null or blank roms first
if (infiles == null || infiles.Count == 0)
return new List<DatItem>();
// Create output list
List<DatItem> outfiles = new List<DatItem>();
// Then deduplicate them by checking to see if data matches previous saved roms
int nodumpCount = 0;
2020-07-19 13:42:07 -07:00
for (int f = 0; f < infiles.Count; f++)
{
2020-07-19 13:42:07 -07:00
DatItem file = infiles[f];
// If we don't have a Dis, Media, or Rom, we skip checking for duplicates
if (file.ItemType != ItemType.Disk && file.ItemType != ItemType.Media && file.ItemType != ItemType.Rom)
continue;
// If it's a nodump, add and skip
2020-08-17 17:28:32 -07:00
if (file.ItemType == ItemType.Rom && (file as Rom).ItemStatus == ItemStatus.Nodump)
{
outfiles.Add(file);
nodumpCount++;
continue;
}
2020-08-17 17:28:32 -07:00
else if (file.ItemType == ItemType.Disk && (file as Disk).ItemStatus == ItemStatus.Nodump)
{
outfiles.Add(file);
nodumpCount++;
continue;
}
// If it's the first non-nodump rom in the list, don't touch it
else if (outfiles.Count == 0 || outfiles.Count == nodumpCount)
{
outfiles.Add(file);
continue;
}
// Check if the rom is a duplicate
DupeType dupetype = 0x00;
2020-08-17 17:28:32 -07:00
DatItem saveditem = new Blank();
int pos = -1;
for (int i = 0; i < outfiles.Count; i++)
{
DatItem lastrom = outfiles[i];
// Get the duplicate status
dupetype = file.GetDuplicateStatus(lastrom);
// If it's a duplicate, skip adding it to the output but add any missing information
if (dupetype != 0x00)
{
saveditem = lastrom;
pos = i;
// Disks, Media, and Roms have more information to fill
2020-08-17 17:28:32 -07:00
if (file.ItemType == ItemType.Disk)
(saveditem as Disk).FillMissingInformation(file as Disk);
else if (file.ItemType == ItemType.Media)
(saveditem as Media).FillMissingInformation(file as Media);
2020-08-17 17:28:32 -07:00
else if (file.ItemType == ItemType.Rom)
(saveditem as Rom).FillMissingInformation(file as Rom);
saveditem.DupeType = dupetype;
// If the current system has a lower ID than the previous, set the system accordingly
2020-08-20 13:17:14 -07:00
if (file.Source.Index < saveditem.Source.Index)
{
2020-08-20 13:17:14 -07:00
saveditem.Source = file.Source.Clone() as Source;
saveditem.CopyMachineInformation(file);
2020-09-02 12:19:12 -07:00
saveditem.SetFields(new Dictionary<Field, string> { [Field.DatItem_Name] = file.GetName() });
}
// If the current machine is a child of the new machine, use the new machine instead
2020-08-20 13:17:14 -07:00
if (saveditem.Machine.CloneOf == file.Machine.Name || saveditem.Machine.RomOf == file.Machine.Name)
{
saveditem.CopyMachineInformation(file);
2020-09-02 12:19:12 -07:00
saveditem.SetFields(new Dictionary<Field, string> { [Field.DatItem_Name] = file.GetName() });
}
break;
}
}
// If no duplicate is found, add it to the list
if (dupetype == 0x00)
{
outfiles.Add(file);
}
// Otherwise, if a new rom information is found, add that
else
{
outfiles.RemoveAt(pos);
outfiles.Insert(pos, saveditem);
}
}
// Then return the result
return outfiles;
}
/// <summary>
/// Resolve name duplicates in an arbitrary set of ROMs based on the supplied information
/// </summary>
/// <param name="infiles">List of File objects representing the roms to be merged</param>
/// <returns>A List of DatItem objects representing the renamed roms</returns>
public static List<DatItem> ResolveNames(List<DatItem> infiles)
{
// Create the output list
List<DatItem> output = new List<DatItem>();
// First we want to make sure the list is in alphabetical order
Sort(ref infiles, true);
// Now we want to loop through and check names
DatItem lastItem = null;
string lastrenamed = null;
int lastid = 0;
for (int i = 0; i < infiles.Count; i++)
{
DatItem datItem = infiles[i];
// If we have the first item, we automatically add it
if (lastItem == null)
{
output.Add(datItem);
lastItem = datItem;
continue;
}
2020-09-02 12:19:12 -07:00
// Get the last item name, if applicable
string lastItemName = lastItem.GetName() ?? lastItem.ItemType.ToString();
// Get the current item name, if applicable
string datItemName = datItem.GetName() ?? datItem.ItemType.ToString();
// If the current item exactly matches the last item, then we don't add it
if (datItem.GetDuplicateStatus(lastItem).HasFlag(DupeType.All))
{
2020-09-02 12:19:12 -07:00
Globals.Logger.Verbose($"Exact duplicate found for '{datItemName}'");
continue;
}
// If the current name matches the previous name, rename the current item
2020-09-02 12:19:12 -07:00
else if (datItemName == lastItemName)
{
2020-09-02 12:19:12 -07:00
Globals.Logger.Verbose($"Name duplicate found for '{datItemName}'");
if (datItem.ItemType == ItemType.Disk || datItem.ItemType == ItemType.Media || datItem.ItemType == ItemType.Rom)
{
2020-09-02 12:19:12 -07:00
datItemName += GetDuplicateSuffix(datItem);
#if NET_FRAMEWORK
2020-09-02 12:19:12 -07:00
lastrenamed = lastrenamed ?? datItemName;
#else
2020-09-02 12:19:12 -07:00
lastrenamed ??= datItemName;
#endif
}
// If we have a conflict with the last renamed item, do the right thing
2020-09-02 12:19:12 -07:00
if (datItemName == lastrenamed)
{
2020-09-02 12:19:12 -07:00
lastrenamed = datItemName;
datItemName += (lastid == 0 ? string.Empty : "_" + lastid);
lastid++;
}
// If we have no conflict, then we want to reset the lastrenamed and id
else
{
lastrenamed = null;
lastid = 0;
}
2020-09-02 12:19:12 -07:00
// Set the item name back to the datItem
datItem.SetFields(new Dictionary<Field, string> { [Field.DatItem_Name] = datItemName });
output.Add(datItem);
}
// Otherwise, we say that we have a valid named file
else
{
output.Add(datItem);
lastItem = datItem;
lastrenamed = null;
lastid = 0;
}
}
// One last sort to make sure this is ordered
Sort(ref output, true);
return output;
}
/// <summary>
/// Get duplicate suffix based on the item type
/// </summary>
private static string GetDuplicateSuffix(DatItem datItem)
{
if (datItem.ItemType == ItemType.Disk)
2020-08-17 17:28:32 -07:00
return (datItem as Disk).GetDuplicateSuffix();
else if (datItem.ItemType == ItemType.Media)
return (datItem as Media).GetDuplicateSuffix();
else if (datItem.ItemType == ItemType.Rom)
2020-08-17 17:28:32 -07:00
return (datItem as Rom).GetDuplicateSuffix();
return "_1";
}
/// <summary>
2020-08-28 01:13:55 -07:00
/// Sort a list of File objects by SourceID, Game, and Name (in order)
/// </summary>
/// <param name="roms">List of File objects representing the roms to be sorted</param>
/// <param name="norename">True if files are not renamed, false otherwise</param>
/// <returns>True if it sorted correctly, false otherwise</returns>
public static bool Sort(ref List<DatItem> roms, bool norename)
{
roms.Sort(delegate (DatItem x, DatItem y)
{
try
{
NaturalComparer nc = new NaturalComparer();
2020-08-20 13:17:14 -07:00
if (x.Source.Index == y.Source.Index)
{
2020-08-20 13:17:14 -07:00
if (x.Machine.Name == y.Machine.Name)
{
2020-08-31 16:46:04 -07:00
if (x.ItemType == y.ItemType)
{
2020-09-02 12:19:12 -07:00
if (Path.GetDirectoryName(Sanitizer.RemovePathUnsafeCharacters(x.GetName() ?? string.Empty)) == Path.GetDirectoryName(Sanitizer.RemovePathUnsafeCharacters(y.GetName() ?? string.Empty)))
return nc.Compare(Path.GetFileName(Sanitizer.RemovePathUnsafeCharacters(x.GetName() ?? string.Empty)), Path.GetFileName(Sanitizer.RemovePathUnsafeCharacters(y.GetName() ?? string.Empty)));
2020-09-02 12:19:12 -07:00
return nc.Compare(Path.GetDirectoryName(Sanitizer.RemovePathUnsafeCharacters(x.GetName() ?? string.Empty)), Path.GetDirectoryName(Sanitizer.RemovePathUnsafeCharacters(y.GetName() ?? string.Empty)));
2020-08-31 16:46:04 -07:00
}
return x.ItemType - y.ItemType;
}
2020-08-20 13:17:14 -07:00
return nc.Compare(x.Machine.Name, y.Machine.Name);
}
2020-08-20 13:17:14 -07:00
return (norename ? nc.Compare(x.Machine.Name, y.Machine.Name) : x.Source.Index - y.Source.Index);
}
catch (Exception)
{
// Absorb the error
return 0;
}
});
return true;
}
#endregion
#endregion // Static Methods
}
2016-09-19 20:52:55 -07:00
}