MenuFileCache.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections.Generic;
  2. using System.IO;
  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 MeidoPhotoStudio.Plugin;
  8. public class MenuFileCache
  9. {
  10. public static readonly string CachePath = Path.Combine(Constants.ConfigPath, "cache.dat");
  11. private const int CacheVersion = 765;
  12. private readonly Dictionary<string, ModItem> modItems;
  13. private bool rebuild;
  14. public MenuFileCache()
  15. {
  16. modItems = new();
  17. if (File.Exists(CachePath))
  18. Deserialize();
  19. }
  20. public ModItem this[string menu]
  21. {
  22. get => modItems[menu];
  23. set
  24. {
  25. if (modItems.ContainsKey(menu))
  26. return;
  27. rebuild = true;
  28. modItems[menu] = value;
  29. }
  30. }
  31. public bool Has(string menuFileName) =>
  32. modItems.ContainsKey(menuFileName);
  33. public void Serialize()
  34. {
  35. if (!rebuild)
  36. return;
  37. using var binaryWriter = new BinaryWriter(File.OpenWrite(CachePath));
  38. binaryWriter.Write(CacheVersion);
  39. foreach (var item in modItems.Values)
  40. item.Serialize(binaryWriter);
  41. }
  42. private void Deserialize()
  43. {
  44. using var binaryReader = new BinaryReader(File.OpenRead(CachePath));
  45. if (binaryReader.ReadInt32() is not CacheVersion)
  46. {
  47. Utility.LogInfo("Cache version out of date. Rebuilding");
  48. return;
  49. }
  50. while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
  51. {
  52. var item = ModItem.Deserialize(binaryReader);
  53. modItems[item.MenuFile] = item;
  54. }
  55. }
  56. }