MenuFileCache.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.IO;
  2. using System.Collections.Generic;
  3. /*
  4. All of this is pretty much stolen from COM3D2.CacheEditMenu. Thanks Mr. Horsington.
  5. https://git.coder.horse/ghorsington/COM3D2.CacheEditMenu
  6. */
  7. namespace COM3D2.MeidoPhotoStudio.Plugin
  8. {
  9. using static MenuFileUtility;
  10. public class MenuFileCache
  11. {
  12. private const int cacheVersion = 765;
  13. public static readonly string cachePath = Path.Combine(Constants.configPath, "cache.dat");
  14. private readonly Dictionary<string, ModItem> modItems;
  15. private bool rebuild;
  16. public ModItem this[string menu]
  17. {
  18. get => modItems[menu];
  19. set
  20. {
  21. if (!modItems.ContainsKey(menu))
  22. {
  23. rebuild = true;
  24. modItems[menu] = value;
  25. }
  26. }
  27. }
  28. public MenuFileCache()
  29. {
  30. modItems = new Dictionary<string, ModItem>();
  31. if (File.Exists(cachePath)) Deserialize();
  32. }
  33. public bool Has(string menuFileName) => modItems.ContainsKey(menuFileName);
  34. private void Deserialize()
  35. {
  36. using BinaryReader binaryReader = new BinaryReader(File.OpenRead(cachePath));
  37. if (binaryReader.ReadInt32() != cacheVersion)
  38. {
  39. Utility.LogInfo("Cache version out of date. Rebuilding");
  40. return;
  41. }
  42. while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
  43. {
  44. ModItem item = ModItem.Deserialize(binaryReader);
  45. modItems[item.MenuFile] = item;
  46. }
  47. }
  48. public void Serialize()
  49. {
  50. if (!rebuild) return;
  51. using BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(cachePath));
  52. binaryWriter.Write(cacheVersion);
  53. foreach (ModItem item in modItems.Values) item.Serialize(binaryWriter);
  54. }
  55. }
  56. }